repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
omikolaj/neos-fair-api
config/routes.rb
<reponame>omikolaj/neos-fair-api Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html namespace :api, defaults: {:format => :json} do resources :users do resources :drafts, :controller => :ad, type: 'Draft' resources :ads resources :orders end post '/pay', to: 'ads#pay' post '/login', to: 'sessions#login' post '/guest', to: 'sessions#guest' get '/auth/github/callback', to: 'sessions#github' resources :ads end end
omikolaj/neos-fair-api
app/models/user.rb
class User < ApplicationRecord before_create -> {self.token = generate_token} before_save :downcase_email has_secure_password has_many :drafts, class_name: 'Draft' has_many :ad_items has_many :ads, :through => :ad_items has_many :items, :through => :ads has_many :orders validates :email, presence: true validates_uniqueness_of :email, case_sensitive: false validates :password, :length => {:within=>6..100}, :presence => true, unless: :oauth validates :username, presence: true validates_uniqueness_of :username, case_sensitive: false validates :name, presence: true include FormatPrice def recharge(amount) if format_f(self.wallet).to_f.round(2) < 10000.00 recharge_amount = format_f(self.wallet).to_f.round(2) + amount.to_f.round(2) self.update_attribute(:wallet, BigDecimal.new("#{recharge_amount}")) return true else return false end end def new_purchase?(adID) ad = Ad.find_by(:id=>adID) self.orders.find_by(:ad_item_id=>ad.ad_item_id) ? false : true end def can_afford?(price) format_f(self.wallet).to_f.round(2) >= price.to_f.round(2) end def adjust_wallet(price) remaining = format_f(self.wallet).to_f.round(2) - price.to_f.round(2) self.update_attribute(:wallet, BigDecimal.new("#{remaining}")) end def create_new_order(adID) self.orders.create!(:ad_item_id => Ad.find_by(:id => adID).ad_item.id) end def self.find_or_create_by_oauth(user_info) self.where(:uid => user_info["id"]).first_or_create do |user| user.email = user.set_github_email(user_info) user.password = <PASSWORD> user.name = user.set_github_name(user_info) user.username = user_info["login"] user.oauth = true end end def set_github_email(info) info["email"].nil? ? "#{info["<EMAIL>"]}<EMAIL>" : info["email"] end def set_github_name(info) info["name"].nil? ? "#{info["login"]}" : info["name"] end private def downcase_email self.email = self.email.delete(" ").downcase end def generate_token loop do token = SecureRandom.hex return token unless User.exists?({token: token}) end end end
omikolaj/neos-fair-api
app/controllers/api/ads_controller.rb
class Api::AdsController < ApplicationController def pay user = User.find_by(:id=>params[:userID]) price = params[:price] adID = params[:adID] if user if !user.ads.find_by(:id=> adID) if user.new_purchase?(adID) if user.can_afford?(price) user.adjust_wallet(price) user.create_new_order(adID) Ad.set_to_sold(adID) render json: {success: "You have successfully purchased your item", status: 200}, status: 200 else render json: {fail: "You do not have enough money to purchase this item", status: 401}, status: 401 end else render json: {fail: "You have already purchased this item", status: 401}, status: 401 end else render json: {fail: "You cannot buy your own item", status: 401}, status: 401 end else render json: {fail: "Something went wrong...", status: 401}, status: 401 end end def index if authenticate_request! if user = User.find_by(:id => params[:user_id]) ads = user.ads.where('sold = ?', false).order('published ASC') render json: {ads: ads, status: 200}, status: 200 else ads = Ad.where("published = ? AND sold = ?", true, false) newAds = serialize_ads(ads) render json: {ads:newAds, status: 200}, status: 200 # Non-Authoritative Information end else render json: {fail: "Unauthorized Request", status: 401}, status: 401 end end def show if authenticate_request! if ad = Ad.find_by_id(params[:id]) render json: {description: ad.description, id: ad.id, published: ad.published, title: ad.title, type: ad.type, user: ad.user, item: ad.item, category: ad.category, ad_item: ad.ad_item, status: 200}, status: 200 else render json: {fail: "Ad was not found", status: 400}, status: 400 end else render json: {fail: "Unauthorized Request", status: 401}, status: 401 end end def create if authenticate_request! ad = Ad.new(ad_params) if ad.save render json: { :success => "You're add has been successfully posted", :id => ad.id, status: 201 }, status: 201 # Created else render json: { :fail => "Something went wrong.", :validations => ad.errors.full_messages, :status=> 400}, status: 400 # Bad Request end else render json: { :fail => "Unauthorized request", :validations => [], :status=> 401}, status: 401 end end def update if ad = User.find_by(:id => params[:user_id]).ads.find_by(:id=>params[:id]) ad.update_attributes!(:published => !ad.published) ad = {:id => ad.id, :ad_item_id => ad.ad_item_id, :description => ad.description, :title => ad.title, :published => ad.published} render json: {:success => "Successfully updated ad's status", ad: ad, status: 200}, status: 200 else render json: {:fail => 'User or ad were not found', :validations => ad.errors.full_messages, :status=>400}, status: 400 end end def destroy if ad = User.find_by(:id=>params[:user_id]).ads.find_by(:id=>params[:id]) removed_ad_id = ad.id ad.destroy render json: {:success => "Ad successfully deleted", :removed_ad_id => removed_ad_id, status: 200}, status: 200 else render json: {:fail => "Ad cannot be deleted", status: 400}, status: 400 end end private def ad_params params.require(:ad).permit(:id, :price, :auth, :title, :description, :user_id, :ad_item_attributes => [:price], :user_attributes => [:id], :item_attributes => [:title, :condition], :category_attributes => [:name]) end def serialize_ads(ads) newAds = [] ads.each do |ad| ad = {title: ad.title, description: ad.description, id: ad.id, published: ad.published, type: ad.type, ad_item: ad.ad_item, category: ad.category, item: ad.item, user: ad.user} newAds.push(ad) end newAds end end
omikolaj/neos-fair-api
app/models/category.rb
class Category < ApplicationRecord belongs_to :ad_item has_many :ads, :through => :ad_item def category_attributes=(category_attributes) binding.pry end end
omikolaj/neos-fair-api
app/models/ad_item.rb
<gh_stars>0 class AdItem < ApplicationRecord belongs_to :user has_one :ad has_one :order has_one :item has_one :category validates :price, presence: true end
omikolaj/neos-fair-api
app/models/order.rb
class Order < ApplicationRecord belongs_to :user belongs_to :ad_item has_one :ad, :through => :ad_item has_one :item, :through => :ad_item end
omikolaj/neos-fair-api
app/controllers/api/sessions_controller.rb
class Api::SessionsController < ActionController::Base require 'github_service' def login user = User.where("lower(username) = ?", params[:session][:user][:username].downcase).first if user && user.authenticate(params[:session][:user][:password]) auth_token = auth_token(user.id) render json: {token: auth_token, expiresIn: ENV["EXPIRES_IN"], userID: user.id, status: 200}, status: 200 else render json: {error: 'Invalid username / password', status: 401}, status: 401 end end def guest user = User.find_by(:id => 2) if user auth_token = auth_token(user.id) render json: {token: auth_token, expiresIn: ENV["EXPIRES_IN"], userID: user.id, status: 200}, status: 200 else render json: {error: 'User was not found', status: 401}, status: 401 end end def github github = GithubService.new user_hash = github.user_info(params[:code]) user = User.find_or_create_by_oauth(user_hash) if user.valid? && user.uid token = auth_token(user.uid) redirect_to "#{ENV["NEOS_FAIR_CLIENT_URL"]}/?token=#{token}&expiresIn=#{ENV["EXPIRES_IN"]}&id=#{user.id}" else error = "#{user_hash["message"]}. 500 Internal Server Error." redirect_to "#{ENV["NEOS_FAIR_CLIENT_URL"]}?error=#{error}" end end private def auth_token(id) JsonWebToken.encode({user_id: id}) end end
omikolaj/neos-fair-api
app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer attributes :id, :name, :email, :token, :username has_many :ads, serializer: UserAdsSerializer end
omikolaj/neos-fair-api
app/serializers/ad_ad_item_serializer.rb
class AdAdItemSerializer < ActiveModel::Serializer include FormatPrice attributes :price def price format(self.object.price) end end
omikolaj/neos-fair-api
db/migrate/20180430182921_create_ads.rb
class CreateAds < ActiveRecord::Migration[5.1] def change create_table :ads do |t| t.integer :ad_item_id t.string :type t.string :description t.string :title t.boolean :published, default: true t.boolean :sold, default: false t.timestamps end add_index :ads, [:type, :ad_item_id] end end
omikolaj/neos-fair-api
db/migrate/20180430191405_create_ad_items.rb
<filename>db/migrate/20180430191405_create_ad_items.rb class CreateAdItems < ActiveRecord::Migration[5.1] def change create_table :ad_items do |t| t.integer :user_id t.money :price t.datetime :post_date t.timestamps end end end
omikolaj/neos-fair-api
app/controllers/api/orders_controller.rb
class Api::OrdersController < ApplicationController include FormatPrice def index if user = User.find_by(:id=>params[:user_id]) orders = retrieve_orders_hash(user) render json: {orders: orders, status: 200}, status: 200 else render json: {error: "No user found to retrieve the orders", status: 400}, status: 400 end end private def retrieve_orders_hash(user) userOrdersArr = [] user.orders.each_with_index do |order, index| orderItem = {title: order.item.title, condition: order.item.condition} userOrders = {"order" => {item: orderItem, price: format(order.item.ad_item.price)}} userOrdersArr.push(userOrders) end userOrdersArr end end
omikolaj/neos-fair-api
lib/github_service.rb
class GithubService def user_info(code) access_token = fetch_access_token(code) user_data = fetch_user_info(access_token) end private def fetch_access_token(code) resp = Faraday.post(ENV['GITHUB_ACCESS_TOKEN_URL']) do |req| req.params["client_id"] = ENV['GITHUB_ID'] req.params["client_secret"] = ENV['GITHUB_SECRET'] req.params["code"] = code req.headers["Accept"] = 'application/json' end JSON.parse(resp.body)["access_token"] end def fetch_user_info(access_token) resp = Faraday.get(ENV['GITHUB_USER_INFO_URL']) do |req| req.params["access_token"] = access_token end JSON.parse(resp.body) end end
omikolaj/neos-fair-api
app/models/draft.rb
class Draft < Ad end
omikolaj/neos-fair-api
db/schema.rb
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20180502212410) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "ad_items", force: :cascade do |t| t.integer "user_id" t.money "price", scale: 2 t.datetime "post_date" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "ads", force: :cascade do |t| t.integer "ad_item_id" t.string "type" t.string "description" t.string "title" t.boolean "published", default: true t.boolean "sold", default: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["type", "ad_item_id"], name: "index_ads_on_type_and_ad_item_id" end create_table "categories", force: :cascade do |t| t.string "name" t.integer "ad_item_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "items", force: :cascade do |t| t.integer "ad_item_id" t.string "title" t.string "condition" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "orders", force: :cascade do |t| t.integer "user_id" t.integer "ad_item_id" t.boolean "old" t.date "purchased_date" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "name" t.string "username" t.string "<PASSWORD>" t.string "email" t.boolean "oauth", default: false t.integer "uid", default: -1 t.money "wallet", scale: 2, default: "1000.0" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "token" t.index ["token"], name: "index_users_on_token" end end
omikolaj/neos-fair-api
app/serializers/ad_user_serializer.rb
class AdUserSerializer < ActiveModel::Serializer attributes :id, :name, :username, :email end
omikolaj/neos-fair-api
app/controllers/concerns/format_price.rb
<filename>app/controllers/concerns/format_price.rb module FormatPrice def format(price) "$%.2f" % price.truncate(2) end def format_f(price) "%.2f" % price.truncate(2) end end
cogniteev/logstash-input-intercom
lib/logstash/inputs/intercom.rb
# encoding: utf-8 require "logstash/inputs/base" require "logstash/namespace" require "logstash/timestamp" require "logstash/util" require "intercom" # This plugin was created as a way to ingest data from Intercom into Logstash. # # ==== Usage: # # Here is an example of setting up the plugin to fetch data from Intercom. # # [source,ruby] # ---------------------------------- # input { # intercom { # app_id => ":appId" # app_api_key => ":appApiKey" # sync_users => true # sync_events => true # flatten_excludes => [] # } # } # ---------------------------------- # class LogStash::Inputs::Intercom < LogStash::Inputs::Base config_name "intercom" # If undefined, Logstash will complain, even if codec is unused. default :codec, "plain" # Application ID config :app_id, :validate => :string # Application API Key config :app_api_key, :validate => :string # Set if we want to synchronize events config :sync_events, :validate => :boolean, :default => true #Set if we want to synchronize users config :sync_users, :validate => :boolean, :default => true # Set a list of keys to not flatten during export config :flatten_excludes, :validate => :array, :default => [] public def register configure_intercom_client end # def register def run(queue) sync_all(queue) end # def run def stop end private def configure_intercom_client Intercom.app_id = @app_id Intercom.app_api_key = @app_api_key end def sync_all(queue) if @sync_users or @sync_events begin get_users.each { |user| push_event queue, from_user(user) if @sync_users sync_events_for queue, user.id if @sync_events } rescue Intercom::IntercomError => error @logger.error? @logger.error("Failed to sync", :error => error.to_s) end end end def sync_events_for(queue, intercom_user_id) begin get_events(intercom_user_id).each { |event| push_event queue, from_event(event) } rescue Intercom::IntercomError => error @logger.error? @logger.error("Failed to sync events for user", :intercom_user_id => intercom_user_id, :error => error.to_s) end end def get_users Intercom::User.all end def get_events(intercom_user_id) Intercom::Event.find_all(:type => 'user', :intercom_user_id => intercom_user_id) end def from_user(intercom_user) hash = intercom_object_to_hash intercom_user, 'user' hash_to_logstash_event hash, intercom_user.created_at end def from_event(intercom_event) hash = intercom_object_to_hash intercom_event, 'event' hash_to_logstash_event hash, intercom_event.created_at end def hash_to_logstash_event(hash, timestamp) event = LogStash::Event.new LogStash::Util.stringify_symbols(hash) event.timestamp = LogStash::Timestamp.new timestamp event end def intercom_object_to_hash(intercom_object, type) # flatten object hash = flatten_hash intercom_object.to_hash # prefix all keys by the object type (avoid collision between fields names) hash = prefix_keys hash, "#{type}_" # adds identity hash['type'] = type hash['document_id'] = "#{type}_#{intercom_object.id}" hash end def prefix_keys(hash, prefix) hash.each_with_object({}) do |(k, v), h| if k.start_with? prefix h[k] = v else h["#{prefix}#{k}"] = v end end end def flatten_hash(hash) hash.each_with_object({}) do |(k, v), h| if v.respond_to? :to_hash and not @flatten_excludes.include? k flatten_hash(v.to_hash).map do |h_k, h_v| h["#{k}_#{h_k}"] = h_v end else h[k] = v end end end def push_event(queue, event) decorate(event) queue << event end end # class LogStash::Inputs::Intercom
cogniteev/logstash-input-intercom
spec/inputs/intercom_spec.rb
# encoding: utf-8 require "logstash/devutils/rspec/spec_helper" require "logstash/inputs/intercom" describe LogStash::Inputs::Intercom do # TODO: write tests ! end
darabiesvampire/acts_as_tenant
spec/acts_as_tenant/configuration_spec.rb
<reponame>darabiesvampire/acts_as_tenant require 'spec_helper' describe ActsAsTenant::Configuration do describe 'no configuration given' do before do ActsAsTenant.configure end it 'provides defaults' do expect(ActsAsTenant.configuration.require_tenant).not_to be_truthy end end describe 'with config block' do after do ActsAsTenant.configure end it 'stores config' do ActsAsTenant.configure do |config| config.require_tenant = true end expect(ActsAsTenant.configuration.require_tenant).to eq(true) end end end
darabiesvampire/acts_as_tenant
lib/acts_as_tenant/test_tenant_middleware.rb
<gh_stars>10-100 module ActsAsTenant class TestTenantMiddleware def initialize(app) @app = app end def call(env) previously_set_test_tenant = ActsAsTenant.test_tenant ActsAsTenant.test_tenant = nil @app.call(env) ensure ActsAsTenant.test_tenant = previously_set_test_tenant end end end
darabiesvampire/acts_as_tenant
spec/acts_as_tenant/model_extensions_spec.rb
require 'spec_helper' require 'active_record_models' describe ActsAsTenant do after { ActsAsTenant.current_tenant = nil } # Setting and getting describe 'Setting the current tenant' do before { ActsAsTenant.current_tenant = :foo } it { ActsAsTenant.current_tenant == :foo } end describe 'is_scoped_as_tenant should return the correct value when true' do it {expect(Project.respond_to?(:scoped_by_tenant?)).to eq(true)} end describe 'is_scoped_as_tenant should return the correct value when false' do it {expect(UnscopedModel.respond_to?(:scoped_by_tenant?)).to eq(false)} end describe 'tenant_id should be immutable, if already set' do before do @account = Account.create!(:name => 'foo') @project = @account.projects.create!(:name => 'bar') end it { expect {@project.account_id = @account.id + 1}.to raise_error(ActsAsTenant::Errors::TenantIsImmutable) } end describe 'setting tenant_id to the same value should not error' do before do @account = Account.create!(:name => 'foo') @project = @account.projects.create!(:name => 'bar') end it { expect {@project.account_id = @account.id}.not_to raise_error } end describe 'setting tenant_id to a string with same to_i value should not error' do before do @account = Account.create!(:name => 'foo') @project = @account.projects.create!(:name => 'bar') end it { expect {@project.account_id = @account.id.to_s}.not_to raise_error } end describe 'tenant_id should be mutable, if not already set' do before do @account = Account.create!(:name => 'foo') @project = Project.create!(:name => 'bar') end it { expect(@project.account_id).to be_nil } it { expect { @project.account = @account }.not_to raise_error } end describe 'tenant_id should auto populate after initialization' do before do @account = Account.create!(:name => 'foo') ActsAsTenant.current_tenant = @account end it {expect(Project.new.account_id).to eq(@account.id)} end describe 'Handles custom foreign_key on tenant model' do before do @account = Account.create!(:name => 'foo') ActsAsTenant.current_tenant = @account @custom_foreign_key_task = CustomForeignKeyTask.create!(:name => 'foo') end it { expect(@custom_foreign_key_task.account).to eq(@account) } end describe 'Handles custom primary_key on tenant model' do before do @account = Account.create!(:name => 'foo') CustomPrimaryKeyTask.create!(name: 'bar') ActsAsTenant.current_tenant = @account @custom_primary_key_task = CustomPrimaryKeyTask.create! end it { expect(@custom_primary_key_task.account).to eq(@account) } it { expect(CustomPrimaryKeyTask.count).to eq(1) } end # Scoping models describe 'Project.all should be scoped to the current tenant if set' do before do @account1 = Account.create!(:name => 'foo') @account2 = Account.create!(:name => 'bar') @project1 = @account1.projects.create!(:name => 'foobar') @project2 = @account2.projects.create!(:name => 'baz') ActsAsTenant.current_tenant= @account1 @projects = Project.all end it { expect(@projects.length).to eq(1) } it { expect(@projects).to eq([@project1]) } end describe 'Project.unscoped.all should return the unscoped value' do before do @account1 = Account.create!(:name => 'foo') @account2 = Account.create!(:name => 'bar') @project1 = @account1.projects.create!(:name => 'foobar') @project2 = @account2.projects.create!(:name => 'baz') ActsAsTenant.current_tenant= @account1 @projects = Project.unscoped end it { expect(@projects.count).to eq(2) } end describe 'Querying the tenant from a scoped model without a tenant set' do before do @project = Project.create!(:name => 'bar') end it { @project.account } end describe 'Querying the tenant from a scoped model with a tenant set' do before do @account = Account.create!(:name => 'foo') @project = @account.projects.create!(:name => 'foobar') ActsAsTenant.current_tenant= @account1 end it { @project.account } end describe 'A tenant model with global records' do before do @account = Account.create!(:name => 'foo') @project1 = GlobalProject.create!(:name => 'foobar global') @project2 = GlobalProject.create!(:name => 'unaccessible project', :account => Account.create!) ActsAsTenant.current_tenant = @account @project3 = GlobalProject.create!(:name => 'foobar') end it 'should return two projects' do expect(GlobalProject.all.count).to eq(2) end it 'should validate the project name against the global records too' do expect(GlobalProject.new(:name => 'foobar').valid?).to be(false) expect(GlobalProject.new(:name => 'foobar new').valid?).to be(true) expect(GlobalProject.new(:name => 'foobar global').valid?).to be(false) expect(@project1.valid?).to be(true) end it 'should add the model to ActsAsTenant.models_with_global_records' do expect(ActsAsTenant.models_with_global_records.include?(GlobalProject)).to be(true) expect(ActsAsTenant.models_with_global_records.include?(Project)).to be(false) end end # Associations describe 'Associations should be correctly scoped by current tenant' do before do @account = Account.create!(:name => 'foo') @project = Project.create!(:name => 'foobar', :account => @account ) # the next line should normally be (nearly) impossible: a task assigned to a tenant project, # but the task has no tenant assigned @task1 = Task.create!(:name => 'no_tenant', :project => @project) ActsAsTenant.current_tenant = @account @task2 = @project.tasks.create!(:name => 'baz') @project.reload end it 'should correctly set the tenant on the task created with current_tenant set' do expect(@task2.account).to eq(@account) end it 'should filter out the non-tenant task from the project' do expect(@project.tasks.length).to eq(1) end end describe 'Associations can only be made with in-scope objects' do before do @account = Account.create!(:name => 'foo') @project1 = Project.create!(:name => 'inaccessible_project', :account => Account.create!) ActsAsTenant.current_tenant = @account @project2 = Project.create!(:name => 'accessible_project') @task = @project2.tasks.create!(:name => 'bar') end it { expect(@task.update_attributes(:project_id => @project1.id)).to eq(false) } end describe "Create and save an AaT-enabled child without it having a parent" do before do @account = Account.create!(:name => 'baz') ActsAsTenant.current_tenant = @account end it { expect(Task.create(:name => 'bar').valid?).to eq(true) } end describe "It should be possible to use aliased associations" do it { expect(AliasedTask.create(:name => 'foo', :project_alias => @project2).valid?).to eq(true) } end describe "It should be possible to use associations with foreign_key from polymorphic" do context 'tenanted objects have a polymorphic association' do before do @account = Account.create!(name: 'foo') ActsAsTenant.current_tenant = @account @project = Project.create!(name: 'project', account: @account) @comment = Comment.new commentable: @project, account: @account end it { expect(@comment.save!).to eq(true) } end context 'tenant is polymorphic' do before do @account = Account.create!(name: 'foo') @project = Project.create!(name: 'polymorphic project') ActsAsTenant.current_tenant = @project @comment = PolymorphicTenantComment.new(account: @account) end it 'populates commentable_type with the current tenant' do expect(@comment.polymorphic_tenant_commentable_id).to eql(@project.id) expect(@comment.polymorphic_tenant_commentable_type).to eql(@project.class.to_s) end context 'with another type of tenant, same id' do before do @comment.save! @article = Article.create!(id: @project.id, title: 'article title') @comment_on_article = @article.polymorphic_tenant_comments.create! end it 'correctly scopes to the current tenant type' do expect(@comment_on_article).to be_persisted expect(@comment).to be_persisted expect(PolymorphicTenantComment.count).to eql(1) expect(PolymorphicTenantComment.all.first.attributes).to eql(@comment.attributes) end end end end # Additional default_scopes describe 'When dealing with a user defined default_scope' do before do @account = Account.create!(:name => 'foo') @project1 = Project.create!(:name => 'inaccessible') @task1 = Task.create!(:name => 'no_tenant', :project => @project1) ActsAsTenant.current_tenant = @account @project2 = Project.create!(:name => 'accessible') @task2 = @project2.tasks.create!(:name => 'bar') @task3 = @project2.tasks.create!(:name => 'baz') @task4 = @project2.tasks.create!(:name => 'foo') @task5 = @project2.tasks.create!(:name => 'foobar', :completed => true ) @tasks= Task.all end it 'should apply both the tenant scope and the user defined default_scope, including :order' do expect(@tasks.length).to eq(3) expect(@tasks).to eq([@task2, @task3, @task4]) end end # Validates_uniqueness describe 'When using validates_uniqueness_to_tenant in a aat model' do before do account = Account.create!(:name => 'foo') ActsAsTenant.current_tenant = account Project.create!(:name => 'existing_name') end it 'should not be possible to create a duplicate within the same tenant' do expect(Project.create(:name => 'existing_name').valid?).to eq(false) end it 'should be possible to create a duplicate outside the tenant scope' do account = Account.create!(:name => 'baz') ActsAsTenant.current_tenant = account expect(Project.create(:name => 'bar').valid?).to eq(true) end end describe 'Handles user defined scopes' do before do UniqueTask.create!(:name => 'foo', :user_defined_scope => 'unique_scope') end it { expect(UniqueTask.create(:name => 'foo', :user_defined_scope => 'another_scope')).to be_valid } it { expect(UniqueTask.create(:name => 'foo', :user_defined_scope => 'unique_scope')).not_to be_valid } end describe 'When using validates_uniqueness_of in a NON-aat model' do before do UnscopedModel.create!(:name => 'foo') end it 'should not be possible to create duplicates' do expect(UnscopedModel.create(:name => 'foo').valid?).to eq(false) end end # ::with_tenant describe "::with_tenant" do it "should set current_tenant to the specified tenant inside the block" do @account = Account.create!(:name => 'baz') ActsAsTenant.with_tenant(@account) do expect(ActsAsTenant.current_tenant).to eq(@account) end end it "should reset current_tenant to the previous tenant once exiting the block" do @account1 = Account.create!(:name => 'foo') @account2 = Account.create!(:name => 'bar') ActsAsTenant.current_tenant = @account1 ActsAsTenant.with_tenant @account2 do end expect(ActsAsTenant.current_tenant).to eq(@account1) end it "should return the value of the block" do @account1 = Account.create!(:name => 'foo') @account2 = Account.create!(:name => 'bar') ActsAsTenant.current_tenant = @account1 value = ActsAsTenant.with_tenant @account2 do "something" end expect(value).to eq "something" end it "should raise an error when no block is provided" do expect { ActsAsTenant.with_tenant(nil) }.to raise_error(ArgumentError, /block required/) end end describe "::without_tenant" do it "should set current_tenant to nil inside the block" do ActsAsTenant.without_tenant do expect(ActsAsTenant.current_tenant).to be_nil end end it "should set current_tenant to nil even if default_tenant is set" do begin old_default_tenant = ActsAsTenant.default_tenant ActsAsTenant.default_tenant = Account.create!(name: 'foo') ActsAsTenant.without_tenant do expect(ActsAsTenant.current_tenant).to be_nil end ensure ActsAsTenant.default_tenant = old_default_tenant end end it "should reset current_tenant to the previous tenant once exiting the block" do @account1 = Account.create!(:name => 'foo') ActsAsTenant.current_tenant = @account1 ActsAsTenant.without_tenant do end expect(ActsAsTenant.current_tenant).to eq(@account1) end it "should return the value of the block" do value = ActsAsTenant.without_tenant do "something" end expect(value).to eq "something" end it "should raise an error when no block is provided" do expect { ActsAsTenant.without_tenant }.to raise_error(ArgumentError, /block required/) end end # Tenant required context "tenant required" do before do @account1 = Account.create!(:name => 'foo') @project1 = @account1.projects.create!(:name => 'foobar') allow(ActsAsTenant.configuration).to receive_messages(require_tenant: true) end describe "raises exception if no tenant specified" do it "should raise an error when no tenant is provided" do expect { Project.all }.to raise_error(ActsAsTenant::Errors::NoTenantSet) end end describe "does not raise exception when run in unscoped mode" do it "should not raise an error when no tenant is provided" do expect do ActsAsTenant.without_tenant { Project.all } end.to_not raise_error end end end context "no tenant required" do describe "does not raise exception if no tenant specified" do before do @account1 = Account.create!(:name => 'foo') @project1 = @account1.projects.create!(:name => 'foobar') end it "should not raise an error when no tenant is provided" do expect { Project.all }.to_not raise_error end end end describe "ActsAsTenant.default_tenant=" do before(:each) do @account = Account.create! end after(:each) do ActsAsTenant.default_tenant = nil end it "provides current_tenant" do ActsAsTenant.default_tenant = @account expect(ActsAsTenant.current_tenant).to eq(@account) end it "can be overridden by assignment" do ActsAsTenant.default_tenant = @account @account2 = Account.create! ActsAsTenant.current_tenant = @account2 expect(ActsAsTenant.current_tenant).not_to eq(@account) end it "can be overridden by with_tenant" do ActsAsTenant.default_tenant = @account @account2 = Account.create! ActsAsTenant.with_tenant @account2 do expect(ActsAsTenant.current_tenant).to eq(@account2) end expect(ActsAsTenant.current_tenant).to eq(@account) end it "doesn't override existing current_tenant" do @account2 = Account.create! ActsAsTenant.current_tenant = @account2 ActsAsTenant.default_tenant = @account expect(ActsAsTenant.current_tenant).to eq(@account2) end it "survives request resets" do ActsAsTenant.default_tenant = @account RequestStore.clear! expect(ActsAsTenant.current_tenant).to eq(@account) end end end
darabiesvampire/acts_as_tenant
rails/init.rb
ActiveRecord::Base.send(:include, ActsAsTenant::ModelExtensions) ActionController::Base.extend ActsAsTenant::ControllerExtensions
darabiesvampire/acts_as_tenant
lib/acts_as_tenant.rb
require "request_store" #$LOAD_PATH.unshift(File.dirname(__FILE__)) require "acts_as_tenant/version" require "acts_as_tenant/errors" require "acts_as_tenant/configuration" require "acts_as_tenant/controller_extensions" require "acts_as_tenant/model_extensions" #$LOAD_PATH.shift ActiveSupport.on_load(:active_record) do |base| base.include ActsAsTenant::ModelExtensions end ActiveSupport.on_load(:action_controller) do |base| base.extend ActsAsTenant::ControllerExtensions end module ActsAsTenant end
darabiesvampire/acts_as_tenant
spec/spec_helper.rb
<reponame>darabiesvampire/acts_as_tenant $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require "active_record_helper" require 'rspec/rails' require 'acts_as_tenant' RSpec.configure do |config| config.after(:each) do ActsAsTenant.current_tenant = nil end config.infer_base_class_for_anonymous_controllers = true end # Setup a test app module Rollcall class Application < Rails::Application; end end Rollcall::Application.config.secret_token = '1234567890123456789012345678901234567890' Rollcall::Application.config.secret_key_base = '1234567890123456789012345678901234567890'
darabiesvampire/acts_as_tenant
lib/acts_as_tenant/configuration.rb
<reponame>darabiesvampire/acts_as_tenant<gh_stars>0 module ActsAsTenant @@configuration = nil def self.configure @@configuration = Configuration.new if block_given? yield configuration end configuration end def self.configuration @@configuration || configure end class Configuration attr_writer :require_tenant, :pkey def require_tenant @require_tenant ||= false end def pkey @pkey ||= :id end end end
klimkin/fig
lib/fig/command/option_error.rb
<gh_stars>10-100 # coding: utf-8 require 'fig/user_input_error' module Fig; end class Fig::Command; end # Bad command-line option. class Fig::Command::OptionError < Fig::UserInputError end
klimkin/fig
lib/fig/command/action/role/publish.rb
<reponame>klimkin/fig<filename>lib/fig/command/action/role/publish.rb # coding: utf-8 require 'fig/command/package_loader' require 'fig/package' require 'fig/statement/configuration' require 'fig/user_input_error' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::Publish def descriptor_requirement() return :required end def allow_both_descriptor_and_file?() # Actually, publishing requires a descriptor and another source of the base # package. return true end def cares_about_asset_options?() return true end def modifies_repository?() return true end def load_base_package?() return true end def base_package_can_come_from_descriptor?() return false end def register_base_package?() return false end def apply_config?() return true end def apply_base_config?() return nil # don't care end # Is this a publish action? def publish?() return true end def configure(options) @descriptor = options.descriptor @environment_statements = options.environment_statements @asset_statements = options.asset_statements @force = options.force? return end def publish_preflight() if @descriptor.name.nil? || @descriptor.version.nil? raise Fig::UserInputError.new( 'Please specify a package name and a version name.' ) end if @descriptor.name == '_meta' raise Fig::UserInputError.new( %q<Due to implementation issues, cannot create a package named "_meta".> ) end if not @environment_statements.empty? derive_publish_statements_from_environment_statements elsif not @asset_statements.empty? raise Fig::UserInputError.new( '--resource/--archive options were specified, but no --set/--append option was given. Will not publish.' ) else if not @execution_context.base_package.statements.empty? @publish_statements = @execution_context.base_package.statements else raise Fig::UserInputError.new('Nothing to publish.') end end return end def derive_publish_statements_from_environment_statements if @execution_context.package_load_path_description message = 'Cannot publish based upon both a package definition file (' message << @execution_context.package_load_path_description message << ') and --set/--append options.' if @execution_context.package_source_description == Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE || @execution_context.package_source_description == Fig::Command::PackageLoader::DEFAULT_APPLICATION_FILE || message << "\n\n" message << 'You can avoid loading ' message << @execution_context.package_source_description message << ' by using the --no-file option.' end raise Fig::UserInputError.new(message) end @publish_statements = @asset_statements + [ Fig::Statement::Configuration.new( nil, nil, Fig::Package::DEFAULT_CONFIG, @environment_statements ) ] return end end
klimkin/fig
lib/fig/environment_variables/case_insensitive.rb
<filename>lib/fig/environment_variables/case_insensitive.rb<gh_stars>10-100 # coding: utf-8 require 'fig/environment_variables' module Fig; end; module Fig::EnvironmentVariables; end # Manager of a set of environment variables where the variable names are # case-insensitive, e.g. on MS Windows. class Fig::EnvironmentVariables::CaseInsensitive include Fig::EnvironmentVariables def [](key) return @variables[key_to_store_under(key)] end def []=(key, new_value) @variables[key_to_store_under(key)] = new_value return end def prepend_variable(key, new_value) existing_key = key_to_store_under(key) if existing_key assign_value_to_existing_key(existing_key, new_value) else @variables[key] = new_value end return end private def assign_value_to_existing_key(existing_key, new_value) current_value = @variables[existing_key] if current_value @variables[existing_key] = new_value + File::PATH_SEPARATOR + current_value else @variables[existing_key] = new_value end return end def key_to_store_under(key) return @variables.keys.detect(lambda {key}) {|stored| stored.downcase == key.downcase} end end
klimkin/fig
lib/fig/command/action/role/list_dependencies_in_a_tree.rb
# coding: utf-8 require 'fig/command/action' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListDependenciesInATree def execute() walk_dependency_tree( @execution_context.base_package, base_display_config_names() ) do |package, config_name, depth| print ' ' * (depth * 4) puts package.to_s_with_config(config_name) end return Fig::Command::Action::EXIT_SUCCESS end end
klimkin/fig
lib/fig/not_yet_parsed_package.rb
<reponame>klimkin/fig<filename>lib/fig/not_yet_parsed_package.rb # coding: utf-8 module Fig; end # Metadata about a package definition file that hasn't been read yet. class Fig::NotYetParsedPackage attr_accessor :descriptor attr_accessor :working_directory attr_accessor :include_file_base_directory attr_accessor :source_description attr_accessor :unparsed_text def extended_source_description() if source_description if source_description.include? "(#{working_directory})" return source_description end extended = source_description if working_directory != '.' extended << " (#{working_directory})" end return extended end return working_directory end end
klimkin/fig
lib/fig/working_directory_maintainer.rb
<gh_stars>0 # coding: utf-8 require 'set' require 'fig/logging' require 'fig/logging/colorizable' require 'fig/package_descriptor' require 'fig/repository_error' require 'fig/working_directory_metadata' module Fig; end # Copies files from the project directories in FIG_HOME to the user's working # directory. It keeps track of which files have already been copied, and which # package/versions they came from, and deletes files as necessary to ensure # that we never have files from two different versions of the same package in # the user's working directory. class Fig::WorkingDirectoryMaintainer def initialize(base_dir) @base_dir = base_dir @package_metadata_by_name = {} @local_fig_data_directory = File.join(@base_dir, '.fig') @metadata_file = File.join(@local_fig_data_directory, 'retrieve') if File.exist?(@metadata_file) load_metadata() end end def switch_to_package_version(name, version) @package_meta = @package_metadata_by_name[name] if @package_meta && @package_meta.current_version != version clean_up_package_files() @package_meta = nil end if not @package_meta @package_meta = reset_package_metadata_with_version(name, version) end return end SYMLOOP_MAX = 20 # https://duckduckgo.com/html?q=posix_symloop_max def retrieve(source, relpath) resolved_source = source # When recursing through a retrieve, if we encounter a symlink that doesn't # point to a directory, we copy it as a symlink. However, if the retrieve # path itself is a symlink, we copy the target of the symlink, not the # symlink itself. if File.exist? resolved_source # Ruby v1.8 does not have File.realdirpath(). traversal_count = 0 while File.symlink? resolved_source resolved_source = File.join( File.dirname(resolved_source), File.readlink(resolved_source) ) traversal_count += 1 if traversal_count > SYMLOOP_MAX raise Fig::RepositoryError.new( %Q<Could not resolve symlink "#{source}"; symlink chain exceeded #{SYMLOOP_MAX}.> ) end end end copy(resolved_source, relpath) return end def find_package_version_for_file(file) @package_metadata_by_name.each do |name, package_meta| package_meta.each_file do |target| if File.identical? file, target return formatted_meta(package_meta) end end end return nil end def prepare_for_shutdown(purged_unused_packages) if purged_unused_packages clean_up_unused_packages() end save_metadata() return end private def load_metadata() File.open(@metadata_file).each_line do |line| line.strip!() if line =~ /^(.+)=(.+)\/(.+)$/ target = $1 package_name = $2 package_version = $3 package_meta = @package_metadata_by_name[package_name] if package_meta if package_meta.current_version != package_version raise "Version mismatch for #{package_meta.package_name} in #{@metadata_file}." end else package_meta = reset_package_metadata_with_version(package_name, package_version) end package_meta.add_file(target) else raise "parse error in #{@metadata_file}: #{line}" end end return end def reset_package_metadata_with_version(name, version) metadata = @package_metadata_by_name[name] if not metadata metadata = Fig::WorkingDirectoryMetadata.new(name, version) @package_metadata_by_name[name] = metadata else metadata.reset_with_version(version) end return metadata end def copy(source, relpath) target = File.join(@base_dir, relpath) if source_and_target_are_same?(source, target) # Actually happened: Retrieve and "set" both set to ".". Victim's current # directory included a ".git" directory. Update was done and then later, # an update with different dependencies. Fig proceeded to delete all # files that had previously existed in the current directory, including # out of the git repo. Whoops. Fig::Logging.warn %Q<Skipping copying "#{source}" to itself.> return end if File.directory?(source) copy_directory(source, relpath, target) else copy_file(source, relpath, target) end return end def source_and_target_are_same?(source, target) # Ruby 1.8 doesn't have File.absolute_path(), so we have to fall back to # .expand_path(). source_absolute = File.expand_path(source) target_absolute = File.expand_path(target) return source_absolute == target_absolute end def copy_directory(source, relpath, target) FileUtils.mkdir_p(target) Fig::Logging.debug "Copying directory #{source} to #{target}." Dir.foreach(source) do |child| if child != '.' and child != '..' source_file = File.join(source, child) target_file = File.join(relpath, child) copy(source_file, target_file) end end return end def copy_file(source, relpath, target) if should_copy_file?(source, target) if Fig::Logging.debug? Fig::Logging.debug \ "Copying file from #{source} to #{target}." else Fig::Logging.info( Fig::Logging::Colorizable.new( "+ [#{formatted_meta()}] #{relpath}", :green, nil ) ) end FileUtils.mkdir_p(File.dirname(target)) # If the source is a dangling symlink, then there's no time, etc. to # preserve. preserve = File.exist?(source) && ! File.symlink?(source) FileUtils.copy_entry( source, target, preserve, false, :remove_destination ) end if @package_meta @package_meta.add_file(relpath) @package_meta.mark_as_retrieved() end return end def should_copy_file?(source, target) if File.symlink?(target) if File.symlink?(source) && File.readlink(source) == File.readlink(target) return false end FileUtils.rm(target) return true end return true if ! File.exist?(target) return File.mtime(source) > File.mtime(target) end def clean_up_package_files(package_meta = @package_meta) package_meta.each_file do |relpath| Fig::Logging.info( Fig::Logging::Colorizable.new( "- [#{formatted_meta(package_meta)}] #{relpath}", :magenta, nil ) ) FileUtils.rm_f(File.join(@base_dir, relpath)) end return end def clean_up_unused_packages() @package_metadata_by_name.each_value do |metadata| if not metadata.retrieved? clean_up_package_files(metadata) metadata.reset_with_version(nil) end end return end def save_metadata() FileUtils.mkdir_p(@local_fig_data_directory) File.open(@metadata_file, 'w') do |file| @package_metadata_by_name.each do |name, package_meta| package_meta.each_file do |target| file << target << '=' << formatted_meta(package_meta) << "\n" end end end return end def formatted_meta(package_meta = @package_meta) return Fig::PackageDescriptor.format( package_meta.package_name, package_meta.current_version, nil ) end end
klimkin/fig
lib/fig/config_file_error.rb
# coding: utf-8 require 'fig/user_input_error' module Fig # Could not determine some kind of information from a configuration file, # whether .figrc, log4r, package.fig, etc. class ConfigFileError < UserInputError attr_reader :file def initialize(message, file) super(message) @file = file return end end end
klimkin/fig
spec/command/grammar_environment_variable_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/grammar_spec_helper') describe 'Fig' do ILLEGAL_CHARACTERS_IN_V0_PATH_STATEMENTS = %w< ; : < > | > describe %q<uses the correct grammar version in the package definition created for publishing> do before(:each) do clean_up_test_environment set_up_test_environment end ENVIRONMENT_VARIABLE_PUBLISHED_QUOTING_EXAMPLES = { [%q<VARIABLE='foo\'bar'>, 1] => [ %q<VARIABLE=foo\'bar>, %q<VARIABLE="foo'bar">, %q<VARIABLE='foo\'bar'> ], [%q<VARIABLE='foobar\''>, 1] => [ %q<VARIABLE=foobar\'>, %q<VARIABLE="foobar'">, %q<VARIABLE='foobar\''> ], [%q<VARIABLE='foobar"'>, 1] => [ %q<VARIABLE=foobar\">, %q<VARIABLE="foobar\"">, %q<VARIABLE='foobar"'> ], [%q<VARIABLE='foo"bar'>, 1] => [ %q<VARIABLE=foo\"bar>, %q<VARIABLE="foo\"bar">, %q<VARIABLE='foo"bar'> ], [%q<VARIABLE='foo#bar'>, 1] => [ %q<VARIABLE="foo#bar">, %q<VARIABLE='foo#bar'> ], [%q<VARIABLE=foo@bar>, 0] => [ %q<VARIABLE=foo@bar>, %q<VARIABLE="foo@bar">, ], [%q<VARIABLE=foo\@bar>, 0] => [ %q<VARIABLE=foo\@bar>, %q<VARIABLE="foo\@bar">, %q<VARIABLE='foo@bar'> ], [%q<VARIABLE=foo\\\\bar>, 0] => [ %q<VARIABLE=foo\\\\bar>, %q<VARIABLE="foo\\\\bar">, %q<VARIABLE='foo\\\\bar'> ] } shared_examples_for 'environment variable option' do |assignment_type| it 'with simple value' do fig( [%w<--publish foo/1.2.3>, "--#{assignment_type}", 'VARIABLE=VALUE'], :fork => false ) out, * = check_published_grammar_version(0) out.should =~ / \b #{assignment_type} \s+ VARIABLE=VALUE \b /x end { 'unquoted' => %q<>, 'double quoted' => %q<">, 'single quoted' => %q<'> }.each do |name, quote| it "with #{name} whitespace" do fig( [ %w<--publish foo/1.2.3>, "--#{assignment_type}", "VARIABLE=#{quote}foo bar#{quote}" ], :fork => false ) out, * = check_published_grammar_version(1) out.should =~ / \b #{assignment_type} \s+ VARIABLE='foo[ ]bar' /x end end ENVIRONMENT_VARIABLE_PUBLISHED_QUOTING_EXAMPLES.each do |expected, inputs| result, version = *expected inputs.each do |value| it "with «#{value}»" do fig( [ %w<--publish foo/1.2.3>, "--#{assignment_type}", value ], :fork => false ) out, * = check_published_grammar_version(version) out.should =~ / \b #{assignment_type} \s+ #{Regexp.quote result} /x end end end it "with «VARIABLE=foo#bar»" do fig( [ %w<--publish foo/1.2.3>, "--#{assignment_type}", %q<VARIABLE=foo#bar> ], :fork => false ) out, * = check_published_grammar_version(1) out.should =~ / \b #{assignment_type} \s+ VARIABLE='foo[#]bar' /x end { 'unquoted' => %q<>, 'double quoted' => %q<"> }.each do |name, quote| it "with #{name}, unescaped at sign, but forced to v1 grammar" do fig( [ %w<--publish foo/1.2.3>, "--#{assignment_type}", 'VARIABLE_WITH_WHITESPACE_TO_FORCE=v1 grammar', "--#{assignment_type}", "VARIABLE=#{quote}foo@bar#{quote}" ], :fork => false ) out, * = check_published_grammar_version(1) out.should =~ / \b #{assignment_type} \s+ VARIABLE="foo@bar" /x end end end describe 'for --set' do it_behaves_like 'environment variable option', 'set' ILLEGAL_CHARACTERS_IN_V0_PATH_STATEMENTS.each do |character| it "for «#{character}»" do fig( [ %w<--publish foo/1.2.3 --set>, "VARIABLE=#{character}" ], :fork => false ) out, * = check_published_grammar_version(0) out.should =~ / \b set \s+ VARIABLE=#{Regexp.quote character} [^'] /x end end end describe 'for --add' do it_behaves_like 'environment variable option', 'add' ILLEGAL_CHARACTERS_IN_V0_PATH_STATEMENTS.each do |character| it "for «VARIABLE=#{character}»" do fig( [ %w<--publish foo/1.2.3 --append>, "VARIABLE=#{character}" ], :fork => false ) out, * = check_published_grammar_version(1) out.should =~ / \b add \s+ VARIABLE='#{Regexp.quote character}' /x end end end shared_examples_for 'environment variable statement' do |assignment_type| it 'with simple value' do out, * = check_published_grammar_version(0, <<-"END_INPUT") grammar v1 config default #{assignment_type} VARIABLE=VALUE end END_INPUT out.should =~ / \b #{assignment_type} \s+ VARIABLE=VALUE \b /x end { 'double quoted' => %q<">, 'single quoted' => %q<'> }.each do |name, quote| it "with #{name} whitespace" do out, * = check_published_grammar_version(1, <<-"END_INPUT") grammar v1 config default #{assignment_type} VARIABLE=#{quote}foo bar#{quote} end END_INPUT out.should =~ / \b #{assignment_type} \s+ VARIABLE='foo[ ]bar' /x end end ENVIRONMENT_VARIABLE_PUBLISHED_QUOTING_EXAMPLES.each do |expected, inputs| result, version = *expected inputs.each do |value| it "with «#{value}»" do out, * = check_published_grammar_version(version, <<-"END_INPUT") grammar v1 config default #{assignment_type} #{value} end END_INPUT out.should =~ / \b #{assignment_type} \s+ #{Regexp.quote result} /x end end end end describe 'for set statement in v1 grammar' do it_behaves_like 'environment variable statement', 'set' ILLEGAL_CHARACTERS_IN_V0_PATH_STATEMENTS.each do |character| it "for «#{character}»" do out, * = check_published_grammar_version(0, <<-"END_INPUT") grammar v1 config default set VARIABLE=#{character} end END_INPUT out.should =~ / \b set \s+ VARIABLE=#{Regexp.quote character} [^'] /x end end end describe 'for add statement in v1 grammar' do it_behaves_like 'environment variable statement', 'add' ILLEGAL_CHARACTERS_IN_V0_PATH_STATEMENTS.each do |character| it "for «#{character}»" do out, * = check_published_grammar_version(1, <<-"END_INPUT") grammar v1 config default add VARIABLE=#{character} end END_INPUT out.should =~ / \b add \s+ VARIABLE='#{Regexp.quote character}' /x end end end end describe %q<rejects path statements from v0 package definition files containing> do before(:each) do clean_up_test_environment set_up_test_environment end ILLEGAL_CHARACTERS_IN_V0_PATH_STATEMENTS.each do |character| it %Q<«#{character}»> do input = <<-END grammar v0 config default add VARIABLE=x#{character}x end END out, err, exit_code = fig [], input, :no_raise_on_error => true, :fork => false err.should =~ /value of path variable VARIABLE.*contains.*"#{Regexp.quote character}"/ out.should == '' exit_code.should_not == 0 end end it %Q<«'»> do input = <<-END grammar v0 config default add VARIABLE=x'x end END out, err, exit_code = fig [], input, :no_raise_on_error => true, :fork => false err.should =~ /value of VARIABLE.*contains.*single quote/ out.should == '' exit_code.should_not == 0 end it %Q<«"»> do input = <<-END grammar v0 config default add VARIABLE=x"x end END out, err, exit_code = fig [], input, :no_raise_on_error => true, :fork => false err.should =~ /value of VARIABLE.*contains.*double quote/ out.should == '' exit_code.should_not == 0 end end describe %q<rejects set statements from v0 package definition files containing> do before(:each) do clean_up_test_environment set_up_test_environment end it %Q<«'»> do input = <<-END grammar v0 config default set VARIABLE=x'x end END out, err, exit_code = fig [], input, :no_raise_on_error => true, :fork => false err.should =~ /value of VARIABLE.*contains.*single quote/ out.should == '' exit_code.should_not == 0 end it %Q<«"»> do input = <<-END grammar v0 config default set VARIABLE=x"x end END out, err, exit_code = fig [], input, :no_raise_on_error => true, :fork => false err.should =~ /value of VARIABLE.*contains.*double quote/ out.should == '' exit_code.should_not == 0 end end end # vim: set fileencoding=utf8 :
klimkin/fig
lib/fig/tokenized_string.rb
# coding: utf-8 module Fig; end class Fig::TokenizedString def initialize(segments, single_quoted, metacharacters) @segments = segments @single_quoted = single_quoted @metacharacters = metacharacters return end def single_quoted?() return @single_quoted end def can_be_single_quoted?() return true if single_quoted? return @segments.all? {|segment| segment.type.nil?} end def to_expanded_string(&block) return ( @segments.collect { |segment| segment.to_expanded_string(&block) } ).join '' end def to_escaped_string() return ( @segments.collect {|segment| segment.to_escaped_string} ).join '' end def to_single_quoted_string() return to_escaped_string if single_quoted? return ( @segments.collect {|segment| segment.to_single_quoted_string} ).join '' end def to_double_quotable_string() return to_escaped_string if ! single_quoted? return ( @segments.collect { |segment| segment.to_double_quotable_string @metacharacters } ).join '' end end
klimkin/fig
lib/fig/command/action/list_dependencies/yaml_all_configs.rb
<filename>lib/fig/command/action/list_dependencies/yaml_all_configs.rb # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/list_all_configs' require 'fig/command/action/role/list_as_yaml' require 'fig/command/action/role/list_dependencies_from_data_structure' require 'fig/command/action/role/list_from_data_structure' require 'fig/command/action/role/list_walking_dependency_tree' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListDependencies; end class Fig::Command::Action::ListDependencies::YAMLAllConfigs include Fig::Command::Action include Fig::Command::Action::Role::ListAllConfigs include Fig::Command::Action::Role::ListAsYAML include Fig::Command::Action::Role::ListDependenciesFromDataStructure include Fig::Command::Action::Role::ListFromDataStructure include Fig::Command::Action::Role::ListWalkingDependencyTree def options() return %w<--list-dependencies --yaml --list-all-configs> end def descriptor_requirement() return nil end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end def apply_base_config?() return nil # don't care end end
klimkin/fig
lib/fig/include_backtrace.rb
<filename>lib/fig/include_backtrace.rb # coding: utf-8 require 'fig/repository_error' module Fig; end # Stack of applied "include" statements. # # Keeps track of overrides and can produce package definition stack traces. # # Pushing and popping actually happens via instances being held/let go by # recursive method calls on RuntimeEnvironment. class Fig::IncludeBacktrace attr_reader :overrides def initialize(parent, descriptor) @parent = parent @descriptor = descriptor @overrides = {} end def add_override(statement) package_name = statement.package_name # Don't replace an existing override on the stack return if @parent && @parent.get_override(package_name) new_version = statement.version existing_version = @overrides[package_name] if existing_version && existing_version != new_version stacktrace = dump_to_string() raise Fig::RepositoryError.new( "Override #{package_name} version conflict (#{existing_version} vs #{new_version})#{statement.position_string}." + ( stacktrace.empty? ? '' : "\n#{stacktrace}" ) ) end @overrides[package_name] = new_version end # Returns a version. def get_override(package_name, default_version = nil) version = @overrides[package_name] return version if version return @parent.get_override(package_name, default_version) if @parent return default_version end # Prints a stack trace to the IO object. def dump(out) stack = [] collect(stack) i = 0 for descriptor in stack indent='' i.times { indent += ' ' } out.puts indent + descriptor.to_string(:use_default_config, :use_description) i += 1 end end protected def dump_to_string() string_handle = StringIO.new dump(string_handle) return string_handle.string end def collect(stack) if @parent @parent.collect(stack) end stack << @descriptor end end
klimkin/fig
lib/fig/url.rb
# coding: utf-8 require 'cgi' require 'uri' require 'fig/user_input_error' module Fig; end module Fig::URL # From https://www.rfc-editor.org/rfc/rfc1738.txt def self.is_url?(url) # We don't count single-letter "protocols" to allow for Windows drive # letters in paths. return !! ( url =~ %r< \A [a-z0-9+.-]{2,} : >ix ) end # Encodes components and joins with slashes. def self.append_path_components(base_url, components) url = base_url.sub(%r< / \z >x, '') encoded = components.map { |component| CGI.escape component } return [url, encoded].flatten.join('/') end # URI.parse() doesn't like space characters, unlike most of the world. def self.parse(url) begin return URI.parse(url.gsub ' ', '+') rescue URI::InvalidURIError => error raise Fig::UserInputError.new \ %Q<Cannot parse URL "#{url}": #{error.message}> end end end
klimkin/fig
lib/fig/protocol/netrc_enabled.rb
# coding: utf-8 require 'highline' require 'net/netrc' require 'fig/logging' require 'fig/user_input_error' module Fig; end module Fig::Protocol; end # Login information acquisition via .netrc. module Fig::Protocol::NetRCEnabled private NetRCEntry = Struct.new :username, :password def initialize_netrc() @netrc_entries_by_host = {} return end def get_authentication_for(host, prompt_if_missing) if @netrc_entries_by_host.include? host return @netrc_entries_by_host[host] end entry = nil if prompt_if_missing entry = get_authentication_from_environment end if ! entry begin login_data = Net::Netrc.locate host if login_data entry = NetRCEntry.new login_data.login, login_data.password elsif prompt_if_missing entry = get_authentication_from_user(host) end rescue SecurityError => error raise Fig::UserInputError.new error.message end end @netrc_entries_by_host[host] = entry return entry end def get_authentication_from_environment() username = ENV['FIG_USERNAME'] password = ENV['<PASSWORD>'] if username.nil? && password.nil? return nil end if ! username.nil? && ! password.nil? return NetRCEntry.new username, password end if password.nil? raise Fig::UserInputError.new \ 'FIG_USERNAME is set but FIG_PASSWORD is not.' end raise Fig::UserInputError.new 'FIG_PASSWORD is set but FIG_USERNAME is not.' end def get_authentication_from_user(host) # This defaults to true, but Net::SSH::Prompt turns it off. Unfortunately, # this causes HighLine to barf when there's no input on STDIN, e.g. when # running on a continuous integration server. HighLine.track_eof = true begin username = HighLine.new.ask("Username for #{host}: ") { |q| q.echo = true } password = HighLine.new.ask("Password for #{username}@#{host}: ") { |q| q.echo = false } return NetRCEntry.new username, password rescue EOFError => error Fig::Logging.debug(error) return nil end end end
klimkin/fig
lib/fig/application_configuration.rb
<filename>lib/fig/application_configuration.rb # coding: utf-8 module Fig; end # Configuration for the Fig program, as opposed to a config in a package. class Fig::ApplicationConfiguration attr_accessor :base_whitelisted_url attr_accessor :remote_repository_url def initialize() @data = [] clear_cached_data end def ensure_url_whitelist_initialized() return if not @whitelist.nil? whitelist = self['url whitelist'] if whitelist.nil? @whitelist = [] elsif @base_whitelisted_url @whitelist = [@base_whitelisted_url, whitelist].flatten elsif whitelist.is_a? Array @whitelist = whitelist else @whitelist = [whitelist] end end def [](key) @data.each do |dataset| if dataset.has_key?(key) return dataset[key] end end return nil end def push_dataset(dataset) @data.push(dataset) end # After push_dataset, call clear_cached, and lazy initialize as far as the # list of things to exclude def clear_cached_data() @whitelist = nil end def url_access_allowed?(url) ensure_url_whitelist_initialized return true if @whitelist.empty? @whitelist.each do |allowed_url| return true if url.match(/\A#{Regexp.quote(allowed_url)}\b/) end return false end end
klimkin/fig
lib/fig/protocol/ftp.rb
# coding: utf-8 require 'net/ftp' require 'fig/file_not_found_error' require 'fig/logging' require 'fig/network_error' require 'fig/protocol' require 'fig/protocol/netrc_enabled' require 'fig/url' module Fig; end module Fig::Protocol; end # File transfers via FTP class Fig::Protocol::FTP include Fig::Protocol include Fig::Protocol::NetRCEnabled def initialize(login) @login = login initialize_netrc end def download_list(uri) ftp = Net::FTP.new(uri.host) ftp_login(ftp, uri.host, :prompt_for_login) ftp.chdir(uri.path) dirs = ftp.nlst ftp.close download_ftp_list(uri, dirs) end # Determine whether we need to update something. Returns nil to indicate # "don't know". def path_up_to_date?(uri, path, prompt_for_login) begin ftp = Net::FTP.new(uri.host) ftp_login(ftp, uri.host, prompt_for_login) if ftp.size(uri.path) != ::File.size(path) return false end if ftp.mtime(uri.path) <= ::File.mtime(path) return true end return false rescue Net::FTPPermError => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri rescue SocketError => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri end end # Returns whether the file was not downloaded because the file already # exists and is already up-to-date. def download(uri, path, prompt_for_login) begin ftp = Net::FTP.new(uri.host) ftp_login(ftp, uri.host, prompt_for_login) if ::File.exist?(path) && ftp.mtime(uri.path) <= ::File.mtime(path) Fig::Logging.debug "#{path} is up to date." return false else log_download(uri, path) ftp.getbinaryfile(uri.path, path, 256*1024) return true end rescue Net::FTPPermError => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri rescue SocketError => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri rescue Errno::ETIMEDOUT => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri end end def upload(local_file, uri) ftp_uri = Fig::URL.parse(ENV['FIG_REMOTE_URL']) ftp_root_path = ftp_uri.path ftp_root_dirs = ftp_uri.path.split('/') remote_publish_path = uri.path[0, uri.path.rindex('/')] remote_publish_dirs = remote_publish_path.split('/') # Use array subtraction to deduce which project/version folder to upload # to, i.e. [1,2,3] - [2,3,4] = [1] remote_project_dirs = remote_publish_dirs - ftp_root_dirs Net::FTP.open(uri.host) do |ftp| ftp_login(ftp, uri.host, :prompt_for_login) # Assume that the FIG_REMOTE_URL path exists. ftp.chdir(ftp_root_path) remote_project_dirs.each do |dir| # Can't automatically create parent directories, so do it manually. if ftp.nlst().index(dir).nil? ftp.mkdir(dir) ftp.chdir(dir) else ftp.chdir(dir) end end ftp.putbinaryfile(local_file) end end private def ftp_login(ftp, host, prompt_for_login) begin if @login authentication = get_authentication_for host, prompt_for_login if authentication ftp.login authentication.username, authentication.password else ftp.login end else ftp.login end ftp.passive = true rescue Net::FTPPermError => error raise Fig::NetworkError.new "Could not log in: #{error.message}" end return end def download_ftp_list(uri, dirs) # Run a bunch of these in parallel since they're slow as hell num_threads = (ENV['FIG_FTP_THREADS'] || '16').to_i threads = [] all_packages = [] (0..num_threads-1).each { |num| all_packages[num] = [] } (0..num_threads-1).each do |num| threads << Thread.new do packages = all_packages[num] ftp = Net::FTP.new(uri.host) ftp_login(ftp, uri.host, :prompt_for_login) ftp.chdir(uri.path) pos = num while pos < dirs.length pkg = dirs[pos] begin ftp.nlst(dirs[pos]).each do |ver| packages << pkg + '/' + ver end rescue Net::FTPPermError # Ignore this error because it's indicative of the FTP library # encountering a file or directory that it does not have # permission to open. Fig needs to be able to have secure # repos/packages and there is no way easy way to deal with the # permissions issues other than consuming these errors. # # Actually, with FTP, you can't tell the difference between a # file not existing and not having permission to access it (which # is probably a good thing). end pos += num_threads end ftp.close end end threads.each { |thread| thread.join } all_packages.flatten.sort end end
klimkin/fig
lib/fig/command/action/role/list_as_json.rb
# coding: utf-8 require 'json' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end # Requires a #set_up_object_to_be_serialized method. module Fig::Command::Action::Role::ListAsJSON def execute() set_up_object_to_be_serialized puts JSON.pretty_generate @object_to_be_serialized return Fig::Command::Action::EXIT_SUCCESS end end
klimkin/fig
lib/fig/command/action/role/list_all_configs.rb
<filename>lib/fig/command/action/role/list_all_configs.rb # coding: utf-8 module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListAllConfigs def list_all_configs? return true end def base_display_config_names() return @execution_context.base_package.config_names end end
klimkin/fig
lib/fig/command/action/role/list_as_graphviz.rb
<reponame>klimkin/fig # coding: utf-8 require 'set' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end # Requires a #node_content(package, config_name) method. module Fig::Command::Action::Role::ListAsGraphviz def execute() @subgraphs = {} puts 'digraph {' puts ' node [shape = box];' walk_dependency_tree( @execution_context.base_package, base_display_config_names(), include_emit, &package_gather ) emit_subgraphs puts '}' return Fig::Command::Action::EXIT_SUCCESS end private def include_emit visited = Set.new return lambda do |including_package, including_config, included_package, included_config| including_name = node_name(including_package, including_config) included_name = node_name(included_package, included_config) edge = %Q/ "#{including_name}" -> "#{included_name}";/ if ! visited.include? edge visited << edge puts edge end end end def package_gather visited = Set.new return lambda do |package, config_name, depth| name = node_name package, config_name if ! visited.include? name visited << name package_name = node_name package, nil @subgraphs[package_name] ||= [] @subgraphs[package_name] << node_content(package, config_name) end end end def emit_subgraphs() @subgraphs.each do |package_name, nodes| cluster = nodes.size > 1 ? 'cluster ' : '' puts %Q< subgraph "#{cluster}#{package_name}" {> nodes.each { |node| puts %Q< #{node}> } puts %q< }> end return end def node_name(package, config_name) return package.to_s_with_config(config_name) end end
klimkin/fig
lib/fig/command/action/role/list_walking_dependency_tree.rb
<gh_stars>10-100 # coding: utf-8 require 'set' require 'fig/include_backtrace' require 'fig/package_descriptor' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListWalkingDependencyTree def modifies_repository?() return false end def walk_dependency_tree( base_package, config_names, include_block = nil, &package_block ) do_walk_dependency_tree( base_package, config_names, nil, 0, include_block, &package_block ) return end def configure(options) @descriptor = options.descriptor end def gather_package_dependency_configurations() packages = {} starting_config_names = base_display_config_names() base_package = @execution_context.base_package if ! base_package.name.nil? packages[base_package] = starting_config_names.to_set end do_walk_dependency_tree(base_package, starting_config_names, nil, 0, nil) do |package, config_name, depth| if ( ! package.name.nil? \ && ! ( ! list_all_configs? \ && @descriptor \ && package.name == @descriptor.name ) ) packages[package] ||= Set.new packages[package] << config_name end end if ! list_all_configs? && @descriptor packages.reject! do |package, config_names| package.name == @descriptor.name end end return packages end private def do_walk_dependency_tree( base_package, config_names, backtrace, depth, include_block, &package_block ) config_names.each do |config_name| if depth < 1 @execution_context.repository.reset_cached_data @execution_context.non_repository_packages.reset_cached_data end package_block.call base_package, config_name, depth new_backtrace = new_backtrace(backtrace, base_package, config_name) base_package.package_dependencies(config_name, new_backtrace).each do |descriptor| package = package_for_descriptor descriptor, base_package do_walk_dependency_tree( package, [descriptor.config || Fig::Package::DEFAULT_CONFIG], new_backtrace, depth + 1, include_block, &package_block ) if include_block include_block.call( base_package, config_name, package, descriptor.config ) end end end return end def new_backtrace(backtrace, base_package, config_name) return Fig::IncludeBacktrace.new( backtrace, Fig::PackageDescriptor.new( base_package.name(), base_package.version(), config_name, :description => base_package.description ) ) end def package_for_descriptor(descriptor, base_package) if descriptor.name return @execution_context.repository.get_package( descriptor, :allow_any_version ) elsif descriptor.file_path return @execution_context.non_repository_packages[descriptor.file_path] end return base_package end end
klimkin/fig
lib/fig/statement/override.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/package_descriptor' require 'fig/statement' module Fig; end # Overrides one package version dependency with another. # # config whatever # override somedependency/3.2.6 # end # # indicates that, regardless of which version of somedependency the blah # package says it needs, the blah package will actually use v3.2.6. class Fig::Statement::Override < Fig::Statement attr_reader :package_name, :version # Centralized definition of requirements for descriptors for override # statements. def self.parse_descriptor(raw_string, options = {}) filled_in_options = {} filled_in_options.merge!(options) filled_in_options[:name] = :required filled_in_options[:version] = :required filled_in_options[:config] = :forbidden return Fig::PackageDescriptor.parse(raw_string, filled_in_options) end def initialize(line_column, source_description, package_name, version) super(line_column, source_description) @package_name = package_name @version = version end def statement_type() return 'override' end def deparse_as_version(deparser) return deparser.override(self) end def minimum_grammar_for_emitting_input() return [0] end def minimum_grammar_for_publishing() return [0] end end
klimkin/fig
spec/command/include_file_spec.rb
<reponame>klimkin/fig<gh_stars>10-100 # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do def set_up_include_files() cleanup_home_and_remote base_included = "#{CURRENT_DIRECTORY}/included" sub_included = "#{base_included}/subdirectory" FileUtils.mkdir_p sub_included write_file "#{sub_included}/leaf.fig", <<-END_PACKAGE grammar v2 config default set SUB_PACKAGE=@/default set SHOULD_BE_OVERRIDDEN='not overridden' end config non-default set SUB_PACKAGE=@/non-default end config not-used set SHOULD_NOT_BE_SET='was set' end END_PACKAGE write_file "#{base_included}/peer.fig", <<-END_PACKAGE grammar v2 config default set PEER='was set' # Note path relative to this file and not to CURRENT_DIRECTORY. include-file "subdirectory/leaf.fig":non-default end END_PACKAGE write_file "#{base_included}/base.fig", <<-END_PACKAGE grammar v2 config default include-file subdirectory/leaf.fig include-file 'peer.fig' set SHOULD_BE_OVERRIDDEN=overridden end END_PACKAGE write_file "#{CURRENT_DIRECTORY}/test.fig", <<-END_PACKAGE grammar v2 retrieve SUB_PACKAGE->somewhere config default include-file 'included/base.fig' end END_PACKAGE return end it 'handles include-file' do set_up_include_files out, err, * = fig( [ '--file', "#{CURRENT_DIRECTORY}/test.fig", '--update', '--list-variables', ], :fork => false, ) out.should =~ /^PEER=was set$/ out.should =~ %r<^SUB_PACKAGE=.*subdirectory/non-default$> out.should =~ /^SHOULD_BE_OVERRIDDEN=overridden$/ out.should_not =~ /^SHOULD_NOT_BE_SET=/ err.should =~ /[Rr]etrieve.*SUB_PACKAGE.*ignored/ end end
klimkin/fig
lib/fig/deparser/v1_base.rb
# coding: utf-8 module Fig; end module Fig::Deparser; end # Handles serializing of statements in the v1 grammar. module Fig::Deparser::V1Base def command(statement) add_indent @text << %Q<command\n> add_indent(@indent_level + 1) statement.command.each do |argument| emit_tokenized_value argument @text << ' ' end @text << %Q<\n> add_indent @text << %Q<end\n> return end def retrieve(statement) add_indent @text << 'retrieve ' @text << statement.variable @text << '->' emit_tokenized_value statement.tokenized_path @text << "\n" return end private def asset(keyword, statement) quote = statement.glob_if_not_url? ? %q<"> : %q<'> path = asset_path(statement).gsub('\\', ('\\' * 4)).gsub(quote, "\\\\#{quote}") add_indent @text << keyword @text << ' ' @text << quote @text << path @text << quote @text << "\n" return end def environment_variable(statement, keyword) add_indent @text << keyword @text << ' ' @text << statement.name @text << '=' emit_tokenized_value statement.tokenized_value @text << "\n" return end def emit_tokenized_value(tokenized_value) if tokenized_value.can_be_single_quoted? @text << %q<'> @text << tokenized_value.to_single_quoted_string @text << %q<'> else @text << %q<"> @text << tokenized_value.to_escaped_string @text << %q<"> end return end end
klimkin/fig
lib/fig/command/action/list_variables/all_configs.rb
<gh_stars>10-100 # coding: utf-8 require 'set' require 'fig/command/action' require 'fig/command/action/role/list_all_configs' require 'fig/command/action/role/list_walking_dependency_tree' require 'fig/statement/path' require 'fig/statement/set' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListVariables; end class Fig::Command::Action::ListVariables::AllConfigs include Fig::Command::Action include Fig::Command::Action::Role::ListAllConfigs include Fig::Command::Action::Role::ListWalkingDependencyTree def options() return %w<--list-variables --list-all-configs> end def descriptor_requirement() return nil end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end def execute() variable_names = Set.new() walk_dependency_tree( @execution_context.base_package, base_display_config_names() ) do |package, config_name, depth| package[config_name].walk_statements() do |statement| if statement.is_environment_variable? variable_names << statement.name() end end end variable_names.sort.each { |name| puts name } return EXIT_SUCCESS end end
klimkin/fig
lib/fig/package_parse_error.rb
# coding: utf-8 require 'fig/user_input_error' module Fig # An issue with parsing a .fig file. class PackageParseError < UserInputError end end
klimkin/fig
lib/fig/command/action/list_variables/default.rb
<filename>lib/fig/command/action/list_variables/default.rb # coding: utf-8 require 'fig/command/action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListVariables; end class Fig::Command::Action::ListVariables::Default include Fig::Command::Action def options() return %w<--list-variables> end def descriptor_requirement() return nil end def modifies_repository?() return false end def load_base_package?() return true end def register_base_package?() return true end def apply_config?() return true end def apply_base_config?() return true end def execute() variables = @execution_context.environment.variables() if variables.empty? and $stdout.tty? puts '<no variables>' else variables.keys.sort.each do |variable| puts variable + "=" + variables[variable] end end return EXIT_SUCCESS end end
klimkin/fig
lib/fig/command/action/role/list_dependencies_as_graphviz.rb
# coding: utf-8 module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListDependenciesAsGraphviz private def node_content(package, config_name) name = node_name package, config_name style = '' color = '' if package == @execution_context.base_package if base_display_config_names.include?(config_name) style = ' style = "rounded, bold"' end if config_name == @execution_context.base_config color = ' color = blue' end end return %Q<"#{name}" [label = "#{name}"#{style}#{color}];> end end
klimkin/fig
lib/fig/no_such_package_config_error.rb
# coding: utf-8 require 'fig/package_descriptor' require 'fig/user_input_error' module Fig # User specified a configuration for a Package that does not exist. class NoSuchPackageConfigError < UserInputError attr_reader :descriptor attr_reader :package def initialize(message, descriptor, package) super(message) @descriptor = descriptor @package = package end end end
klimkin/fig
spec/command/suppress_warning_include_statement_missing_version_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do describe 'suppress unversioned include statement warnings' do before(:each) do clean_up_test_environment set_up_test_environment cleanup_home_and_remote input = <<-END config default end END out, err = fig(%w<--publish bar/1.2.3>, input) input = <<-END config default include bar/1.2.3 end config non-default include bar end END out, err = fig(%w<--publish foo/1.2.3>, input) end describe 'emits warnings when warnings are not suppressed' do it 'for the package.fig' do input = <<-END config default include foo end END out, err = fig(%w<--list-configs>, input) out.should == 'default' err.should =~ /No version in the package descriptor of "foo" in an include statement \(line/ end it 'for depended upon packages' do input = <<-END config default include foo/1.2.3 end END out, err = fig(%w<--list-dependencies>, input) out.should == "bar/1.2.3\nfoo/1.2.3" err.should =~ %r<No version in the package descriptor of "bar" in an include statement in the \.fig file for "foo/1\.2\.3:default" \(line> end end describe 'emits warning for base package even when warnings are suppressed' do it 'with --suppress-warning-include-statement-missing-version' do input = <<-END config default include foo end END out, err = fig( %w< --list-configs --suppress-warning-include-statement-missing-version >, input ) out.should == 'default' err.should =~ /No version in the package descriptor of "foo" in an include statement \(line/ end it 'with figrc' do figrc = File.join(FIG_SPEC_BASE_DIRECTORY, 'test-figrc') File.open(figrc, 'w') do |handle| handle.puts %q< { "suppress warnings": ["include statement missing version"] } > end input = <<-END config default include foo end END out, err = fig(%w<--list-configs>, input) out.should == 'default' err.should =~ /No version in the package descriptor of "foo" in an include statement \(line/ end end describe 'does not emit warning for depended upon packages when warnings are suppressed' do it 'with --suppress-warning-include-statement-missing-version' do input = <<-END config default include foo/1.2.3 end END out, err = fig( %w< --list-dependencies --suppress-warning-include-statement-missing-version >, input ) out.should == "bar/1.2.3\nfoo/1.2.3" err.should_not =~ /No version in the package descriptor of "bar" in an include statement/ end it 'with figrc' do figrc = File.join(FIG_SPEC_BASE_DIRECTORY, 'test-figrc') File.open(figrc, 'w') do |handle| handle.puts %q< { "suppress warnings": ["include statement missing version"] } > end input = <<-END config default include foo/1.2.3 end END out, err = fig(%w<--list-dependencies>, input, :figrc => figrc) out.should == "bar/1.2.3\nfoo/1.2.3" err.should_not =~ /No version in the package descriptor of "bar" in an include statement/ end end end end
klimkin/fig
lib/fig/command/action/role/list_variables_as_graphviz.rb
# coding: utf-8 require 'cgi' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListVariablesAsGraphviz def descriptor_requirement() return nil end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end private def node_content(package, config_name) style = '' color = '' if package == @execution_context.base_package if base_display_config_names.include?(config_name) style = ' style = "rounded, bold"' end if config_name == @execution_context.base_config color = ' color = blue' end end name = node_name package, config_name rows = variable_statement_rows package, config_name label = nil if rows.empty? label = %Q<"#{name}"> else label = %Q[<<table border="0"><tr><td border="0" colspan="3"><b>#{name}</b></td></tr>#{rows}</table>>] end return %Q<"#{name}" [label = #{label}#{style}#{color}];> end def variable_statement_rows(package, config_name) string = '' package[config_name].walk_statements do |statement| if statement.is_environment_variable? string << format_variable_statement(statement) end end return string end def format_variable_statement(statement) string = '<tr><td align="right">' string << statement.statement_type string << '</td><td align="left">$' string << CGI.escape_html(statement.name) string << '</td><td align="left">' string << CGI.escape_html(statement.tokenized_value.to_escaped_string) string << '</td></tr>' return string end end
klimkin/fig
lib/fig/protocol/http.rb
<filename>lib/fig/protocol/http.rb # coding: utf-8 require 'net/http' require 'uri' require 'fig/file_not_found_error' require 'fig/logging' require 'fig/network_error' require 'fig/protocol' module Fig; end module Fig::Protocol; end # File transfers via HTTP. class Fig::Protocol::HTTP include Fig::Protocol # Returns whether the file was not downloaded because the file already # exists and is already up-to-date. def download(uri, path, prompt_for_login) log_download(uri, path) ::File.open(path, 'wb') do |file| file.binmode begin download_via_http_get(uri, file) rescue SystemCallError => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri rescue SocketError => error Fig::Logging.debug error.message raise Fig::FileNotFoundError.new error.message, uri end end end private def download_via_http_get(uri_string, file, redirection_limit = 10) if redirection_limit < 1 Fig::Logging.debug 'Too many HTTP redirects.' raise Fig::FileNotFoundError.new 'Too many HTTP redirects.', uri_string end response = Net::HTTP.get_response(URI(uri_string)) case response when Net::HTTPSuccess then file.write(response.body) when Net::HTTPRedirection then location = response['location'] Fig::Logging.debug "Redirecting to #{location}." download_via_http_get(location, file, redirection_limit - 1) else Fig::Logging.debug "Download failed: #{response.code} #{response.message}." raise Fig::FileNotFoundError.new( "Download failed: #{response.code} #{response.message}.", uri_string ) end return end end
klimkin/fig
spec/command/grammar_spec_helper.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') def check_published_grammar_version(version, input = nil) if input fig %w< --publish foo/1.2.3 >, input, :fork => false end out, err = fig(%w< foo/1.2.3 --dump-package-definition-text >, :fork => false) if version == 0 out.should =~ /^# grammar v0\b/ else out.should =~ / ^ grammar [ ] v #{version} \b/x end err.should == '' return [out, err] end # vim: set fileencoding=utf8 :
klimkin/fig
spec/statement/configuration_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fig/statement/command' require 'fig/statement/configuration' require 'fig/statement/include' require 'fig/statement/override' require 'fig/statement/path' require 'fig/statement/set' require 'fig/statement/synthetic_raw_text' describe 'Statement::Configuration' do it 'moves override statements to the front of the set of statements' do override_c = Fig::Statement::Override.new(nil, nil, 'C', 'version') override_b = Fig::Statement::Override.new(nil, nil, 'B', 'version') override_a = Fig::Statement::Override.new(nil, nil, 'A', 'version') command = Fig::Statement::Command.new(nil, nil, %w< something to run >) incorporate = Fig::Statement::Include.new(nil, nil, nil, nil, nil) parsed_name, parsed_value = Fig::Statement::Path.parse_name_value 'name=value' path = Fig::Statement::Path.new(nil, nil, parsed_name, parsed_value) set = Fig::Statement::Set.new(nil, nil, parsed_name, parsed_value) config = Fig::Statement::Configuration.new( nil, nil, 'name', [command, override_c, incorporate, override_b, path, override_a, set] ) statements_to_be_checked = config.statements.reject { |statement| statement.is_a? Fig::Statement::SyntheticRawText } statements_to_be_checked.should == [override_c, override_b, override_a, command, incorporate, path, set] end end
klimkin/fig
lib/fig/statement/path.rb
# coding: utf-8 require 'fig/statement' require 'fig/statement/environment_variable' module Fig; end # A statement that specifies or modifies a path environment variable, e.g. # "append", "path", "add" (though those are all synonyms). class Fig::Statement::Path < Fig::Statement include Fig::Statement::EnvironmentVariable # Yields on error. def self.parse_name_value(combined, &error_block) variable, raw_value = seperate_name_and_value combined, &error_block tokenized_value = tokenize_value(raw_value, &error_block) if tokenized_value.to_escaped_string.length < 1 yield %Q<The value of path variable #{variable} is empty.> return end return [variable, tokenized_value] end def self.parse_v0_name_value(combined, &error_block) variable, raw_value = seperate_name_and_value combined, &error_block if raw_value.length < 1 yield %Q<The value of path variable #{variable} is empty.> return end base_v0_value_validation(variable, raw_value, &error_block) if raw_value =~ /([;:<>|])/ yield %Q<The value of path variable #{variable} (#{raw_value}) contains a "#{$1}" character.> return end return [variable, tokenize_value(raw_value, &error_block)] end def initialize(line_column, source_description, name, tokenized_value) super(line_column, source_description) @name = name @tokenized_value = tokenized_value end def statement_type() return 'path' end def is_environment_variable?() return true end def deparse_as_version(deparser) return deparser.path(self) end private def minimum_grammar() base_grammar_version = standard_minimum_grammar return base_grammar_version if base_grammar_version[0] != 0 value = tokenized_value.to_escaped_string if value =~ / ( [;:<>|] ) /x return [1, %Q<contains a "#{$1}" character>] end return [0] end end
klimkin/fig
lib/fig/deparser/v0.rb
# coding: utf-8 require 'fig/deparser' module Fig; end module Fig::Deparser; end # Handles serializing of statements in the v0 grammar. class Fig::Deparser::V0 include Fig::Deparser def initialize( emit_as_input_or_to_be_published_values, indent_string = ' ' * 2, initial_indent_level = 0 ) @emit_as_input_or_to_be_published_values = emit_as_input_or_to_be_published_values @indent_string = indent_string @initial_indent_level = initial_indent_level return end def command(statement) add_indent @text << %q<command "> @text << statement.command.first.to_double_quotable_string @text << %Q<"\n> return end def grammar_version(statement) add_indent # Comment out so that older clients don't have issues. @text << "# grammar v0\n\n" return end def retrieve(statement) add_indent @text << 'retrieve ' @text << statement.variable @text << '->' @text << statement.tokenized_path.to_double_quotable_string @text << "\n" return end def grammar_description() return 'v0' end private def asset(keyword, statement) path = asset_path statement quote = path =~ /[*?\[\]{}]/ ? '' : %q<"> add_indent @text << keyword @text << ' ' @text << quote @text << path @text << quote @text << "\n" return end def environment_variable(statement, keyword) add_indent @text << keyword @text << ' ' @text << statement.name @text << '=' @text << statement.tokenized_value.to_double_quotable_string @text << "\n" return end end
klimkin/fig
lib/fig/protocol/ssh.rb
<reponame>klimkin/fig<gh_stars>10-100 # coding: utf-8 require 'cgi' require 'fig/logging' require 'fig/network_error' require 'fig/protocol' module Fig; end module Fig::Protocol; end # File transfers using external ssh and scp programs class Fig::Protocol::SSH include Fig::Protocol def download_list(uri) packages = [] unescaped_path = CGI.unescape uri.path ls = ssh(uri.host, 'find', unescaped_path, '-type', 'd') { |error_message| raise Fig::NetworkError.new error_message } strip_paths_for_list(ls, packages, unescaped_path) return packages end # Determine whether we need to update something. Returns nil to indicate # "don't know". def path_up_to_date?(uri, path, prompt_for_login) unescaped_path = CGI.unescape uri.path size_mtime = ssh(uri.host, 'stat', '--format="%s %Z"', unescaped_path) { |error_message| raise Fig::NetworkError.new( "Unable to get size and modification time for remote path #{path}: #{error_message}", ) } remote_size, remote_mtime = size_mtime.split remote_size = remote_size.to_i remote_mtime = remote_mtime.to_i if remote_size != ::File.size(path) return false end if remote_mtime <= ::File.mtime(path).to_i return true end return false end # Returns whether the file was not downloaded because the file already # exists and is already up-to-date. def download(uri, path, prompt_for_login) unescaped_path = CGI.unescape uri.path exists = remote_path_exists(uri.host, unescaped_path) { |error_message| raise Fig::NetworkError.new( "Unable to determine whether #{uri} exists: #{error_message}", ) } if not exists raise Fig::FileNotFoundError.new "#{uri} doesn't exist.", uri end scp("#{uri.host}:#{unescaped_path}", path) { |error_message| raise Fig::NetworkError.new( "Unable to copy remote file to #{path}: #{error_message}", ) } return true end def upload(local_file, uri) unescaped_path = CGI.unescape uri.path ssh(uri.host, 'mkdir', '-p', ::File.dirname(unescaped_path)) { |error_message| raise Fig::NetworkError.new( "Unable to create directory on remote: #{error_message}", ) } scp(local_file, "#{uri.host}:#{unescaped_path}") { |error_message| raise Fig::NetworkError.new( "Unable to copy #{local_file} to remote: #{error_message}", ) } return end private # Execute command on remote host with external ssh program. def ssh(host, *command, &error_block) ssh_command = ['ssh', '-n', host, *command] begin output, errors, result = Fig::ExternalProgram.capture ssh_command rescue Errno::ENOENT => error yield %Q<Could not run "#{ssh_command.join ' '}": #{error.message}.> return end if result && ! result.success? yield %Q<Could not run "#{ssh_command.join ' '}": #{result}: #{errors}> return end return output end def remote_path_exists(host, path, &error_block) ssh_command = ['ssh', '-n', host, 'test', '-e', path] begin *, result = Fig::ExternalProgram.capture ssh_command rescue Errno::ENOENT => error yield %Q<Could not run "#{ssh_command.join ' '}": #{error.message}.> return end if result && ! result.success? return false end return true end # Use external scp program to copy a file. def scp(from, to, &error_block) command = ['scp', from, to] begin output, errors, result = Fig::ExternalProgram.capture command rescue Errno::ENOENT => error yield %Q<Could not run "#{command.join ' '}": #{error.message}.> return end if result && ! result.success? yield %Q<Could not run "#{command.join ' '}": #{result}: #{errors}> return end return output end end
klimkin/fig
lib/fig/repository_package_publisher.rb
# coding: utf-8 require 'fileutils' require 'etc' require 'set' require 'socket' require 'tmpdir' require 'fig' require 'fig/at_exit' require 'fig/external_program' require 'fig/file_not_found_error' require 'fig/logging' require 'fig/not_yet_parsed_package' require 'fig/package_cache' require 'fig/package_definition_text_assembler' require 'fig/package_descriptor' require 'fig/package_parse_error' require 'fig/parser' require 'fig/repository' require 'fig/repository_error' require 'fig/statement/archive' require 'fig/statement/grammar_version' require 'fig/statement/resource' require 'fig/statement/synthetic_raw_text' require 'fig/url' module Fig; end # Handles package publishing for the Repository. class Fig::RepositoryPackagePublisher attr_writer :application_configuration attr_writer :options attr_writer :operating_system attr_writer :publish_listeners attr_writer :descriptor attr_writer :source_package attr_writer :was_forced attr_writer :base_temp_dir attr_writer :runtime_for_package attr_writer :local_directory_for_package attr_writer :remote_directory_for_package attr_writer :local_fig_file_for_package attr_writer :remote_fig_file_for_package attr_writer :local_only def initialize() @text_assembler = Fig::PackageDefinitionTextAssembler.new :emit_as_to_be_published return end def package_statements=(statements) @text_assembler.add_input(statements) end def publish_package() derive_publish_metadata() temp_dir = publish_temp_dir() @operating_system.delete_and_recreate_directory(temp_dir) @operating_system.delete_and_recreate_directory( @local_directory_for_package ) @operating_system.delete_and_recreate_directory(@runtime_for_package) fig_file = File.join(temp_dir, Fig::Repository::PACKAGE_FILE_IN_REPO) content, published_package = derive_definition_file_and_create_resource_archive @operating_system.write(fig_file, content) publish_package_contents if not @local_only @operating_system.upload(fig_file, @remote_fig_file_for_package) end @operating_system.copy(fig_file, @local_fig_file_for_package) notify_listeners FileUtils.rm_rf(temp_dir) check_published_environment_variables published_package return true end private def derive_publish_metadata() @publish_time = Time.now() @publish_login = derive_login() @publish_host = Socket.gethostname() return end def derive_login() # Etc.getpwuid() returns nil on Windows, but Etc.getlogin() will return the # wrong result on some systems if you su(1) to a different user. if password_entry = Etc.getpwuid() and password_entry.name return password_entry.name end return Etc.getlogin() end def derive_definition_file_and_create_resource_archive() add_package_metadata_comments() assemble_output_statements_and_accumulate_assets() validate_asset_names() create_resource_archive() add_unparsed_text() file_content, explanations = @text_assembler.assemble_package_definition() if Fig::Logging.info? explanations.each {|explanation| Fig::Logging.info explanation} end to_be_published_package = nil begin unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = @descriptor unparsed_package.working_directory = unparsed_package.include_file_base_directory = @runtime_for_package unparsed_package.source_description = '<package to be published>' unparsed_package.unparsed_text = file_content to_be_published_package = Fig::Parser.new(nil, false).parse_package(unparsed_package) rescue Fig::PackageParseError => error raise \ "Bug in code! Could not parse package definition to be published.\n" + "#{error}\n\nGenerated contents:\n#{file_content}" end return file_content, to_be_published_package end def add_package_metadata_comments() add_publish_comment @text_assembler.add_header( %Q<# Publishing information for #{@descriptor.to_string()}:> ) @text_assembler.add_header %q<#> @text_assembler.add_header( %Q<# Time: #{@publish_time} (epoch: #{@publish_time.to_i()})> ) @text_assembler.add_header %Q<# User: #{@publish_login}> @text_assembler.add_header %Q<# Host: #{@publish_host}> sanitized_argv = ARGV.map {|arg| arg.gsub "\n", '\\n'} @text_assembler.add_header %Q<# Args: "#{sanitized_argv.join %q[", "]}"> @text_assembler.add_header %Q<# Fig: v#{Fig::VERSION}> add_environment_variables_to_package_metadata add_version_control_to_package_metadata @text_assembler.add_header %Q<\n> return end def add_publish_comment return if not @options.publish_comment and not @options.publish_comment_path if @options.publish_comment comment = @options.publish_comment comment = comment.strip.gsub(/[ \t]*\n/, "\n# ").gsub(/^#[ ]+\n/, "#\n") @text_assembler.add_header %Q<# #{comment}> @text_assembler.add_header %q<#> end if @options.publish_comment_path begin comment = IO.read( @options.publish_comment_path, :external_encoding => Encoding::UTF_8, ) comment = comment.strip.gsub(/[ \t]*\n/, "\n# ").gsub(/^#[ ]+\n/, "#\n") rescue Errno::ENOENT Fig::Logging.fatal( %Q<Comment file "#{@options.publish_comment_path}" does not exist.> ) raise Fig::RepositoryError.new rescue Errno::EACCES Fig::Logging.fatal( %Q<Could not read comment file "#{@options.publish_comment_path}".> ) raise Fig::RepositoryError.new end @text_assembler.add_header %Q<# #{comment}> @text_assembler.add_header %q<#> end @text_assembler.add_header %q<#> return end def add_environment_variables_to_package_metadata() variables = @application_configuration[ 'environment variables to include in comments in published packages' ] return if ! variables || variables.empty? @text_assembler.add_header %q<#> @text_assembler.add_header %q<# Values of some environment variables at time of publish:> @text_assembler.add_header %q<#> variables.each do |variable| value = ENV[variable] if value.nil? value = ' was unset.' else value = "=#{value}" end @text_assembler.add_header %Q<# #{variable}#{value}> end return end def add_version_control_to_package_metadata() return if @options.suppress_vcs_comments_in_published_packages? add_subversion_metadata_to_package_metadata() add_git_metadata_to_package_metadata() return end def add_subversion_metadata_to_package_metadata() output = get_subversion_working_directory_info return if not output =~ /^URL: +(.*\S)\s*$/ url = $1 revision = '' if output =~ /^Revision: +(\S+)\s*$/ revision = ", revision #{$1}" end @text_assembler.add_header %q<#> @text_assembler.add_header( %Q<# Publish happened in a Subversion working directory from\n# #{url}#{revision}.> ) return end def get_subversion_working_directory_info() executable = get_version_control_executable('FIG_SVN_EXECUTABLE', 'svn') or return return run_version_control_command( [executable, 'info'], 'Subversion', 'FIG_SVN_EXECUTABLE' ) end def run_version_control_command(command, version_control_name, variable) begin output, errors, result = Fig::ExternalProgram.capture command rescue Errno::ENOENT => error Fig::Logging.warn( %Q<Could not run "#{command.join ' '}": #{error.message}. Set #{variable} to the path to use for #{version_control_name} or to the empty string to suppress #{version_control_name} support.> ) return end if result && ! result.success? Fig::Logging.debug( %Q<Could not run "#{command.join ' '}": #{result}: #{errors}> ) return end return output end def get_version_control_executable(variable, default) executable = ENV[variable] if ! executable || executable.empty? || executable =~ /\A\s*\z/ return if ENV.include? variable return default end return executable end def add_git_metadata_to_package_metadata() url = get_git_origin_url or return url.strip! return if url.empty? branch = get_git_branch if branch.nil? branch = '' else branch = ", branch #{branch}" end sha1 = get_git_sha1 if sha1.nil? sha1 = '' else sha1 = ",\n# SHA1 #{sha1}" end @text_assembler.add_header %q<#> @text_assembler.add_header( %Q<# Publish happened in a Git working directory from\n# #{url}#{branch}#{sha1}.> ) return end def get_git_origin_url() executable = get_version_control_executable('FIG_GIT_EXECUTABLE', 'git') or return return run_version_control_command( [executable, 'config', '--get', 'remote.origin.url'], 'Git', 'FIG_GIT_EXECUTABLE' ) end def get_git_branch() executable = get_version_control_executable('FIG_GIT_EXECUTABLE', 'git') or return reference = run_version_control_command( [executable, 'rev-parse', '--abbrev-ref=strict', 'HEAD'], 'Git', 'FIG_GIT_EXECUTABLE' ) return if reference.nil? reference.strip! return if reference.empty? return reference end def get_git_sha1() executable = get_version_control_executable('FIG_GIT_EXECUTABLE', 'git') or return reference = run_version_control_command( [executable, 'rev-parse', 'HEAD'], 'Git', 'FIG_GIT_EXECUTABLE' ) return if reference.nil? reference.strip! return if reference.empty? return reference end def assemble_output_statements_and_accumulate_assets() @local_resource_paths = [] @asset_names_with_associated_input_statements = {} @text_assembler.input_statements.each do |statement| if statement.is_asset? add_asset_to_output_statements(statement) else @text_assembler.add_output statement end end return end def add_asset_to_output_statements(asset_statement) if Fig::URL.is_url? asset_statement.location add_output_asset_statement_based_upon_input_statement( asset_statement, asset_statement ) elsif asset_statement.is_a? Fig::Statement::Archive if asset_statement.requires_globbing? expand_globs_from( [asset_statement.location] ).each do |file| add_output_asset_statement_based_upon_input_statement( Fig::Statement::Archive.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, file, false # No globbing ), asset_statement ) end else add_output_asset_statement_based_upon_input_statement( asset_statement, asset_statement ) end elsif asset_statement.requires_globbing? @local_resource_paths.concat expand_globs_from( [asset_statement.location] ) else @local_resource_paths << asset_statement.location end return end def add_output_asset_statement_based_upon_input_statement( output_statement, input_statement ) @text_assembler.add_output output_statement asset_name = output_statement.asset_name input_statements = @asset_names_with_associated_input_statements[asset_name] if input_statements.nil? input_statements = [] @asset_names_with_associated_input_statements[asset_name] = input_statements end input_statements << input_statement return end def validate_asset_names() found_problem = false @asset_names_with_associated_input_statements.keys.sort.each do |asset_name| statements = @asset_names_with_associated_input_statements[asset_name] if asset_name == Fig::Repository::RESOURCES_FILE Fig::Logging.fatal \ %Q<You cannot have an asset with the name "#{Fig::Repository::RESOURCES_FILE}"#{collective_position_string(statements)} due to Fig implementation details.> found_problem = true end archive_statements = statements.select { |s| s.is_a? Fig::Statement::Archive } if ( not archive_statements.empty? \ and not ( asset_name =~ /\.tar\.gz$/ \ or asset_name =~ /\.tgz$/ \ or asset_name =~ /\.tar\.bz2$/ \ or asset_name =~ /\.zip$/ ) ) Fig::Logging.fatal \ %Q<Unknown archive type "#{asset_name}"#{collective_position_string(archive_statements)}.> found_problem = true end if statements.size > 1 Fig::Logging.fatal \ %Q<Found multiple assets with the name "#{asset_name}"#{collective_position_string(statements)}. If these were allowed, assets would overwrite each other.> found_problem = true end end if found_problem raise Fig::RepositoryError.new end end def collective_position_string(statements) return ( statements.map { |statement| position_string = statement.position_string position_string.empty? ? '<unknown>' : position_string.strip } ).join(', ') end def create_resource_archive() if @local_resource_paths.size > 0 check_asset_paths(@local_resource_paths) file = File.join publish_temp_dir, Fig::Repository::RESOURCES_FILE @operating_system.create_archive(file, @local_resource_paths) Fig::AtExit.add { FileUtils.rm_f(file) } @text_assembler.add_output( Fig::Statement::SyntheticRawText.new(nil, nil, "\n"), Fig::Statement::Archive.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, file, false # No globbing ) ) end return end def publish_package_contents() @text_assembler.output_statements.each do |statement| if statement.is_asset? publish_asset(statement) end end return end def publish_asset(asset_statement) asset_name = asset_statement.asset_name() asset_remote = Fig::URL.append_path_components @remote_directory_for_package, [asset_name] if Fig::URL.is_url? asset_statement.location asset_local = File.join(publish_temp_dir(), asset_name) begin @operating_system.download(asset_statement.location, asset_local, false) rescue Fig::FileNotFoundError Fig::Logging.fatal "Could not download #{asset_statement.location}." raise Fig::RepositoryError.new end else asset_local = asset_statement.location check_asset_path(asset_local) end if not @local_only @operating_system.upload(asset_local, asset_remote) end @operating_system.copy( asset_local, @local_directory_for_package + '/' + asset_name ) if asset_statement.is_a?(Fig::Statement::Archive) @operating_system.unpack_archive( @runtime_for_package, File.absolute_path(asset_local) ) else @operating_system.copy( asset_local, @runtime_for_package + '/' + asset_name ) end return end def add_unparsed_text() if @source_package && @source_package.unparsed_text @text_assembler.add_footer '' @text_assembler.add_footer '# Original, unparsed package text:' @text_assembler.add_footer '#' @text_assembler.add_footer( @source_package.unparsed_text.gsub(/^(?=[^\n]+$)/, '# ').gsub(/^$/, '#') ) end return end def notify_listeners() publish_information = {} publish_information[:descriptor] = @descriptor publish_information[:time] = @publish_time publish_information[:login] = @publish_login publish_information[:host] = @publish_host # Ensure that we've really got booleans and not merely true or false # values. publish_information[:was_forced] = @was_forced ? true : false publish_information[:local_only] = @local_only ? true : false publish_information[:local_destination] = @local_directory_for_package publish_information[:remote_destination] = @remote_directory_for_package @publish_listeners.each do |listener| listener.published(publish_information) end return end def publish_temp_dir() File.join(@base_temp_dir, 'publish') end def check_asset_path(asset_path) if not File.exist?(asset_path) Fig::Logging.fatal "Could not find file #{asset_path}." raise Fig::RepositoryError.new end return end def check_asset_paths(asset_paths) non_existing_paths = asset_paths.select {|path| ! File.exist?(path) && ! File.symlink?(path) } if not non_existing_paths.empty? if non_existing_paths.size > 1 Fig::Logging.fatal "Could not find files: #{ non_existing_paths.join(', ') }" else Fig::Logging.fatal "Could not find file #{non_existing_paths[0]}." end raise Fig::RepositoryError.new end return end def check_published_environment_variables(published_package) published_package.walk_statements do |statement| if statement.is_environment_variable? tokenized_value = statement.tokenized_value expansion_happened = false expanded_value = tokenized_value.to_expanded_string { expansion_happened = true; published_package.runtime_directory } if expansion_happened && ! File.exists?(expanded_value) && ! File.symlink?(expanded_value) Fig::Logging.warn( %Q<The #{statement.name} variable points to a path that does not exist (#{expanded_value}); retrieve statements that are active when this package is included may fail.> ) end end end return end # 'paths' is an Array of fileglob patterns: ['tmp/foo/file1', # 'tmp/foo/*.jar'] def expand_globs_from(paths) expanded_files = [] paths.each do |path| globbed_files = Dir.glob(path) if globbed_files.empty? expanded_files << path else expanded_files.concat(globbed_files) end end return expanded_files end end
klimkin/fig
spec/command/publishing_retrieval_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fig/operating_system' describe 'Fig' do describe 'publishing/retrieval' do let(:publish_from_directory) { "#{FIG_SPEC_BASE_DIRECTORY}/publish-home" } let(:lib_directory) { "#{publish_from_directory}/lib" } let(:retrieve_directory) { "#{CURRENT_DIRECTORY}/retrieve" } before(:each) do clean_up_test_environment FileUtils.mkdir_p CURRENT_DIRECTORY FileUtils.mkdir_p lib_directory end describe 'retrieves resources' do before(:each) do write_file("#{lib_directory}/a library", 'some library') another_library = "#{lib_directory}/another library" url = 'file://' + File.expand_path(another_library) write_file(another_library, 'some other library') fig( [ '--publish', 'prerequisite/1.2.3', '--resource', 'lib/a library', '--resource', url, '--append', 'FOOPATH=@/lib/a library', '--append', 'FOOPATH=@/another library' ].flatten, :current_directory => publish_from_directory ) end it 'and produces absolute path warning' do input = <<-END # Leading slash on path to test warning. retrieve FOOPATH->/retrieve/[package] config default include prerequisite/1.2.3 end END out, err = fig(%w<--update-if-missing>, input) File.read("#{retrieve_directory}/prerequisite/a library").should == 'some library' File.read("#{retrieve_directory}/prerequisite/another library").should == 'some other library' # Check for warning about the leading slash in FOOPATH looking like an # absolute path. err.should =~ /absolute/ err.should =~ /relative/ err.should =~ %r</retrieve/\[package\]> end it 'and ignores the append statement in the updating config' do input = <<-END retrieve FOOPATH->retrieve/[package] config default include prerequisite/1.2.3 append FOOPATH=@/does/not/exist end END fig(%w<--update-if-missing>, input) File.read("#{retrieve_directory}/prerequisite/a library").should == 'some library' File.read("#{retrieve_directory}/prerequisite/another library").should == 'some other library' end it 'and can tell you where they came from' do input = <<-END retrieve FOOPATH->retrieve/[package] config default include prerequisite/1.2.3 end END out, * = fig( [ '--update-if-missing', '--source-package', "#{retrieve_directory}/prerequisite/a library", ], input ) out.should == 'prerequisite/1.2.3' end end it 'retrieves resource that is a directory' do write_file("#{lib_directory}/a library", 'some library') # To copy the contents of a directory, instead of the directory itself, # use '/.' as a suffix to the directory name in 'append'. input = <<-END grammar v1 resource 'lib/a library' config default append FOOPATH=@/lib/. end END fig( %w<--publish prerequisite/1.2.3>, input, :current_directory => publish_from_directory ) input = <<-END retrieve FOOPATH->retrieve/[package] config default include prerequisite/1.2.3 end END fig(%w<--update-if-missing>, input) File.read("#{retrieve_directory}/prerequisite/a library").should == 'some library' end it 'reports error for missing file in a package' do write_file("#{lib_directory}/a library", 'some library') fig( [ %w< --publish prerequisite/1.2.3 >, '--resource', 'lib/a library', '--append', 'FOOPATH=@/lib/a library', ], :current_directory => publish_from_directory ) FileUtils.rm("#{FIG_HOME}/runtime/prerequisite/1.2.3/lib/a library") input = <<-END retrieve FOOPATH->retrieve/[package] config default include prerequisite/1.2.3 end END out, err, exit_code = fig( %w<--update-if-missing>, input, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r<the FOOPATH variable points to a path that does not exist>i end it 'reports error for retrieve of source and destination being the same path' do fig(%w<--publish prerequisite/1.2.3 --set SOME_PATH=.>) input = <<-END retrieve SOME_PATH->. config default include prerequisite/1.2.3 end END out, err = fig(%w<--update-if-missing>, input) err.should =~ %r<skipping copying>i err.should =~ %r<" [.] ">x err.should =~ %r<to itself>i end it %q<preserves the path after '//' when copying files into your project directory while retrieving> do include_directory = "#{publish_from_directory}/include" FileUtils.mkdir_p(include_directory) write_file("#{include_directory}/hello.h", 'a header file') write_file("#{include_directory}/hello2.h", 'another header file') input = <<-END resource include/hello.h resource include/hello2.h config default append INCLUDE=@//include/hello.h append INCLUDE=@//include/hello2.h end END fig( %w<--publish prerequisite/1.2.3>, input, :current_directory => publish_from_directory ) input = <<-END retrieve INCLUDE->include2/[package] config default include prerequisite/1.2.3 end END fig %w<--update>, input File.read( "#{CURRENT_DIRECTORY}/include2/prerequisite/include/hello.h" ).should == 'a header file' File.read( "#{CURRENT_DIRECTORY}/include2/prerequisite/include/hello2.h" ).should == 'another header file' end it 'updates without there being a copy of the package in the FIG_HOME left there from publishing' do include_directory = "#{publish_from_directory}/include" FileUtils.mkdir_p(include_directory) write_file("#{include_directory}/hello.h", 'a header file') write_file("#{include_directory}/hello2.h", 'another header file') input = <<-END resource include/hello.h resource include/hello2.h config default append INCLUDE=@/include/hello.h append INCLUDE=@/include/hello2.h end END fig( %w<--publish prerequisite/1.2.3>, input, :current_directory => publish_from_directory ) FileUtils.rm_rf FIG_HOME input = <<-END retrieve INCLUDE->include2/[package] config default include prerequisite/1.2.3 end END fig %w<-u>, input File.read( "#{CURRENT_DIRECTORY}/include2/prerequisite/hello.h" ).should == 'a header file' File.read( "#{CURRENT_DIRECTORY}/include2/prerequisite/hello2.h" ).should == 'another header file' end it 'packages multiple resources' do write_file("#{lib_directory}/a library", 'some library') write_file("#{lib_directory}/a library2", 'some other library') input = <<-END grammar v1 resource 'lib/a library' resource 'lib/a library2' config default append FOOPATH="@/lib/a library" append FOOPATH="@/lib/a library2" end END fig( %w<--publish prerequisite/1.2.3>, input, :current_directory => publish_from_directory ) input = <<-END retrieve FOOPATH->retrieve/[package] config default include prerequisite/1.2.3 end END fig(%w<-m>, input) File.read("#{retrieve_directory}/prerequisite/a library").should == 'some library' File.read("#{retrieve_directory}/prerequisite/a library2").should == 'some other library' end it 'packages multiple resources with wildcards' do write_file("#{lib_directory}/foo.jar", 'some library') write_file("#{lib_directory}/bar.jar", 'some other library') input = <<-END resource **/*.jar config default append FOOPATH=@/lib/foo.jar end END fig( %w<--publish prerequisite/1.2.3>, input, :current_directory => publish_from_directory ) input = <<-END retrieve FOOPATH->retrieve/[package] config default include prerequisite/1.2.3 end END fig(%w<--update-if-missing>, input) File.read("#{retrieve_directory}/prerequisite/foo.jar").should == 'some library' end if Fig::OperatingSystem.unix? it 'can publish and retrieve dangling symlinks' do FileUtils.rm_rf(publish_from_directory) FileUtils.mkdir_p(publish_from_directory) File.symlink( 'does-not-exist', "#{publish_from_directory}/dangling-symlink" ) input = <<-END resource dangling-symlink config default set TEST_FILE=@/dangling-symlink end END fig( %w<--publish dependency/1.2.3>, input, :current_directory => publish_from_directory ) FileUtils.rm_rf(publish_from_directory) FileUtils.mkdir_p(publish_from_directory) input = <<-END retrieve TEST_FILE->. config default include dependency/1.2.3 end END fig( %w<--publish dependent/1.2.3>, input, :current_directory => publish_from_directory ) FileUtils.rm_rf(FIG_HOME) File.exist?("#{CURRENT_DIRECTORY}/dangling-symlink") and fail 'Symlink should not exist prior to using package.' fig(%w<--update dependent/1.2.3 -- echo>) File.symlink?("#{CURRENT_DIRECTORY}/dangling-symlink") or fail 'Symlink should exist after using package.' end end describe 'cleanup' do let(:cleanup_dependency_basename) { 'from-dependency.txt' } let(:cleanup_dependency_file) { "#{CURRENT_DIRECTORY}/#{cleanup_dependency_basename}" } before(:each) do FileUtils.rm_rf(publish_from_directory) FileUtils.mkdir_p(publish_from_directory) FileUtils.touch "#{publish_from_directory}/#{cleanup_dependency_basename}" input = <<-END resource #{cleanup_dependency_basename} config default set TEST_FILE=@/#{cleanup_dependency_basename} end END fig( %w<--publish dependency/1.2.3>, input, :current_directory => publish_from_directory ) FileUtils.rm_rf(publish_from_directory) FileUtils.mkdir_p(publish_from_directory) input = <<-END retrieve TEST_FILE->. config default include dependency/1.2.3 end END fig( %w<--publish alpha/1.2.3>, input, :current_directory => publish_from_directory ) fig( %w< --publish beta/1.2.3 --no-file --set set_something=so-we-have-some-content > ) File.exist?(cleanup_dependency_file) and fail 'File should not exist prior to using alpha.' fig(%w<--update alpha/1.2.3 -- echo>) File.exist?(cleanup_dependency_file) or fail 'File should exist after using alpha.' end it 'happens with --update' do fig(%w<--update beta/1.2.3 -- echo>) File.exist?(cleanup_dependency_file) and fail 'File should not exist after using beta.' end it 'does not happen with --update and --suppress-cleanup-of-retrieves' do fig(%w<--update --suppress-cleanup-of-retrieves beta/1.2.3 -- echo>) File.exist?(cleanup_dependency_file) or fail 'File should exist after using beta.' end it 'does not happen without --update' do fig(%w<beta/1.2.3 -- echo>) File.exist?(cleanup_dependency_file) or fail 'File should exist after using beta.' end end it 'warns on unused retrieval' do set_up_test_environment() input = <<-END retrieve UNREFERENCED_VARIABLE->somewhere config default set WHATEVER=SOMETHING end END out, err, exit_code = fig(%w<--update-if-missing>, input) err.should =~ /UNREFERENCED_VARIABLE.*was never referenced.*retrieve UNREFERENCED_VARIABLE->somewhere.*was ignored/ end end end
klimkin/fig
spec/command/grammar_retrieve_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/grammar_spec_helper') describe 'Fig' do before(:each) do clean_up_test_environment set_up_test_environment end describe %q<uses the correct grammar version in the package definition created for publishing> do it 'from v1 file input with a simple, unquoted retrieve statement' do check_published_grammar_version 0, <<-'END' grammar v1 retrieve variable->value END end it 'from v1 file input with a simple, single-quoted retrieve statement (v1 currently, should change to v0 eventually)' do check_published_grammar_version 0, <<-'END' grammar v1 retrieve variable->'value' END end it 'from v1 file input with a package-expanded, single-quoted retrieve statement' do check_published_grammar_version 0, <<-'END' grammar v1 retrieve variable->"value[package]value" END end it 'from v1 file input with package-escaped, single-quoted retrieve statement' do # Backslashes are not allowed in v0 grammar, at all. Not even to escape # "[package]". check_published_grammar_version 1, <<-'END' grammar v1 retrieve variable->"value\[package]value" END end it 'from v1 file input with a retrieve statement containing whitespace' do check_published_grammar_version 1, <<-'END' grammar v1 retrieve variable->"some value" END end it 'from v1 file input with a retrieve statement containing an octothorpe' do check_published_grammar_version 1, <<-'END' grammar v1 retrieve variable->"some#value" END end end it %q<considers a retrieve path containing an unescaped square bracket that is not followed by "package]" to be a syntax error> do input = <<-'END' grammar v1 retrieve variable->value[something]value END out, err, exit_code = fig( %w< --publish foo/1.2.3 >, input, :no_raise_on_error => true, :fork => false ) err.should =~ /\[something\]/ out.should == '' exit_code.should_not == 0 end end # vim: set fileencoding=utf8 :
klimkin/fig
lib/fig/command/action/list_variables.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListVariables include Fig::Command::Action include Fig::Command::Action::Role::HasSubAction def options() if sub_action return sub_action.options end return %w<--list-variables> end def reset_environment?() return true end # Is this --list-variables? def list_variables?() return true end end
klimkin/fig
spec/repository_spec.rb
<reponame>klimkin/fig # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'fig/application_configuration' require 'fig/command/options' require 'fig/file_not_found_error' require 'fig/logging' require 'fig/package_descriptor' require 'fig/repository' require 'fig/repository_error' require 'fig/statement/configuration' require 'fig/statement/path' def create_local_repository() application_config = Fig::ApplicationConfiguration.new() application_config.base_whitelisted_url = FIG_REMOTE_URL application_config.remote_repository_url = FIG_REMOTE_URL parser = Fig::Parser.new(application_config, false) repository = Fig::Repository.new( application_config, Fig::Command::Options.new, Fig::OperatingSystem.new(nil), FIG_HOME, FIG_REMOTE_URL, parser, [], # publish listeners ) repository.update_if_missing return repository end def generate_package_statements parsed_name, parsed_value = Fig::Statement::Path.parse_name_value 'FOO=bar' path_statement = Fig::Statement::Path.new(nil, nil, parsed_name, parsed_value) configuration_statement = Fig::Statement::Configuration.new( nil, nil, Fig::Package::DEFAULT_CONFIG, [path_statement] ) package_statements = [configuration_statement] return package_statements end describe 'Repository' do before(:each) do clean_up_test_environment set_up_test_environment end it 'cleans a package from the repository' do repository = create_local_repository repository.list_packages.include?('foo/1.0.0').should be_false package_statements = generate_package_statements descriptor = Fig::PackageDescriptor.new('foo', '1.0.0', nil) repository.publish_package(package_statements, descriptor, false, nil, false) repository.list_packages.include?('foo/1.0.0').should be_true repository.clean(descriptor) repository.list_packages.include?('foo/1.0.0').should be_false end describe 'handles errors while installing packages' do it %q<that don't exist> do repository = create_local_repository repository.stub(:install_package) do raise Fig::FileNotFoundError.new('test FileNotFoundError', 'fake path') end # Evil knowledge of implementation: repository.instance_variable_set(:@updating_package_definition, true) Fig::Logging.should_receive(:fatal).with( /package.*package-name.*not found/i ) descriptor = Fig::PackageDescriptor.new( 'package-name', 'package-version', nil ) expect { repository.get_package(descriptor) }.to raise_error(Fig::RepositoryError) end it 'that have some sort of installation issue' do repository = create_local_repository exception_message = 'test StandardError' repository.stub(:install_package) do raise StandardError.new(exception_message) end Fig::Logging.should_receive(:fatal).with( %r<install of package-name/package-version failed.*#{exception_message}>i ) descriptor = Fig::PackageDescriptor.new( 'package-name', 'package-version', nil ) expect { repository.get_package(descriptor) }.to raise_error(Fig::RepositoryError) end end end
klimkin/fig
lib/fig/deparser/v2.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/deparser' require 'fig/deparser/v1_base' module Fig; end module Fig::Deparser; end # Handles serializing of statements in the v2 grammar. class Fig::Deparser::V2 include Fig::Deparser include Fig::Deparser::V1Base def initialize( emit_as_input_or_to_be_published_values, indent_string = ' ' * 2, initial_indent_level = 0 ) @emit_as_input_or_to_be_published_values = emit_as_input_or_to_be_published_values @indent_string = indent_string @initial_indent_level = initial_indent_level return end def grammar_version(statement) add_indent @text << "grammar v2\n\n" return end def include_file(statement) path = statement.path quote = (path.include?(%q<'>) && ! path.include?(%q<">)) ? %q<"> : %q<'> add_indent @text << 'include-file ' @text << quote @text << path.gsub('\\', ('\\' * 4)).gsub(quote, "\\\\#{quote}") @text << quote if ! statement.config_name.nil? @text << ':' @text << statement.config_name end @text << "\n" return end def grammar_description() return 'v2' end end
klimkin/fig
lib/fig/logging.rb
<reponame>klimkin/fig # coding: utf-8 require 'log4r' require 'log4r/configurator' require 'log4r/yamlconfigurator' require 'fig/config_file_error' require 'fig/log4r_config_error' require 'fig/log4r/outputter' module Fig; end # Logging facility that handles the fact that we may wish to do logging prior # to Log4r being properly configured. module Fig::Logging if not Log4r::Logger['initial'] @@logger = Log4r::Logger.new('initial') end STRING_TO_LEVEL_MAPPING = { 'off' => Log4r::OFF, 'fatal' => Log4r::FATAL, 'error' => Log4r::ERROR, 'warn' => Log4r::WARN, 'info' => Log4r::INFO, 'debug' => Log4r::DEBUG, 'all' => Log4r::ALL } def self.initialize_pre_configuration(log_to_stdout, log_level) log_level ||= 'info' assign_log_level(@@logger, log_level) setup_default_outputter(@@logger, log_to_stdout) end def self.initialize_post_configuration( config_file, log_to_stdout, log_level, suppress_default_configuration = false ) if config_file begin case config_file when / [.] xml \z /x Log4r::Configurator.load_xml_file(config_file) when / [.] ya?ml \z /x Log4r::YamlConfigurator.load_yaml_file(config_file) else raise Fig::ConfigFileError, %Q<Don't know what format #{config_file} is in.>, config_file end if Log4r::Logger['fig'].nil? $stderr.puts %q<A value was provided for --log-config but no "fig" logger was defined.> end rescue Log4r::ConfigError, ArgumentError => exception raise Fig::Log4rConfigError.new(config_file, exception) end end if Log4r::Logger['fig'].nil? @@logger = Log4r::Logger.new('fig') else @@logger = Log4r::Logger['fig'] end if not config_file and not suppress_default_configuration assign_log_level(@@logger, 'info') setup_default_outputter(@@logger, log_to_stdout) end assign_log_level(@@logger, log_level) return end def self.fatal(data = nil, propagated = nil) @@logger.fatal data, propagated end def self.fatal?() return @@logger.fatal? end def self.error(data = nil, propagated = nil) @@logger.error data, propagated end def self.error?() return @@logger.error? end def self.warn(data = nil, propagated = nil) @@logger.warn data, propagated end def self.warn?() return @@logger.warn? end def self.info(data = nil, propagated = nil) @@logger.info data, propagated end def self.info?() return @@logger.info? end def self.debug(data = nil, propagated = nil) @@logger.debug data, propagated end def self.debug?() return @@logger.debug? end private def self.assign_log_level(logger, string_level) return if string_level.nil? level = STRING_TO_LEVEL_MAPPING[string_level.downcase] logger.level = level logger.outputters.each { | outputter | outputter.level = level } return end def self.setup_default_outputter(logger, log_to_stdout) if log_to_stdout outputter = Fig::Log4r::Outputter.new('fig stdout', $stdout) else outputter = Fig::Log4r::Outputter.new('fig stderr', $stderr) end logger.add outputter outputter.formatter = Log4r::PatternFormatter.new :pattern => '%M' return end end
klimkin/fig
lib/fig/statement/retrieve.rb
<gh_stars>10-100 # coding: utf-8 require 'fig/logging' require 'fig/operating_system' require 'fig/statement' module Fig; end # Specifies that files from a package should be copied into the current # directory when an environment variable has its value changed. class Fig::Statement::Retrieve < Fig::Statement def self.tokenize_path(path, &error_block) tokenizer = Fig::StringTokenizer.new TOKENIZING_SUBEXPRESSION_MATCHER, '\\[' return tokenizer.tokenize path, &error_block end attr_reader :variable attr_reader :tokenized_path def initialize(line_column, source_description, variable, tokenized_path) super(line_column, source_description) @variable = variable @tokenized_path = tokenized_path path = tokenized_path.to_escaped_string # Yeah, it's not cross-platform, but File doesn't have an #absolute? method # and this is better than nothing. if ( path =~ %r< ^ [\\/] >x \ || Fig::OperatingSystem.windows? && path =~ %r< ^ [a-z] : >xi ) Fig::Logging.warn( %Q<The retrieve path "#{path}"#{position_string()} looks like it is intended to be absolute; retrieve paths are always treated as relative.> ) end end def statement_type() return 'retrieve' end def loaded_but_not_referenced?() return added_to_environment? && ! referenced? end def added_to_environment?() return @added_to_environment end def added_to_environment(yea_or_nay) @added_to_environment = yea_or_nay end def referenced?() return @referenced end def referenced(yea_or_nay) @referenced = yea_or_nay end def deparse_as_version(deparser) return deparser.retrieve(self) end def minimum_grammar_for_emitting_input() return minimum_grammar() end def minimum_grammar_for_publishing() return minimum_grammar() end private def minimum_grammar() path = tokenized_path.to_escaped_string if path =~ /\s/ return [1, 'contains whitespace'] end # Can't have octothorpes anywhere in v0 due to comment stripping via # regex. if path =~ /#/ return [1, 'contains a comment ("#") character'] end if path =~ %r< ' >x return [1, %Q<contains a single quote character>] end if path =~ %r< " >x return [1, %Q<contains a double quote character>] end if path =~ %r< ( [^a-zA-Z0-9_/.\[\]-] ) >x return [1, %Q<contains a "#{$1}" character>] end return [0] end TOKENIZING_SUBEXPRESSION_MATCHER = [ { # Shortest sequence of characters that starts with an open square bracket # and ends with either a close square bracket or end of string. :pattern => %r< \[ [^\]]* \]? >x, :action => lambda { |subexpression, error_block| if subexpression == '[package]' return Fig::TokenizedString::Token.new :package_path, '[package]' end error_block.call \ %q<contains an unescaped "[" that is not followed by "ackage]".> return } } ] end
klimkin/fig
lib/fig/statement.rb
<reponame>klimkin/fig # coding: utf-8 require 'set' module Fig; end # A statement within a package definition file (package.fig). class Fig::Statement ENVIRONMENT_VARIABLE_NAME_REGEX = %r< \A \w+ \z >x def self.position_description(line, column, source_description) if not line or not column return '' if not source_description return " (#{source_description})" end description = " (line #{line}, column #{column}" if source_description description << ", #{source_description}" end description << ')' return description end attr_reader :line, :column, :source_description # This mess of getting these as a single array necessary is due to # limitations of the "*" array splat operator in ruby v1.8. def initialize(line_column, source_description) if line_column @line, @column = *line_column end @source_description = source_description end # A name for this kind of Statement, usually a keyword for this statement as # it appears in package definition files. def statement_type() raise NotImplementedError.new self.class.name end # Block will receive a Statement. def walk_statements(&block) return end def deparse_as_version(deparser) raise NotImplementedError.new self.class.name end # Returns a two element array containing the version and an explanation of # why the version is necessary if the version is greater than 0. def minimum_grammar_for_emitting_input() raise NotImplementedError.new self.class.name end # Returns a two element array containing the version and an explanation of # why the version is necessary if the version is greater than 0. def minimum_grammar_for_publishing() raise NotImplementedError.new self.class.name end def urls() return [] end def is_asset?() return false end def is_environment_variable?() return false end # Returns a representation of the position of this statement, if the position # is known, empty string otherwise. This is written with the idea that you # can do something like "puts %Q<Found a # statement%{statement.position_string()}.>" and get nice looking output # regardless of whether the position is actually known or not. def position_string return Fig::Statement.position_description( @line, @column, @source_description ) end end # vim: set fileencoding=utf8 :
klimkin/fig
spec/command_options_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'fig/command/option_error' require 'fig/command/options' def new_options(argv) options = Fig::Command::Options.new() options.process_command_line(argv) return options end def check_environment_variable_option(option_name) it 'complains if there is no variable name' do expect_invalid_value_error(option_name, '=whatever') end it 'accepts a simple variable value' do new_options(["--#{option_name}", 'variable=value']) # no exception end it 'complains if there are unbalanced single quotes' do expect_invalid_value_error(option_name, %q<'>) end it 'allows a variable value containing an escaped single quote' do new_options( ["--#{option_name}", %q<variable=\'>] ) # no exception end it 'complains if there are unbalanced double quotes' do expect_invalid_value_error(option_name, %q<">) end it 'allows a variable value containing an escaped double quote' do new_options( ["--#{option_name}", %q<variable=\">] ) # no exception end it 'allows a variable value containing a space character' do new_options( ["--#{option_name}", 'variable= stuff'] ) # no exception end it 'allows a variable value containing an octothorpe' do new_options( ["--#{option_name}", 'variable=red#green#blue'] ) # no exception end end describe 'Command::Options' do def expect_invalid_value_error(option_name, value) expect { new_options(["--#{option_name}", value]) }.to raise_error( Fig::Command::OptionError, %r<\AInvalid value for --#{option_name}: "#{Regexp.quote(value)}"> ) end describe %q<complains if a value isn't given to> do [ %w< get >, # Queries %w< set add append include override >, # Environment %w< archive resource >, # Package contents %w< file config log-level figrc > # Configuration ].flatten.each do |option_name| describe "--#{option_name}" do it 'when it is the last option on the command-line' do expect { new_options(["--#{option_name}"]) }.to raise_error( Fig::Command::OptionError, "Please provide a value for --#{option_name}." ) end describe 'when it is followed by' do # One long option example and one short option example. %w< --version -c >.each do |following_option| it following_option do expect { new_options( ["--#{option_name}", following_option]) }.to raise_error( Fig::Command::OptionError, "Please provide a value for --#{option_name}." ) end end end end end end describe '--file' do { 'a' => 'a single character', 'x-' => 'a name without a hyphen at the front', '-' => 'the stdin indicator' }.each do |option_value, description| it %Q<allows #{description} ("#{option_value}") as a value> do options = new_options(['--file', option_value]) options.package_definition_file.should == option_value end end end describe '--set' do check_environment_variable_option('set') it 'allows the absence of an equals sign' do new_options(%w< --set whatever >) # no exception end it 'allows an empty value' do new_options(%w< --set whatever= >) # no exception end end %w< append add >.each do |option_name| describe "--#{option_name}" do check_environment_variable_option(option_name) it 'complains if there is no variable value' do expect_invalid_value_error(option_name, 'whatever=') end %w[ ; : < > | ].each do |character| # Need to check this because they are not allowed in the v0 grammar. it %Q<allows a variable value containing "#{character}"> do new_options( ["--#{option_name}", "variable=#{character}"] ) # no exception end end end end %w< archive resource >.each do |asset_type| describe "--#{asset_type}" do it 'complains if there is no value' do expect_invalid_value_error(asset_type, '') end %w[ " ' ].each do |character| it %Q<complains about a value containing unbalanced «#{character}»> do expect_invalid_value_error(asset_type, character) end it "accepts a value quoted by «#{character}»" do new_options(["--#{asset_type}", "#{character}x#{character}"]) # no exception end it "accepts a value with an escaped «#{character}»" do new_options(["--#{asset_type}", "x\\#{character}x"]) # no exception end end # Just to check that people don't think that "@" is a special character # here. it %Q<complains about a value containing escaped «@»> do expect_invalid_value_error(asset_type, '\\@') end end end end # vim: set fileencoding=utf8 :
klimkin/fig
lib/fig/command/action/version_plain.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig' require 'fig/command' require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::VersionPlain include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--version-plain> end def execute_immediately_after_command_line_parse? return true end def configure(options) @version_plain = options.version_plain end def execute() print @version_plain || Fig::VERSION return EXIT_SUCCESS end end
klimkin/fig
lib/fig/command/action/role/list_base_config.rb
<gh_stars>10-100 # coding: utf-8 module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListBaseConfig def list_all_configs? return false end def base_display_config_names() return [@execution_context.base_config] end end
klimkin/fig
lib/fig/figrc.rb
<gh_stars>0 # coding: utf-8 require 'json' require 'fig/application_configuration' require 'fig/config_file_error' require 'fig/file_not_found_error' require 'fig/operating_system' require 'fig/repository' module Fig; end # Parse multiple figrc files and assemble them into a single # ApplicationConfiguration object. class Fig::FigRC REPOSITORY_CONFIGURATION = "#{Fig::Repository::METADATA_SUBDIRECTORY}/figrc" def self.find( override_path, specified_repository_url, operating_system, fig_home, disable_figrc = false, disable_remote_figrc = false ) configuration = Fig::ApplicationConfiguration.new() handle_override_configuration(configuration, override_path) handle_figrc(configuration) if not disable_figrc repository_url = derive_repository_url(specified_repository_url, configuration) configuration.base_whitelisted_url = repository_url configuration.remote_repository_url = repository_url handle_repository_configuration( configuration, repository_url, operating_system, fig_home ) if not disable_remote_figrc return configuration end private def self.handle_override_configuration(configuration, override_path) begin if not override_path.nil? configuration_text = File::open(override_path).read if configuration_text.length > 0 configuration.push_dataset JSON.parse(configuration_text) end end rescue JSON::ParserError => exception translate_parse_error(exception, override_path) end return end def self.handle_figrc(configuration) user_figrc_path = File.expand_path('~/.figrc') return if not File.exists? user_figrc_path begin configuration_text = File::open(user_figrc_path).read configuration.push_dataset JSON.parse(configuration_text) rescue JSON::ParserError => exception translate_parse_error(exception, user_figrc_path) end return end def self.derive_repository_url(specified_repository_url, configuration) if specified_repository_url.nil? return configuration['default FIG_REMOTE_URL'] end if specified_repository_url.empty? || specified_repository_url =~ /\A\s*\z/ return nil end return specified_repository_url end def self.handle_repository_configuration( configuration, repository_url, operating_system, fig_home ) return if repository_url.nil? figrc_url = "#{repository_url}/#{REPOSITORY_CONFIGURATION}" repo_figrc_path = File.expand_path(File.join(fig_home, REPOSITORY_CONFIGURATION)) repo_config_exists = nil begin operating_system.download figrc_url, repo_figrc_path, :prompt_for_login repo_config_exists = true rescue Fig::FileNotFoundError repo_config_exists = false end return if not repo_config_exists begin configuration_text = File.open(repo_figrc_path).read configuration.push_dataset JSON.parse(configuration_text) rescue JSON::ParserError => exception translate_parse_error(exception, figrc_url) end return end def self.translate_parse_error(json_parse_error, config_file_path) message = json_parse_error.message message.chomp! # JSON::ParserError tends to include final newline inside of single # quotes, which makes error messages ugly. message.sub!(/ \n+ ' \z /xm, %q<'>) # Also, there's a useless source code line number in the message. message.sub!(/ \A \d+ : \s+ /xm, %q<>) raise Fig::ConfigFileError.new( "Parse issue with #{config_file_path}: #{message}", config_file_path ) end end
klimkin/fig
lib/fig/command/action/role/list_as_yaml.rb
# coding: utf-8 require 'yaml' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end # Requires a #set_up_object_to_be_serialized method. module Fig::Command::Action::Role::ListAsYAML def execute() set_up_object_to_be_serialized YAML.dump @object_to_be_serialized, $stdout return Fig::Command::Action::EXIT_SUCCESS end end
klimkin/fig
lib/fig/statement/asset.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/statement' require 'fig/string_tokenizer' require 'fig/url' module Fig; end class Fig::Statement; end # Some sort of file to be included in a package. module Fig::Statement::Asset attr_reader :location def self.included(class_included_into) class_included_into.extend(ClassMethods) return end def glob_if_not_url?() return @glob_if_not_url end def urls() return [location()] end def is_asset?() return true end def requires_globbing?() return glob_if_not_url? && ! Fig::URL.is_url?(location()) end def standard_asset_name() # Not so hot of an idea if the location is a URL and has query parameters # in it, but not going to fix this now. basename = location().split('/').last if Fig::URL.is_url? location return CGI.unescape basename end return basename end def minimum_grammar_for_emitting_input() return minimum_grammar_for_value location end def minimum_grammar_for_publishing() return minimum_grammar_for_value asset_name end private def minimum_grammar_for_value(value) return [0] if value.nil? if value =~ /\s/ return [1, 'contains whitespace'] end # Can't have octothorpes anywhere in v0 due to comment stripping via # regex. if value =~ /#/ return [1, 'contains a "#" character'] end if ! glob_if_not_url? && value =~ / ( [*?\[\]{}] ) /x return [ 1, %Q<contains a glob character ("#{$1}") which should not be globbed> ] end if value =~ / ( ["'<>|] ) /x return [1, %Q<contains a "#{$1}" character>] end return [0] end module ClassMethods def validate_and_process_escapes_in_location(location, &block) return Fig::StringTokenizer.new.tokenize(location, &block) end end end
klimkin/fig
lib/fig/command/action/list_dependencies.rb
<gh_stars>10-100 # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListDependencies include Fig::Command::Action include Fig::Command::Action::Role::HasSubAction def options() if sub_action return sub_action.options end return %w<--list-dependencies> end # Is this --list-dependencies? def list_dependencies?() return true end end
klimkin/fig
lib/fig/statement/grammar_version.rb
<filename>lib/fig/statement/grammar_version.rb # coding: utf-8 require 'fig/statement' module Fig; end # A statement that declares the syntax that a package is to be serialized in. class Fig::Statement::GrammarVersion < Fig::Statement attr_reader :version def initialize(line_column, source_description, version) super(line_column, source_description) @version = version end def statement_type() return 'grammar' end def deparse_as_version(deparser) return deparser.grammar_version(self) end def minimum_grammar_for_emitting_input() return [version] end def minimum_grammar_for_publishing() return [version] end end
klimkin/fig
lib/fig/statement/include.rb
<reponame>klimkin/fig<filename>lib/fig/statement/include.rb # coding: utf-8 require 'fig/package_descriptor' require 'fig/statement' module Fig; end # Dual role: "include :configname" incorporates one configuration into another; # "include package[/version]" declares a dependency upon another package (with # incorporation of the "default" configuration from that other package if no # ":configname" is specified. class Fig::Statement::Include < Fig::Statement attr_reader :descriptor attr_reader :included_package attr_reader :containing_package_descriptor # Centralized definition of requirements for descriptors for include # statements. def self.parse_descriptor(raw_string, options = {}) return Fig::PackageDescriptor.parse(raw_string, options) end def initialize( line_column, source_description, descriptor, included_package, # For synthetic Package for command-line options. containing_package_descriptor ) super(line_column, source_description) @descriptor = descriptor @included_package = included_package @containing_package_descriptor = containing_package_descriptor end def statement_type() return 'include' end def package_name return @descriptor.name end def version return @descriptor.version end def config_name return @descriptor.config end def complain_if_version_missing() if @descriptor.name && ! @descriptor.version message = %Q<No version in the package descriptor of "#{@descriptor.name}" in an include statement> if @containing_package_descriptor package_string = @containing_package_descriptor.to_string() if package_string && package_string != '' message += %Q< in the .fig file for "#{package_string}"> end end message += %Q<#{position_string()}. Whether or not the include statement will work is dependent upon the recursive dependency load order.> Fig::Logging.warn(message) end end # Assume that this statement is part of the parameter and return a descriptor # that represents the fully resolved dependency, taking into account that the # version might have been overridden. def resolved_dependency_descriptor(containing_package, backtrace) return Fig::PackageDescriptor.new( referenced_package_name(containing_package), referenced_version(containing_package, backtrace), referenced_config_name() ) end def deparse_as_version(deparser) return deparser.include(self) end def minimum_grammar_for_emitting_input() return minimum_grammar end def minimum_grammar_for_publishing() return minimum_grammar end private def referenced_package_name(containing_package) return package_name() || containing_package.name() end def referenced_version(containing_package, backtrace) package_name = nil original_version = nil if package_name() package_name = package_name() original_version = version() else package_name = containing_package.name() original_version = containing_package.version() end return backtrace.get_override(package_name, original_version) end def referenced_config_name() config_name() || Fig::Package::DEFAULT_CONFIG end def minimum_grammar() if included_package raise 'Cannot deparse synthetic include statement with directly referenced package.' end return [0] end end
klimkin/fig
lib/fig/environment_variables/case_sensitive.rb
# coding: utf-8 require 'fig/environment_variables' module Fig; end; module Fig::EnvironmentVariables; end # Manager of a set of environment variables where the variable names are # case-sensitive, e.g. on *nix. class Fig::EnvironmentVariables::CaseSensitive include Fig::EnvironmentVariables def [](key) return @variables[key] end def []=(new_key, new_value) @variables[new_key] = new_value return end def prepend_variable(key, new_value) if @variables.key?(key) @variables[key] = new_value + File::PATH_SEPARATOR + @variables[key] else @variables[key] = new_value end return end end
klimkin/fig
spec/command/command_line_vs_package_spec.rb
<reponame>klimkin/fig # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do before(:each) do clean_up_test_environment set_up_test_environment end describe 'command-line options vs package files' do it %q<gives a "--set" option priority over a "set" statement> do input = <<-END config default set TEST=package.fig end END fig(%w<--set TEST=command-line --get TEST>, input)[0].should == 'command-line' end it %q<gives an "--add" option priority over an "append" statement> do input = <<-END config default add TEST_PATH=package.fig end END fig(%w<--append TEST_PATH=command-line --get TEST_PATH>, input)[0].should == "command-line#{File::PATH_SEPARATOR}package.fig" end end end
klimkin/fig
spec/command/running_commands_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fig/operating_system' describe 'Fig' do describe 'running commands' do before(:each) do clean_up_test_environment set_up_test_environment end describe 'in a package config section' do describe %q<executes the command> do describe %q<in a published v0 package> do it %q<when not told to --run-command-statement> do input = <<-END config default command "echo foo" end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3> out.should == 'foo' err.should == '' end it %q<when told to --run-command-statement> do input = <<-END config default command "echo foo" end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3 --run-command-statement> out.should == 'foo' err.should == '' end if Fig::OperatingSystem.unix? # Command statements used to be split on whitespace and put back # together with space characters. it %q<without manipulating whitespace> do input = <<-END config default command "echo 'foo bar'" end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3> out.should == 'foo bar' err.should == '' end end end describe %q<in a published v1 package> do it %q<when not told to --run-command-statement> do input = <<-END grammar v1 config default command "echo foo" end set force='publishing in v1 grammar' end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3> out.should == 'foo' err.should == '' end it %q<when told to --run-command-statement> do input = <<-END grammar v1 config default command "echo foo" end set force='publishing in v1 grammar' end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3 --run-command-statement> out.should == 'foo' err.should == '' end if Fig::OperatingSystem.unix? # Command statements used to be split on whitespace and put back # together with space characters. it %q<without manipulating whitespace> do input = <<-END grammar v1 config default command "echo 'foo bar'" end set force='publishing in v1 grammar' end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3> out.should == 'foo bar' err.should == '' end end end it %q<in the default config in an unpublished v0 package when told to --run-command-statement> do input = <<-END config default command "echo foo" end END out, err = fig %w<--run-command-statement>, input out.should == 'foo' err.should == '' end it %q<in the default config in an unpublished v1 package when told to --run-command-statement> do input = <<-END grammar v1 config default command "echo foo" end end END out, err = fig %w<--run-command-statement>, input out.should == 'foo' err.should == '' end it %q<in a non-default config in an unpublished v0 package when told to --run-command-statement> do input = <<-END config default command "echo default" end config non-default command "echo non-default" end END out, err = fig %w<--run-command-statement --config non-default>, input out.should == 'non-default' err.should == '' end it %q<in a non-default config in an unpublished v1 package when told to --run-command-statement> do input = <<-END grammar v1 config default command "echo default" end end config non-default command "echo non-default" end end END out, err = fig %w<--run-command-statement --config non-default>, input out.should == 'non-default' err.should == '' end end describe %q<passes command-line arguments to the command> do it %q<in a published v0 package> do input = <<-END config default command "echo Hi" end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3 --command-extra-args there> out.should == 'Hi there' err.should == '' end it %q<in a published v1 package with a single command-line component> do input = <<-END grammar v1 config default command "echo Hi" end set force='publishing in v1 grammar' end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3 --command-extra-args there> out.should == 'Hi there' err.should == '' end if Fig::OperatingSystem.unix? # "echo" does not exist outside of the command interpreter on Windows. it %q<in a published v1 package with multiple command-line components> do input = <<-END grammar v1 config default command echo Hi, won\\'t "you" 'be my' end end END fig %w<--publish foo/1.2.3>, input out, err = fig %w<foo/1.2.3 --command-extra-args neighbor?> out.should == %q<Hi, won't you be my neighbor?> err.should == '' end end describe %q<in an unpublished package> do it %q<when only given --command-extra-args with the v0 grammar> do input = <<-END config default command "echo Hi" end END out, err = fig %w<--command-extra-args there>, input out.should == 'Hi there' err.should == '' end if Fig::OperatingSystem.unix? # "echo" does not exist outside of the command interpreter on Windows. it %q<when only given --command-extra-args with the v1 grammar> do input = <<-END grammar v1 config default command echo Hi end end END out, err = fig %w<--command-extra-args there>, input out.should == 'Hi there' err.should == '' end end it %q<when also given --run-command-statement with the v0 grammar> do input = <<-END config default command "echo Hi" end END out, err = fig %w<--run-command-statement --command-extra-args there>, input out.should == 'Hi there' err.should == '' end if Fig::OperatingSystem.unix? # Cannot figure out the quoting to get this to work on Windows. it %q<when also given --run-command-statement with the v1 grammar> do input = <<-END grammar v1 config default command "echo 'Hi" end end END out, err = fig( [%w<--run-command-statement --command-extra-args>, %q< there\\'>], input ) # Two spaces due to command-line concatenation and running through # the shell. out.should == 'Hi there' err.should == '' end end end end describe 'fails' do it %q<if command-line arguments specified but no command statement found> do input = <<-END config default end END fig %w<--publish foo/1.2.3>, input out, err, exit_code = fig( %w<foo/1.2.3 --command-extra-args yadda>, :no_raise_on_error => true ) out.should == '' err.should =~ /does not contain a command/ exit_code.should_not == 0 end it %q<if it finds multiple command statements> do input = <<-END config default command "echo foo" command "echo bar" end END out, err, exit_code = fig %w<--publish foo/1.2.3.4>, input, :no_raise_on_error => true err.should =~ %r<Found a second "command" statement within a "config" block \(line> exit_code.should_not == 0 end it %q<with an unpublished package and --run-command-statement wasn't specified> do input = <<-END config default command "echo foo" end END out, err, exit_code = fig [], input, :no_raise_on_error => true err.should =~ /\bnothing to do\b/i err.should =~ /\byou have a command statement\b/i err.should =~ /--run-command-statement\b/i out.should == '' exit_code.should_not == 0 end end end if Fig::OperatingSystem.unix? describe %q<from the command line> do it %q<via the shell if given a single argument> do out, err = fig ['--', 'echo foo $0 bar'] out.should =~ /\A foo [ ] .+ [ ] bar \z/x out.should_not == 'foo $0 bar' err.should == '' end it %q<without the shell if given multiple arguments> do out, err = fig %w<-- echo foo $0 bar> out.should == 'foo $0 bar' err.should == '' end it %q<fails if no actual command specified> do out, err, exit_code = fig ['--'], :no_raise_on_error => true err.should =~ /no command.*specified/i out.should == '' exit_code.should_not == 0 end end end end end
klimkin/fig
lib/fig/package_cache.rb
# coding: utf-8 module Fig; end # Simple double-level (name, version) cache of Packages. class Fig::PackageCache def initialize() @packages = {} end def add_package(package) versions = @packages[package.name] if not versions versions = {} @packages[package.name] = versions end versions[package.version] = package return end def get_package(name, version) versions = @packages[name] return if not versions return versions[version] end # Don't care which one, just gimme. def get_any_version_of_package(name) versions = @packages[name] return if not versions return versions.values.first() end def remove_package(name, version) versions = @packages[name] return if not versions versions.delete(version) return end end
klimkin/fig
spec/working_directory_maintainer_spec.rb
<reponame>klimkin/fig # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'fig/working_directory_maintainer' describe 'WorkingDirectoryMaintainer' do let(:base_directory) { "#{CURRENT_DIRECTORY}/retrieve-test" } let(:working_directory) { "#{base_directory}/working" } let(:source_directory) { "#{base_directory}/source" } before(:each) do clean_up_test_environment set_up_test_environment [working_directory, source_directory].each do |directory| FileUtils.rm_rf(directory) FileUtils.mkdir_p(directory) end end it 'maintains files for a single package' do # Set up some test files source_foo = "#{source_directory}/foo.txt" source_bar = "#{source_directory}/bar.txt" source_baz = "#{source_directory}/baz.txt" File.open(source_foo, 'w') {|f| f << 'FOO'} File.open(source_bar, 'w') {|f| f << 'BAR'} File.open(source_baz, 'w') {|f| f << 'BAZ'} working_foo = File.join(working_directory, 'foo.txt') working_bar = File.join(working_directory, 'bar.txt') working_baz = File.join(working_directory, 'baz.txt') # Retrieve files A and B maintainer = Fig::WorkingDirectoryMaintainer.new(working_directory) maintainer.switch_to_package_version('foo', '1.2.3') maintainer.retrieve(source_foo, 'foo.txt') maintainer.retrieve(source_bar, 'bar.txt') File.read(working_foo).should == 'FOO' File.read(working_bar).should == 'BAR' # Retrieve files B and C for a different version maintainer.switch_to_package_version('foo', '4.5.6') maintainer.retrieve(source_bar, 'bar.txt') maintainer.retrieve(source_baz, 'baz.txt') File.read(working_bar).should == 'BAR' File.read(working_baz).should == 'BAZ' File.exist?(working_foo).should == false # Save and reload maintainer.prepare_for_shutdown(:purged_unused_packages) maintainer = Fig::WorkingDirectoryMaintainer.new(working_directory) # Switch back to original version maintainer.switch_to_package_version('foo', '1.2.3') maintainer.retrieve(source_foo, 'foo.txt') maintainer.retrieve(source_bar, 'bar.txt') File.read(working_foo).should == 'FOO' File.read(working_bar).should == 'BAR' File.exist?(working_baz).should == false end it 'preserves executable bit' do File.open("#{source_directory}/plain", 'w') {|f| f << 'plain'} File.open("#{source_directory}/executable", 'w') {|f| f << 'executable.exe'} FileUtils.chmod(0755, "#{source_directory}/executable") maintainer = Fig::WorkingDirectoryMaintainer.new(working_directory) maintainer.switch_to_package_version('foo', '1.2.3') maintainer.retrieve("#{source_directory}/plain", 'plain') maintainer.retrieve("#{source_directory}/executable", 'executable.exe') File.stat(File.join(working_directory, 'plain')).executable?.should == false File.stat(File.join(working_directory, 'executable.exe')).executable?.should == true end it 'fails on corrupted metadata' do FileUtils.mkdir_p("#{working_directory}/.fig") metadata_file = "#{working_directory}/.fig/retrieve" write_file(metadata_file, 'random garbage') expect { Fig::WorkingDirectoryMaintainer.new(working_directory) }.to raise_error(/parse error/) # This is so much fun. It appears that once we've had a file open within # this process, we cannot delete that file, i.e. "File.rm(metadata_file)" # results in an EACCESS on Windows. So, in lieu of removing the file, we # just make it empty. write_file(metadata_file, '') end end
klimkin/fig
lib/fig/file_not_found_error.rb
# coding: utf-8 module Fig # A (possibly remote) file that was looked for was not found. This may or # may not actually be a problem; i.e. this may be the result of an existence # test. class FileNotFoundError < StandardError attr_reader :path def initialize(message, path) super(message) @path = path end end end
klimkin/fig
lib/fig/command/action/role/list_dependencies_flat.rb
<reponame>klimkin/fig<filename>lib/fig/command/action/role/list_dependencies_flat.rb # coding: utf-8 require 'fig/command/action' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListDependenciesFlat def execute() packages = gather_package_dependency_configurations() if packages.empty? and $stdout.tty? puts '<no dependencies>' else strings = derive_package_strings(packages) puts strings.uniq.sort.join("\n") end return Fig::Command::Action::EXIT_SUCCESS end end
klimkin/fig
lib/fig/package_definition_text_assembler.rb
# coding: utf-8 require 'fig/deparser' require 'fig/deparser/v0' require 'fig/deparser/v1' require 'fig/deparser/v2' require 'fig/statement/grammar_version' module Fig; end # Used for building packages for publishing. class Fig::PackageDefinitionTextAssembler attr_reader :input_statements attr_reader :output_statements def initialize(emit_as_input_or_to_be_published_values) @emit_as_input_or_to_be_published_values = emit_as_input_or_to_be_published_values @input_statements = [] @output_statements = [] @header_text = [] @footer_text = [] return end # Argument can either be a single Statement or an array of them. def add_input(statements) @input_statements << statements @input_statements.flatten! return end # Argument can either be a single Statement or an array of them. def add_output(*statements) # Version gets determined by other statements, not by existing grammar. @output_statements << statements.flatten.reject { |s| s.is_a? Fig::Statement::GrammarVersion } @output_statements.flatten! return end def asset_input_statements() return @input_statements.select { |statement| statement.is_asset? } end # Argument can be a single string or an array of strings def add_header(text) @header_text << text return end # Argument can be a single string or an array of strings def add_footer(text) @footer_text << text return end def assemble_package_definition() unparsed_statements, explanations = deparse_statements() definition = [@header_text, unparsed_statements, @footer_text].flatten.join("\n") definition.gsub!(/\n{3,}/, "\n\n") definition.strip! definition << "\n" return definition, explanations end private def deparse_statements() deparser_class, explanations = Fig::Deparser.class_for_statements( @output_statements, @emit_as_input_or_to_be_published_values ) grammar_statement = Fig::Statement::GrammarVersion.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, %q<Fake grammar version that shouldn't be used because the Deparser should determine what gets emitted.> ) deparser = deparser_class.new @emit_as_input_or_to_be_published_values text = deparser.deparse( [grammar_statement] + @output_statements ) explanations.unshift( "Publishing using the #{deparser.grammar_description} grammar." ) return text, explanations end end
klimkin/fig
spec/command/miscellaneous_spec.rb
<gh_stars>10-100 # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fig/command/package_loader' describe 'Fig' do before(:each) do clean_up_test_environment set_up_test_environment end it 'ignores comments' do input = <<-END # Some comment config default set FOO=BAR # Another comment end END fig(%w<--get FOO>, input)[0].should == 'BAR' end describe '--file' do it 'reads from the value' do dot_fig_file = "#{FIG_SPEC_BASE_DIRECTORY}/file-option-test.fig" write_file(dot_fig_file, <<-END) config default set FOO=BAR end END fig(['--file', dot_fig_file, '--get', 'FOO'])[0].should == 'BAR' end it 'complains about the value not existing' do out, err, exit_code = fig(%w<--file does-not-exist --get FOO>, :no_raise_on_error => true) out.should == '' err.should =~ /does-not-exist/ exit_code.should_not == 0 end end [ Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE, Fig::Command::PackageLoader::DEFAULT_APPLICATION_FILE, ].each do |file_name| it "ignores #{file_name} with the --no-file option" do dot_fig_file = "#{FIG_SPEC_BASE_DIRECTORY}/#{file_name}" write_file(dot_fig_file, <<-END) config default set FOO=BAR end END fig(%w<--no-file --get FOO>)[0].should == '' end end it 'complains about conflicting package versions' do fig(%w<--publish foo/1.2.3 --set VARIABLE=VALUE>) fig(%w<--publish foo/4.5.6 --set VARIABLE=VALUE>) out, err, exit_code = fig( %w<--update --include foo/1.2.3 --include foo/4.5.6>, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ /version mismatch for package foo/i end describe 'emits the version number' do %w/-v --version/.each do |option| it "descriptively with #{option}" do (out, err, exitstatus) = fig([option]) exitstatus.should == 0 err.should == '' out.should =~ %r< \A # Start of string \w+ # Some text... \s+ # ... followed by some whitespace .* # whatever (so test doesn't change as the text does) \d+ \. \d+ \. \d+ # Some dotted number >x end end it 'plainly with --version-plain' do (out, err, exitstatus) = fig %w< --version-plain >, :dont_strip_output => true exitstatus.should == 0 err.should == '' out.should =~ %r< \A # Start of string \d+ \. \d+ \. \d+ # Some dotted number >x out.should_not =~ %r< \n \z >x end end describe 'emits help summary for' do %w/-? -h --help/.each do |option| it option do out, err = fig([option]) err.should == '' out.should =~ / \b summary \b /xi out.should =~ / \b fig \b /x out.should =~ / --update \b /x out.should =~ / --set \b /x out.should =~ / --publish \b /x out.should =~ / --options \b /x out.should =~ / --help-long \b /x end end end it 'emits full help with --help-long' do out, err = fig(['--help-long']) err.should == '' out.should =~ / \b fig \b /x out.should =~ / --update \b /x out.should =~ / --set \b /x out.should =~ / --publish \b /x out.should =~ / --force \b /x out.should =~ / --help \b /x out.should =~ / --help-long \b /x out.should =~ / --options \b /x out.should =~ / \b FIG_REMOTE_URL \b /x out.should =~ / \b FIG_HOME \b /x end it 'emits option list with --options' do out, err = fig(['--options']) err.should == '' out.should =~ / options: /ix out.should =~ / --help \b /x out.should =~ / --options \b /x end end
klimkin/fig
lib/fig/command/action/list_configs.rb
<gh_stars>10-100 # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListConfigs include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--list-configs> end def descriptor_requirement() return nil end def modifies_repository?() return false end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end def execute() @execution_context.base_package.configs.each do |config| puts config.name end return EXIT_SUCCESS end end
klimkin/fig
spec/application_configuration_spec.rb
<reponame>klimkin/fig # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'fig/application_configuration' REPOSITORY_TEST_URL = 'http://example.com' WHITELIST_TEST_URL = 'http://foo.com' describe 'ApplicationConfiguration' do def new_configuration() config = Fig::ApplicationConfiguration.new config.base_whitelisted_url = REPOSITORY_TEST_URL config.remote_repository_url = REPOSITORY_TEST_URL return config end it 'allows arbitrary urls when there is no whitelist' do config = new_configuration config.url_access_allowed?('').should == true end it 'allows the repo url when whitelist is empty' do config = new_configuration config.push_dataset({'url whitelist' => []}) config.url_access_allowed?(REPOSITORY_TEST_URL).should == true end it 'disallows a non-repo url when whitelist is empty' do config = new_configuration config.push_dataset({'url whitelist' => []}) config.url_access_allowed?('').should == false end it 'disallows a url that starts with a whitelisted url that is a hostname only' do config = new_configuration config.push_dataset({'url whitelist' => []}) config.url_access_allowed?(REPOSITORY_TEST_URL + 'x').should == false end it 'allows a full url with empty whitelist' do config = new_configuration config.push_dataset({'url whitelist' => []}) config.url_access_allowed?(REPOSITORY_TEST_URL + '/x').should == true end it 'allows a url when it\'s on the whitelist' do config = new_configuration config.push_dataset({'url whitelist' => [REPOSITORY_TEST_URL]}) config.url_access_allowed?(REPOSITORY_TEST_URL + '/x').should == true end it 'disallows a url when it\'s not on the whitelist' do config = new_configuration config.push_dataset({'url whitelist' => [WHITELIST_TEST_URL]}) config.url_access_allowed?('http://bar.com' + '/x').should == false end it 'disallows a non-repo url when whitelist is not empty' do config = new_configuration config.push_dataset({'url whitelist' => [WHITELIST_TEST_URL]}) config.url_access_allowed?('').should == false end it 'disallows a url with a different port (but the first part matches)' do config = new_configuration config.push_dataset({'url whitelist' => [WHITELIST_TEST_URL+':2000']}) config.url_access_allowed?(WHITELIST_TEST_URL+':20001').should == false end end
klimkin/fig
lib/fig/deparser/v1.rb
# coding: utf-8 require 'fig/deparser' require 'fig/deparser/v1_base' module Fig; end module Fig::Deparser; end # Handles serializing of statements in the v1 grammar. class Fig::Deparser::V1 include Fig::Deparser include Fig::Deparser::V1Base def initialize( emit_as_input_or_to_be_published_values, indent_string = ' ' * 2, initial_indent_level = 0 ) @emit_as_input_or_to_be_published_values = emit_as_input_or_to_be_published_values @indent_string = indent_string @initial_indent_level = initial_indent_level return end def grammar_version(statement) add_indent @text << "grammar v1\n\n" return end def grammar_description() return 'v1' end end
klimkin/fig
lib/fig/command/options/parser.rb
# coding: utf-8 require 'optparse' require 'fig/command/option_error' module Fig; end class Fig::Command; end class Fig::Command::Options; end # Command-line processing. class Fig::Command::Options::Parser # This class knows way too much about how OptionParser works. SHORT_USAGE = <<-'END_SHORT_USAGE' Short usage summary (use --help-long for everything): Running under Fig: fig [...] [DESCRIPTOR] [-- COMMAND] fig [...] [DESCRIPTOR] --command-extra-args VALUES fig [...] [DESCRIPTOR] --run-command-statement Publishing packages: fig {--publish | --publish-local} [--force] DESCRIPTOR [...] Querying: fig {-g | --get} VARIABLE [DESCRIPTOR] [...] fig --list-dependencies [--list-tree] [--list-all-configs] [DESCRIPTOR] [...] fig --list-variables [--list-tree] [--list-all-configs] [DESCRIPTOR] [...] Standard options (represented as "[...]" above): [--update | --update-if-missing] [--set VARIABLE=VALUE] [--add VARIABLE=VALUE] [--resource PATH] [--archive PATH] [--include DESCRIPTOR] [--include-file PATH:CONFIG] [--override DESCRIPTOR] [--file PATH] [--no-file] (--options for full option list; --help-long for everything) END_SHORT_USAGE FULL_USAGE = <<-'END_FULL_USAGE' Running under Fig: fig [...] [DESCRIPTOR] [-- COMMAND] fig [...] [DESCRIPTOR] --command-extra-args VALUES fig [...] [DESCRIPTOR] --run-command-statement Publishing packages: fig {--publish | --publish-local} [--force] DESCRIPTOR [...] Local repository maintenance: fig --clean DESCRIPTOR [...] Querying: fig {--list-local | --list-remote} [...] fig {-g | --get} VARIABLE [DESCRIPTOR] [...] fig --list-dependencies [...list options...] [DESCRIPTOR] [...] fig --list-variables [...list options...] [DESCRIPTOR] [...] fig --list-configs [DESCRIPTOR] [...] fig --source-package FILE [DESCRIPTOR] [...] fig {-T | --dump-package-definition-text} [DESCRIPTOR] [...] fig --dump-package-definition-parsed [DESCRIPTOR] [...] fig --dump-package-definition-for-command-line [DESCRIPTOR] [...] List options (represented as "[...list options...]" above): [--list-tree | --json | --yaml | --graphviz] [--list-all-configs] Standard options (represented as "[...]" above): [-u | --update | -m | --update-if-missing] --update-lock-response {wait | fail | ignore} [{-s | --set} VARIABLE=VALUE] [{-p | --add | --append} VARIABLE=VALUE] [--resource PATH] [--archive PATH] [{-i | --include} DESCRIPTOR] [--include-file PATH:CONFIG] [--override DESCRIPTOR] [-R | --suppress-retrieves] [--suppress-cleanup-of-retrieves] [--suppress-all-includes] [--suppress-cross-package-includes] [--file PATH] [--no-file] [{-c | --config} CONFIG] [-l | --login] [--log-level LEVEL] [--log-config PATH | --log-to-stdout] [--figrc PATH] [--no-figrc] [--no-remote-figrc] [--suppress-vcs-comments-in-published-packages] [--suppress-warning-include-statement-missing-version] [--suppress-warning-unused-retrieve] Information: fig --help fig --help-long fig --options fig {-v | --version | --version-plain} A DESCRIPTOR looks like <package name>[/<version>][:<config>] e.g. "foo", "foo/1.2.3", and "foo/1.2.3:default". Whether ":<config>" and "/<version>" are required or allowed is dependent upon what your are doing. Environment variables: FIG_REMOTE_URL location of remote repository, required for remote operations FIG_HOME path to local repository, defaults to $HOME/.fighome FIG_SVN_EXECUTABLE path to svn executable, set to empty string to suppress use of Subversion FIG_GIT_EXECUTABLE path to git executable, set to empty string to suppress use of Git END_FULL_USAGE def initialize() @switches = {} @argument_description = {} @parser = OptionParser.new @parser.banner = "#{FULL_USAGE}\nAll options:\n\n" end def add_argument_description(options, description) if options.is_a? Array options.each do |option| @argument_description[option] = description end else @argument_description[options] = description end return end def on_head(*arguments, &block) switch_array = make_switch_array(arguments, block) return if not switch_array @parser.top.prepend(*switch_array) return end def on(*arguments, &block) switch_array = make_switch_array(arguments, block) return if not switch_array @parser.top.append(*switch_array) return end def separator(string) @parser.separator string return end def on_tail(*arguments, &block) switch_array = make_switch_array(arguments, block) return if not switch_array @parser.base.append(*switch_array) return end def short_help() return SHORT_USAGE end def full_help() return @parser.help end def options_message() return @parser.summarize('') end def parse!(argv) begin @parser.parse!(argv) rescue OptionParser::InvalidArgument => error raise_invalid_argument(error.args[0], error.args[1]) rescue OptionParser::MissingArgument => error raise_missing_argument(error.args[0]) rescue OptionParser::InvalidOption => error raise Fig::Command::OptionError.new( "Unknown option #{error.args[0]}.\n\n#{SHORT_USAGE}" ) rescue OptionParser::ParseError => error raise Fig::Command::OptionError.new(error.to_s) end return end def raise_invalid_argument(option, value, description = nil) # *sigh* OptionParser does not raise MissingArgument for the case of an # option with a required value being followed by another option. It # assigns the next option as the value instead. E.g. for # # fig --set --get FOO # # it assigns "--get" as the value of the "--set" option. if @switches.has_key? value raise_missing_argument(option) end description ||= @argument_description[option] if description.nil? description = '' else description = ' ' + description end raise Fig::Command::OptionError.new( %Q<Invalid value for #{option}: "#{value}"#{description}> ) end private def make_switch_array(arguments, block) # This method is a means of interjecting ourselves between the creation of # a Switch object and putting it into the list of actual switches. # # From the OptionParser code, the contents of the array: # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. # +nolong_opts+:: List of long style options with "no-" prefix. # # Why returning this data separate from the Switch object is necessary, I # do not understand. switch_array = @parser.make_switch(arguments, block) switch = switch_array[0] options = [switch.long, switch.short].flatten return if options.any? {|option| @switches.has_key? option} options.each {|option| @switches[option] = switch} return switch_array end def raise_missing_argument(option) raise Fig::Command::OptionError.new( "Please provide a value for #{option}." ) end end
klimkin/fig
lib/fig/at_exit.rb
<filename>lib/fig/at_exit.rb<gh_stars>10-100 # coding: utf-8 module Fig; end # This exists because standard Kernel#at_exit blocks don't get run before # Kernel#exec. class Fig::AtExit def self.add(&block) EXIT_PROCS << block return end def self.execute() EXIT_PROCS.each do |proc| begin proc.call() rescue StandardError => exception $stderr.puts( [ %q<Got exception from "at exit" processing.>, exception.message, exception.backtrace ].flatten.join("\n") ) end end return end private EXIT_PROCS = [] at_exit { Fig::AtExit.execute() } end
klimkin/fig
spec/command/clean_spec.rb
<reponame>klimkin/fig<gh_stars>10-100 # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do describe '--clean' do before(:each) do clean_up_test_environment set_up_test_environment cleanup_home_and_remote end it 'cleans a named package from the FIG_HOME' do fig(%w<--publish foo/1.2.3 --set FOO=BAR>)[2].should == 0 fig(%w<--clean foo/1.2.3>)[2].should == 0 fail unless not File.directory? FIG_HOME + '/packages/foo/1.2.3' end it 'cleans a named package from the FIG_HOME and does not clean packages differing only by version' do input = <<-END config default set FOO=BAR end END fig(%w<--publish foo/1.2.3>, input)[2].should == 0 fig(%w<--publish foo/4.5.6>, input)[2].should == 0 fig(%w<--clean foo/1.2.3>)[2].should == 0 fail unless File.directory? FIG_HOME + '/packages/foo/4.5.6' end it 'should complain if you clean without a package descriptor' do out, err, exit_code = fig(%w<--clean>, :no_raise_on_error => true) err.should =~ /need to specify a descriptor/i exit_code.should_not == 0 end it %q<should complain if local repository isn't in the expected format version> do fig(%w<--publish foo/1.2.3 --set FOO=BAR>)[2].should == 0 set_local_repository_format_to_future_version() out, err, exit_code = fig(%w<--clean foo/1.2.3>, :no_raise_on_error => true) err.should =~ /Local repository is in version \d+ format. This version of fig can only deal with repositories in version \d+ format\./ exit_code.should_not == 0 end %w< --update --update-if-missing >.each do |option| it %Q<should complain if #{option} is specified> do fig(%w<--publish foo/1.2.3 --set FOO=BAR>)[2].should == 0 out, err, exit_code = fig([option, '--clean', 'foo/1.2.3'], :no_raise_on_error => true) err.should =~ /because they disagree on whether the base package should be loaded/ exit_code.should_not == 0 end end end end
klimkin/fig
lib/fig/statement/configuration.rb
# coding: utf-8 require 'fig/statement' require 'fig/statement/command' require 'fig/statement/synthetic_raw_text' module Fig; end # A grouping of statements within a package. May not be nested. # # Any processing of statements is guaranteed to hit any Overrides first. class Fig::Statement::Configuration < Fig::Statement attr_reader :name, :statements def initialize(line_column, source_description, name, statements) super(line_column, source_description) @name = name overrides, others = statements.partition do |statement| statement.is_a?(Fig::Statement::Override) end text = [] if ! overrides.empty? text << Fig::Statement::SyntheticRawText.new(nil, nil, "\n") end @statements = [overrides, text, others].flatten end def statement_type() return 'config' end def command_statement return statements.find do |statement| statement.is_a?(Fig::Statement::Command) end end # Block will receive a Statement. def walk_statements(&block) @statements.each do |statement| yield statement statement.walk_statements(&block) end end def deparse_as_version(deparser) return deparser.configuration(self) end def minimum_grammar_for_emitting_input() return [0] end def minimum_grammar_for_publishing() return [0] end end
klimkin/fig
lib/fig/statement/set.rb
# coding: utf-8 require 'fig/statement' require 'fig/statement/environment_variable' module Fig; end # A statement that sets the value of an environment variable. class Fig::Statement::Set < Fig::Statement include Fig::Statement::EnvironmentVariable # Yields on error. def self.parse_name_value(combined, &error_block) variable, raw_value = seperate_name_and_value combined, &error_block return [variable, tokenize_value(raw_value, &error_block)] end def self.parse_v0_name_value(combined, &error_block) variable, raw_value = seperate_name_and_value combined, &error_block base_v0_value_validation(variable, raw_value, &error_block) return [variable, tokenize_value(raw_value, &error_block)] end def initialize(line_column, source_description, name, tokenized_value) super(line_column, source_description) @name = name @tokenized_value = tokenized_value end def statement_type() return 'set' end def is_environment_variable?() return true end def deparse_as_version(deparser) return deparser.set(self) end private def minimum_grammar() return standard_minimum_grammar end end
klimkin/fig
lib/fig/user_input_error.rb
<reponame>klimkin/fig<filename>lib/fig/user_input_error.rb # coding: utf-8 module Fig # Bad user! Bad! (Indicates we should exit with an error, but because it's # a user caused issue, it's not a bug and should not produce a stack trace.) class UserInputError < StandardError end end
klimkin/fig
lib/fig/statement/environment_variable.rb
# coding: utf-8 require 'fig/statement' require 'fig/string_tokenizer' require 'fig/tokenized_string/token' module Fig; end class Fig::Statement; end # A statement that manipulates an environment variable. module Fig::Statement::EnvironmentVariable attr_reader :name, :tokenized_value def self.included(class_included_into) class_included_into.extend(ClassMethods) return end def minimum_grammar_for_emitting_input() return minimum_grammar() end def minimum_grammar_for_publishing() return minimum_grammar() end private def standard_minimum_grammar() value = tokenized_value.to_escaped_string if value =~ /\s/ return [1, 'contains whitespace'] end # Can't have octothorpes anywhere in v0 due to comment stripping via # regex. if value =~ /#/ return [1, 'contains a comment ("#") character'] end if value =~ / ( ["'] ) /x return [1, %Q<contains a "#{$1}" character>] end return [0] end module ClassMethods def seperate_name_and_value(combined, &error_block) variable, raw_value = combined.split '=', 2 if variable !~ Fig::Statement::ENVIRONMENT_VARIABLE_NAME_REGEX yield \ %Q<"#{variable}" does not consist solely of alphanumerics and underscores.> return end return [variable, raw_value || ''] end def tokenize_value(value, &error_block) tokenizer = Fig::StringTokenizer.new TOKENIZING_SUBEXPRESSION_MATCHER, '@' return tokenizer.tokenize value, &error_block end # TODO: Test coverage doesn't appear to be running this. def base_v0_value_validation(variable, raw_value) if raw_value =~ /\s/ yield %Q<The value of #{variable} (#{raw_value}) contains whitespace.> return end if raw_value =~ /'/ yield %Q<The value of #{variable} (#{raw_value}) contains a single quote.> return end if raw_value =~ /"/ yield %Q<The value of #{variable} (#{raw_value}) contains a double quote.> return end return end private TOKENIZING_SUBEXPRESSION_MATCHER = [ { :pattern => %r<\@>, :action => lambda { |subexpression, error_block| Fig::TokenizedString::Token.new :package_path, '@' } } ] end end
klimkin/fig
lib/fig/grammar_monkey_patches.rb
<gh_stars>10-100 # coding: utf-8 # The existence of this &!#%)(*!&% file makes me want to hurl, but it's the # simplest way to modify the classes generated by Treetop: the Treetop grammar # doesn't allow extensions at the grammar level, only the rule level. require 'fig/grammar/v0' require 'fig/grammar/v1' require 'fig/grammar/v2' module Fig; end module Fig::Grammar; end class Fig::Grammar::V0Parser def version() return 0 end end class Fig::Grammar::V1Parser def version() return 1 end end class Fig::Grammar::V2Parser def version() return 2 end end
klimkin/fig
spec/command/publish_local_and_updates_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<doesn't remove --publish-local packages during a failed --update.> do fig %w<--publish-local publish-local/test --set foo=bar> out, err, exit_code = fig( %w<publish-local/test --get foo>, :fork => false ) out.should == 'bar' # Should not work because we didn't send it to the remote repo. out, err, exit_code = fig( %w<publish-local/test --update --get foo>, :no_raise_on_error => true ) exit_code.should_not == 0 # Should still work out, err, exit_code = fig( %w<publish-local/test --get foo>, :fork => false ) out.should == 'bar' end end