repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/time_tracker.rb
lib/time_tracker.rb
class TimeTracker attr_accessor :elapsed_time, :result def self.track start = Process.clock_gettime(Process::CLOCK_MONOTONIC) result = yield new(Process.clock_gettime(Process::CLOCK_MONOTONIC) - start, result) end def initialize(elapsed_time, result) @elapsed_time = elapsed_time @result = result end def method_missing(method_sym, *arguments, &block) if @result.respond_to?(method_sym) @result.send(method_sym, *arguments, &block) else super end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/capistrano/sync.rb
lib/capistrano/sync.rb
require 'yaml' require 'pathname' require 'dotenv' # Edited by Andrew Cantino. Based on: https://gist.github.com/339471 # Original info: # # Capistrano sync.rb task for syncing databases and directories between the # local development environment and different multi_stage environments. You # cannot sync directly between two multi_stage environments, always use your # local machine as loop way. # # This version pulls credentials for the remote database from # {shared_path}/config/database.yml on the remote server, thus eliminating # the requirement to have your production database credentials on your local # machine or in your repository. # # Author: Michael Kessler aka netzpirat # Gist: 111597 # # Edits By: Evan Dorn, Logical Reality Design, March 2010 # Gist: 339471 # # Released under the MIT license. # Kindly sponsored by Screen Concept, www.screenconcept.ch namespace :sync do namespace :db do desc <<-DESC Syncs database from the selected environment to the local development environment. The database credentials will be read from your local config/database.yml file and a copy of the dump will be kept within the shared sync directory. The amount of backups that will be kept is declared in the sync_backups variable and defaults to 5. DESC task :down, :roles => :db, :only => {:primary => true} do run "mkdir -p #{shared_path}/sync" env = fetch :rails_env, 'production' filename = "database.#{env}.#{Time.now.strftime '%Y-%m-%d_%H:%M:%S'}.sql.bz2" on_rollback { delete "#{shared_path}/sync/#{filename}" } # Remote DB dump username, password, database, host = remote_database_config(env) hostcmd = host.nil? ? '' : "-h #{host}" puts "hostname: #{host}" puts "database: #{database}" opts = "-c --max_allowed_packet=128M --hex-blob --single-transaction --skip-extended-insert --quick" run "mysqldump #{opts} -u #{username} --password='#{password}' #{hostcmd} #{database} | bzip2 -9 > #{shared_path}/sync/#{filename}" do |channel, stream, data| puts data end purge_old_backups "database" # Download dump download "#{shared_path}/sync/#{filename}", filename # Local DB import username, password, database = database_config('development') system "bzip2 -d -c #{filename} | mysql --max_allowed_packet=128M -u #{username} --password='#{password}' #{database}" system "rake db:migrate" system "rake db:test:prepare" logger.important "sync database from '#{env}' to local has finished" end end namespace :fs do desc <<-DESC Sync declared remote directories to the local development environment. The synced directories must be declared as an array of Strings with the sync_directories variable. The path is relative to the rails root. DESC task :down, :roles => :web, :once => true do server, port = host_and_port Array(fetch(:sync_directories, [])).each do |syncdir| unless File.directory? "#{syncdir}" logger.info "create local '#{syncdir}' folder" Dir.mkdir "#{syncdir}" end logger.info "sync #{syncdir} from #{server}:#{port} to local" destination, base = Pathname.new(syncdir).split system "rsync --verbose --archive --compress --copy-links --delete --stats --rsh='ssh -p #{port}' #{user}@#{server}:#{current_path}/#{syncdir} #{destination.to_s}" end logger.important "sync filesystem from remote to local finished" end end # Used by database_config and remote_database_config to parse database configs that depend on .env files. Depends on the dotenv-rails gem. class EnvLoader def initialize(data) @env = Dotenv::Parser.call(data) end def with_loaded_env begin saved_env = ENV.to_hash.dup ENV.update(@env) yield ensure ENV.replace(saved_env) end end end # # Reads the database credentials from the local config/database.yml file # +db+ the name of the environment to get the credentials for # Returns username, password, database # def database_config(db) local_config = File.read('config/database.yml') local_env = File.read('.env') database = nil EnvLoader.new(local_env).with_loaded_env do database = YAML::load(ERB.new(local_config).result) end return database["#{db}"]['username'], database["#{db}"]['password'], database["#{db}"]['database'], database["#{db}"]['host'] end # # Reads the database credentials from the remote config/database.yml file # +db+ the name of the environment to get the credentials for # Returns username, password, database # def remote_database_config(db) remote_config = capture("cat #{current_path}/config/database.yml") remote_env = capture("cat #{current_path}/.env") database = nil EnvLoader.new(remote_env).with_loaded_env do database = YAML::load(ERB.new(remote_config).result) end return database["#{db}"]['username'], database["#{db}"]['password'], database["#{db}"]['database'], database["#{db}"]['host'] end # # Returns the actual host name to sync and port # def host_and_port return roles[:web].servers.first.host, ssh_options[:port] || roles[:web].servers.first.port || 22 end # # Purge old backups within the shared sync directory # def purge_old_backups(base) count = fetch(:sync_backups, 5).to_i backup_files = capture("ls -xt #{shared_path}/sync/#{base}*").split.reverse if count >= backup_files.length logger.important "no old backups to clean up" else logger.info "keeping #{count} of #{backup_files.length} sync backups" delete_backups = (backup_files - backup_files.last(count)).join(" ") run "rm #{delete_backups}" end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/lib/utils/html_transformer.rb
lib/utils/html_transformer.rb
module Utils module HtmlTransformer SINGLE = 1 MULTIPLE = 2 COMMA_SEPARATED = 3 SRCSET = 4 URI_ATTRIBUTES = { 'a' => { 'href' => SINGLE }, 'applet' => { 'archive' => COMMA_SEPARATED, 'codebase' => SINGLE }, 'area' => { 'href' => SINGLE }, 'audio' => { 'src' => SINGLE }, 'base' => { 'href' => SINGLE }, 'blockquote' => { 'cite' => SINGLE }, 'body' => { 'background' => SINGLE }, 'button' => { 'formaction' => SINGLE }, 'command' => { 'icon' => SINGLE }, 'del' => { 'cite' => SINGLE }, 'embed' => { 'src' => SINGLE }, 'form' => { 'action' => SINGLE }, 'frame' => { 'longdesc' => SINGLE, 'src' => SINGLE }, 'head' => { 'profile' => SINGLE }, 'html' => { 'manifest' => SINGLE }, 'iframe' => { 'longdesc' => SINGLE, 'src' => SINGLE }, 'img' => { 'longdesc' => SINGLE, 'src' => SINGLE, 'srcset' => SRCSET, 'usemap' => SINGLE }, 'input' => { 'formaction' => SINGLE, 'src' => SINGLE, 'usemap' => SINGLE }, 'ins' => { 'cite' => SINGLE }, 'link' => { 'href' => SINGLE }, 'object' => { 'archive' => MULTIPLE, 'classid' => SINGLE, 'codebase' => SINGLE, 'data' => SINGLE, 'usemap' => SINGLE }, 'q' => { 'cite' => SINGLE }, 'script' => { 'src' => SINGLE }, 'source' => { 'src' => SINGLE, 'srcset' => SRCSET }, 'video' => { 'poster' => SINGLE, 'src' => SINGLE }, } URI_ELEMENTS_XPATH = '//*[%s]' % URI_ATTRIBUTES.keys.map { |name| "name()='#{name}'" }.join(' or ') module_function def transform(html, &block) block or raise ArgumentError, 'block must be given' case html when /\A\s*(?:<\?xml[\s?]|<!DOCTYPE\s)/i doc = Nokogiri.parse(html) yield doc doc.to_s when /\A\s*<(html|head|body)[\s>]/i # Libxml2 automatically adds DOCTYPE and <html>, so we need to # skip them. element_name = $1 doc = Nokogiri::HTML::Document.parse(html) yield doc doc.at_xpath("//#{element_name}").xpath('self::node() | following-sibling::node()').to_s else doc = Nokogiri::HTML::Document.parse("<html><body>#{html}") yield doc doc.xpath("/html/body/node()").to_s end end def replace_uris(html, &block) block or raise ArgumentError, 'block must be given' transform(html) { |doc| doc.xpath(URI_ELEMENTS_XPATH).each { |element| uri_attrs = URI_ATTRIBUTES[element.name] or next uri_attrs.each { |name, format| attr = element.attribute(name) or next case format when SINGLE attr.value = block.call(attr.value.strip) when MULTIPLE attr.value = attr.value.gsub(/(\S+)/) { block.call($1) } when COMMA_SEPARATED, SRCSET attr.value = attr.value.gsub(/((?:\A|,)\s*)(\S+)/) { $1 + block.call($2) } end } } } end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/application.rb
config/application.rb
require_relative 'boot' require 'rails' require 'active_model/railtie' require 'active_job/railtie' require 'active_record/railtie' # require "active_storage/engine" require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' # require "action_cable/engine" require 'sprockets/railtie' require 'rails/test_unit/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Huginn class Application < Rails::Application Dotenv.overload File.expand_path('../spec/env.test', __dir__) if Rails.env.test? # Initialize configuration defaults for originally generated Rails version. config.load_defaults 7.0 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # Custom directories with classes and modules you want to be autoloadable. config.autoload_paths += %W[#{config.root}/lib #{config.root}/app/presenters #{config.root}/app/jobs] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = ENV['TIMEZONE'].presence || 'Pacific Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = 'utf-8' # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql config.active_job.queue_adapter = :delayed_job config.action_view.sanitized_allowed_tags = %w[strong em b i p code pre tt samp kbd var sub sup dfn cite big small address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dl dt dd abbr acronym a img blockquote del ins style table thead tbody tr th td] config.action_view.sanitized_allowed_attributes = %w[href src width height alt cite datetime title class name xml:lang abbr border cellspacing cellpadding valign style] config.after_initialize do config.active_record.yaml_column_permitted_classes = [Symbol, Date, Time] end ActiveSupport::XmlMini.backend = 'Nokogiri' end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/environment.rb
config/environment.rb
# Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/routes.rb
config/routes.rb
Rails.application.routes.draw do resources :agents do member do post :run post :handle_details_post put :leave_scenario post :reemit_events delete :remove_events delete :memory, action: :destroy_memory end collection do put :toggle_visibility post :propagate get :type_details get :event_descriptions post :validate post :complete delete :undefined, action: :destroy_undefined end resources :logs, :only => [:index] do collection do delete :clear end end resources :events, :only => [:index] scope module: :agents do resources :dry_runs, only: [:index, :create] end end scope module: :agents do resources :dry_runs, only: [:index, :create] end resource :diagram, :only => [:show] resources :events, :only => [:index, :show, :destroy] do member do post :reemit end end resources :scenarios do collection do resource :scenario_imports, :only => [:new, :create] end member do get :share get :export put :enable_or_disable_all_agents end resource :diagram, :only => [:show] end resources :user_credentials, :except => :show do collection do post :import end end resources :services, :only => [:index, :destroy] do member do post :toggle_availability end end resources :jobs, :only => [:index, :destroy] do member do put :run end collection do delete :destroy_failed delete :destroy_all post :retry_queued end end namespace :admin do resources :users, except: :show do member do put :deactivate put :activate get :switch_to_user end collection do get :switch_back end end end get "/worker_status" => "worker_status#show" match "/users/:user_id/web_requests/:agent_id/:secret" => "web_requests#handle_request", :as => :web_requests, :via => [:get, :post, :put, :delete] post "/users/:user_id/webhooks/:agent_id/:secret" => "web_requests#handle_request" # legacy post "/users/:user_id/update_location/:secret" => "web_requests#update_location" # legacy devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks', registrations: 'users/registrations' }, sign_out_via: [:post, :delete] if Rails.env.development? mount LetterOpenerWeb::Engine, at: "/letter_opener" end get "/about" => "home#about" root :to => "home#index" end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/deploy.rb
config/deploy.rb
require 'dotenv' Dotenv.load # config valid only for current version of Capistrano lock '3.11.0' set :application, 'huginn' set :repo_url, ENV['CAPISTRANO_DEPLOY_REPO_URL'] || 'https://github.com/huginn/huginn.git' # Default branch is :master set :branch, ENV['CAPISTRANO_DEPLOY_BRANCH'] || ENV['BRANCH'] || 'master' set :deploy_to, '/home/huginn' # Set to :debug for verbose ouput set :log_level, :info # Default value for :linked_files is [] set :linked_files, fetch(:linked_files, []).push('.env', 'Procfile', 'config/unicorn.rb') # Default value for linked_dirs is [] set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle') # Default value for keep_releases is 5 # set :keep_releases, 5 set :bundle_jobs, 4 set :conditionally_migrate, true # Defaults to false. If true, it's skip migration if files in db/migrate not modified task :deploy => [:production] namespace :deploy do after 'check:make_linked_dirs', :migrate_to_cap do on roles(:all) do # Try to migrate from the manual installation to capistrano directory structure next if test('[ -L ~/huginn ]') fetch(:linked_files).each do |f| if !test("[ -f ~/shared/#{f} ] ") && test("[ -f ~/huginn/#{f} ]") execute("cp ~/huginn/#{f} ~/shared/#{f}") end end execute('mv ~/huginn ~/huginn.manual') execute('ln -s ~/current ~/huginn') end end after :publishing, :restart do on roles(:all) do within release_path do execute :rake, 'production:restart' end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/spring.rb
config/spring.rb
Spring.watch( ".ruby-version", ".rbenv-vars", "tmp/restart.txt", "tmp/caching-dev.txt" )
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/boot.rb
config/boot.rb
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require "bundler/setup" # Set up gems listed in the Gemfile. require "bootsnap/setup" # Speed up boot time by caching expensive operations. autoload :Logger, "logger"
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy # For further information see the following documentation # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy # Rails.application.config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # If you are using UJS then enable automatic nonce generation # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } # Set the nonce only to specific directives # Rails.application.config.content_security_policy_nonce_directives = %w(script-src) # Report CSP violations to a specified URI # For further information see the following documentation: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only # Rails.application.config.content_security_policy_report_only = true
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [ :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn ]
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/application_controller_renderer.rb
config/initializers/application_controller_renderer.rb
# Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/mail_encoding_patch.rb
config/initializers/mail_encoding_patch.rb
require 'mail' module Mail module Utilities class ImprovedEncoder < BestEffortCharsetEncoder def pick_encoding(charset) case charset when /\Aiso-2022-jp\z/i Encoding::CP50220 when /\Ashift_jis\z/i Encoding::Windows_31J else super end end end self.charset_encoder = ImprovedEncoder.new end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/session_store.rb
config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_rails_session'
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/devise.rb
config/initializers/devise.rb
require 'utils' # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = ENV['EMAIL_FROM_ADDRESS'].presence || 'you@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. config.authentication_keys = [ :login ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = "SOME LONG HASH GENERATED WITH rake secret" # Send a notification email when the user's password is changed # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. config.allow_unconfirmed_access_for = Utils.parse_duration(ENV['ALLOW_UNCONFIRMED_ACCESS_FOR']).presence || 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. config.confirm_within = Utils.parse_duration(ENV['CONFIRM_WITHIN']).presence || 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account config.confirmation_keys = [ :login ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. config.remember_for = Utils.parse_duration(ENV['REMEMBER_FOR']).presence || 4.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. if Rails.env.production? config.rememberable_options = { secure: true } else config.rememberable_options = { } end # ==> Configuration for :validatable # Range for password length. config.password_length = (Utils.if_present(ENV['MIN_PASSWORD_LENGTH'], :to_i) || 8)..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. config.lock_strategy = Utils.if_present(ENV['LOCK_STRATEGY'], :to_sym) || :failed_attempts # Defines which key will be used when locking and unlocking an account config.unlock_keys = [ :login ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. config.unlock_strategy = Utils.if_present(ENV['UNLOCK_STRATEGY'], :to_sym) || :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. config.maximum_attempts = Utils.if_present(ENV['MAX_FAILED_LOGIN_ATTEMPTS'], :to_i) || 10 # Time interval to unlock the account if :time is enabled as unlock_strategy. config.unlock_in = Utils.parse_duration(ENV['UNLOCK_AFTER']).presence || 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account config.reset_password_keys = [ :login ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = Utils.parse_duration(ENV['RESET_PASSWORD_WITHIN']).presence || 6.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :get # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' if defined?(OmniAuth::Strategies::Twitter) && (key = ENV["TWITTER_OAUTH_KEY"]).present? && (secret = ENV["TWITTER_OAUTH_SECRET"]).present? config.omniauth :twitter, key, secret, authorize_params: {force_login: 'true', use_authorize: 'true'} end if defined?(OmniAuth::Strategies::Tumblr) && (key = ENV["TUMBLR_OAUTH_KEY"]).present? && (secret = ENV["TUMBLR_OAUTH_SECRET"]).present? config.omniauth :'tumblr', key, secret end if defined?(OmniAuth::Strategies::DropboxOauth2) && (key = ENV["DROPBOX_OAUTH_KEY"]).present? && (secret = ENV["DROPBOX_OAUTH_SECRET"]).present? config.omniauth :dropbox, key, secret, strategy_class: OmniAuth::Strategies::DropboxOauth2, request_path: '/auth/dropbox', callback_path: '/auth/dropbox/callback' end if defined?(OmniAuth::Strategies::Evernote) && (key = ENV["EVERNOTE_OAUTH_KEY"]).present? && (secret = ENV["EVERNOTE_OAUTH_SECRET"]).present? if ENV["USE_EVERNOTE_SANDBOX"] == "true" config.omniauth :evernote, key, secret, client_options: { :site => 'https://sandbox.evernote.com' } else config.omniauth :evernote, key, secret end end if defined?(OmniAuth::Strategies::GoogleOauth2) && (key = ENV["GOOGLE_CLIENT_ID"]).present? && (secret = ENV["GOOGLE_CLIENT_SECRET"]).present? config.omniauth :google_oauth2, key, secret, { name: :google, scope: [ 'userinfo.email', 'userinfo.profile', 'https://mail.google.com/', # ImapFolderAgent ].join(','), access_type: 'offline', prompt: 'consent' } end # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using omniauth, Devise cannot automatically set Omniauth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' config.omniauth_path_prefix = "/auth" OmniAuth.config.logger = Rails.logger OmniAuth.config.allowed_request_methods = [:post, :get] end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/timezone.rb
config/initializers/timezone.rb
# Set the timezone for the JavascriptAgent (libv8 only relies on the TZ variable) ENV['TZ'] = Time.zone.tzinfo.canonical_identifier
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/requires.rb
config/initializers/requires.rb
require 'pp' Rails.application.config.to_prepare do HuginnAgent.require! end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/wrap_parameters.rb
config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/aws.rb
config/initializers/aws.rb
if defined?(RTurk) && !Rails.env.test? RTurk::logger.level = Logger::DEBUG RTurk.setup(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_ACCESS_KEY'], :sandbox => ENV['AWS_SANDBOX'] == "true") end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/inflections.rb
config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/liquid.rb
config/initializers/liquid.rb
module Liquid # https://github.com/Shopify/liquid/pull/623 remove_const :PartialTemplateParser remove_const :TemplateParser PartialTemplateParser = /#{TagStart}.*?#{TagEnd}|#{VariableStart}(?:(?:[^'"{}]+|#{QuotedString})*?|.*?)#{VariableIncompleteEnd}/m TemplateParser = /(#{PartialTemplateParser}|#{AnyStartingTag})/m end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/mysqlpls.rb
config/initializers/mysqlpls.rb
# see https://github.com/rails/rails/issues/9855#issuecomment-28874587 # circumvents the default InnoDB limitation for index prefix bytes maximum when using proper 4byte UTF8 (utf8mb4) # (for server-side workaround see http://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_large_prefix) if ENV['ON_HEROKU'].nil? require 'active_record/connection_adapters/abstract_mysql_adapter' module ActiveRecord module ConnectionAdapters class AbstractMysqlAdapter NATIVE_DATABASE_TYPES[:string] = { :name => "varchar", :limit => 191 } end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/delayed_job.rb
config/initializers/delayed_job.rb
Delayed::Worker.destroy_failed_jobs = false Delayed::Worker.max_attempts = 5 Delayed::Worker.max_run_time = (ENV['DELAYED_JOB_MAX_RUNTIME'].presence || 2).to_i.minutes Delayed::Worker.read_ahead = 5 Delayed::Worker.default_priority = 10 Delayed::Worker.delay_jobs = !Rails.env.test? Delayed::Worker.sleep_delay = (ENV['DELAYED_JOB_SLEEP_DELAY'].presence || 10).to_f Delayed::Worker.logger = Rails.logger # Delayed::Worker.logger = Logger.new(Rails.root.join('log', 'delayed_job.log')) # Delayed::Worker.logger.level = Logger::DEBUG class Delayed::Job scope :pending, -> { where("locked_at IS NULL AND attempts = 0") } scope :awaiting_retry, -> { where("failed_at IS NULL AND attempts > 0 AND locked_at IS NULL") } scope :failed_jobs, -> { where("failed_at IS NOT NULL") } end Delayed::Backend::ActiveRecord.configure do |config| config.reserve_sql_strategy = :default_sql end if ENV["DATABASE_ADAPTER"] == "mysql2"
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/cookies_serializer.rb
config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/permissions_policy.rb
config/initializers/permissions_policy.rb
# Define an application-wide HTTP permissions policy. For further # information see https://developers.google.com/web/updates/2018/06/feature-policy # # Rails.application.config.permissions_policy do |f| # f.camera :none # f.gyroscope :none # f.microphone :none # f.usb :none # f.fullscreen :self # f.payment :self, "https://secure.example.com" # end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/faraday_patch.rb
config/initializers/faraday_patch.rb
# Monkey patch https://github.com/lostisland/faraday/pull/513 # Fixes encoding issue when passing an URL with non UTF-8 characters module Faraday module Utils def unescape(s) string = s.to_s string.force_encoding(Encoding::BINARY) if RUBY_VERSION >= '1.9' CGI.unescape string end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/silence_worker_status_logger.rb
config/initializers/silence_worker_status_logger.rb
module SilencedLogger def call(env) return super(env) if env['PATH_INFO'] !~ %r{^/worker_status} Rails.logger.silence(Logger::ERROR) do super(env) end end end Rails::Rack::Logger.send(:prepend, SilencedLogger)
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/assets.rb
config/initializers/assets.rb
# Be sure to restart your server when you modify this file. Rails.application.config.assets.enabled = true Rails.application.config.assets.initialize_on_precompile = false # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/multi_xml_patch.rb
config/initializers/multi_xml_patch.rb
# Same vulnerability as CVE-2013-0156 # https://groups.google.com/forum/#!topic/rubyonrails-security/61bkgvnSGTQ/discussion # Code has been submitted back to the project: # https://github.com/sferik/multi_xml/pull/34 # Until the fix is released, use this monkey-patch. require "multi_xml" module MultiXml class DisallowedTypeError < StandardError def initialize(type) super "Disallowed type attribute: #{type.inspect}" end end DISALLOWED_XML_TYPES = %w(symbol yaml) unless defined?(DISALLOWED_XML_TYPES) class << self def parse(xml, options={}) xml ||= '' xml.strip! if xml.respond_to?(:strip!) begin xml = StringIO.new(xml) unless xml.respond_to?(:read) char = xml.getc return {} if char.nil? xml.ungetc(char) hash = typecast_xml_value(undasherize_keys(parser.parse(xml)), options[:disallowed_types]) || {} rescue DisallowedTypeError raise rescue parser.parse_error => error raise ParseError, error.to_s, error.backtrace end hash = symbolize_keys(hash) if options[:symbolize_keys] hash end private def typecast_xml_value(value, disallowed_types=nil) disallowed_types ||= DISALLOWED_XML_TYPES case value when Hash if value.include?('type') && !value['type'].is_a?(Hash) && disallowed_types.include?(value['type']) raise DisallowedTypeError, value['type'] end if value['type'] == 'array' # this commented-out suggestion helps to avoid the multiple attribute # problem, but it breaks when there is only one item in the array. # # from: https://github.com/jnunemaker/httparty/issues/102 # # _, entries = value.detect { |k, v| k != 'type' && v.is_a?(Array) } # This attempt fails to consider the order that the detect method # retrieves the entries. #_, entries = value.detect {|key, _| key != 'type'} # This approach ignores attribute entries that are not convertable # to an Array which allows attributes to be ignored. _, entries = value.detect {|k, v| k != 'type' && (v.is_a?(Array) || v.is_a?(Hash)) } if entries.nil? || (entries.is_a?(String) && entries.strip.empty?) [] else case entries when Array entries.map {|entry| typecast_xml_value(entry, disallowed_types)} when Hash [typecast_xml_value(entries, disallowed_types)] else raise "can't typecast #{entries.class.name}: #{entries.inspect}" end end elsif value.has_key?(CONTENT_ROOT) content = value[CONTENT_ROOT] if block = PARSING[value['type']] if block.arity == 1 value.delete('type') if PARSING[value['type']] if value.keys.size > 1 value[CONTENT_ROOT] = block.call(content) value else block.call(content) end else block.call(content, value) end else value.keys.size > 1 ? value : content end elsif value['type'] == 'string' && value['nil'] != 'true' '' # blank or nil parsed values are represented by nil elsif value.empty? || value['nil'] == 'true' nil # If the type is the only element which makes it then # this still makes the value nil, except if type is # a XML node(where type['value'] is a Hash) elsif value['type'] && value.size == 1 && !value['type'].is_a?(Hash) nil else xml_value = value.inject({}) do |hash, (k, v)| hash[k] = typecast_xml_value(v, disallowed_types) hash end # Turn {:files => {:file => #<StringIO>} into {:files => #<StringIO>} so it is compatible with # how multipart uploaded files from HTML appear xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value end when Array value.map!{|i| typecast_xml_value(i, disallowed_types)} value.length > 1 ? value : value.first when String value else raise "can't typecast #{value.class.name}: #{value.inspect}" end end end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/action_mailer.rb
config/initializers/action_mailer.rb
ActionMailer::Base.smtp_settings = {}.tap { |config| config[:address] = ENV['SMTP_SERVER'] || 'smtp.gmail.com' config[:port] = ENV['SMTP_PORT']&.to_i || 587 config[:domain] = ENV['SMTP_DOMAIN'] authentication = ENV['SMTP_AUTHENTICATION'].presence || 'plain' user_name = ENV['SMTP_USER_NAME'].presence || 'none' if authentication != 'none' && user_name != 'none' config[:authentication] = authentication config[:user_name] = user_name config[:password] = ENV['SMTP_PASSWORD'].presence end config[:enable_starttls_auto] = ENV['SMTP_ENABLE_STARTTLS_AUTO'] == 'true' config[:ssl] = ENV['SMTP_SSL'] == 'true' config[:openssl_verify_mode] = ENV['SMTP_OPENSSL_VERIFY_MODE'].presence config[:ca_path] = ENV['SMTP_OPENSSL_CA_PATH'].presence config[:ca_file] = ENV['SMTP_OPENSSL_CA_FILE'].presence config[:read_timeout] = ENV['SMTP_READ_TIMEOUT']&.to_i config[:open_timeout] = ENV['SMTP_OPEN_TIMEOUT']&.to_i }
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/initializers/secret_token.rb
config/initializers/secret_token.rb
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Huginn::Application.config.secret_key_base = ENV['APP_SECRET_TOKEN']
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/deploy/production.rb
config/deploy/production.rb
server ENV['CAPISTRANO_DEPLOY_SERVER'], user: ENV['CAPISTRANO_DEPLOY_USER'] || 'huginn', port: ENV['CAPISTRANO_DEPLOY_PORT'] || 22, roles: %w{app db web}
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/environments/test.rb
config/environments/test.rb
require 'active_support/core_ext/integer/time' # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. config.cache_classes = false # do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Store uploaded files on the local file system in a temporary directory. # config.active_storage.service = :test config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test config.action_mailer.raise_delivery_errors = true # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Raise exception for unpermitted parameters config.action_controller.action_on_unpermitted_parameters = :raise config.action_mailer.default_url_options = { host: ENV['DOMAIN'] || 'localhost' } config.action_mailer.perform_deliveries = true if ENV['CI'] config.eager_load = true config.assets.debug = false config.assets.compile = true config.assets.digest = true end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/environments/development.rb
config/environments/development.rb
require "active_support/core_ext/integer/time" $stdout.sync = true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. config.hosts << ENV['DOMAIN'] # In the development environment your application's code is reloaded any time # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join('tmp', 'caching-dev.txt').exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options). # config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception for unpermitted parameters config.action_controller.action_on_unpermitted_parameters = :raise # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true config.action_mailer.default_url_options = { :host => ENV['DOMAIN'] } config.action_mailer.asset_host = ENV['DOMAIN'] config.action_mailer.raise_delivery_errors = true if ENV['SEND_EMAIL_IN_DEVELOPMENT'] == 'true' config.action_mailer.delivery_method = :smtp else config.action_mailer.delivery_method = :letter_opener_web end config.action_mailer.perform_caching = false # smtp_settings moved to config/initializers/action_mailer.rb # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/config/environments/production.rb
config/environments/production.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = false # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? if ENV["RAILS_LOG_TO_STDOUT"].present? || ENV['ON_HEROKU'] || ENV['HEROKU_POSTGRESQL_ROSE_URL'] || ENV['HEROKU_POSTGRESQL_GOLD_URL'] || File.read(File.join(File.dirname(__FILE__), '../../Procfile')) =~ /intended for Heroku/ logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Compress JavaScripts and CSS config.assets.js_compressor = :terser config.assets.css_compressor = :scss # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). # config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = ENV['FORCE_SSL'] == 'true' # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [:request_id] # Use a different cache store in production. config.cache_store = :memory_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "huginn_production" # Enable serving of images, stylesheets, and JavaScripts from an asset server if ENV['ASSET_HOST'].present? config.action_controller.asset_host = ENV['ASSET_HOST'] end # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false config.action_mailer.default_url_options = { host: ENV['DOMAIN'] } config.action_mailer.asset_host = ENV['DOMAIN'] if ENV['ASSET_HOST'].present? config.action_mailer.asset_host = ENV['ASSET_HOST'] end config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = ENV.fetch('SMTP_DELIVERY_METHOD', 'smtp').to_sym config.action_mailer.perform_caching = false # smtp_settings moved to config/initializers/action_mailer.rb # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/doc/deployment/capistrano/deploy.rb
doc/deployment/capistrano/deploy.rb
# This is an example Capistrano deployment script for Huginn. It # assumes you're running on an Ubuntu box and want to use Foreman, # Upstart, and Unicorn. default_run_options[:pty] = true set :application, "huginn" set :deploy_to, "/home/you/app" set :user, "you" set :use_sudo, false set :scm, :git set :rails_env, 'production' set :repository, "git@github.com:you/huginn-private.git" set :branch, ENV['BRANCH'] || "master" set :deploy_via, :remote_cache set :keep_releases, 5 puts " Deploying #{branch}" set :bundle_without, [:development] server "yourdomain.com", :app, :web, :db, :primary => true set :sync_backups, 3 before 'deploy:restart', 'deploy:migrate' after 'deploy', 'deploy:cleanup' set :bundle_without, [:development, :test] after 'deploy:update_code', 'deploy:symlink_configs' after 'deploy:update', 'foreman:export' after 'deploy:update', 'foreman:restart' namespace :deploy do desc 'Link the .env environment and Procfile from shared/config into the new deploy directory' task :symlink_configs, :roles => :app do run <<-CMD cd #{latest_release} && ln -nfs #{shared_path}/config/.env #{latest_release}/.env CMD run <<-CMD cd #{latest_release} && ln -nfs #{shared_path}/config/Procfile #{latest_release}/Procfile CMD end end namespace :foreman do desc "Export the Procfile to Ubuntu's upstart scripts" task :export, :roles => :app do run "cd #{latest_release} && rvmsudo bundle exec foreman export upstart /etc/init -a #{application} -u #{user} -l #{deploy_to}/upstart_logs" end desc 'Start the application services' task :start, :roles => :app do sudo "sudo start #{application}" end desc 'Stop the application services' task :stop, :roles => :app do sudo "sudo stop #{application}" end desc 'Restart the application services' task :restart, :roles => :app do run "sudo start #{application} || sudo restart #{application}" end end # If you want to use rvm on your server and have it maintained by Capistrano, uncomment these lines: # set :rvm_ruby_string, '2.3.4@huginn' # set :rvm_type, :user # before 'deploy', 'rvm:install_rvm' # before 'deploy', 'rvm:install_ruby' # require "rvm/capistrano" # Load Capistrano additions Dir[File.expand_path("../../lib/capistrano/*.rb", __FILE__)].each{|f| load f } require "bundler/capistrano" load 'deploy/assets'
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/doc/deployment/unicorn/production.rb
doc/deployment/unicorn/production.rb
app_path = "/home/you/app/current" worker_processes 2 preload_app true timeout 180 listen '/home/you/app/shared/pids/unicorn.socket' working_directory app_path rails_env = ENV['RAILS_ENV'] || 'production' # Log everything to one file stderr_path "log/unicorn.log" stdout_path "log/unicorn.log" # Set master PID location pid '/home/you/app/shared/pids/unicorn.pid' before_fork do |server, worker| ActiveRecord::Base.connection.disconnect! old_pid = "#{server.config[:pid]}.oldbin" if File.exist?(old_pid) && server.pid != old_pid begin Process.kill("QUIT", File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH # someone else did our job for us end end end after_fork do |server, worker| ActiveRecord::Base.establish_connection end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/doc/deployment/backup/example_backup.rb
doc/deployment/backup/example_backup.rb
# This file contains an example template for using the Backup gem for backing up your Huginn installation to S3. # In your crontab do something like: # 0 0,12 * * * /bin/bash -l -c "RAILS_ENV=production backup perform -t huginn_backup --config_file /home/you/huginn_backup.rb" 2>&1 >> /home/you/huginn_backup_log.txt # In backups.password on your server: # some password # In huginn_backup.rb on your server put an edited version of the following file. REMEMBER TO EDIT THE FILE! # You'll also need to install the backup gem on your server, as well as the net-ssh, excon, net-scp, and fog gems. Backup::Model.new(:huginn_backup, 'The Huginn backup configuration') do split_into_chunks_of 4000 database MySQL do |database| database.name = "your-database-name" database.username = "your-database-username" database.password = "your-database-password" database.host = "your-database-host" database.port = "your-database-port" database.socket = "your-database-socket" database.additional_options = ['--single-transaction', '--quick', '--hex-blob', '--add-drop-table'] end encrypt_with OpenSSL do |encryption| encryption.password_file = "/home/you/backups.password" encryption.base64 = true encryption.salt = true end compress_with Gzip do |compression| compression.level = 8 end store_with S3 do |s3| s3.access_key_id = 'YOUR_AWS_ACCESS_KEY' s3.secret_access_key = 'YOUR_AWS_SECRET' s3.region = 'us-east-1' s3.bucket = 'my-huginn-backups' s3.keep = 20 end notify_by Mail do |mail| mail.on_success = false mail.on_warning = true mail.on_failure = true mail.from = 'you@example.com' mail.to = 'you@example.com' mail.address = 'smtp.gmail.com' mail.domain = "example.com" mail.user_name = 'you@example.com' mail.password = 'password' mail.port = 587 mail.authentication = "plain" mail.encryption = :starttls end end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
huginn/huginn
https://github.com/huginn/huginn/blob/8edec55aab03d4e3f13b205db02d21dc36e34e4f/deployment/heroku/unicorn.rb
deployment/heroku/unicorn.rb
require "net/http" worker_processes Integer(ENV["WEB_CONCURRENCY"] || 2) timeout 15 preload_app true # Note that this will only work correctly when running Heroku with ONE web worker. # If you want to run more than one, use the standard Huginn Procfile instead, with separate web and job entries. # You'll need to set the Heroku config variable PROCFILE_PATH to 'Procfile'. Thread.new do worker_pid = nil while true if worker_pid.nil? worker_pid = spawn("bundle exec rails runner bin/threaded.rb") puts "New threaded worker PID: #{worker_pid}" end sleep 45 begin Process.getpgid worker_pid rescue Errno::ESRCH # No longer running worker_pid = nil end end end before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
ruby
MIT
8edec55aab03d4e3f13b205db02d21dc36e34e4f
2026-01-04T15:37:27.328445Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/support/docker_gateway.rb
features/support/docker_gateway.rb
# Ensure Docker container is completely stopped when Ruby exits. at_exit do DockerGateway.new.stop end # Manages the Docker-based SSH server that is declared in docker-compose.yml. class DockerGateway def initialize(log_proc=$stderr.method(:puts)) @log_proc = log_proc end def start run_compose_command("up -d") end def stop run_compose_command("down") end def run_shell_command(command) run_compose_command("exec ssh_server /bin/bash -c #{command.shellescape}") end private def run_compose_command(command) log "[docker compose] #{command}" stdout, stderr, status = Open3.popen3("docker compose #{command}") do |stdin, stdout, stderr, wait_threads| stdin << "" stdin.close out = Thread.new { read_lines(stdout, &$stdout.method(:puts)) } err = Thread.new { stderr.read } [out.value, err.value.to_s, wait_threads.value] end (stdout + stderr).each_line { |line| log "[docker compose] #{line}" } [stdout, stderr, status] end def read_lines(io) buffer = + "" while (line = io.gets) buffer << line yield line end buffer end def log(message) @log_proc.call(message) end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/support/env.rb
features/support/env.rb
require_relative "../../spec/support/test_app"
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/support/remote_command_helpers.rb
features/support/remote_command_helpers.rb
module RemoteCommandHelpers def test_dir_exists(path) exists?("d", path) end def test_symlink_exists(path) exists?("L", path) end def test_file_exists(path) exists?("f", path) end def exists?(type, path) %Q{[[ -#{type} "#{path}" ]]} end def symlinked?(symlink_path, target_path) "[ #{symlink_path} -ef #{target_path} ]" end def safely_remove_file(_path) run_remote_ssh_command("rm #{test_file}") rescue RemoteSSHHelpers::RemoteSSHCommandError end end World(RemoteCommandHelpers)
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/support/remote_ssh_helpers.rb
features/support/remote_ssh_helpers.rb
require "open3" require "socket" require_relative "docker_gateway" module RemoteSSHHelpers extend self class RemoteSSHCommandError < RuntimeError; end def start_ssh_server docker_gateway.start end def wait_for_ssh_server(retries=3) Socket.tcp("localhost", 2022, connect_timeout: 1).close rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT retries -= 1 sleep(2) && retry if retries.positive? raise end def run_remote_ssh_command(command) stdout, stderr, status = docker_gateway.run_shell_command(command) return [stdout, stderr] if status.success? raise RemoteSSHCommandError, status end def docker_gateway @docker_gateway ||= DockerGateway.new(method(:log)) end end World(RemoteSSHHelpers)
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/step_definitions/assertions.rb
features/step_definitions/assertions.rb
require "shellwords" Then(/^references in the remote repo are listed$/) do expect(@output).to include("refs/heads/master") end Then(/^git wrapper permissions are 0700$/) do permissions_test = %Q([ $(stat -c "%a" #{TestApp.git_wrapper_path_glob}) == "700" ]) expect { run_remote_ssh_command(permissions_test) }.not_to raise_error end Then(/^the shared path is created$/) do run_remote_ssh_command(test_dir_exists(TestApp.shared_path)) end Then(/^the releases path is created$/) do run_remote_ssh_command(test_dir_exists(TestApp.releases_path)) end Then(/^(\d+) valid releases are kept/) do |num| test = %Q([ $(ls -g #{TestApp.releases_path} | grep -E '[0-9]{14}' | wc -l) == "#{num}" ]) expect { run_remote_ssh_command(test) }.not_to raise_error end Then(/^the invalid (.+) release is ignored$/) do |filename| test = "ls -g #{TestApp.releases_path} | grep #{filename}" expect { run_remote_ssh_command(test) }.not_to raise_error end Then(/^directories in :linked_dirs are created in shared$/) do TestApp.linked_dirs.each do |dir| run_remote_ssh_command(test_dir_exists(TestApp.shared_path.join(dir))) end end Then(/^directories referenced in :linked_files are created in shared$/) do dirs = TestApp.linked_files.map { |path| TestApp.shared_path.join(path).dirname } dirs.each do |dir| run_remote_ssh_command(test_dir_exists(dir)) end end Then(/^the repo is cloned$/) do run_remote_ssh_command(test_dir_exists(TestApp.repo_path)) end Then(/^the release is created$/) do stdout, _stderr = run_remote_ssh_command("ls #{TestApp.releases_path}") expect(stdout.strip).to match(/\A#{Time.now.utc.strftime("%Y%m%d")}\d{6}\Z/) end Then(/^the REVISION file is created in the release$/) do stdout, _stderr = run_remote_ssh_command("cat #{@release_paths[0]}/REVISION") expect(stdout.strip).to match(/\h{40}/) end Then(/^the REVISION_TIME file is created in the release$/) do stdout, _stderr = run_remote_ssh_command("cat #{@release_paths[0]}/REVISION_TIME") expect(stdout.strip).to match(/\d{10}/) end Then(/^file symlinks are created in the new release$/) do TestApp.linked_files.each do |file| run_remote_ssh_command(test_symlink_exists(TestApp.current_path.join(file))) end end Then(/^directory symlinks are created in the new release$/) do pending TestApp.linked_dirs.each do |dir| run_remote_ssh_command(test_symlink_exists(TestApp.release_path.join(dir))) end end Then(/^the current directory will be a symlink to the release$/) do run_remote_ssh_command(exists?("e", TestApp.current_path)) end Then(/^the deploy\.rb file is created$/) do file = TestApp.test_app_path.join("config/deploy.rb") expect(File.exist?(file)).to be true end Then(/^the default stage files are created$/) do staging = TestApp.test_app_path.join("config/deploy/staging.rb") production = TestApp.test_app_path.join("config/deploy/production.rb") expect(File.exist?(staging)).to be true expect(File.exist?(production)).to be true end Then(/^the tasks folder is created$/) do path = TestApp.test_app_path.join("lib/capistrano/tasks") expect(Dir.exist?(path)).to be true end Then(/^the specified stage files are created$/) do qa = TestApp.test_app_path.join("config/deploy/qa.rb") production = TestApp.test_app_path.join("config/deploy/production.rb") expect(File.exist?(qa)).to be true expect(File.exist?(production)).to be true end Then(/^it creates the file with the remote_task prerequisite$/) do TestApp.linked_files.each do |file| run_remote_ssh_command(test_file_exists(TestApp.shared_path.join(file))) end end Then(/^it will not recreate the file$/) do # end Then(/^the task is successful$/) do expect(@success).to be true end Then(/^the task fails$/) do expect(@success).to be_falsey end Then(/^the failure task will run$/) do failed = TestApp.shared_path.join("failed") run_remote_ssh_command(test_file_exists(failed)) end Then(/^the failure task will not run$/) do failed = TestApp.shared_path.join("failed") expect { run_remote_ssh_command(test_file_exists(failed)) } .to raise_error(RemoteSSHHelpers::RemoteSSHCommandError) end When(/^an error is raised$/) do error = TestApp.shared_path.join("fail") run_remote_ssh_command(test_file_exists(error)) end Then(/contains "([^"]*)" in the output/) do |expected| expect(@output).to include(expected) end Then(/the output matches "([^"]*)" followed by "([^"]*)"/) do |expected, followedby| expect(@output).to match(/#{expected}.*#{followedby}/m) end Then(/doesn't contain "([^"]*)" in the output/) do |expected| expect(@output).not_to include(expected) end Then(/the current symlink points to the previous release/) do previous_release_path = @release_paths[-2] run_remote_ssh_command(symlinked?(TestApp.current_path, previous_release_path)) end Then(/^the current symlink points to that specific release$/) do specific_release_path = TestApp.releases_path.join(@rollback_release) run_remote_ssh_command(symlinked?(TestApp.current_path, specific_release_path)) end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/step_definitions/setup.rb
features/step_definitions/setup.rb
Given(/^a test app with the default configuration$/) do TestApp.install end Given(/^a test app without any configuration$/) do TestApp.create_test_app end Given(/^servers with the roles app and web$/) do start_ssh_server wait_for_ssh_server end Given(/^a linked file "(.*?)"$/) do |file| # ignoring other linked files TestApp.append_to_deploy_file("set :linked_files, ['#{file}']") end Given(/^file "(.*?)" exists in shared path$/) do |file| file_shared_path = TestApp.shared_path.join(file) run_remote_ssh_command("mkdir -p #{file_shared_path.dirname}") run_remote_ssh_command("touch #{file_shared_path}") end Given(/^all linked files exists in shared path$/) do TestApp.linked_files.each do |linked_file| step %Q{file "#{linked_file}" exists in shared path} end end Given(/^file "(.*?)" does not exist in shared path$/) do |file| file_shared_path = TestApp.shared_path.join(file) run_remote_ssh_command("mkdir -p #{TestApp.shared_path}") run_remote_ssh_command("touch #{file_shared_path} && rm #{file_shared_path}") end Given(/^a custom task to generate a file$/) do TestApp.copy_task_to_test_app("spec/support/tasks/database.rake") end Given(/^a task which executes as root$/) do TestApp.copy_task_to_test_app("spec/support/tasks/root.rake") end Given(/config stage file has line "(.*?)"/) do |line| TestApp.append_to_deploy_file(line) end Given(/^the configuration is in a custom location$/) do TestApp.move_configuration_to_custom_location("app") end Given(/^a custom task that will simulate a failure$/) do safely_remove_file(TestApp.shared_path.join("failed")) TestApp.copy_task_to_test_app("spec/support/tasks/fail.rake") end Given(/^a custom task to run in the event of a failure$/) do safely_remove_file(TestApp.shared_path.join("failed")) TestApp.copy_task_to_test_app("spec/support/tasks/failed.rake") end Given(/^a stage file named (.+)$/) do |filename| TestApp.write_local_stage_file(filename) end Given(/^I make (\d+) deployments?$/) do |count| step "all linked files exists in shared path" @release_paths = (1..count.to_i).map do TestApp.cap("deploy") stdout, _stderr = run_remote_ssh_command("readlink #{TestApp.current_path}") stdout.strip end end Given(/^(\d+) valid existing releases$/) do |num| a_day = 86_400 # in seconds (1...num).each_slice(100) do |num_batch| dirs = num_batch.map do |i| offset = -(a_day * i) TestApp.release_path(TestApp.timestamp(offset)) end run_remote_ssh_command("mkdir -p #{dirs.join(' ')}") end end Given(/^an invalid release named "(.+)"$/) do |filename| run_remote_ssh_command("mkdir -p #{TestApp.release_path(filename)}") end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/features/step_definitions/cap_commands.rb
features/step_definitions/cap_commands.rb
When(/^I run cap "(.*?)"$/) do |task| @success, @output = TestApp.cap(task) end When(/^I run cap "(.*?)" within the "(.*?)" directory$/) do |task, directory| @success, @output = TestApp.cap(task, directory) end When(/^I run cap "(.*?)" as part of a release$/) do |task| TestApp.cap("deploy:new_release_path #{task}") end When(/^I run "(.*?)"$/) do |command| @success, @output = TestApp.run(command) end When(/^I rollback to a specific release$/) do @rollback_release = @release_paths.first.split("/").last step %Q{I run cap "deploy:rollback ROLLBACK_RELEASE=#{@rollback_release}"} end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/integration_spec_helper.rb
spec/integration_spec_helper.rb
require "spec_helper" require "support/test_app" require "support/matchers" include TestApp
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) $LOAD_PATH.unshift(File.dirname(__FILE__)) require "capistrano/all" require "rspec" require "mocha/api" require "time" # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir['#{File.dirname(__FILE__)}/support/**/*.rb'].each { |f| require f } RSpec.configure do |config| config.raise_errors_for_deprecations! config.mock_framework = :mocha config.order = "random" config.around(:example, capture_io: true) do |example| begin Rake.application.options.trace_output = StringIO.new $stdout = StringIO.new $stderr = StringIO.new example.run ensure Rake.application.options.trace_output = STDERR $stdout = STDOUT $stderr = STDERR end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/support/test_app.rb
spec/support/test_app.rb
require "English" require "fileutils" require "pathname" require "open3" module TestApp extend self def install install_test_app_with(default_config) end def default_config <<-CONFIG set :deploy_to, '#{deploy_to}' set :repo_url, 'https://github.com/capistrano/capistrano.git' set :branch, 'master' set :ssh_options, { keys: '#{File.expand_path('../../.docker/ssh_key_rsa', __dir__)}', auth_methods: ['publickey'] } server 'deployer@localhost:2022', roles: %w{web app} set :linked_files, #{linked_files} set :linked_dirs, #{linked_dirs} set :format_options, log_file: nil set :local_user, #{current_user.inspect} CONFIG end def linked_files %w{config/database.yml} end def linked_file shared_path.join(linked_files.first) end def linked_dirs %w{bin log public/system} end def create_test_app FileUtils.rm_rf(test_app_path) FileUtils.mkdir(test_app_path) File.write(gemfile, <<-GEMFILE.gsub(/^\s+/, "")) source "https://rubygems.org" gem "capistrano", path: #{path_to_cap.to_s.inspect} gem "ed25519", ">= 1.2", "< 2.0" gem "bcrypt_pbkdf", ">= 1.0", "< 2.0" GEMFILE Dir.chdir(test_app_path) do run "bundle" end end def install_test_app_with(config) create_test_app Dir.chdir(test_app_path) do run "cap install STAGES=#{stage}" end write_local_deploy_file(config) end def write_local_deploy_file(config) File.open(test_stage_path, "w") do |file| file.write config end end def write_local_stage_file(filename, config=nil) File.open(test_app_path.join("config/deploy/#{filename}"), "w") do |file| file.write(config) if config end end def append_to_deploy_file(config) File.open(test_stage_path, "a") do |file| file.write config + "\n" end end def prepend_to_capfile(config) current_capfile = File.read(capfile) File.open(capfile, "w") do |file| file.write config file.write current_capfile end end def create_shared_directory(path) FileUtils.mkdir_p(shared_path.join(path)) end def create_shared_file(path) File.open(shared_path.join(path), "w") end def cap(task, subdirectory=nil) run "cap #{stage} #{task} --trace", subdirectory end def run(command, subdirectory=nil) command = "bundle exec #{command}" unless command =~ /^bundle\b/ dir = subdirectory ? test_app_path.join(subdirectory) : test_app_path output, status = Dir.chdir(dir) do with_clean_bundler_env { Open3.capture2e(command) } end [status.success?, output] end def stage "test" end def test_stage_path test_app_path.join("config/deploy/test.rb") end def test_app_path Pathname.new("/tmp/test_app") end def deploy_to Pathname.new("/home/deployer/var/www/deploy") end def shared_path deploy_to.join("shared") end def current_path deploy_to.join("current") end def releases_path deploy_to.join("releases") end def release_path(t=timestamp) releases_path.join(t) end def timestamp(offset=0) (Time.now.utc + offset).strftime("%Y%m%d%H%M%S") end def repo_path deploy_to.join("repo") end def path_to_cap File.expand_path(".") end def gemfile test_app_path.join("Gemfile") end def capfile test_app_path.join("Capfile") end def current_user "(GitHub Web Flow) via ShipIt" end def task_dir test_app_path.join("lib/capistrano/tasks") end def copy_task_to_test_app(source) FileUtils.cp(source, task_dir) end def config_path test_app_path.join("config") end def move_configuration_to_custom_location(location) prepend_to_capfile( <<-CONFIG set :stage_config_path, "app/config/deploy" set :deploy_config_path, "app/config/deploy.rb" CONFIG ) location = test_app_path.join(location) FileUtils.mkdir_p(location) FileUtils.mv(config_path, location) end def git_wrapper_path_glob "/tmp/git-ssh-*.sh" end def with_clean_bundler_env(&block) return yield unless defined?(Bundler) if Bundler.respond_to?(:with_unbundled_env) Bundler.with_unbundled_env(&block) else Bundler.with_clean_env(&block) end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/support/matchers.rb
spec/support/matchers.rb
RSpec::Matchers.define :be_a_symlink_to do |expected| match do |actual| File.identical?(expected, actual) end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/integration/dsl_spec.rb
spec/integration/dsl_spec.rb
require "spec_helper" describe Capistrano::DSL do let(:dsl) { Class.new.extend Capistrano::DSL } before do Capistrano::Configuration.reset! end describe "setting and fetching hosts" do describe "when defining a host using the `server` syntax" do before do dsl.server "example1.com", roles: %w{web}, active: true dsl.server "example2.com", roles: %w{web} dsl.server "example3.com", roles: %w{app web}, active: true dsl.server "example4.com", roles: %w{app}, primary: true dsl.server "example5.com", roles: %w{db}, no_release: true, active: true end describe "fetching all servers" do subject { dsl.roles(:all) } it "returns all servers" do expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com example5.com} end end describe "fetching all release servers" do context "with no additional options" do subject { dsl.release_roles(:all) } it "returns all release servers" do expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com} end end context "with property filter options" do subject { dsl.release_roles(:all, filter: :active) } it "returns all release servers that match the property filter" do expect(subject.map(&:hostname)).to eq %w{example1.com example3.com} end end end describe "fetching servers by multiple roles" do it "does not confuse the last role with options" do expect(dsl.roles(:app, :web).count).to eq 4 expect(dsl.roles(:app, :web, filter: :active).count).to eq 2 end end describe "fetching servers by role" do subject { dsl.roles(:app) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com example4.com} end end describe "fetching servers by an array of roles" do subject { dsl.roles([:app]) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com example4.com} end end describe "fetching filtered servers by role" do subject { dsl.roles(:app, filter: :active) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com} end end describe "fetching selected servers by role" do subject { dsl.roles(:app, select: :active) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com} end end describe "fetching the primary server by role" do context "when inferring primary status based on order" do subject { dsl.primary(:web) } it "returns the servers" do expect(subject.hostname).to eq "example1.com" end end context "when the attribute `primary` is explicitly set" do subject { dsl.primary(:app) } it "returns the servers" do expect(subject.hostname).to eq "example4.com" end end end describe "setting an internal host filter" do subject { dsl.roles(:app) } it "is ignored" do dsl.set :filter, host: "example3.com" expect(subject.map(&:hostname)).to eq(["example3.com", "example4.com"]) end end describe "setting an internal role filter" do subject { dsl.roles(:app) } it "ignores it" do dsl.set :filter, role: :web expect(subject.map(&:hostname)).to eq(["example3.com", "example4.com"]) end end describe "setting an internal host and role filter" do subject { dsl.roles(:app) } it "ignores it" do dsl.set :filter, role: :web, host: "example1.com" expect(subject.map(&:hostname)).to eq(["example3.com", "example4.com"]) end end describe "setting an internal regexp host filter" do subject { dsl.roles(:all) } it "is ignored" do dsl.set :filter, host: /1/ expect(subject.map(&:hostname)).to eq(%w{example1.com example2.com example3.com example4.com example5.com}) end end describe "setting an internal hosts filter" do subject { dsl.roles(:app) } it "is ignored" do dsl.set :filter, hosts: "example3.com" expect(subject.map(&:hostname)).to eq(["example3.com", "example4.com"]) end end describe "setting an internal roles filter" do subject { dsl.roles(:app) } it "ignores it" do dsl.set :filter, roles: :web expect(subject.map(&:hostname)).to eq(["example3.com", "example4.com"]) end end describe "setting an internal hosts and roles filter" do subject { dsl.roles(:app) } it "ignores it" do dsl.set :filter, roles: :web, hosts: "example1.com" expect(subject.map(&:hostname)).to eq(["example3.com", "example4.com"]) end end describe "setting an internal regexp hosts filter" do subject { dsl.roles(:all) } it "is ignored" do dsl.set :filter, hosts: /1/ expect(subject.map(&:hostname)).to eq(%w{example1.com example2.com example3.com example4.com example5.com}) end end end describe "when defining role with reserved name" do it "fails with ArgumentError" do expect do dsl.role :all, %w{example1.com} end.to raise_error(ArgumentError, "all reserved name for role. Please choose another name") end end describe "when defining hosts using the `role` syntax" do before do dsl.role :web, %w{example1.com example2.com example3.com} dsl.role :web, %w{example1.com}, active: true dsl.role :app, %w{example3.com example4.com} dsl.role :app, %w{example3.com}, active: true dsl.role :app, %w{example4.com}, primary: true dsl.role :db, %w{example5.com}, no_release: true end describe "fetching all servers" do subject { dsl.roles(:all) } it "returns all servers" do expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com example5.com} end end describe "fetching all release servers" do context "with no additional options" do subject { dsl.release_roles(:all) } it "returns all release servers" do expect(subject.map(&:hostname)).to eq %w{example1.com example2.com example3.com example4.com} end end context "with filter options" do subject { dsl.release_roles(:all, filter: :active) } it "returns all release servers that match the filter" do expect(subject.map(&:hostname)).to eq %w{example1.com example3.com} end end end describe "fetching servers by role" do subject { dsl.roles(:app) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com example4.com} end end describe "fetching servers by an array of roles" do subject { dsl.roles([:app]) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com example4.com} end end describe "fetching filtered servers by role" do subject { dsl.roles(:app, filter: :active) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com} end end describe "fetching selected servers by role" do subject { dsl.roles(:app, select: :active) } it "returns the servers" do expect(subject.map(&:hostname)).to eq %w{example3.com} end end describe "fetching the primary server by role" do context "when inferring primary status based on order" do subject { dsl.primary(:web) } it "returns the servers" do expect(subject.hostname).to eq "example1.com" end end context "when the attribute `primary` is explicitly set" do subject { dsl.primary(:app) } it "returns the servers" do expect(subject.hostname).to eq "example4.com" end end end end describe "when defining a host using a combination of the `server` and `role` syntax" do before do dsl.server "db@example1.com:1234", roles: %w{db}, active: true dsl.server "root@example1.com:1234", roles: %w{web}, active: true dsl.server "example1.com:5678", roles: %w{web}, active: true dsl.role :app, %w{deployer@example1.com:1234} dsl.role :app, %w{example1.com:5678} end describe "fetching all servers" do it "creates one server per hostname, ignoring user combinations" do expect(dsl.roles(:all).size).to eq(2) end end describe "fetching servers for a role" do it "roles defined using the `server` syntax are included" do as = dsl.roles(:web).map { |server| "#{server.user}@#{server.hostname}:#{server.port}" } expect(as.size).to eq(2) expect(as[0]).to eq("deployer@example1.com:1234") expect(as[1]).to eq("@example1.com:5678") end it "roles defined using the `role` syntax are included" do as = dsl.roles(:app).map { |server| "#{server.user}@#{server.hostname}:#{server.port}" } expect(as.size).to eq(2) expect(as[0]).to eq("deployer@example1.com:1234") expect(as[1]).to eq("@example1.com:5678") end end end describe "when setting user and port" do subject { dsl.roles(:all).map { |server| "#{server.user}@#{server.hostname}:#{server.port}" }.first } describe "using the :user property" do it "takes precedence over in the host string" do dsl.server "db@example1.com:1234", roles: %w{db}, active: true, user: "brian" expect(subject).to eq("brian@example1.com:1234") end end describe "using the :port property" do it "takes precedence over in the host string" do dsl.server "db@example1.com:9090", roles: %w{db}, active: true, port: 1234 expect(subject).to eq("db@example1.com:1234") end end end end describe "setting and fetching variables" do before do dsl.set :scm, :git end context "without a default" do context "when the variables is defined" do it "returns the variable" do expect(dsl.fetch(:scm)).to eq :git end end context "when the variables is undefined" do it "returns nil" do expect(dsl.fetch(:source_control)).to be_nil end end end context "with a default" do context "when the variables is defined" do it "returns the variable" do expect(dsl.fetch(:scm, :svn)).to eq :git end end context "when the variables is undefined" do it "returns the default" do expect(dsl.fetch(:source_control, :svn)).to eq :svn end end end context "with a block" do context "when the variables is defined" do it "returns the variable" do expect(dsl.fetch(:scm) { :svn }).to eq :git end end context "when the variables is undefined" do it "calls the block" do expect(dsl.fetch(:source_control) { :svn }).to eq :svn end end end end describe "asking for a variable" do let(:stdin) { stub(tty?: true) } before do dsl.ask(:scm, :svn, stdin: stdin) $stdout.stubs(:print) end context "variable is provided" do before do stdin.expects(:gets).returns("git") end it "sets the input as the variable" do expect(dsl.fetch(:scm)).to eq "git" end end context "variable is not provided" do before do stdin.expects(:gets).returns("") end it "sets the variable as the default" do expect(dsl.fetch(:scm)).to eq :svn end end end describe "checking for presence" do subject { dsl.any? :linked_files } before do dsl.set(:linked_files, linked_files) end context "variable is an non-empty array" do let(:linked_files) { %w{1} } it { expect(subject).to be_truthy } end context "variable is an empty array" do let(:linked_files) { [] } it { expect(subject).to be_falsey } end context "variable exists, is not an array" do let(:linked_files) { stub } it { expect(subject).to be_truthy } end context "variable is nil" do let(:linked_files) { nil } it { expect(subject).to be_falsey } end end describe "configuration SSHKit" do let(:config) { SSHKit.config } let(:backend) { SSHKit.config.backend.config } let(:default_env) { { rails_env: :production } } before do dsl.set(:format, :dot) dsl.set(:log_level, :debug) dsl.set(:default_env, default_env) dsl.set(:pty, true) dsl.set(:connection_timeout, 10) dsl.set(:ssh_options, keys: %w(/home/user/.ssh/id_rsa), forward_agent: false, auth_methods: %w(publickey password)) dsl.configure_backend end it "sets the output" do expect(config.output).to be_a SSHKit::Formatter::Dot end it "sets the output verbosity" do expect(config.output_verbosity).to eq 0 end it "sets the default env" do expect(config.default_env).to eq default_env end it "sets the backend pty" do expect(backend.pty).to be_truthy end it "sets the backend connection timeout" do expect(backend.connection_timeout).to eq 10 end it "sets the backend ssh_options" do expect(backend.ssh_options[:keys]).to eq %w(/home/user/.ssh/id_rsa) expect(backend.ssh_options[:forward_agent]).to eq false expect(backend.ssh_options[:auth_methods]).to eq %w(publickey password) end end describe "on()" do describe "when passed server objects" do before do dsl.server "example1.com", roles: %w{web}, active: true dsl.server "example2.com", roles: %w{web} dsl.server "example3.com", roles: %w{app web}, active: true dsl.server "example4.com", roles: %w{app}, primary: true dsl.server "example5.com", roles: %w{db}, no_release: true @coordinator = mock("coordinator") @coordinator.expects(:each).returns(nil) ENV.delete "ROLES" ENV.delete "HOSTS" end it "filters by role from the :filter variable" do hosts = dsl.roles(:web) all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator) dsl.set :filter, role: "web" dsl.on(all) end it "filters by host and role from the :filter variable" do all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) dsl.set :filter, role: "db", host: "example3.com" dsl.on(all) end it "filters by roles from the :filter variable" do hosts = dsl.roles(:web) all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator) dsl.set :filter, roles: "web" dsl.on(all) end it "filters by hosts and roles from the :filter variable" do all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) dsl.set :filter, roles: "db", hosts: "example3.com" dsl.on(all) end it "filters from ENV[ROLES]" do hosts = dsl.roles(:db) all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator) ENV["ROLES"] = "db" dsl.on(all) end it "filters from ENV[HOSTS]" do hosts = dsl.roles(:db) all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with(hosts).returns(@coordinator) ENV["HOSTS"] = "example5.com" dsl.on(all) end it "filters by ENV[HOSTS] && ENV[ROLES]" do all = dsl.roles(:all) SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) ENV["HOSTS"] = "example5.com" ENV["ROLES"] = "web" dsl.on(all) end end describe "when passed server literal names" do before do ENV.delete "ROLES" ENV.delete "HOSTS" @coordinator = mock("coordinator") @coordinator.expects(:each).returns(nil) end it "selects nothing when a role filter is present" do dsl.set :filter, role: "web" SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) dsl.on("my.server") end it "selects using the string when a host filter is present" do dsl.set :filter, host: "server.local" SSHKit::Coordinator.expects(:new).with(["server.local"]).returns(@coordinator) dsl.on("server.local") end it "doesn't select when a host filter is present that doesn't match" do dsl.set :filter, host: "ruby.local" SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) dsl.on("server.local") end it "selects nothing when a roles filter is present" do dsl.set :filter, roles: "web" SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) dsl.on("my.server") end it "selects using the string when a hosts filter is present" do dsl.set :filter, hosts: "server.local" SSHKit::Coordinator.expects(:new).with(["server.local"]).returns(@coordinator) dsl.on("server.local") end it "doesn't select when a hosts filter is present that doesn't match" do dsl.set :filter, hosts: "ruby.local" SSHKit::Coordinator.expects(:new).with([]).returns(@coordinator) dsl.on("server.local") end end end describe "role_properties()" do before do dsl.role :redis, %w[example1.com example2.com], redis: { port: 6379, type: :slave } dsl.server "example1.com", roles: %w{web}, active: true, web: { port: 80 } dsl.server "example2.com", roles: %w{web redis}, web: { port: 81 }, redis: { type: :master } dsl.server "example3.com", roles: %w{app}, primary: true end it "retrieves properties for a single role as a set" do rps = dsl.role_properties(:app) expect(rps).to eq(Set[{ hostname: "example3.com", role: :app }]) end it "retrieves properties for multiple roles as a set" do rps = dsl.role_properties(:app, :web) expect(rps).to eq(Set[{ hostname: "example3.com", role: :app }, { hostname: "example1.com", role: :web, port: 80 }, { hostname: "example2.com", role: :web, port: 81 }]) end it "yields the properties for a single role" do recipient = mock("recipient") recipient.expects(:doit).with("example1.com", :redis, { port: 6379, type: :slave }) recipient.expects(:doit).with("example2.com", :redis, { port: 6379, type: :master }) dsl.role_properties(:redis) do |host, role, props| recipient.doit(host, role, props) end end it "yields the properties for multiple roles" do recipient = mock("recipient") recipient.expects(:doit).with("example1.com", :redis, { port: 6379, type: :slave }) recipient.expects(:doit).with("example2.com", :redis, { port: 6379, type: :master }) recipient.expects(:doit).with("example3.com", :app, nil) dsl.role_properties(:redis, :app) do |host, role, props| recipient.doit(host, role, props) end end it "yields the merged properties for multiple roles" do recipient = mock("recipient") recipient.expects(:doit).with("example1.com", :redis, { port: 6379, type: :slave }) recipient.expects(:doit).with("example2.com", :redis, { port: 6379, type: :master }) recipient.expects(:doit).with("example1.com", :web, { port: 80 }) recipient.expects(:doit).with("example2.com", :web, { port: 81 }) dsl.role_properties(:redis, :web) do |host, role, props| recipient.doit(host, role, props) end end it "honours a property filter before yielding" do recipient = mock("recipient") recipient.expects(:doit).with("example1.com", :redis, { port: 6379, type: :slave }) recipient.expects(:doit).with("example1.com", :web, { port: 80 }) dsl.role_properties(:redis, :web, select: :active) do |host, role, props| recipient.doit(host, role, props) end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano_spec.rb
spec/lib/capistrano_spec.rb
require "spec_helper" module Capistrano describe Application do let(:app) { Application.new } end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/upload_task_spec.rb
spec/lib/capistrano/upload_task_spec.rb
require "spec_helper" describe Capistrano::UploadTask do let(:app) { Rake.application = Rake::Application.new } subject(:upload_task) { described_class.define_task("path/file.yml") } it { is_expected.to be_a(Rake::FileCreationTask) } it { is_expected.to be_needed } context "inside namespace" do let(:normal_task) { Rake::Task.define_task("path/other_file.yml") } around { |ex| app.in_namespace("namespace", &ex) } it { expect(upload_task.name).to eq("path/file.yml") } it { expect(upload_task.scope.path).to eq("namespace") } end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/dsl_spec.rb
spec/lib/capistrano/dsl_spec.rb
require "spec_helper" module Capistrano class DummyDSL include DSL end # see also - spec/integration/dsl_spec.rb describe DSL do let(:dsl) { DummyDSL.new } describe "#t" do before do I18n.expects(:t).with(:phrase, count: 2, scope: :capistrano) end it "delegates to I18n" do dsl.t(:phrase, count: 2) end end describe "#stage_set?" do subject { dsl.stage_set? } context "stage is set" do before do dsl.set(:stage, :sandbox) end it { expect(subject).to be_truthy } end context "stage is not set" do before do dsl.set(:stage, nil) end it { expect(subject).to be_falsey } end end describe "#sudo" do before do dsl.expects(:execute).with(:sudo, :my, :command) end it "prepends sudo, delegates to execute" do dsl.sudo(:my, :command) end end describe "#execute" do context "use outside of on scope" do after do task.clear Rake::Task.clear end let(:task) do Rake::Task.define_task("execute_outside_scope") do dsl.execute "whoami" end end it "prints helpful message to stderr", capture_io: true do expect do expect do task.invoke end.to output(/^.*Warning: `execute' should be wrapped in an `on' scope/).to_stderr end.to raise_error(NoMethodError) end end end describe "#invoke" do context "reinvoking" do it "will not re-enable invoking task", capture_io: true do counter = 0 Rake::Task.define_task("A") do counter += 1 end expect do dsl.invoke("A") dsl.invoke("A") end.to change { counter }.by(1) end it "will print a message on stderr", capture_io: true do Rake::Task.define_task("B") expect do dsl.invoke("B") dsl.invoke("B") end.to output(/If you really meant to run this task again, use invoke!/).to_stderr end end end describe "#invoke!" do context "reinvoking" do it "will re-enable invoking task", capture_io: true do counter = 0 Rake::Task.define_task("C") do counter += 1 end expect do dsl.invoke!("C") dsl.invoke!("C") end.to change { counter }.by(2) end it "will not print a message on stderr", capture_io: true do Rake::Task.define_task("D") expect do dsl.invoke!("D") dsl.invoke!("D") end.to_not output(/If you really meant to run this task again, use invoke!/).to_stderr end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration_spec.rb
spec/lib/capistrano/configuration_spec.rb
require "spec_helper" module Capistrano describe Configuration do let(:config) { Configuration.new } let(:servers) { stub } describe ".new" do it "accepts initial hash" do configuration = described_class.new(custom: "value") expect(configuration.fetch(:custom)).to eq("value") end end describe ".env" do it "is a global accessor to a single instance" do Configuration.env.set(:test, true) expect(Configuration.env.fetch(:test)).to be_truthy end end describe ".reset!" do it "blows away the existing `env` and creates a new one" do old_env = Configuration.env Configuration.reset! expect(Configuration.env).not_to be old_env end end describe "roles" do context "adding a role" do subject { config.role(:app, %w{server1 server2}) } before do Configuration::Servers.expects(:new).returns(servers) servers.expects(:add_role).with(:app, %w{server1 server2}, {}) end it "adds the role" do expect(subject) end end end describe "setting and fetching" do subject { config.fetch(:key, :default) } context "set" do it "sets by value" do config.set(:key, :value) expect(subject).to eq :value end it "sets by block" do config.set(:key) { :value } expect(subject).to eq :value end it "raises an exception when given both a value and block" do expect { config.set(:key, :value) { :value } }.to raise_error(Capistrano::ValidationError) end end context "set_if_empty" do it "sets by value when none is present" do config.set_if_empty(:key, :value) expect(subject).to eq :value end it "sets by block when none is present" do config.set_if_empty(:key) { :value } expect(subject).to eq :value end it "does not overwrite existing values" do config.set(:key, :value) config.set_if_empty(:key, :update) config.set_if_empty(:key) { :update } expect(subject).to eq :value end end context "value is not set" do it "returns the default value" do expect(subject).to eq :default end end context "value is a proc" do subject { config.fetch(:key, proc { :proc }) } it "calls the proc" do expect(subject).to eq :proc end end context "value is a lambda" do subject { config.fetch(:key, -> { :lambda }) } it "calls the lambda" do expect(subject).to eq :lambda end end context "value inside proc inside a proc" do subject { config.fetch(:key, proc { proc { "some value" } }) } it "calls all procs and lambdas" do expect(subject).to eq "some value" end end context "value inside lambda inside a lambda" do subject { config.fetch(:key, -> { -> { "some value" } }) } it "calls all procs and lambdas" do expect(subject).to eq "some value" end end context "value inside lambda inside a proc" do subject { config.fetch(:key, proc { -> { "some value" } }) } it "calls all procs and lambdas" do expect(subject).to eq "some value" end end context "value inside proc inside a lambda" do subject { config.fetch(:key, -> { proc { "some value" } }) } it "calls all procs and lambdas" do expect(subject).to eq "some value" end end context "lambda with parameters" do subject { config.fetch(:key, ->(c) { c }).call(42) } it "is returned as a lambda" do expect(subject).to eq 42 end end context "block is passed to fetch" do subject { config.fetch(:key, :default) { raise "we need this!" } } it "returns the block value" do expect { subject }.to raise_error(RuntimeError) end end context "validations" do before do config.validate :key do |_, value| raise Capistrano::ValidationError unless value.length > 3 end end it "validates string without error" do config.set(:key, "longer_value") end it "validates block without error" do config.set(:key) { "longer_value" } expect(config.fetch(:key)).to eq "longer_value" end it "validates lambda without error" do config.set :key, -> { "longer_value" } expect(config.fetch(:key)).to eq "longer_value" end it "raises an exception on invalid string" do expect { config.set(:key, "sho") }.to raise_error(Capistrano::ValidationError) end it "raises an exception on invalid string provided by block" do config.set(:key) { "sho" } expect { config.fetch(:key) }.to raise_error(Capistrano::ValidationError) end it "raises an exception on invalid string provided by lambda" do config.set :key, -> { "sho" } expect { config.fetch(:key) }.to raise_error(Capistrano::ValidationError) end end context "appending" do subject { config.append(:linked_dirs, "vendor/bundle", "tmp") } it "returns appended value" do expect(subject).to eq ["vendor/bundle", "tmp"] end context "on non-array variable" do before { config.set(:linked_dirs, "string") } subject { config.append(:linked_dirs, "vendor/bundle") } it "returns appended value" do expect(subject).to eq ["string", "vendor/bundle"] end end end context "removing" do before :each do config.set(:linked_dirs, ["vendor/bundle", "tmp"]) end subject { config.remove(:linked_dirs, "vendor/bundle") } it "returns without removed value" do expect(subject).to eq ["tmp"] end context "on non-array variable" do before { config.set(:linked_dirs, "string") } context "when removing same value" do subject { config.remove(:linked_dirs, "string") } it "returns without removed value" do expect(subject).to eq [] end end context "when removing different value" do subject { config.remove(:linked_dirs, "othervalue") } it "returns without removed value" do expect(subject).to eq ["string"] end end end end end describe "keys" do subject { config.keys } before do config.set(:key1, :value1) config.set(:key2, :value2) end it "returns all set keys" do expect(subject).to match_array %i(key1 key2) end end describe "deleting" do before do config.set(:key, :value) end it "deletes the value" do config.delete(:key) expect(config.fetch(:key)).to be_nil end end describe "asking" do let(:question) { stub } let(:options) { {} } before do Configuration::Question.expects(:new).with(:branch, :default, options) .returns(question) end it "prompts for the value when fetching" do config.ask(:branch, :default, options) expect(config.fetch(:branch)).to eq question end end describe "setting the backend" do it "by default, is SSHKit" do expect(config.backend).to eq SSHKit end it "can be set to another class" do config.backend = :test expect(config.backend).to eq :test end describe "ssh_options for Netssh" do it "merges them with the :ssh_options variable" do config.set :format, :pretty config.set :log_level, :debug config.set :ssh_options, user: "albert" SSHKit::Backend::Netssh.configure { |ssh| ssh.ssh_options = { password: "einstein" } } config.configure_backend expect( config.backend.config.backend.config.ssh_options ).to include(user: "albert", password: "einstein") end end end describe "dry_run?" do it "returns false when using default backend" do expect(config.dry_run?).to eq(false) end it "returns true when using printer backend" do config.set :sshkit_backend, SSHKit::Backend::Printer expect(config.dry_run?).to eq(true) end end describe "custom filtering" do it "accepts a custom filter object" do filter = Object.new def filter.filter(servers) servers end config.add_filter(filter) end it "accepts a custom filter as a block" do config.add_filter { |servers| servers } end it "raises an error if passed a block and an object" do filter = Object.new def filter.filter(servers) servers end expect { config.add_filter(filter) { |servers| servers } }.to raise_error(ArgumentError) end it "raises an error if the filter lacks a filter method" do filter = Object.new expect { config.add_filter(filter) }.to raise_error(TypeError) end it "calls the filter method of a custom filter" do ENV.delete "ROLES" ENV.delete "HOSTS" servers = Configuration::Servers.new servers.add_host("test1") servers.add_host("test2") servers.add_host("test3") filtered_servers = servers.take(2) filter = mock("custom filter") filter.expects(:filter) .with { |subset| subset.is_a? Configuration::Servers } .returns(filtered_servers) config.add_filter(filter) expect(config.filter(servers)).to eq(filtered_servers) end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/plugin_spec.rb
spec/lib/capistrano/plugin_spec.rb
require "spec_helper" require "capistrano/plugin" module Capistrano describe Plugin do include Rake::DSL include Capistrano::DSL class DummyPlugin < Capistrano::Plugin def define_tasks task :hello do end end def register_hooks before "deploy:published", "hello" end end class ExternalTasksPlugin < Capistrano::Plugin def define_tasks eval_rakefile( File.expand_path("../../../support/tasks/plugin.rake", __FILE__) ) end # Called from plugin.rake to demonstrate that helper methods work def hello set :plugin_result, "hello" end end before do # Define an example task to allow testing hooks task "deploy:published" end after do # Clean up any tasks or variables we created during the tests Rake::Task.clear Capistrano::Configuration.reset! end it "defines tasks when constructed" do install_plugin(DummyPlugin) expect(Rake::Task["hello"]).not_to be_nil end it "registers hooks when constructed" do install_plugin(DummyPlugin) expect(Rake::Task["deploy:published"].prerequisites).to include("hello") end it "skips registering hooks if load_hooks: false" do install_plugin(DummyPlugin, load_hooks: false) expect(Rake::Task["deploy:published"].prerequisites).to be_empty end it "doesn't call set_defaults immediately" do dummy = DummyPlugin.new install_plugin(dummy) dummy.expects(:set_defaults).never end it "calls set_defaults during load:defaults", capture_io: true do dummy = DummyPlugin.new dummy.expects(:set_defaults).once install_plugin(dummy) Rake::Task["load:defaults"].invoke end it "is able to load tasks from a .rake file", capture_io: true do install_plugin(ExternalTasksPlugin) Rake::Task["plugin_test"].invoke expect(fetch(:plugin_result)).to eq("hello") end it "exposes the SSHKit backend to subclasses" do SSHKit::Backend.expects(:current).returns(:backend) plugin = DummyPlugin.new expect(plugin.send(:backend)).to eq(:backend) end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/application_spec.rb
spec/lib/capistrano/application_spec.rb
require "spec_helper" describe Capistrano::Application do it "provides a --trace option which enables SSHKit/NetSSH trace output" it "provides a --format option which enables the choice of output formatting" it "displays documentation URL as help banner", capture_io: true do flags "--help", "-h" expect($stdout.string.each_line.first).to match(/capistranorb.com/) end %w(quiet silent verbose).each do |switch| it "doesn't include --#{switch} in help", capture_io: true do flags "--help", "-h" expect($stdout.string).not_to match(/--#{switch}/) end end it "overrides the rake method, but still prints the rake version", capture_io: true do flags "--version", "-V" out = $stdout.string expect(out).to match(/\bCapistrano Version\b/) expect(out).to match(/\b#{Capistrano::VERSION}\b/) expect(out).to match(/\bRake Version\b/) expect(out).to match(/\b#{Rake::VERSION}\b/) end it "overrides the rake method, and sets the sshkit_backend to SSHKit::Backend::Printer", capture_io: true do flags "--dry-run", "-n" sshkit_backend = Capistrano::Configuration.fetch(:sshkit_backend) expect(sshkit_backend).to eq(SSHKit::Backend::Printer) end it "enables printing all config variables on command line parameter", capture_io: true do begin flags "--print-config-variables", "-p" expect(Capistrano::Configuration.fetch(:print_config_variables)).to be true ensure Capistrano::Configuration.reset! end end def flags(*sets) sets.each do |set| ARGV.clear @exit = catch(:system_exit) { command_line(*set) } end yield(subject.options) if block_given? end def command_line(*options) options.each { |opt| ARGV << opt } subject.define_singleton_method(:exit) do |*_args| throw(:system_exit, :exit) end subject.run subject.options end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/scm_spec.rb
spec/lib/capistrano/scm_spec.rb
require "spec_helper" require "capistrano/scm" module RaiseNotImplementedMacro def raise_not_implemented_on(method) it "should raise NotImplemented on #{method}" do expect do subject.send(method) end.to raise_error(NotImplementedError) end end end RSpec.configure do include RaiseNotImplementedMacro end module DummyStrategy def test test!("you dummy!") end end module BlindStrategy; end module Capistrano describe SCM do let(:context) { mock } describe "#initialize" do subject { Capistrano::SCM.new(context, DummyStrategy) } it "should load the provided strategy" do context.expects(:test).with("you dummy!") subject.test end end describe "Convenience methods" do subject { Capistrano::SCM.new(context, BlindStrategy) } describe "#test!" do it "should return call test on the context" do context.expects(:test).with(:x) subject.test!(:x) end end describe "#repo_url" do it "should return the repo url according to the context" do context.expects(:repo_url).returns(:url) expect(subject.repo_url).to eq(:url) end end describe "#repo_path" do it "should return the repo path according to the context" do context.expects(:repo_path).returns(:path) expect(subject.repo_path).to eq(:path) end end describe "#release_path" do it "should return the release path according to the context" do context.expects(:release_path).returns("/path/to/nowhere") expect(subject.release_path).to eq("/path/to/nowhere") end end describe "#fetch" do it "should call fetch on the context" do context.expects(:fetch) subject.fetch(:branch) end end end describe "With a 'blind' strategy" do subject { Capistrano::SCM.new(context, BlindStrategy) } describe "#test" do raise_not_implemented_on(:test) end describe "#check" do raise_not_implemented_on(:check) end describe "#clone" do raise_not_implemented_on(:clone) end describe "#update" do raise_not_implemented_on(:update) end describe "#release" do raise_not_implemented_on(:release) end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/version_validator_spec.rb
spec/lib/capistrano/version_validator_spec.rb
require "spec_helper" module Capistrano describe VersionValidator do let(:validator) { VersionValidator.new(version) } let(:version) { stub } describe "#new" do it "takes a version" do expect(validator) end end describe "#verify" do let(:current_version) { "3.0.1" } subject { validator.verify } before do validator.stubs(:current_version).returns(current_version) end context "with exact version" do context "valid" do let(:version) { "3.0.1" } it { expect(subject).to be_truthy } end context "invalid - lower" do let(:version) { "3.0.0" } it "fails" do expect { subject }.to raise_error(RuntimeError) end end context "invalid - higher" do let(:version) { "3.0.2" } it "fails" do expect { subject }.to raise_error(RuntimeError) end end end context "with optimistic versioning" do context "valid" do let(:version) { ">= 3.0.0" } it { expect(subject).to be_truthy } end context "invalid - lower" do let(:version) { "<= 2.0.0" } it "fails" do expect { subject }.to raise_error(RuntimeError) end end end context "with pessimistic versioning" do context "2 decimal places" do context "valid" do let(:version) { "~> 3.0.0" } it { expect(subject).to be_truthy } end context "invalid" do let(:version) { "~> 3.1.0" } it "fails" do expect { subject }.to raise_error(RuntimeError) end end end context "1 decimal place" do let(:current_version) { "3.5.0" } context "valid" do let(:version) { "~> 3.1" } it { expect(subject).to be_truthy } end context "invalid" do let(:version) { "~> 3.6" } it "fails" do expect { subject }.to raise_error(RuntimeError) end end end context "with multiple versions" do let(:current_version) { "3.5.9" } context "valid" do let(:version) { [">= 3.5.0", "< 3.5.10"] } it { is_expected.to be_truthy } end context "invalid" do let(:version) { [">= 3.5.0", "< 3.5.8"] } it "fails" do expect { subject }.to raise_error(RuntimeError) end end context "invalid" do let(:version) { ["> 3.5.9", "< 3.5.13"] } it "fails" do expect { subject }.to raise_error(RuntimeError) end end end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/immutable_task_spec.rb
spec/lib/capistrano/immutable_task_spec.rb
require "spec_helper" require "rake" require "capistrano/immutable_task" module Capistrano describe ImmutableTask do after do # Ensure that any tasks we create in these tests don't pollute other tests Rake::Task.clear end it "prints warning and raises when task is enhanced" do extend(Rake::DSL) load_defaults = Rake::Task.define_task("load:defaults") load_defaults.extend(Capistrano::ImmutableTask) $stderr.expects(:puts).with do |message| message =~ /^ERROR: load:defaults has already been invoked/ end expect do namespace :load do task :defaults do # Never reached since load_defaults is frozen and can't be enhanced end end end.to raise_error(/frozen/i) end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/dsl/task_enhancements_spec.rb
spec/lib/capistrano/dsl/task_enhancements_spec.rb
require "spec_helper" module Capistrano class DummyTaskEnhancements include TaskEnhancements end describe TaskEnhancements do let(:task_enhancements) { DummyTaskEnhancements.new } describe "ordering" do after do task.clear before_task.clear after_task.clear Rake::Task.clear end let(:order) { [] } let!(:task) do Rake::Task.define_task("task", [:order]) do |_t, args| args["order"].push "task" end end let!(:before_task) do Rake::Task.define_task("before_task") do order.push "before_task" end end let!(:after_task) do Rake::Task.define_task("after_task") do order.push "after_task" end end it "invokes in proper order if define after than before", capture_io: true do task_enhancements.after("task", "after_task") task_enhancements.before("task", "before_task") Rake::Task["task"].invoke order expect(order).to eq(%w(before_task task after_task)) end it "invokes in proper order if define before than after", capture_io: true do task_enhancements.before("task", "before_task") task_enhancements.after("task", "after_task") Rake::Task["task"].invoke order expect(order).to eq(%w(before_task task after_task)) end it "invokes in proper order when referring to as-yet undefined tasks", capture_io: true do task_enhancements.after("task", "not_loaded_task") Rake::Task.define_task("not_loaded_task") do order.push "not_loaded_task" end Rake::Task["task"].invoke order expect(order).to eq(%w(task not_loaded_task)) end it "invokes in proper order and with arguments and block", capture_io: true do task_enhancements.after("task", "after_task_custom", :order) do |_t, _args| order.push "after_task" end task_enhancements.before("task", "before_task_custom", :order) do |_t, _args| order.push "before_task" end Rake::Task["task"].invoke(order) expect(order).to eq(%w(before_task task after_task)) end it "invokes using the correct namespace when defined within a namespace", capture_io: true do Rake.application.in_namespace("namespace") do Rake::Task.define_task("task") do |t| order.push(t.name) end task_enhancements.before("task", "before_task", :order) do |t| order.push(t.name) end task_enhancements.after("task", "after_task", :order) do |t| order.push(t.name) end end Rake::Task["namespace:task"].invoke expect(order).to eq( ["namespace:before_task", "namespace:task", "namespace:after_task"] ) end it "raises a sensible error if the task isn't found", capture_io: true do task_enhancements.after("task", "non_existent_task") expect { Rake::Task["task"].invoke order }.to raise_error(ArgumentError, 'Task "non_existent_task" not found') end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/dsl/paths_spec.rb
spec/lib/capistrano/dsl/paths_spec.rb
require "spec_helper" describe Capistrano::DSL::Paths do let(:dsl) { Class.new.extend Capistrano::DSL } let(:parent) { Pathname.new("/var/shared") } let(:paths) { Class.new.extend Capistrano::DSL::Paths } let(:linked_dirs) { %w{log public/system} } let(:linked_files) { %w{config/database.yml log/my.log log/access.log} } before do dsl.set(:deploy_to, "/var/www") end describe "#linked_dirs" do subject { paths.linked_dirs(parent) } before do paths.expects(:fetch).with(:linked_dirs).returns(linked_dirs) end it "returns the full pathnames" do expect(subject).to eq [ Pathname.new("/var/shared/log"), Pathname.new("/var/shared/public/system") ] end end describe "#linked_files" do subject { paths.linked_files(parent) } before do paths.expects(:fetch).with(:linked_files).returns(linked_files) end it "returns the full pathnames" do expect(subject).to eq [ Pathname.new("/var/shared/config/database.yml"), Pathname.new("/var/shared/log/my.log"), Pathname.new("/var/shared/log/access.log") ] end end describe "#linked_file_dirs" do subject { paths.linked_file_dirs(parent) } before do paths.expects(:fetch).with(:linked_files).returns(linked_files) end it "returns the full paths names of the parent dirs" do expect(subject).to eq [ Pathname.new("/var/shared/config"), Pathname.new("/var/shared/log") ] end end describe "#linked_dir_parents" do subject { paths.linked_dir_parents(parent) } before do paths.expects(:fetch).with(:linked_dirs).returns(linked_dirs) end it "returns the full paths names of the parent dirs" do expect(subject).to eq [ Pathname.new("/var/shared"), Pathname.new("/var/shared/public") ] end end describe "#release path" do subject { dsl.release_path } context "where no release path has been set" do before do dsl.delete(:release_path) end it "returns the `current_path` value" do expect(subject.to_s).to eq "/var/www/current" end end context "where the release path has been set" do before do dsl.set(:release_path, "/var/www/release_path") end it "returns the set `release_path` value" do expect(subject.to_s).to eq "/var/www/release_path" end end end describe "#set_release_path" do let(:now) { Time.parse("Oct 21 16:29:00 2015") } subject { dsl.release_path } context "without a timestamp" do before do dsl.env.expects(:timestamp).returns(now) dsl.set_release_path end it "returns the release path with the current env timestamp" do expect(subject.to_s).to eq "/var/www/releases/20151021162900" end end context "with a timestamp" do before do dsl.set_release_path("timestamp") end it "returns the release path with the timestamp" do expect(subject.to_s).to eq "/var/www/releases/timestamp" end end end describe "#releases_path" do subject { paths.releases_path } context "with custom releases directory" do before do paths.expects(:fetch).with(:releases_directory, "releases").returns("test123") paths.expects(:fetch).with(:deploy_to).returns("/var/www") end it "returns the releases path with the custom directory" do expect(subject.to_s).to eq "/var/www/test123" end end end describe "#shared_path" do subject { paths.shared_path } context "with custom shared directory" do before do paths.expects(:fetch).with(:shared_directory, "shared").returns("test123") paths.expects(:fetch).with(:deploy_to).returns("/var/www") end it "returns the shared path with the custom directory" do expect(subject.to_s).to eq "/var/www/test123" end end end describe "#deploy_config_path" do subject { dsl.deploy_config_path.to_s } context "when not specified" do before do dsl.delete(:deploy_config_path) end it 'returns "config/deploy.rb"' do expect(subject).to eq "config/deploy.rb" end end context "when the variable :deploy_config_path is set" do before do dsl.set(:deploy_config_path, "my/custom/path.rb") end it "returns the custom path" do expect(subject).to eq "my/custom/path.rb" end end end describe "#stage_config_path" do subject { dsl.stage_config_path.to_s } context "when not specified" do before do dsl.delete(:stage_config_path) end it 'returns "config/deploy"' do expect(subject).to eq "config/deploy" end end context "when the variable :stage_config_path is set" do before do dsl.set(:stage_config_path, "my/custom/path") end it "returns the custom path" do expect(subject).to eq "my/custom/path" end end end describe "#repo_path" do subject { dsl.repo_path.to_s } context "when not specified" do before do dsl.delete(:repo_path) end it 'returns the default #{deploy_to}/repo' do dsl.set(:deploy_to, "/var/www") expect(subject).to eq "/var/www/repo" end end context "when the variable :repo_path is set" do before do dsl.set(:repo_path, "my/custom/path") end it "returns the custom path" do expect(subject).to eq "my/custom/path" end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/plugin_installer_spec.rb
spec/lib/capistrano/configuration/plugin_installer_spec.rb
require "spec_helper" require "capistrano/plugin" require "capistrano/scm/plugin" module Capistrano class Configuration class ExamplePlugin < Capistrano::Plugin def set_defaults set_if_empty :example_variable, "foo" end def define_tasks task :example task :example_prerequisite end def register_hooks before :example, :example_prerequisite end end class ExampleSCMPlugin < Capistrano::SCM::Plugin end describe PluginInstaller do include Capistrano::DSL let(:installer) { PluginInstaller.new } let(:options) { {} } let(:plugin) { ExamplePlugin.new } before do installer.install(plugin, **options) end after do Rake::Task.clear Capistrano::Configuration.reset! end context "installing plugin" do it "defines tasks" do expect(Rake::Task[:example]).to_not be_nil expect(Rake::Task[:example_prerequisite]).to_not be_nil end it "registers hooks" do task = Rake::Task[:example] expect(task.prerequisites).to eq([:example_prerequisite]) end it "sets defaults when load:defaults is invoked", capture_io: true do expect(fetch(:example_variable)).to be_nil invoke "load:defaults" expect(fetch(:example_variable)).to eq("foo") end it "doesn't say an SCM is installed" do expect(installer.scm_installed?).to be_falsey end end context "installing plugin class" do let(:plugin) { ExamplePlugin } it "defines tasks" do expect(Rake::Task[:example]).to_not be_nil expect(Rake::Task[:example_prerequisite]).to_not be_nil end end context "installing plugin without hooks" do let(:options) { { load_hooks: false } } it "doesn't register hooks" do task = Rake::Task[:example] expect(task.prerequisites).to be_empty end end context "installing plugin and loading immediately" do let(:options) { { load_immediately: true } } it "sets defaults immediately" do expect(fetch(:example_variable)).to eq("foo") end end context "installing an SCM plugin" do let(:plugin) { ExampleSCMPlugin } it "says an SCM is installed" do expect(installer.scm_installed?).to be_truthy end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/scm_resolver_spec.rb
spec/lib/capistrano/configuration/scm_resolver_spec.rb
require "spec_helper" require "capistrano/scm" module Capistrano class Configuration describe SCMResolver do include Capistrano::DSL let(:resolver) { SCMResolver.new } before do Rake::Task.define_task("deploy:check") Rake::Task.define_task("deploy:new_release_path") Rake::Task.define_task("deploy:set_current_revision") Rake::Task.define_task("deploy:set_current_revision_time") set :scm, SCMResolver::DEFAULT_GIT end after do Rake::Task.clear Capistrano::Configuration.reset! end context "default scm, no plugin installed" do it "emits a warning" do expect { resolver.resolve }.to output(/will not load the git scm/i).to_stderr end it "activates the git scm", capture_io: true do resolver.resolve expect(Rake::Task["git:wrapper"]).not_to be_nil end it "sets :scm to :git", capture_io: true do resolver.resolve expect(fetch(:scm)).to eq(:git) end end context "default scm, git plugin installed" do before do install_plugin Capistrano::SCM::Git end it "emits no warning" do expect { resolver.resolve }.not_to output.to_stderr end it "deletes :scm" do resolver.resolve expect(fetch(:scm)).to be_nil end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/null_filter_spec.rb
spec/lib/capistrano/configuration/null_filter_spec.rb
require "spec_helper" module Capistrano class Configuration describe NullFilter do subject(:null_filter) { NullFilter.new } describe "#filter" do let(:servers) { mock("servers") } it "returns the servers passed in as arguments" do expect(null_filter.filter(servers)).to eq(servers) end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/question_spec.rb
spec/lib/capistrano/configuration/question_spec.rb
require "spec_helper" module Capistrano class Configuration describe Question do let(:question) { Question.new(key, default, stdin: stdin) } let(:question_without_echo) { Question.new(key, default, echo: false, stdin: stdin) } let(:question_without_default) { Question.new(key, nil, stdin: stdin) } let(:question_prompt) { Question.new(key, default, stdin: stdin, prompt: "Your favorite branch") } let(:question_prompt_without_default) { Question.new(key, nil, stdin: stdin, prompt: "Your favorite branch") } let(:default) { :default } let(:key) { :branch } let(:stdin) { stub(tty?: true) } describe ".new" do it "takes a key, default, options" do question end end describe "#call" do context "value is entered" do let(:branch) { "branch" } it "returns the echoed value" do $stdout.expects(:print).with("Please enter branch (default): ") stdin.expects(:gets).returns(branch) stdin.expects(:noecho).never expect(question.call).to eq(branch) end it "returns the value but does not echo it" do $stdout.expects(:print).with("Please enter branch (default): ") stdin.expects(:noecho).returns(branch) $stdout.expects(:print).with("\n") expect(question_without_echo.call).to eq(branch) end it "returns the value but has no default between parenthesis" do $stdout.expects(:print).with("Please enter branch: ") stdin.expects(:gets).returns(branch) stdin.expects(:noecho).never expect(question_without_default.call).to eq(branch) end it "uses prompt and returns the value" do $stdout.expects(:print).with("Your favorite branch (default): ") stdin.expects(:gets).returns(branch) stdin.expects(:noecho).never expect(question_prompt.call).to eq(branch) end it "uses prompt and returns the value but has no default between parenthesis" do $stdout.expects(:print).with("Your favorite branch: ") stdin.expects(:gets).returns(branch) stdin.expects(:noecho).never expect(question_prompt_without_default.call).to eq(branch) end end context "value is not entered" do let(:branch) { default } before do $stdout.expects(:print).with("Please enter branch (default): ") stdin.expects(:gets).returns("") end it "returns the default as the value" do expect(question.call).to eq(branch) end end context "tty unavailable", capture_io: true do before do stdin.expects(:gets).never stdin.expects(:tty?).returns(false) end it "returns the default as the value" do expect(question.call).to eq(default) end end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/empty_filter_spec.rb
spec/lib/capistrano/configuration/empty_filter_spec.rb
require "spec_helper" module Capistrano class Configuration describe EmptyFilter do subject(:empty_filter) { EmptyFilter.new } describe "#filter" do let(:servers) { mock("servers") } it "returns an empty array" do expect(empty_filter.filter(servers)).to eq([]) end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/filter_spec.rb
spec/lib/capistrano/configuration/filter_spec.rb
require "spec_helper" module Capistrano class Configuration describe Filter do let(:available) do [ Server.new("server1").add_roles(%i(web db)), Server.new("server2").add_role(:web), Server.new("server3").add_role(:redis), Server.new("server4").add_role(:db), Server.new("server5").add_role(:stageweb) ] end describe "#new" do it "won't create an invalid type of filter" do expect do Filter.new(:zarg) end.to raise_error RuntimeError end context "with type :host" do context "and no values" do it "creates an EmptyFilter strategy" do expect(Filter.new(:host).instance_variable_get(:@strategy)).to be_a(EmptyFilter) end end context "and :all" do it "creates an NullFilter strategy" do expect(Filter.new(:host, :all).instance_variable_get(:@strategy)).to be_a(NullFilter) end end context "and [:all]" do it "creates an NullFilter strategy" do expect(Filter.new(:host, [:all]).instance_variable_get(:@strategy)).to be_a(NullFilter) end end context "and [:all]" do it "creates an NullFilter strategy" do expect(Filter.new(:host, "all").instance_variable_get(:@strategy)).to be_a(NullFilter) end end end context "with type :role" do context "and no values" do it "creates an EmptyFilter strategy" do expect(Filter.new(:role).instance_variable_get(:@strategy)).to be_a(EmptyFilter) end end context "and :all" do it "creates an NullFilter strategy" do expect(Filter.new(:role, :all).instance_variable_get(:@strategy)).to be_a(NullFilter) end end context "and [:all]" do it "creates an NullFilter strategy" do expect(Filter.new(:role, [:all]).instance_variable_get(:@strategy)).to be_a(NullFilter) end end context "and [:all]" do it "creates an NullFilter strategy" do expect(Filter.new(:role, "all").instance_variable_get(:@strategy)).to be_a(NullFilter) end end end end describe "#filter" do let(:strategy) { filter.instance_variable_get(:@strategy) } let(:results) { mock("result") } shared_examples "it calls #filter on its strategy" do it "calls #filter on its strategy" do strategy.expects(:filter).with(available).returns(results) expect(filter.filter(available)).to eq(results) end end context "for an empty filter" do let(:filter) { Filter.new(:role) } it_behaves_like "it calls #filter on its strategy" end context "for a null filter" do let(:filter) { Filter.new(:role, :all) } it_behaves_like "it calls #filter on its strategy" end context "for a role filter" do let(:filter) { Filter.new(:role, "web") } it_behaves_like "it calls #filter on its strategy" end context "for a host filter" do let(:filter) { Filter.new(:host, "server1") } it_behaves_like "it calls #filter on its strategy" end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/role_filter_spec.rb
spec/lib/capistrano/configuration/role_filter_spec.rb
require "spec_helper" module Capistrano class Configuration describe RoleFilter do subject(:role_filter) { RoleFilter.new(values) } let(:available) do [ Server.new("server1").add_roles(%i(web db)), Server.new("server2").add_role(:web), Server.new("server3").add_role(:redis), Server.new("server4").add_role(:db), Server.new("server5").add_role(:stageweb), Server.new("server6").add_role(:"db.new") ] end shared_examples "it filters roles correctly" do |expected_size, expected| it "filters correctly" do set = role_filter.filter(available) expect(set.size).to eq(expected_size) expect(set.map(&:hostname)).to eq(expected) end end describe "#filter" do context "with a single role string" do let(:values) { "web" } it_behaves_like "it filters roles correctly", 2, %w{server1 server2} end context "with a single role" do let(:values) { [:web] } it_behaves_like "it filters roles correctly", 2, %w{server1 server2} end context "with multiple roles in a string" do let(:values) { "web,db" } it_behaves_like "it filters roles correctly", 3, %w{server1 server2 server4} end context "with multiple roles" do let(:values) { %i(web db) } it_behaves_like "it filters roles correctly", 3, %w{server1 server2 server4} end context "with a regex" do let(:values) { /red/ } it_behaves_like "it filters roles correctly", 1, %w{server3} end context "with a regex string" do let(:values) { "/red|web/" } it_behaves_like "it filters roles correctly", 4, %w{server1 server2 server3 server5} end context "with both a string and regex" do let(:values) { "db,/red/" } it_behaves_like "it filters roles correctly", 3, %w{server1 server3 server4} end context "with a dot wildcard" do let(:values) { "db.*" } it_behaves_like "it filters roles correctly", 0, %w{} end context "with a dot" do let(:values) { "db.new" } it_behaves_like "it filters roles correctly", 1, %w{server6} end context "with a dot wildcard regex" do let(:values) { "/db.*/" } it_behaves_like "it filters roles correctly", 3, %w{server1 server4 server6} end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/servers_spec.rb
spec/lib/capistrano/configuration/servers_spec.rb
require "spec_helper" module Capistrano class Configuration describe Servers do let(:servers) { Servers.new } describe "adding a role" do it "adds two new server instances" do expect { servers.add_role(:app, %w{1 2}) } .to change { servers.count }.from(0).to(2) end it "handles de-duplification within roles" do servers.add_role(:app, %w{1}) servers.add_role(:app, %w{1}) expect(servers.count).to eq 1 end it "handles de-duplification within roles with users" do servers.add_role(:app, %w{1}, user: "nick") servers.add_role(:app, %w{1}, user: "fred") expect(servers.count).to eq 1 end it "accepts instances of server objects" do servers.add_role(:app, [Capistrano::Configuration::Server.new("example.net"), "example.com"]) expect(servers.roles_for([:app]).length).to eq 2 end it "accepts non-enumerable types" do servers.add_role(:app, "1") expect(servers.roles_for([:app]).count).to eq 1 end it "creates distinct server properties" do servers.add_role(:db, %w{1 2}, db: { port: 1234 }) servers.add_host("1", db: { master: true }) expect(servers.count).to eq(2) expect(servers.roles_for([:db]).count).to eq 2 expect(servers.find { |s| s.hostname == "1" }.properties.db).to eq(port: 1234, master: true) expect(servers.find { |s| s.hostname == "2" }.properties.db).to eq(port: 1234) end end describe "adding a role to an existing server" do before do servers.add_role(:web, %w{1 2}) servers.add_role(:app, %w{1 2}) end it "adds new roles to existing servers" do expect(servers.count).to eq 2 end end describe "collecting server roles" do let(:app) { Set.new([:app]) } let(:web_app) { Set.new(%i(web app)) } let(:web) { Set.new([:web]) } before do servers.add_role(:app, %w{1 2 3}) servers.add_role(:web, %w{2 3 4}) end it "returns an array of the roles" do expect(servers.roles_for([:app]).collect(&:roles)).to eq [app, web_app, web_app] expect(servers.roles_for([:web]).collect(&:roles)).to eq [web_app, web_app, web] end end describe "finding the primary server" do after do Configuration.reset! end it "takes the first server if none have the primary property" do servers.add_role(:app, %w{1 2}) expect(servers.fetch_primary(:app).hostname).to eq("1") end it "takes the first server with the primary have the primary flag" do servers.add_role(:app, %w{1 2}) servers.add_host("2", primary: true) expect(servers.fetch_primary(:app).hostname).to eq("2") end it "ignores any on_filters" do Configuration.env.set :filter, host: "1" servers.add_role(:app, %w{1 2}) servers.add_host("2", primary: true) expect(servers.fetch_primary(:app).hostname).to eq("2") end end describe "fetching servers" do before do servers.add_role(:app, %w{1 2}) servers.add_role(:web, %w{2 3}) end it "returns the correct app servers" do expect(servers.roles_for([:app]).map(&:hostname)).to eq %w{1 2} end it "returns the correct web servers" do expect(servers.roles_for([:web]).map(&:hostname)).to eq %w{2 3} end it "returns the correct app and web servers" do expect(servers.roles_for(%i(app web)).map(&:hostname)).to eq %w{1 2 3} end it "returns all servers" do expect(servers.roles_for([:all]).map(&:hostname)).to eq %w{1 2 3} end end describe "adding a server" do before do servers.add_host("1", roles: [:app, "web"], test: :value) end it "can create a server with properties" do expect(servers.roles_for([:app]).first.hostname).to eq "1" expect(servers.roles_for([:web]).first.hostname).to eq "1" expect(servers.roles_for([:all]).first.properties.test).to eq :value expect(servers.roles_for([:all]).first.properties.keys).to eq [:test] end it "can accept multiple servers with the same hostname but different ports or users" do servers.add_host("1", roles: [:app, "web"], test: :value, port: 12) expect(servers.count).to eq(2) servers.add_host("1", roles: [:app, "web"], test: :value, port: 34) servers.add_host("1", roles: [:app, "web"], test: :value, user: "root") servers.add_host("1", roles: [:app, "web"], test: :value, user: "deployer") servers.add_host("1", roles: [:app, "web"], test: :value, user: "root", port: 34) servers.add_host("1", roles: [:app, "web"], test: :value, user: "deployer", port: 34) servers.add_host("1", roles: [:app, "web"], test: :value, user: "deployer", port: 56) expect(servers.count).to eq(4) end describe "with a :user property" do it "sets the server ssh username" do servers.add_host("1", roles: [:app, "web"], user: "nick") expect(servers.count).to eq(1) expect(servers.roles_for([:all]).first.user).to eq "nick" end it "overwrites the value of a user specified in the hostname" do servers.add_host("brian@1", roles: [:app, "web"], user: "nick") expect(servers.count).to eq(1) expect(servers.roles_for([:all]).first.user).to eq "nick" end end it "overwrites the value of a previously defined scalar property" do servers.add_host("1", roles: [:app, "web"], test: :volatile) expect(servers.count).to eq(1) expect(servers.roles_for([:all]).first.properties.test).to eq :volatile end it "merges previously defined hash properties" do servers.add_host("1", roles: [:b], db: { port: 1234 }) servers.add_host("1", roles: [:b], db: { master: true }) expect(servers.count).to eq(1) expect(servers.roles_for([:b]).first.properties.db).to eq(port: 1234, master: true) end it "concatenates previously defined array properties" do servers.add_host("1", roles: [:b], steps: [1, 3, 5]) servers.add_host("1", roles: [:b], steps: [1, 9]) expect(servers.count).to eq(1) expect(servers.roles_for([:b]).first.properties.steps).to eq([1, 3, 5, 1, 9]) end it "merges previously defined set properties" do servers.add_host("1", roles: [:b], endpoints: Set[123, 333]) servers.add_host("1", roles: [:b], endpoints: Set[222, 333]) expect(servers.count).to eq(1) expect(servers.roles_for([:b]).first.properties.endpoints).to eq(Set[123, 222, 333]) end it "adds array property value only ones for a new host" do servers.add_host("2", roles: [:array_test], array_property: [1, 2]) expect(servers.roles_for([:array_test]).first.properties.array_property).to eq [1, 2] end it "updates roles when custom user defined" do servers.add_host("1", roles: ["foo"], user: "custom") servers.add_host("1", roles: ["bar"], user: "custom") expect(servers.roles_for([:foo]).first.hostname).to eq "1" expect(servers.roles_for([:bar]).first.hostname).to eq "1" end it "updates roles when custom port defined" do servers.add_host("1", roles: ["foo"], port: 1234) servers.add_host("1", roles: ["bar"], port: 1234) expect(servers.roles_for([:foo]).first.hostname).to eq "1" expect(servers.roles_for([:bar]).first.hostname).to eq "1" end end describe "selecting roles" do before do servers.add_host("1", roles: :app, active: true) servers.add_host("2", roles: :app) end it "is empty if the filter would remove all matching hosts" do expect(servers.roles_for([:app, select: :inactive])).to be_empty end it "can filter hosts by properties on the host object using symbol as shorthand" do expect(servers.roles_for([:app, filter: :active]).length).to eq 1 end it "can select hosts by properties on the host object using symbol as shorthand" do expect(servers.roles_for([:app, select: :active]).length).to eq 1 end it "can filter hosts by properties on the host using a regular proc" do expect(servers.roles_for([:app, filter: ->(h) { h.properties.active }]).length).to eq 1 end it "can select hosts by properties on the host using a regular proc" do expect(servers.roles_for([:app, select: ->(h) { h.properties.active }]).length).to eq 1 end it "is empty if the regular proc filter would remove all matching hosts" do expect(servers.roles_for([:app, select: ->(h) { h.properties.inactive }])).to be_empty end end describe "excluding by property" do before do servers.add_host("1", roles: :app, active: true) servers.add_host("2", roles: :app, active: true, no_release: true) end it "is empty if the filter would remove all matching hosts" do hosts = servers.roles_for([:app, exclude: :active]) expect(hosts.map(&:hostname)).to be_empty end it "returns the servers without the attributes specified" do hosts = servers.roles_for([:app, exclude: :no_release]) expect(hosts.map(&:hostname)).to eq %w{1} end it "can exclude hosts by properties on the host using a regular proc" do hosts = servers.roles_for([:app, exclude: ->(h) { h.properties.no_release }]) expect(hosts.map(&:hostname)).to eq %w{1} end it "is empty if the regular proc filter would remove all matching hosts" do hosts = servers.roles_for([:app, exclude: ->(h) { h.properties.active }]) expect(hosts.map(&:hostname)).to be_empty end end describe "filtering roles internally" do before do servers.add_host("1", roles: :app, active: true) servers.add_host("2", roles: :app) servers.add_host("3", roles: :web) servers.add_host("4", roles: :web) servers.add_host("5", roles: :db) end subject { servers.roles_for(roles).map(&:hostname) } context "with the ROLES environment variable set" do before do ENV.stubs(:[]).with("ROLES").returns("web,db") ENV.stubs(:[]).with("HOSTS").returns(nil) end context "when selecting all roles" do let(:roles) { [:all] } it "ignores it" do expect(subject).to eq %w{1 2 3 4 5} end end context "when selecting specific roles" do let(:roles) { %i(app web) } it "ignores it" do expect(subject).to eq %w{1 2 3 4} end end context "when selecting roles not included in ROLE" do let(:roles) { [:app] } it "ignores it" do expect(subject).to eq %w{1 2} end end end context "with the HOSTS environment variable set" do before do ENV.stubs(:[]).with("ROLES").returns(nil) ENV.stubs(:[]).with("HOSTS").returns("3,5") end context "when selecting all roles" do let(:roles) { [:all] } it "ignores it" do expect(subject).to eq %w{1 2 3 4 5} end end context "when selecting specific roles" do let(:roles) { %i(app web) } it "ignores it" do expect(subject).to eq %w{1 2 3 4} end end context "when selecting no roles" do let(:roles) { [] } it "ignores it" do expect(subject).to be_empty end end end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/host_filter_spec.rb
spec/lib/capistrano/configuration/host_filter_spec.rb
require "spec_helper" module Capistrano class Configuration describe HostFilter do subject(:host_filter) { HostFilter.new(values) } let(:available) do [Server.new("server1"), Server.new("server2"), Server.new("server3"), Server.new("server4"), Server.new("server10")] end shared_examples "it filters hosts correctly" do |expected| it "filters correctly" do set = host_filter.filter(available) expect(set.map(&:hostname)).to eq(expected) end end describe "#filter" do context "with a string" do let(:values) { "server1" } it_behaves_like "it filters hosts correctly", %w{server1} context "and a single server" do let(:available) { Server.new("server1") } it_behaves_like "it filters hosts correctly", %w{server1} end end context "with a comma separated string" do let(:values) { "server1,server10" } it_behaves_like "it filters hosts correctly", %w{server1 server10} end context "with an array of strings" do let(:values) { %w{server1 server3} } it_behaves_like "it filters hosts correctly", %w{server1 server3} end context "with mixed splittable and unsplittable strings" do let(:values) { %w{server1 server2,server3} } it_behaves_like "it filters hosts correctly", %w{server1 server2 server3} end context "with a regexp" do let(:values) { "server[13]$" } it_behaves_like "it filters hosts correctly", %w{server1 server3} end context "with a regexp with line boundaries" do let(:values) { "^server" } it_behaves_like "it filters hosts correctly", %w{server1 server2 server3 server4 server10} end context "with a regexp with a comma" do let(:values) { 'server\d{1,3}$' } it_behaves_like "it filters hosts correctly", %w{server1 server2 server3 server4 server10} end context "without number" do let(:values) { "server" } it_behaves_like "it filters hosts correctly", %w{} end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/configuration/server_spec.rb
spec/lib/capistrano/configuration/server_spec.rb
require "spec_helper" module Capistrano class Configuration describe Server do let(:server) { Server.new("root@hostname:1234") } describe "adding a role" do subject { server.add_role(:test) } it "adds the role" do expect { subject }.to change { server.roles.size }.from(0).to(1) end end describe "adding roles" do subject { server.add_roles(%i(things stuff)) } it "adds the roles" do expect { subject }.to change { server.roles.size }.from(0).to(2) end end describe "checking roles" do subject { server.has_role?(:test) } before do server.add_role(:test) end it "adds the role" do expect(subject).to be_truthy end end describe "comparing identity" do subject { server.hostname == Server[hostname].hostname } context "with the same user, hostname and port" do let(:hostname) { "root@hostname:1234" } it { expect(subject).to be_truthy } end context "with a different user" do let(:hostname) { "deployer@hostname:1234" } it { expect(subject).to be_truthy } end context "with a different port" do let(:hostname) { "root@hostname:5678" } it { expect(subject).to be_truthy } end context "with a different hostname" do let(:hostname) { "root@otherserver:1234" } it { expect(subject).to be_falsey } end end describe "identifying as primary" do subject { server.primary } context "server is primary" do before do server.set(:primary, true) end it "returns self" do expect(subject).to eq server end end context "server is not primary" do it "is falesy" do expect(subject).to be_falsey end end end describe "assigning properties" do before do server.with(properties) end context "properties contains roles" do let(:properties) { { roles: [:clouds] } } it "adds the roles" do expect(server.roles.first).to eq :clouds end end context "properties contains user" do let(:properties) { { user: "tomc" } } it "sets the user" do expect(server.user).to eq "tomc" end it "sets the netssh_options user" do expect(server.netssh_options[:user]).to eq "tomc" end end context "properties contains port" do let(:properties) { { port: 2222 } } it "sets the port" do expect(server.port).to eq 2222 end end context "properties contains key" do let(:properties) { { key: "/key" } } it "adds the key" do expect(server.keys).to include "/key" end end context "properties contains password" do let(:properties) { { password: "supersecret" } } it "adds the key" do expect(server.password).to eq "supersecret" end end context "new properties" do let(:properties) { { webscales: 5 } } it "adds the properties" do expect(server.properties.webscales).to eq 5 end end context "existing properties" do let(:properties) { { webscales: 6 } } it "keeps the existing properties" do expect(server.properties.webscales).to eq 6 server.properties.webscales = 5 expect(server.properties.webscales).to eq 5 end end end describe "#include?" do let(:options) { {} } subject { server.select?(options) } before do server.properties.active = true end context "options are empty" do it { expect(subject).to be_truthy } end context "value is a symbol" do context "value matches server property" do context "with :filter" do let(:options) { { filter: :active } } it { expect(subject).to be_truthy } end context "with :select" do let(:options) { { select: :active } } it { expect(subject).to be_truthy } end context "with :exclude" do let(:options) { { exclude: :active } } it { expect(subject).to be_falsey } end end context "value does not match server properly" do context "with :active true" do let(:options) { { active: true } } it { expect(subject).to be_truthy } end context "with :active false" do let(:options) { { active: false } } it { expect(subject).to be_falsey } end end context "value does not match server properly" do context "with :filter" do let(:options) { { filter: :inactive } } it { expect(subject).to be_falsey } end context "with :select" do let(:options) { { select: :inactive } } it { expect(subject).to be_falsey } end context "with :exclude" do let(:options) { { exclude: :inactive } } it { expect(subject).to be_truthy } end end end context "key is a property" do context "with :active true" do let(:options) { { active: true } } it { expect(subject).to be_truthy } end context "with :active false" do let(:options) { { active: false } } it { expect(subject).to be_falsey } end end context "value is a proc" do context "value matches server property" do context "with :filter" do let(:options) { { filter: ->(s) { s.properties.active } } } it { expect(subject).to be_truthy } end context "with :select" do let(:options) { { select: ->(s) { s.properties.active } } } it { expect(subject).to be_truthy } end context "with :exclude" do let(:options) { { exclude: ->(s) { s.properties.active } } } it { expect(subject).to be_falsey } end end context "value does not match server properly" do context "with :filter" do let(:options) { { filter: ->(s) { s.properties.inactive } } } it { expect(subject).to be_falsey } end context "with :select" do let(:options) { { select: ->(s) { s.properties.inactive } } } it { expect(subject).to be_falsey } end context "with :exclude" do let(:options) { { exclude: ->(s) { s.properties.inactive } } } it { expect(subject).to be_truthy } end end end end describe "assign ssh_options" do let(:server) { Server.new("user_name@hostname") } context "defaults" do it "forward agent" do expect(server.netssh_options[:forward_agent]).to eq true end it "contains user" do expect(server.netssh_options[:user]).to eq "user_name" end end context "custom" do let(:properties) do { ssh_options: { user: "another_user", keys: %w(/home/another_user/.ssh/id_rsa), forward_agent: false, auth_methods: %w(publickey password) } } end before do server.with(properties) end it "not forward agent" do expect(server.netssh_options[:forward_agent]).to eq false end it "contains correct user" do expect(server.netssh_options[:user]).to eq "another_user" end it "does not affect server user in host" do expect(server.user).to eq "user_name" end it "contains keys" do expect(server.netssh_options[:keys]).to eq %w(/home/another_user/.ssh/id_rsa) end it "contains auth_methods" do expect(server.netssh_options[:auth_methods]).to eq %w(publickey password) end end end describe ".[]" do it "creates a server if its argument is not already a server" do expect(Server["hostname:1234"]).to be_a Server end it "returns its argument if it is already a server" do expect(Server[server]).to be server end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/doctor/gems_doctor_spec.rb
spec/lib/capistrano/doctor/gems_doctor_spec.rb
require "spec_helper" require "capistrano/doctor/gems_doctor" require "airbrussh/version" require "sshkit/version" require "net/ssh/version" module Capistrano module Doctor describe GemsDoctor do let(:doc) { GemsDoctor.new } it "prints using 4-space indentation" do expect { doc.call }.to output(/^ {4}/).to_stdout end it "prints the Capistrano version" do expect { doc.call }.to\ output(/capistrano\s+#{Regexp.quote(Capistrano::VERSION)}/).to_stdout end it "prints the Rake version" do expect { doc.call }.to\ output(/rake\s+#{Regexp.quote(Rake::VERSION)}/).to_stdout end it "prints the SSHKit version" do expect { doc.call }.to\ output(/sshkit\s+#{Regexp.quote(SSHKit::VERSION)}/).to_stdout end it "prints the Airbrussh version" do expect { doc.call }.to\ output(/airbrussh\s+#{Regexp.quote(Airbrussh::VERSION)}/).to_stdout end it "prints the net-ssh version" do expect { doc.call }.to\ output(/net-ssh\s+#{Regexp.quote(Net::SSH::Version::STRING)}/).to_stdout end it "warns that new version is available" do Gem.stubs(:latest_version_for).returns(Gem::Version.new("99.0.0")) expect { doc.call }.to output(/\(update available\)/).to_stdout end describe "Rake" do before do load File.expand_path("../../../../../lib/capistrano/doctor.rb", __FILE__) end after do Rake::Task.clear end it "has an doctor:gems task that calls GemsDoctor", capture_io: true do GemsDoctor.any_instance.expects(:call) Rake::Task["doctor:gems"].invoke end it "has a doctor task that depends on doctor:gems" do expect(Rake::Task["doctor"].prerequisites).to include("doctor:gems") end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/doctor/output_helpers_spec.rb
spec/lib/capistrano/doctor/output_helpers_spec.rb
require "spec_helper" require "capistrano/doctor/output_helpers" module Capistrano module Doctor describe OutputHelpers do include OutputHelpers # Force color for the purpose of these tests before { ENV.stubs(:[]).with("SSHKIT_COLOR").returns("1") } it "prints titles in blue with newlines and without indentation" do expect { title("Hello!") }.to\ output("\e[0;34;49m\nHello!\n\e[0m\n").to_stdout end it "prints warnings in yellow with 4-space indentation" do expect { warning("Yikes!") }.to\ output(" \e[0;33;49mYikes!\e[0m\n").to_stdout end it "overrides puts to indent 4 spaces per line" do expect { puts("one\ntwo") }.to output(" one\n two\n").to_stdout end it "formats tables with indent, aligned columns and per-row color" do data = [ ["one", ".", "1"], ["two", "..", "2"], ["three", "...", "3"] ] block = proc do |record, row| row.yellow if record.first == "two" row << record[0] row << record[1] row << record[2] end expected_output = <<-OUT one . 1 \e[0;33;49mtwo .. 2\e[0m three ... 3 OUT expect { table(data, &block) }.to output(expected_output).to_stdout end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/doctor/variables_doctor_spec.rb
spec/lib/capistrano/doctor/variables_doctor_spec.rb
require "spec_helper" require "capistrano/doctor/variables_doctor" module Capistrano module Doctor describe VariablesDoctor do include Capistrano::DSL let(:doc) { VariablesDoctor.new } before do set :branch, "master" set :pty, false env.variables.untrusted! do set :application, "my_app" set :repo_tree, "public" set :repo_url, ".git" set :copy_strategy, :scp set :custom_setting, "hello" set "string_setting", "hello" ask :secret end fetch :custom_setting end after { Capistrano::Configuration.reset! } it "prints using 4-space indentation" do expect { doc.call }.to output(/^ {4}/).to_stdout end it "prints variable names and values" do expect { doc.call }.to output(/:branch\s+"master"$/).to_stdout expect { doc.call }.to output(/:pty\s+false$/).to_stdout expect { doc.call }.to output(/:application\s+"my_app"$/).to_stdout expect { doc.call }.to output(/:repo_url\s+".git"$/).to_stdout expect { doc.call }.to output(/:repo_tree\s+"public"$/).to_stdout expect { doc.call }.to output(/:copy_strategy\s+:scp$/).to_stdout expect { doc.call }.to output(/:custom_setting\s+"hello"$/).to_stdout expect { doc.call }.to output(/"string_setting"\s+"hello"$/).to_stdout end it "prints unanswered question variable as <ask>" do expect { doc.call }.to output(/:secret\s+<ask>$/).to_stdout end it "prints warning for unrecognized variable" do expect { doc.call }.to \ output(/:copy_strategy is not a recognized Capistrano setting/)\ .to_stdout end it "does not print warning for unrecognized variable that is fetched" do expect { doc.call }.not_to \ output(/:custom_setting is not a recognized Capistrano setting/)\ .to_stdout end it "does not print warning for whitelisted variable" do expect { doc.call }.not_to \ output(/:repo_tree is not a recognized Capistrano setting/)\ .to_stdout end describe "Rake" do before do load File.expand_path("../../../../../lib/capistrano/doctor.rb", __FILE__) end after do Rake::Task.clear end it "has an doctor:variables task that calls VariablesDoctor", capture_io: true do VariablesDoctor.any_instance.expects(:call) Rake::Task["doctor:variables"].invoke end it "has a doctor task that depends on doctor:variables" do expect(Rake::Task["doctor"].prerequisites).to \ include("doctor:variables") end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/doctor/servers_doctor_spec.rb
spec/lib/capistrano/doctor/servers_doctor_spec.rb
require "spec_helper" require "capistrano/doctor/servers_doctor" module Capistrano module Doctor describe ServersDoctor do include Capistrano::DSL let(:doc) { ServersDoctor.new } before { Capistrano::Configuration.reset! } after { Capistrano::Configuration.reset! } it "prints using 4-space indentation" do expect { doc.call }.to output(/^ {4}/).to_stdout end it "prints the number of defined servers" do role :app, %w(example.com) server "www@example.com:22" expect { doc.call }.to output(/Servers \(2\)/).to_stdout end describe "prints the server's details" do it "including username" do server "www@example.com" expect { doc.call }.to output(/www@example.com/).to_stdout end it "including port" do server "www@example.com:22" expect { doc.call }.to output(/www@example.com:22/).to_stdout end it "including roles" do role :app, %w(example.com) expect { doc.call }.to output(/example.com\s+\[:app\]/).to_stdout end it "including empty roles" do server "example.com" expect { doc.call }.to output(/example.com\s+\[\]/).to_stdout end it "including properties" do server "example.com", roles: %w(app db), primary: true expect { doc.call }.to \ output(/example.com\s+\[:app, :db\]\s+\{ :primary => true \}/).to_stdout end it "including misleading role name alert" do server "example.com", roles: ["web app db"] warning_msg = 'Whitespace detected in role(s) :"web app db". ' \ 'This might be a result of a mistyped "%w()" array literal' expect { doc.call }.to output(/#{Regexp.escape(warning_msg)}/).to_stdout end end it "doesn't fail for no servers" do expect { doc.call }.to output("\nServers (0)\n \n").to_stdout end describe "Rake" do before do load File.expand_path("../../../../../lib/capistrano/doctor.rb", __FILE__) end after do Rake::Task.clear end it "has an doctor:servers task that calls ServersDoctor", capture_io: true do ServersDoctor.any_instance.expects(:call) Rake::Task["doctor:servers"].invoke end it "has a doctor task that depends on doctor:servers" do expect(Rake::Task["doctor"].prerequisites).to \ include("doctor:servers") end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/doctor/environment_doctor_spec.rb
spec/lib/capistrano/doctor/environment_doctor_spec.rb
require "spec_helper" require "capistrano/doctor/environment_doctor" module Capistrano module Doctor describe EnvironmentDoctor do let(:doc) { EnvironmentDoctor.new } it "prints using 4-space indentation" do expect { doc.call }.to output(/^ {4}/).to_stdout end it "prints the Ruby version" do expect { doc.call }.to\ output(/#{Regexp.quote(RUBY_DESCRIPTION)}/).to_stdout end it "prints the Rubygems version" do expect { doc.call }.to output(/#{Regexp.quote(Gem::VERSION)}/).to_stdout end describe "Rake" do before do load File.expand_path("../../../../../lib/capistrano/doctor.rb", __FILE__) end after do Rake::Task.clear end it "has an doctor:environment task that calls EnvironmentDoctor", capture_io: true do EnvironmentDoctor.any_instance.expects(:call) Rake::Task["doctor:environment"].invoke end it "has a doctor task that depends on doctor:environment" do expect(Rake::Task["doctor"].prerequisites).to \ include("doctor:environment") end end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/scm/git_spec.rb
spec/lib/capistrano/scm/git_spec.rb
require "spec_helper" require "capistrano/scm/git" module Capistrano describe SCM::Git do subject { Capistrano::SCM::Git.new } # This allows us to easily use `set`, `fetch`, etc. in the examples. let(:env) { Capistrano::Configuration.env } # Stub the SSHKit backend so we can set up expectations without the plugin # actually executing any commands. let(:backend) { stub } before { SSHKit::Backend.stubs(:current).returns(backend) } # Mimic the deploy flow tasks so that the plugin can register its hooks. before do Rake::Task.define_task("deploy:new_release_path") Rake::Task.define_task("deploy:check") Rake::Task.define_task("deploy:set_current_revision") Rake::Task.define_task("deploy:set_current_revision_time") end # Clean up any tasks or variables that the plugin defined. after do Rake::Task.clear Capistrano::Configuration.reset! end describe "#set_defaults" do it "makes git_wrapper_path using a random hex value" do env.set(:tmp_dir, "/tmp") subject.set_defaults expect(env.fetch(:git_wrapper_path)).to match(%r{/tmp/git-ssh-\h{20}\.sh}) end it "makes git_max_concurrent_connections" do subject.set_defaults expect(env.fetch(:git_max_concurrent_connections)).to eq(10) env.set(:git_max_concurrent_connections, 7) expect(env.fetch(:git_max_concurrent_connections)).to eq(7) end it "makes git_wait_interval" do subject.set_defaults expect(env.fetch(:git_wait_interval)).to eq(0) env.set(:git_wait_interval, 5) expect(env.fetch(:git_wait_interval)).to eq(5) end end describe "#git" do it "should call execute git in the context, with arguments" do backend.expects(:execute).with(:git, :init) subject.git(:init) end end describe "#repo_mirror_exists?" do it "should call test for repo HEAD" do env.set(:repo_path, "/path/to/repo") backend.expects(:test).with " [ -f /path/to/repo/HEAD ] " subject.repo_mirror_exists? end end describe "#check_repo_is_reachable" do it "should test the repo url" do env.set(:repo_url, "url") backend.expects(:execute).with(:git, :'ls-remote', "url", "HEAD").returns(true) subject.check_repo_is_reachable end end describe "#clone_repo" do it "should run git clone" do env.set(:repo_url, "url") env.set(:repo_path, "path") backend.expects(:execute).with(:git, :clone, "--mirror", "url", "path") subject.clone_repo end it "should run git clone in shallow mode" do env.set(:git_shallow_clone, "1") env.set(:repo_url, "url") env.set(:repo_path, "path") backend.expects(:execute).with(:git, :clone, "--mirror", "--depth", "1", "--no-single-branch", "url", "path") subject.clone_repo end context "with username and password specified" do before do env.set(:git_http_username, "hello") env.set(:git_http_password, "topsecret") env.set(:repo_url, "https://example.com/repo.git") env.set(:repo_path, "path") end it "should include the credentials in the url" do backend.expects(:execute).with(:git, :clone, "--mirror", "https://hello:topsecret@example.com/repo.git", "path") subject.clone_repo end end end describe "#update_mirror" do it "should run git update" do env.set(:repo_url, "url") backend.expects(:execute).with(:git, :remote, "set-url", "origin", "url") backend.expects(:execute).with(:git, :remote, :update, "--prune") subject.update_mirror end it "should run git update in shallow mode" do env.set(:git_shallow_clone, "1") env.set(:branch, "branch") env.set(:repo_url, "url") backend.expects(:execute).with(:git, :remote, "set-url", "origin", "url") backend.expects(:execute).with(:git, :fetch, "--depth", "1", "origin", "branch") subject.update_mirror end end describe "#archive_to_release_path" do it "should run git archive without a subtree" do env.set(:branch, "branch") env.set(:release_path, "path") backend.expects(:execute).with(:git, :archive, "branch", "| /usr/bin/env tar -x -f - -C", "path") subject.archive_to_release_path end it "should run git archive with a subtree" do env.set(:repo_tree, "tree") env.set(:branch, "branch") env.set(:release_path, "path") backend.expects(:execute).with(:git, :archive, "branch", "tree", "| /usr/bin/env tar -x --strip-components 1 -f - -C", "path") subject.archive_to_release_path end it "should run tar with an overridden name" do env.set(:branch, "branch") env.set(:release_path, "path") SSHKit.config.command_map.expects(:[]).with(:tar).returns("/usr/bin/env gtar") backend.expects(:execute).with(:git, :archive, "branch", "| /usr/bin/env gtar -x -f - -C", "path") subject.archive_to_release_path end end describe "#fetch_revision" do it "should capture git rev-list" do env.set(:branch, "branch") backend.expects(:capture).with(:git, "rev-list --max-count=1 branch").returns("81cec13b777ff46348693d327fc8e7832f79bf43") revision = subject.fetch_revision expect(revision).to eq("81cec13b777ff46348693d327fc8e7832f79bf43") end end describe "#fetch_revision_time" do it "should capture git log without a pager" do env.set(:branch, "branch") backend.expects(:capture).with(:git, "--no-pager log -1 --pretty=format:\"%ct\" branch").returns("1715828406") revision_time = subject.fetch_revision_time expect(revision_time).to eq("1715828406") end end describe "#verify_commit" do it "should run git verify-commit" do env.set(:branch, "branch") backend.expects(:capture).with(:git, "rev-list --max-count=1 branch").returns("81cec13b777ff46348693d327fc8e7832f79bf43") backend.expects(:execute).with(:git, :"verify-commit", "81cec13b777ff46348693d327fc8e7832f79bf43") subject.verify_commit end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/scm/hg_spec.rb
spec/lib/capistrano/scm/hg_spec.rb
require "spec_helper" require "capistrano/scm/hg" module Capistrano describe SCM::Hg do subject { Capistrano::SCM::Hg.new } # This allows us to easily use `set`, `fetch`, etc. in the examples. let(:env) { Capistrano::Configuration.env } # Stub the SSHKit backend so we can set up expectations without the plugin # actually executing any commands. let(:backend) { stub } before { SSHKit::Backend.stubs(:current).returns(backend) } # Mimic the deploy flow tasks so that the plugin can register its hooks. before do Rake::Task.define_task("deploy:new_release_path") Rake::Task.define_task("deploy:check") Rake::Task.define_task("deploy:set_current_revision") end # Clean up any tasks or variables that the plugin defined. after do Rake::Task.clear Capistrano::Configuration.reset! end describe "#hg" do it "should call execute hg in the context, with arguments" do backend.expects(:execute).with(:hg, :init) subject.hg(:init) end end describe "#repo_mirror_exists?" do it "should call test for repo HEAD" do env.set(:repo_path, "/path/to/repo") backend.expects(:test).with " [ -d /path/to/repo/.hg ] " subject.repo_mirror_exists? end end describe "#check_repo_is_reachable" do it "should test the repo url" do env.set(:repo_url, :url) backend.expects(:execute).with(:hg, "id", :url) subject.check_repo_is_reachable end end describe "#clone_repo" do it "should run hg clone" do env.set(:repo_url, :url) env.set(:repo_path, "path") backend.expects(:execute).with(:hg, "clone", "--noupdate", :url, "path") subject.clone_repo end end describe "#update_mirror" do it "should run hg update" do backend.expects(:execute).with(:hg, "pull") subject.update_mirror end end describe "#archive_to_release_path" do it "should run hg archive without a subtree" do env.set(:branch, :branch) env.set(:release_path, "path") backend.expects(:execute).with(:hg, "archive", "path", "--rev", :branch) subject.archive_to_release_path end it "should run hg archive with a subtree" do env.set(:repo_tree, "tree") env.set(:branch, :branch) env.set(:release_path, "path") env.set(:tmp_dir, "/tmp") SecureRandom.stubs(:hex).with(10).returns("random") backend.expects(:execute).with(:hg, "archive -p . -I", "tree", "--rev", :branch, "/tmp/random.tar") backend.expects(:execute).with(:mkdir, "-p", "path") backend.expects(:execute).with(:tar, "-x --strip-components 1 -f", "/tmp/random.tar", "-C", "path") backend.expects(:execute).with(:rm, "/tmp/random.tar") subject.archive_to_release_path end end describe "#fetch_revision" do it "should capture hg log" do env.set(:branch, :branch) backend.expects(:capture).with(:hg, "log --rev branch --template \"{node}\n\"").returns("01abcde") revision = subject.fetch_revision expect(revision).to eq("01abcde") end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/spec/lib/capistrano/scm/svn_spec.rb
spec/lib/capistrano/scm/svn_spec.rb
require "spec_helper" require "capistrano/scm/svn" module Capistrano describe SCM::Svn do subject { Capistrano::SCM::Svn.new } # This allows us to easily use `set`, `fetch`, etc. in the examples. let(:env) { Capistrano::Configuration.env } # Stub the SSHKit backend so we can set up expectations without the plugin # actually executing any commands. let(:backend) { stub } before { SSHKit::Backend.stubs(:current).returns(backend) } # Mimic the deploy flow tasks so that the plugin can register its hooks. before do Rake::Task.define_task("deploy:new_release_path") Rake::Task.define_task("deploy:check") Rake::Task.define_task("deploy:set_current_revision") end # Clean up any tasks or variables that the plugin defined. after do Rake::Task.clear Capistrano::Configuration.reset! end describe "#svn" do it "should call execute svn in the context, with arguments" do env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") backend.expects(:execute).with(:svn, :init, "--username someuser", "--password somepassword") subject.svn(:init) end end describe "#repo_mirror_exists?" do it "should call test for repo HEAD" do env.set(:repo_path, "/path/to/repo") backend.expects(:test).with " [ -d /path/to/repo/.svn ] " subject.repo_mirror_exists? end end describe "#check_repo_is_reachable" do it "should test the repo url" do env.set(:repo_url, :url) env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") backend.expects(:test).with(:svn, :info, :url, "--username someuser", "--password somepassword").returns(true) subject.check_repo_is_reachable end end describe "#clone_repo" do it "should run svn checkout" do env.set(:repo_url, :url) env.set(:repo_path, "path") env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") backend.expects(:execute).with(:svn, :checkout, :url, "path", "--username someuser", "--password somepassword") subject.clone_repo end end describe "#update_mirror" do it "should run svn update" do env.set(:repo_url, "url") env.set(:repo_path, "path") backend.expects(:capture).with(:svn, :info, "path").returns("URL: url\n") env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") backend.expects(:execute).with(:svn, :update, "--username someuser", "--password somepassword") subject.update_mirror end context "for specific revision" do it "should run svn update" do env.set(:repo_url, "url") env.set(:repo_path, "path") backend.expects(:capture).with(:svn, :info, "path").returns("URL: url\n") env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") env.set(:svn_revision, "12345") backend.expects(:execute).with(:svn, :update, "--username someuser", "--password somepassword", "--revision 12345") subject.update_mirror end end it "should run svn switch if repo_url is changed" do env.set(:repo_url, "url") env.set(:repo_path, "path") backend.expects(:capture).with(:svn, :info, "path").returns("URL: old_url\n") env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") backend.expects(:execute).with(:svn, :switch, "url", "--username someuser", "--password somepassword") backend.expects(:execute).with(:svn, :update, "--username someuser", "--password somepassword") subject.update_mirror end end describe "#archive_to_release_path" do it "should run svn export" do env.set(:release_path, "path") env.set(:svn_username, "someuser") env.set(:svn_password, "somepassword") backend.expects(:execute).with(:svn, :export, "--force", ".", "path", "--username someuser", "--password somepassword") subject.archive_to_release_path end end describe "#fetch_revision" do it "should capture svn version" do env.set(:repo_path, "path") backend.expects(:capture).with(:svnversion, "path").returns("12345") revision = subject.fetch_revision expect(revision).to eq("12345") end end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano.rb
lib/capistrano.rb
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/version.rb
lib/capistrano/version.rb
module Capistrano VERSION = "3.20.0".freeze end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/application.rb
lib/capistrano/application.rb
module Capistrano class Application < Rake::Application def initialize super @rakefiles = %w{capfile Capfile capfile.rb Capfile.rb} end def name "cap" end def run Rake.application = self super end def sort_options(options) not_applicable_to_capistrano = %w(quiet silent verbose) options.reject! do |(switch, *)| switch =~ /--#{Regexp.union(not_applicable_to_capistrano)}/ end super.push(version, dry_run, roles, hostfilter, print_config_variables) end def handle_options options.rakelib = ["rakelib"] options.trace_output = $stderr OptionParser.new do |opts| opts.banner = "See full documentation at http://capistranorb.com/." opts.separator "" opts.separator "Install capistrano in a project:" opts.separator " bundle exec cap install [STAGES=qa,staging,production,...]" opts.separator "" opts.separator "Show available tasks:" opts.separator " bundle exec cap -T" opts.separator "" opts.separator "Invoke (or simulate invoking) a task:" opts.separator " bundle exec cap [--dry-run] STAGE TASK" opts.separator "" opts.separator "Advanced options:" opts.on_tail("-h", "--help", "-H", "Display this help message.") do puts opts exit end standard_rake_options.each { |args| opts.on(*args) } opts.environment("RAKEOPT") end.parse! end def top_level_tasks if tasks_without_stage_dependency.include?(@top_level_tasks.first) @top_level_tasks else @top_level_tasks.unshift(ensure_stage.to_s) end end def display_error_message(ex) unless options.backtrace Rake.application.options.suppress_backtrace_pattern = backtrace_pattern if backtrace_pattern trace "(Backtrace restricted to imported tasks)" end super end def exit_because_of_exception(ex) if respond_to?(:deploying?) && deploying? exit_deploy_because_of_exception(ex) else super end end # allows the `cap install` task to load without a capfile def find_rakefile_location if (location = super).nil? [capfile, Dir.pwd] else location end end private def backtrace_pattern loc = Rake.application.find_rakefile_location return unless loc whitelist = (@imported.dup << loc[0]).map { |f| File.absolute_path(f, loc[1]) } /^(?!#{whitelist.map { |p| Regexp.quote(p) }.join('|')})/ end def load_imports if options.show_tasks && Rake::Task.task_defined?("load:defaults") invoke "load:defaults" set(:stage, "") Dir[deploy_config_path].each { |f| add_import f } end super end def capfile File.expand_path(File.join(File.dirname(__FILE__), "..", "Capfile")) end def version ["--version", "-V", "Display the program version.", lambda do |_value| puts "Capistrano Version: #{Capistrano::VERSION} (Rake Version: #{Rake::VERSION})" exit end] end def dry_run ["--dry-run", "-n", "Do a dry run without executing actions", lambda do |_value| Configuration.env.set(:sshkit_backend, SSHKit::Backend::Printer) end] end def roles ["--roles ROLES", "-r", "Run SSH commands only on hosts matching these roles", lambda do |value| Configuration.env.add_cmdline_filter(:role, value) end] end def hostfilter ["--hosts HOSTS", "-z", "Run SSH commands only on matching hosts", lambda do |value| Configuration.env.add_cmdline_filter(:host, value) end] end def print_config_variables ["--print-config-variables", "-p", "Display the defined config variables before starting the deployment tasks.", lambda do |_value| Configuration.env.set(:print_config_variables, true) end] end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/doctor.rb
lib/capistrano/doctor.rb
require "capistrano/doctor/environment_doctor" require "capistrano/doctor/gems_doctor" require "capistrano/doctor/variables_doctor" require "capistrano/doctor/servers_doctor" load File.expand_path("../tasks/doctor.rake", __FILE__)
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/setup.rb
lib/capistrano/setup.rb
require "capistrano/doctor" require "capistrano/immutable_task" include Capistrano::DSL namespace :load do task :defaults do load "capistrano/defaults.rb" end end require "airbrussh/capistrano" # We don't need to show the "using Airbrussh" banner announcement since # Airbrussh is now the built-in formatter. Also enable command output by # default; hiding the output might be confusing to users new to Capistrano. Airbrussh.configure do |airbrussh| airbrussh.banner = false airbrussh.command_output = true end stages.each do |stage| Rake::Task.define_task(stage) do set(:stage, stage.to_sym) invoke "load:defaults" Rake.application["load:defaults"].extend(Capistrano::ImmutableTask) env.variables.untrusted! do load deploy_config_path load stage_config_path.join("#{stage}.rb") end configure_scm I18n.locale = fetch(:locale, :en) configure_backend end end require "capistrano/dotfile"
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/version_validator.rb
lib/capistrano/version_validator.rb
module Capistrano class VersionValidator def initialize(version) @version = version end def verify return self if match? raise "Capfile locked at #{version}, but #{current_version} is loaded" end private attr_reader :version def match? available =~ requested end def current_version VERSION end def available Gem::Dependency.new("cap", version) end def requested Gem::Dependency.new("cap", current_version) end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/upload_task.rb
lib/capistrano/upload_task.rb
require "rake/file_creation_task" module Capistrano class UploadTask < Rake::FileCreationTask def needed? true # always needed because we can't check remote hosts end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/scm.rb
lib/capistrano/scm.rb
module Capistrano # Base class for SCM strategy providers. # # @abstract # # @attr_reader [Rake] context # # @author Hartog de Mik # class SCM attr_reader :context # Provide a wrapper for the SCM that loads a strategy for the user. # # @param [Rake] context The context in which the strategy should run # @param [Module] strategy A module to include into the SCM instance. The # module should provide the abstract methods of Capistrano::SCM # def initialize(context, strategy) @context = context singleton = class << self; self; end singleton.send(:include, strategy) end # Call test in context def test!(*args) context.test(*args) end # The repository URL according to the context def repo_url context.repo_url end # The repository path according to the context def repo_path context.repo_path end # The release path according to the context def release_path context.release_path end # Fetch a var from the context # @param [Symbol] variable The variable to fetch # @param [Object] default The default value if not found # def fetch(*args) context.fetch(*args) end # @abstract # # Your implementation should check the existence of a cache repository on # the deployment target # # @return [Boolean] # def test raise NotImplementedError, "Your SCM strategy module should provide a #test method" end # @abstract # # Your implementation should check if the specified remote-repository is # available. # # @return [Boolean] # def check raise NotImplementedError, "Your SCM strategy module should provide a #check method" end # @abstract # # Create a (new) clone of the remote-repository on the deployment target # # @return void # def clone raise NotImplementedError, "Your SCM strategy module should provide a #clone method" end # @abstract # # Update the clone on the deployment target # # @return void # def update raise NotImplementedError, "Your SCM strategy module should provide a #update method" end # @abstract # # Copy the contents of the cache-repository onto the release path # # @return void # def release raise NotImplementedError, "Your SCM strategy module should provide a #release method" end # @abstract # # Identify the SHA of the commit that will be deployed. This will most likely involve SshKit's capture method. # # @return void # def fetch_revision raise NotImplementedError, "Your SCM strategy module should provide a #fetch_revision method" end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/plugin.rb
lib/capistrano/plugin.rb
require "capistrano/all" require "rake/tasklib" # IMPORTANT: The Capistrano::Plugin system is not yet considered a stable, # public API, and is subject to change without notice. Eventually it will be # officially documented and supported, but for now, use it at your own risk. # # Base class for Capistrano plugins. Makes building a Capistrano plugin as easy # as writing a `Capistrano::Plugin` subclass and overriding any or all of its # three template methods: # # * set_defaults # * register_hooks # * define_tasks # # Within the plugin you can use any methods of the Rake or Capistrano DSLs, like # `fetch`, `invoke`, etc. In cases when you need to use SSHKit's backend outside # of an `on` block, use the `backend` convenience method. E.g. `backend.test`, # `backend.execute`, or `backend.capture`. # # Package up and distribute your plugin class as a gem and you're good to go! # # To use a plugin, all a user has to do is install it in the Capfile, like this: # # # Capfile # require "capistrano/superfancy" # install_plugin Capistrano::Superfancy # # Or, to install the plugin without its hooks: # # # Capfile # require "capistrano/superfancy" # install_plugin Capistrano::Superfancy, load_hooks: false # class Capistrano::Plugin < Rake::TaskLib include Capistrano::DSL # Implemented by subclasses to provide default values for settings needed by # this plugin. Typically done using the `set_if_empty` Capistrano DSL method. # # Example: # # def set_defaults # set_if_empty :my_plugin_option, true # end # def set_defaults; end # Implemented by subclasses to hook into Capistrano's deployment flow using # using the `before` and `after` DSL methods. Note that `register_hooks` will # not be called if the user has opted-out of hooks when installing the plugin. # # Example: # # def register_hooks # after "deploy:updated", "my_plugin:do_something" # end # def register_hooks; end # Implemented by subclasses to define Rake tasks. Typically a plugin will call # `eval_rakefile` to load Rake tasks from a separate .rake file. # # Example: # # def define_tasks # eval_rakefile File.expand_path("../tasks.rake", __FILE__) # end # # For simple tasks, you can define them inline. No need for a separate file. # # def define_tasks # desc "Do something fantastic." # task "my_plugin:fantastic" do # ... # end # end # def define_tasks; end private # Read and eval a .rake file in such a way that `self` within the .rake file # refers to this plugin instance. This gives the tasks in the file access to # helper methods defined by the plugin. def eval_rakefile(path) contents = IO.read(path) instance_eval(contents, path, 1) end # Convenience to access the current SSHKit backend outside of an `on` block. def backend SSHKit::Backend.current end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/console.rb
lib/capistrano/console.rb
load File.expand_path("../tasks/console.rake", __FILE__)
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/dsl.rb
lib/capistrano/dsl.rb
require "capistrano/dsl/task_enhancements" require "capistrano/dsl/paths" require "capistrano/dsl/stages" require "capistrano/dsl/env" require "capistrano/configuration/filter" module Capistrano module DSL include TaskEnhancements include Env include Paths include Stages def invoke(task_name, *args) task = Rake::Task[task_name] # NOTE: We access instance variable since the accessor was only added recently. Once Capistrano depends on rake 11+, we can revert the following line if task && task.instance_variable_get(:@already_invoked) file, line, = caller.first.split(":") colors = SSHKit::Color.new($stderr) $stderr.puts colors.colorize("Skipping task `#{task_name}'.", :yellow) $stderr.puts "Capistrano tasks may only be invoked once. Since task `#{task}' was previously invoked, invoke(\"#{task_name}\") at #{file}:#{line} will be skipped." $stderr.puts "If you really meant to run this task again, use invoke!(\"#{task_name}\")" $stderr.puts colors.colorize("THIS BEHAVIOR MAY CHANGE IN A FUTURE VERSION OF CAPISTRANO. Please join the conversation here if this affects you.", :red) $stderr.puts colors.colorize("https://github.com/capistrano/capistrano/issues/1686", :red) end task.invoke(*args) end def invoke!(task_name, *args) task = Rake::Task[task_name] task.reenable task.invoke(*args) end def t(key, options={}) I18n.t(key, **options.merge(scope: :capistrano)) end def scm fetch(:scm) end def sudo(*args) execute :sudo, *args end def revision_log_message fetch(:revision_log_message, t(:revision_log_message, branch: fetch(:branch), user: local_user, sha: fetch(:current_revision), release: fetch(:release_timestamp))) end def rollback_log_message t(:rollback_log_message, user: local_user, release: fetch(:rollback_timestamp)) end def local_user fetch(:local_user) end def lock(locked_version) VersionValidator.new(locked_version).verify end # rubocop:disable Security/MarshalLoad def on(hosts, options={}, &block) subset_copy = Marshal.dump(Configuration.env.filter(hosts)) SSHKit::Coordinator.new(Marshal.load(subset_copy)).each(options, &block) end # rubocop:enable Security/MarshalLoad def run_locally(&block) SSHKit::Backend::Local.new(&block).run end # Catch common beginner mistake and give a helpful error message on stderr def execute(*) file, line, = caller.first.split(":") colors = SSHKit::Color.new($stderr) $stderr.puts colors.colorize("Warning: `execute' should be wrapped in an `on' scope in #{file}:#{line}.", :red) $stderr.puts $stderr.puts " task :example do" $stderr.puts colors.colorize(" on roles(:app) do", :yellow) $stderr.puts " execute 'whoami'" $stderr.puts colors.colorize(" end", :yellow) $stderr.puts " end" $stderr.puts raise NoMethodError, "undefined method `execute' for main:Object" end end end extend Capistrano::DSL
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/immutable_task.rb
lib/capistrano/immutable_task.rb
module Capistrano # This module extends a Rake::Task to freeze it to prevent it from being # enhanced. This is used to prevent users from enhancing a task at the wrong # point of Capistrano's boot process, which can happen if a Capistrano plugin # is loaded in deploy.rb by mistake (instead of in the Capfile). # # Usage: # # task = Rake.application["load:defaults"] # task.invoke # task.extend(Capistrano::ImmutableTask) # prevent further modifications # module ImmutableTask def self.extended(task) task.freeze end def enhance(*args, &block) $stderr.puts <<-MESSAGE ERROR: #{name} has already been invoked and can no longer be modified. Check that you haven't loaded a Capistrano plugin in deploy.rb or a stage (e.g. deploy/production.rb) by mistake. Plugins must be loaded in the Capfile to initialize properly. MESSAGE # This will raise a frozen object error super(*args, &block) end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/configuration.rb
lib/capistrano/configuration.rb
require_relative "configuration/filter" require_relative "configuration/question" require_relative "configuration/plugin_installer" require_relative "configuration/server" require_relative "configuration/servers" require_relative "configuration/validated_variables" require_relative "configuration/variables" module Capistrano class ValidationError < RuntimeError; end class Configuration def self.env @env ||= new end def self.reset! @env = new end extend Forwardable attr_reader :variables def_delegators :variables, :set, :fetch, :fetch_for, :delete, :keys, :validate def initialize(values={}) @variables = ValidatedVariables.new(Variables.new(values)) end def ask(key, default=nil, options={}) question = Question.new(key, default, options) set(key, question) end def set_if_empty(key, value=nil, &block) set(key, value, &block) unless keys.include?(key) end def append(key, *values) set(key, Array(fetch(key)).concat(values)) end def remove(key, *values) set(key, Array(fetch(key)) - values) end def any?(key) value = fetch(key) if value && value.respond_to?(:any?) begin return value.any? rescue ArgumentError # Gracefully ignore values whose `any?` method doesn't accept 0 args end end !value.nil? end def is_question?(key) value = fetch_for(key, nil) !value.nil? && value.is_a?(Question) end def role(name, hosts, options={}) if name == :all raise ArgumentError, "#{name} reserved name for role. Please choose another name" end servers.add_role(name, hosts, options) end def server(name, properties={}) servers.add_host(name, properties) end def roles_for(names) servers.roles_for(names) end def role_properties_for(names, &block) servers.role_properties_for(names, &block) end def primary(role) servers.fetch_primary(role) end def backend @backend ||= SSHKit end attr_writer :backend def configure_backend backend.configure do |sshkit| configure_sshkit_output(sshkit) sshkit.output_verbosity = fetch(:log_level) sshkit.default_env = fetch(:default_env) sshkit.backend = fetch(:sshkit_backend, SSHKit::Backend::Netssh) sshkit.backend.configure do |backend| backend.pty = fetch(:pty) backend.connection_timeout = fetch(:connection_timeout) backend.ssh_options = (backend.ssh_options || {}).merge(fetch(:ssh_options, {})) end end end def configure_scm Capistrano::Configuration::SCMResolver.new.resolve end def timestamp @timestamp ||= Time.now.utc end def add_filter(filter=nil, &block) if block raise ArgumentError, "Both a block and an object were given" if filter filter = Object.new def filter.filter(servers) block.call(servers) end elsif !filter.respond_to? :filter raise TypeError, "Provided custom filter <#{filter.inspect}> does " \ "not have a public 'filter' method" end @custom_filters ||= [] @custom_filters << filter end def setup_filters @filters = cmdline_filters @filters += @custom_filters if @custom_filters @filters << Filter.new(:role, ENV["ROLES"]) if ENV["ROLES"] @filters << Filter.new(:host, ENV["HOSTS"]) if ENV["HOSTS"] fh = fetch_for(:filter, {}) || {} @filters << Filter.new(:host, fh[:hosts]) if fh[:hosts] @filters << Filter.new(:role, fh[:roles]) if fh[:roles] @filters << Filter.new(:host, fh[:host]) if fh[:host] @filters << Filter.new(:role, fh[:role]) if fh[:role] end def add_cmdline_filter(type, values) cmdline_filters << Filter.new(type, values) end def filter(list) setup_filters if @filters.nil? @filters.reduce(list) { |l, f| f.filter l } end def dry_run? fetch(:sshkit_backend) == SSHKit::Backend::Printer end def install_plugin(plugin, load_hooks: true, load_immediately: false) installer.install(plugin, load_hooks: load_hooks, load_immediately: load_immediately) end def scm_plugin_installed? installer.scm_installed? end def servers @servers ||= Servers.new end private def cmdline_filters @cmdline_filters ||= [] end def installer @installer ||= PluginInstaller.new end def configure_sshkit_output(sshkit) format_args = [fetch(:format)] format_args.push(fetch(:format_options)) if any?(:format_options) sshkit.use_format(*format_args) end end end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/i18n.rb
lib/capistrano/i18n.rb
require "i18n" en = { starting: "Starting", capified: "Capified", start: "Start", update: "Update", finalize: "Finalise", finishing: "Finishing", finished: "Finished", stage_not_set: "Stage not set, please call something such as `cap production deploy`, where production is a stage you have defined.", written_file: "create %{file}", question: "Please enter %{key}: ", question_default: "Please enter %{key} (%{default_value}): ", question_prompt: "%{key}: ", question_prompt_default: "%{key} (%{default_value}): ", keeping_releases: "Keeping %{keep_releases} of %{releases} deployed releases on %{host}", skip_cleanup: "Skipping cleanup of invalid releases on %{host}; unexpected foldername found (should be timestamp)", wont_delete_current_release: "Current release was marked for being removed but it's going to be skipped on %{host}", no_current_release: "There is no current release present on %{host}", no_old_releases: "No old releases (keeping newest %{keep_releases}) on %{host}", linked_file_does_not_exist: "linked file %{file} does not exist on %{host}", cannot_rollback: "There are no older releases to rollback to", cannot_found_rollback_release: "Cannot rollback because release %{release} does not exist", mirror_exists: "The repository mirror is at %{at}", revision_log_message: "Branch %{branch} (at %{sha}) deployed as release %{release} by %{user}", rollback_log_message: "%{user} rolled back to release %{release}", deploy_failed: "The deploy has failed with an error: %{ex}", console: { welcome: "capistrano console - enter command to execute on %{stage}", bye: "bye" }, error: { invalid_stage_name: '"%{name}" is a reserved word and cannot be used as a stage. Rename "%{path}" to something else.', user: { does_not_exist: "User %{user} does not exists", cannot_switch: "Cannot switch to user %{user}" } } } I18n.backend.store_translations(:en, capistrano: en) if I18n.respond_to?(:enforce_available_locales=) I18n.enforce_available_locales = true end
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/dotfile.rb
lib/capistrano/dotfile.rb
dotfile = Pathname.new(File.join(Dir.home, ".capfile")) load dotfile if dotfile.file?
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/deploy.rb
lib/capistrano/deploy.rb
require "capistrano/framework" load File.expand_path("../tasks/deploy.rake", __FILE__)
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/defaults.rb
lib/capistrano/defaults.rb
validate :application do |_key, value| changed_value = value.gsub(/[^A-Z0-9\.\-]/i, "_") if value != changed_value warn %Q(The :application value "#{value}" is invalid!) warn "Use only letters, numbers, hyphens, dots, and underscores. For example:" warn " set :application, '#{changed_value}'" raise Capistrano::ValidationError end end %i(git_strategy hg_strategy svn_strategy).each do |strategy| validate(strategy) do |key, _value| warn( "[Deprecation Warning] #{key} is deprecated and will be removed in "\ "Capistrano 3.7.0.\n"\ "https://github.com/capistrano/capistrano/blob/master/UPGRADING-3.7.md" ) end end # We use a special :_default_git value so that SCMResolver can tell whether the # default has been replaced by the user via `set`. set_if_empty :scm, Capistrano::Configuration::SCMResolver::DEFAULT_GIT set_if_empty :branch, "master" set_if_empty :deploy_to, -> { "/var/www/#{fetch(:application)}" } set_if_empty :tmp_dir, "/tmp" set_if_empty :default_env, {} set_if_empty :keep_releases, 5 set_if_empty :format, :airbrussh set_if_empty :log_level, :debug set_if_empty :pty, false set_if_empty :local_user, -> { ENV["USER"] || ENV["LOGNAME"] || ENV["USERNAME"] }
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false
capistrano/capistrano
https://github.com/capistrano/capistrano/blob/dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334/lib/capistrano/install.rb
lib/capistrano/install.rb
load File.expand_path(File.join(File.dirname(__FILE__), "tasks/install.rake"))
ruby
MIT
dfe3133012d7d7d4fcd3f34d2790bcaeb4e8c334
2026-01-04T15:37:35.862177Z
false