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
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/notifier.rb
app/models/notifier.rb
class Notifier < ApplicationRecord belongs_to :provider, class_name: 'NotifierProvider' belongs_to :user belongs_to :topic validates :provider, presence: true validates :notify_after_sec, numericality: {greater_than_or_equal_to: 5} serialize :settings, JSON after_initialize :set_defaults def set_defaults self.settings ||= {} end def notify(event) NotificationWorker.enqueue(event: event, notifier: self) end def notify_immediately(event) provider.notify(event: event, notifier: self) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/escalation.rb
app/models/escalation.rb
class Escalation < ApplicationRecord belongs_to :escalation_series belongs_to :escalate_to, class_name: 'User' validates :escalation_series, presence: true validates :escalate_to, presence: true validates :escalate_after_sec, numericality: {greater_than_or_equal_to: 5} end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/escalation_series.rb
app/models/escalation_series.rb
class EscalationSeries < ApplicationRecord has_many :escalations, dependent: :destroy has_many :topics, dependent: :destroy validates :name, presence: true serialize :settings, JSON after_initialize :set_defaults def set_defaults self.settings ||= {} end def update_escalations! updater_class = case self.settings['update_by'] when 'google_calendar' GoogleCalendarEscalationUpdater else nil end if updater_class updater = updater_class.new(self) updater.update! end end class EscalationUpdater def initialize(series) @series = series end def update! raise NotImplementedError end private def settings @series.settings end end class GoogleCalendarEscalationUpdater < EscalationUpdater def initialize(*) super require 'google/api_client' end def update! Rails.logger.info "Update #{@series.inspect} by Google Calendar" if user_as.provider && user_as.provider != 'google_oauth2_with_calendar' raise "User ##{user_as.id} is not authenticated by 'google_oauth2_with_calendar' provider" end client = Google::APIClient.new( application_name: "Waker", application_version: "2.0.0", user_agent: "Waker/2.0.0 google-api-client" ) auth = client.authorization expired = Time.at(user_as.credentials.fetch('expires_at')) < Time.now if user_as.credentials.fetch('expires') && expired Rails.logger.info "Refreshing access token..." auth.client_id = ENV["GOOGLE_CLIENT_ID"] auth.client_secret = ENV["GOOGLE_CLIENT_SECRET"] auth.refresh_token = user_as.credentials.fetch('refresh_token') auth.grant_type = "refresh_token" auth.refresh! user_as.update!( credentials: user_as.credentials.merge( 'token' => auth.access_token, 'expires_at' => auth.expires_at.to_i, ) ) else auth.access_token = user_as.credentials.fetch('token') end calendar_api = client.discovered_api('calendar', 'v3') calendar = client.execute( api_method: calendar_api.calendar_list.list, parameters: {}, ).data.items.find do |cal| cal['summary'] == calendar_name end events = client.execute( api_method: calendar_api.events.list, parameters: { 'calendarId' => calendar['id'], 'timeMax' => (Time.now + 1).iso8601, 'timeMin' => (Time.now).iso8601, 'singleEvents' => true, }, ).data.items events.each do |event| unless event['end']['dateTime'] && event['start']['dateTime'] raise "dateTime field is not found (The event may be all-day event)\n#{event}" end end events.sort! do |a, b| a['end']['dateTime'] - a['start']['dateTime'] <=> b['end']['dateTime'] - b['start']['dateTime'] end # shortest event event = events.first persons = event['summary'].split(event_delimiter).map(&:strip) escalations = @series.escalations.order('escalate_after_sec') persons.each_with_index do |name, i| user = User.find_by(name: name) raise "User '#{name}' is not found." unless user escalation = escalations[i] escalation.update!(escalate_to: user) end end private def user_as User.find(settings.fetch('user_as_id')) end def calendar_name settings.fetch('calendar') end def event_delimiter settings.fetch('event_delimiter') end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/incident.rb
app/models/incident.rb
require 'digest/sha1' class Incident < ApplicationRecord STATUSES = [:opened, :acknowledged, :resolved] belongs_to :topic has_many :events, class_name: 'IncidentEvent', dependent: :destroy enum status: STATUSES has_many :comments validates :topic, presence: true validates :subject, presence: true validates :description, presence: true validates :occured_at, presence: true after_initialize :set_defaults after_create :enqueue def acknowledge! return if self.acknowledged? || self.resolved? self.acknowledged! events.create(kind: :acknowledged) end def resolve! return if self.resolved? self.resolved! events.create(kind: :resolved) end def confirmation_hash Digest::SHA1.hexdigest("#{Rails.application.secrets.secret_key_base}#{self.id}") end private def set_defaults self.status ||= :opened self.occured_at ||= Time.now end def enqueue topic.escalation_series.escalations.each do |escalation| EscalationWorker.enqueue(self, escalation) end events.create(kind: :opened) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/user.rb
app/models/user.rb
require 'securerandom' class User < ApplicationRecord scope :active, -> { where(active: true) } has_many :notifiers serialize :credentials, JSON validates :name, presence: true before_save :set_defaults def self.find_or_create_from_auth_hash(auth_hash) user = self.find_by(provider: auth_hash[:provider], uid: auth_hash[:uid]) return user if user user = self.find_by(email: auth_hash[:info][:email]) if user # email is deprecated user.update!(provider: auth_hash[:provider], uid: auth_hash[:uid], email: nil) return user end self.create!(provider: auth_hash[:provider], uid: auth_hash[:uid], name: auth_hash[:info][:name]) end def update_credentials_from_auth_hash(auth_hash) self.update!(credentials: auth_hash.fetch(:credentials)) end private def set_defaults self.login_token ||= SecureRandom.hex end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/docker/puma.rb
docker/puma.rb
require 'fileutils' listen_unix = ENV['LISTEN_UNIX'] if listen_unix bind "unix://#{listen_unix}" end environment ENV['RAILS_ENV'] port = ENV['PORT'] || 8080 bind "tcp://0.0.0.0:#{port}"
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/seeds.rb
db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first)
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/schema.rb
db/schema.rb
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20161207045554) do create_table "comments", force: :cascade do |t| t.integer "incident_id", limit: 4, null: false t.integer "user_id", limit: 4, null: false t.text "comment", limit: 65535, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "comments", ["incident_id"], name: "index_comments_on_incident_id", using: :btree create_table "escalation_series", force: :cascade do |t| t.string "name", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.text "settings", limit: 65535 end create_table "escalations", force: :cascade do |t| t.bigint "escalate_to_id", limit: 4 t.integer "escalate_after_sec", limit: 4 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.bigint "escalation_series_id", limit: 4 end add_index "escalations", ["escalate_to_id"], name: "index_escalations_on_escalate_to_id", using: :btree add_index "escalations", ["escalation_series_id"], name: "index_escalations_on_escalation_series_id", using: :btree create_table "incident_events", force: :cascade do |t| t.bigint "incident_id", limit: 4 t.integer "kind", limit: 4 t.text "text", limit: 65535 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.text "info", limit: 65535 end add_index "incident_events", ["incident_id"], name: "index_incident_events_on_incident_id", using: :btree create_table "incidents", force: :cascade do |t| t.string "subject", limit: 255 t.text "description", limit: 65535 t.bigint "topic_id", limit: 4 t.datetime "occured_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "status", limit: 4 end add_index "incidents", ["topic_id"], name: "index_incidents_on_topic_id", using: :btree create_table "maintenances", force: :cascade do |t| t.bigint "topic_id", limit: 4 t.datetime "start_time" t.datetime "end_time" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "filter", limit: 255 end add_index "maintenances", ["topic_id"], name: "index_maintenances_on_topic_id", using: :btree create_table "notifier_providers", force: :cascade do |t| t.string "name", limit: 255 t.integer "kind", limit: 4 t.text "settings", limit: 65535 t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "notifiers", force: :cascade do |t| t.text "settings", limit: 65535 t.integer "notify_after_sec", limit: 4 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.bigint "user_id", limit: 4 t.bigint "provider_id", limit: 4 t.bigint "topic_id", limit: 4 t.boolean "enabled", default: true end add_index "notifiers", ["provider_id"], name: "index_notifiers_on_provider_id", using: :btree add_index "notifiers", ["topic_id"], name: "index_notifiers_on_topic_id", using: :btree add_index "notifiers", ["user_id"], name: "index_notifiers_on_user_id", using: :btree create_table "topics", force: :cascade do |t| t.string "name", limit: 255 t.integer "kind", limit: 4 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.bigint "escalation_series_id", limit: 4 t.boolean "enabled", default: true end add_index "topics", ["escalation_series_id"], name: "index_topics_on_escalation_series_id", using: :btree create_table "users", force: :cascade do |t| t.string "name", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "email", limit: 255 t.string "login_token", limit: 255 t.boolean "active", default: false t.string "provider", limit: 255 t.string "uid", limit: 255 t.text "credentials", limit: 65535 end add_foreign_key "escalations", "escalation_series" add_foreign_key "escalations", "users", column: "escalate_to_id" add_foreign_key "incident_events", "incidents" add_foreign_key "incidents", "topics" add_foreign_key "maintenances", "topics" add_foreign_key "notifiers", "notifier_providers", column: "provider_id" add_foreign_key "notifiers", "topics" add_foreign_key "notifiers", "users" add_foreign_key "topics", "escalation_series" end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150203010417_add_settings_to_escalation_series_again.rb
db/migrate/20150203010417_add_settings_to_escalation_series_again.rb
class AddSettingsToEscalationSeriesAgain < ActiveRecord::Migration def change add_column :escalation_series, :settings, :text end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150131121143_set_default_of_enable_of_topic_true.rb
db/migrate/20150131121143_set_default_of_enable_of_topic_true.rb
class SetDefaultOfEnableOfTopicTrue < ActiveRecord::Migration def change change_column :topics, :enable, :boolean, default: true end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120135244_create_escalation_series.rb
db/migrate/20150120135244_create_escalation_series.rb
class CreateEscalationSeries < ActiveRecord::Migration def change create_table :escalation_series do |t| t.string :name t.timestamps null: false end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150125050556_add_provider_to_notifier.rb
db/migrate/20150125050556_add_provider_to_notifier.rb
class AddProviderToNotifier < ActiveRecord::Migration def change add_reference :notifiers, :provider, index: true add_foreign_key :notifiers, :notifier_providers, column: 'provider_id' end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120134905_create_notifiers.rb
db/migrate/20150120134905_create_notifiers.rb
class CreateNotifiers < ActiveRecord::Migration def change create_table :notifiers do |t| t.integer :type t.text :settings t.integer :notify_after_sec t.timestamps null: false end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150123132415_remove_shift.rb
db/migrate/20150123132415_remove_shift.rb
class RemoveShift < ActiveRecord::Migration def change drop_table :shifts end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150202152015_add_settings_to_escalation_series.rb
db/migrate/20150202152015_add_settings_to_escalation_series.rb
class AddSettingsToEscalationSeries < ActiveRecord::Migration def change add_column :escalation_series, :escalation_series, :text end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20151118061253_add_credentials_to_user.rb
db/migrate/20151118061253_add_credentials_to_user.rb
class AddCredentialsToUser < ActiveRecord::Migration def change add_column :users, :credentials, :text end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150201033946_add_login_token_to_user.rb
db/migrate/20150201033946_add_login_token_to_user.rb
class AddLoginTokenToUser < ActiveRecord::Migration def change add_column :users, :login_token, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20151117011141_add_active_to_user.rb
db/migrate/20151117011141_add_active_to_user.rb
class AddActiveToUser < ActiveRecord::Migration def change add_column :users, :active, :boolean, default: false end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120141627_rename_type_with_kind_of_topic.rb
db/migrate/20150120141627_rename_type_with_kind_of_topic.rb
class RenameTypeWithKindOfTopic < ActiveRecord::Migration def change rename_column :topics, :type, :kind end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150127152127_add_info_to_incident_event.rb
db/migrate/20150127152127_add_info_to_incident_event.rb
class AddInfoToIncidentEvent < ActiveRecord::Migration def change add_column :incident_events, :info, :text end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150123150947_create_incident_events.rb
db/migrate/20150123150947_create_incident_events.rb
class CreateIncidentEvents < ActiveRecord::Migration def change create_table :incident_events do |t| t.references :incident, index: true t.integer :kind t.text :text t.references :user_by, index: true t.timestamps null: false end add_foreign_key :incident_events, :incidents add_foreign_key :incident_events, :users, column: 'user_by_id' end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20151118061938_delete_token_from_user.rb
db/migrate/20151118061938_delete_token_from_user.rb
class DeleteTokenFromUser < ActiveRecord::Migration def change User.all.each do |u| if u.token u.update!(credentials: { token: u.token, refresh_token: u.refresh_token, expires_at: u.token_expires_at.to_i, expires: true, }) end end remove_column :users, :token remove_column :users, :token_expires_at remove_column :users, :refresh_token end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150131122151_rename_enable_with_enabled_of_topic.rb
db/migrate/20150131122151_rename_enable_with_enabled_of_topic.rb
class RenameEnableWithEnabledOfTopic < ActiveRecord::Migration def change rename_column :topics, :enable, :enabled end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150131120557_add_enable_to_topic.rb
db/migrate/20150131120557_add_enable_to_topic.rb
class AddEnableToTopic < ActiveRecord::Migration def change add_column :topics, :enable, :boolean end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150125050529_create_notifier_providers.rb
db/migrate/20150125050529_create_notifier_providers.rb
class CreateNotifierProviders < ActiveRecord::Migration def change create_table :notifier_providers do |t| t.string :name t.integer :kind t.text :settings t.timestamps null: false end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150203010332_remove_escalation_series_from_escalation_series.rb
db/migrate/20150203010332_remove_escalation_series_from_escalation_series.rb
class RemoveEscalationSeriesFromEscalationSeries < ActiveRecord::Migration def change remove_column :escalation_series, :escalation_series end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150125101901_remove_kind_from_notifier.rb
db/migrate/20150125101901_remove_kind_from_notifier.rb
class RemoveKindFromNotifier < ActiveRecord::Migration def change remove_column :notifiers, :kind end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20160210010310_create_maintenances.rb
db/migrate/20160210010310_create_maintenances.rb
class CreateMaintenances < ActiveRecord::Migration def change create_table :maintenances do |t| t.references :topic, index: true t.datetime :start_time t.datetime :end_time t.timestamps null: false end add_foreign_key :maintenances, :topics end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150218071007_add_enable_to_notifier.rb
db/migrate/20150218071007_add_enable_to_notifier.rb
class AddEnableToNotifier < ActiveRecord::Migration def change add_column :notifiers, :enabled, :boolean, default: true end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120135123_create_escalations.rb
db/migrate/20150120135123_create_escalations.rb
class CreateEscalations < ActiveRecord::Migration def change create_table :escalations do |t| t.references :escalate_to, index: true t.integer :escalate_after_sec t.timestamps null: false end add_foreign_key :escalations, :users, column: 'escalate_to_id' end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20161207045554_add_filter_to_maintenance.rb
db/migrate/20161207045554_add_filter_to_maintenance.rb
class AddFilterToMaintenance < ActiveRecord::Migration def change add_column :maintenances, :filter, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120154438_add_name_to_shift.rb
db/migrate/20150120154438_add_name_to_shift.rb
class AddNameToShift < ActiveRecord::Migration def change add_column :shifts, :name, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150202155726_add_token_expires_at_to_user.rb
db/migrate/20150202155726_add_token_expires_at_to_user.rb
class AddTokenExpiresAtToUser < ActiveRecord::Migration def change add_column :users, :token_expires_at, :datetime end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20160907123728_create_comments.rb
db/migrate/20160907123728_create_comments.rb
class CreateComments < ActiveRecord::Migration def change create_table "comments", force: :cascade do |t| t.integer "incident_id", limit: 4, null: false t.integer "user_id", limit: 4, null: false t.text "comment", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150202151740_add_refresh_token_to_user.rb
db/migrate/20150202151740_add_refresh_token_to_user.rb
class AddRefreshTokenToUser < ActiveRecord::Migration def change add_column :users, :refresh_token, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120151642_add_escalation_series_to_topic.rb
db/migrate/20150120151642_add_escalation_series_to_topic.rb
class AddEscalationSeriesToTopic < ActiveRecord::Migration def change add_reference :topics, :escalation_series, index: true add_foreign_key :topics, :escalation_series end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120142452_create_incidents.rb
db/migrate/20150120142452_create_incidents.rb
class CreateIncidents < ActiveRecord::Migration def change create_table :incidents do |t| t.string :subject t.text :description t.references :topic, index: true t.datetime :occured_at t.timestamps null: false end add_foreign_key :incidents, :topics end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150128064248_add_email_to_user.rb
db/migrate/20150128064248_add_email_to_user.rb
class AddEmailToUser < ActiveRecord::Migration def change add_column :users, :email, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20151117013824_add_provider_and_uid_to_user.rb
db/migrate/20151117013824_add_provider_and_uid_to_user.rb
class AddProviderAndUidToUser < ActiveRecord::Migration def change add_column :users, :provider, :string add_column :users, :uid, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150207164010_add_topic_to_notifier.rb
db/migrate/20150207164010_add_topic_to_notifier.rb
class AddTopicToNotifier < ActiveRecord::Migration def change add_reference :notifiers, :topic, index: true add_foreign_key :notifiers, :topics end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150123150518_add_status_to_incident.rb
db/migrate/20150123150518_add_status_to_incident.rb
class AddStatusToIncident < ActiveRecord::Migration def change add_column :incidents, :status, :integer end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120135351_add_escalation_series_to_escalation.rb
db/migrate/20150120135351_add_escalation_series_to_escalation.rb
class AddEscalationSeriesToEscalation < ActiveRecord::Migration def change add_reference :escalations, :escalation_series, index: true add_foreign_key :escalations, :escalation_series end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20160914063913_add_comment_index.rb
db/migrate/20160914063913_add_comment_index.rb
class AddCommentIndex < ActiveRecord::Migration def change add_index :comments, :incident_id end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150121150857_rename_type_with_kind_of_notifier.rb
db/migrate/20150121150857_rename_type_with_kind_of_notifier.rb
class RenameTypeWithKindOfNotifier < ActiveRecord::Migration def change rename_column :notifiers, :type, :kind end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150121150043_add_user_to_notifier.rb
db/migrate/20150121150043_add_user_to_notifier.rb
class AddUserToNotifier < ActiveRecord::Migration def change add_reference :notifiers, :user, index: true add_foreign_key :notifiers, :users end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120134616_create_topics.rb
db/migrate/20150120134616_create_topics.rb
class CreateTopics < ActiveRecord::Migration def change create_table :topics do |t| t.string :name t.integer :type t.timestamps null: false end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150127142530_remove_user_by_from_incident_event.rb
db/migrate/20150127142530_remove_user_by_from_incident_event.rb
class RemoveUserByFromIncidentEvent < ActiveRecord::Migration def change remove_foreign_key :incident_events, column: "user_by_id" remove_index :incident_events, :user_by_id remove_column :incident_events, :user_by_id end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120134747_create_users.rb
db/migrate/20150120134747_create_users.rb
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.timestamps null: false end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150120135017_create_shifts.rb
db/migrate/20150120135017_create_shifts.rb
class CreateShifts < ActiveRecord::Migration def change create_table :shifts do |t| t.references :user, index: true t.timestamps null: false end add_foreign_key :shifts, :users end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/db/migrate/20150202144538_add_token_to_user.rb
db/migrate/20150202144538_add_token_to_user.rb
class AddTokenToUser < ActiveRecord::Migration def change add_column :users, :token, :string end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/rails_helper.rb
spec/rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require 'spec_helper' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/spec_helper.rb
spec/spec_helper.rb
require 'simplecov' SimpleCov.start 'rails' do add_filter '/vendor/' add_filter '/.bundle/' end # This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a need to explicitly require it in any files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.before :suite do DatabaseRewinder.clean_all end config.after :each do DatabaseRewinder.clean end # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is recommended. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 =end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/support/sidekiq.rb
spec/support/sidekiq.rb
require 'sidekiq/testing' RSpec.configure do |config| config.before(:each) do Sidekiq::Worker.clear_all end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/support/factory_girl.rb
spec/support/factory_girl.rb
RSpec.configure do |config| config.include FactoryBot::Syntax::Methods config.before(:suite) do begin FactoryBot.lint ensure DatabaseRewinder.clean_all end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/requests/topics_spec.rb
spec/requests/topics_spec.rb
require "rails_helper" RSpec.describe "Topics", type: :request do describe "POST /topics/1/mailgun" do let(:subject) { 'New Alert' } let(:body) { "Your server is on fire" } it "creates a new incident" do topic = create(:topic) post mailgun_topic_path(topic, format: :json), params: { 'subject' => subject, 'body-plain' => body, } expect(response).to have_http_status(200) incident = Incident.last expect(incident.subject).to eq(subject) expect(incident.description).to eq(body) end end describe "POST /topics/1/slack" do it "creates a new incident" do topic = create(:topic) post slack_topic_path(topic, format: :json), params: { 'channel_name' => 'test_channel', 'user_name' => 'test_user', 'text' => 'help me', } expect(response).to have_http_status(200) incident = Incident.last expect(incident.subject).to eq("escalation from slack,channel name:test_channel help me") expect(incident.description).to eq("channel:test_channel user:test_user help me") end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/requests/maintenances_spec.rb
spec/requests/maintenances_spec.rb
require 'rails_helper' RSpec.describe "Maintenances", type: :request do describe "GET /maintenances" do it "works! (now write some real specs)" do get maintenances_path expect(response).to have_http_status(200) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/requests/incident_envets_spec.rb
spec/requests/incident_envets_spec.rb
require 'rails_helper' RSpec.describe "IncidentEvent", type: :request do describe "POST /incident_events/:id/twilio" do let(:incident) { create(:incident) } let(:event) { create(:incident_event, incident_id: incident.id) } describe 'without params[:Digits]' do it "works!" do post "/incident_events/#{event.id}/twilio" expect(response).to have_http_status(200) end end describe 'with params[:Digits]' do before do post "/incident_events/#{event.id}/twilio", params: { Digits: digit} incident.reload end context '1' do let(:digit) { 1 } it "acknowledged" do expect(response).to have_http_status(200) expect(incident.status).to eq 'acknowledged' end end context '2' do let(:digit) { 2 } it "resolved" do expect(response).to have_http_status(200) expect(incident.status).to eq 'resolved' end end end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/helpers/slack_helper_spec.rb
spec/helpers/slack_helper_spec.rb
require 'rails_helper' # Specs in this file have access to a helper object that includes # the SlackHelper. For example: # # describe SlackHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end RSpec.describe SlackHelper, type: :helper do pending "add some examples to (or delete) #{__FILE__}" end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/topic.rb
spec/factories/topic.rb
FactoryBot.define do factory :topic do name { "Infra" } kind { "api" } escalation_series end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/maintenances.rb
spec/factories/maintenances.rb
FactoryBot.define do factory :maintenance do topic nil start_time { "2016-02-10 10:03:10" } end_time { "2016-02-10 10:03:10" } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/notifier_provider.rb
spec/factories/notifier_provider.rb
FactoryBot.define do factory :notifier_provider do name { "Logger" } kind { :rails_logger } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/notifier.rb
spec/factories/notifier.rb
FactoryBot.define do factory :notifier do user association :provider, factory: :notifier_provider notify_after_sec { 60 } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/escalation.rb
spec/factories/escalation.rb
FactoryBot.define do factory :escalation do association :escalate_to, factory: :user escalate_after_sec { 60 } escalation_series end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/escalation_series.rb
spec/factories/escalation_series.rb
FactoryBot.define do factory :escalation_series do name { "Infra" } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/incident_events.rb
spec/factories/incident_events.rb
FactoryBot.define do factory :incident_event do incident_id { 1 } kind { :opened } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/incident.rb
spec/factories/incident.rb
FactoryBot.define do factory :incident do id { 1 } topic subject { "mysql-01 is down" } description { "alert" } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/factories/user.rb
spec/factories/user.rb
FactoryBot.define do factory :user do name { "Ryota Arai" } end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/controllers/slack_controller_spec.rb
spec/controllers/slack_controller_spec.rb
require 'rails_helper' RSpec.describe SlackController, type: :controller do describe "GET interactive" do it "raises token verification failed error" do expect(get: 'slack/interactive').not_to be_routable expect{get :interactive}.to raise_error(RuntimeError, /token verification failed/) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/models/incident_spec.rb
spec/models/incident_spec.rb
require 'rails_helper' RSpec.describe Incident, type: :model do describe "after_create enqueue" do it "creates escalation jobs" do series = create(:escalation_series) escalation = create(:escalation, escalation_series: series) notifier = create(:notifier, user: escalation.escalate_to) topic = create(:topic, escalation_series: series) incident = nil expect { incident = create(:incident, topic: topic) }.to change(EscalationWorker.jobs, :size).by(1).and change(NotificationWorker.jobs, :size).by(1) expect { EscalationWorker.drain }.to change(incident.events, :count).by(1) event = incident.events.last expect(event.kind).to eq('escalated') expect(event.escalation).to eq(escalation) expect(NotificationWorker.jobs.size).to eq(2) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/models/maintenance_spec.rb
spec/models/maintenance_spec.rb
require 'rails_helper' RSpec.describe Maintenance, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/models/comment_spec.rb
spec/models/comment_spec.rb
require 'rails_helper' RSpec.describe Comment, type: :model do let(:incident) { create(:incident) } let(:user) { create(:user) } it 'should be valid' do comment = Comment.new( incident: incident, user: user, comment: 'Help Me', ) expect(comment).to be_valid end it 'should be invalid without incident' do comment = Comment.new( incident: nil, user: user, comment: 'Help Me', ) expect(comment).not_to be_valid end it 'should be invalid without user' do comment = Comment.new( incident: incident, user: nil, comment: 'Help Me', ) expect(comment).not_to be_valid end it 'should be invalid without comment' do comment = Comment.new( incident: incident, user: user, comment: '', ) expect(comment).not_to be_valid end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/models/escalation_series_spec.rb
spec/models/escalation_series_spec.rb
require 'rails_helper' require 'ostruct' require 'google/api_client' require 'json' RSpec.describe EscalationSeries, type: :model do describe "after_create enqueue" do before do # I understand that this is not the recommended method, but it is enough. allow_any_instance_of(Google::APIClient).to receive(:execute).and_return( OpenStruct.new( { data: OpenStruct.new({ items: [{ 'id' => 1, 'summary' => 'test_calendar' }] }) } ), OpenStruct.new( { data: OpenStruct.new({ items: [{ 'summary' => 'c,b,a', 'start' => { 'dateTime' => Time.now }, 'end' => { 'dateTime' => Time.now + 300 }, }] }) } ), ) end it "#update_escalations" do users = %w(a b c).map { |n| create(:user, name: n, credentials: { expires_at: Time.now.to_i + 300, token: "dummy", expires: nil, }) } series = create(:escalation_series, settings: { update_by: 'google_calendar', user_as_id: users.first.id, calendar: 'test_calendar', event_delimiter: ',', }) escalations = users.map { |u| create(:escalation, escalation_series: series, escalate_to: u ) } expect(series.update_escalations!).to be_truthy users.reverse.each_with_index do |u,i| expect(Escalation.find(escalations[i].id).escalate_to.id).to eq(u.id) end end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/spec/views/slack/interactive.html.erb_spec.rb
spec/views/slack/interactive.html.erb_spec.rb
require 'rails_helper' RSpec.describe "slack/interactive.html.erb", type: :view do pending "add some examples to (or delete) #{__FILE__}" end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/application.rb
config/application.rb
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" 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 Waker class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # 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. if time_zone = ENV['TIME_ZONE'] config.time_zone = time_zone end # 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 # Do not swallow errors in after_commit/after_rollback callbacks. config.middleware.use Rack::Health config.middleware.use OmniAuth::Builder do config = {} config[:hd] = ENV['GOOGLE_DOMAIN'] if ENV['GOOGLE_DOMAIN'] provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"], config.merge(scope: 'userinfo.profile,userinfo.email,calendar', name: 'google_oauth2_with_calendar', access_type: 'offline', approval_prompt: 'force', prompt: 'consent') end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/environment.rb
config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/routes.rb
config/routes.rb
Rails.application.routes.draw do post 'slack/interactive' get '/auth/:provider/callback', to: 'sessions#create' resources :incident_events, only: [] do member do post 'twilio' get 'twilio' end end resources :incidents do member do get 'acknowledge' get 'resolve' end collection do patch 'acknowledge', to: "incidents#bulk_acknowledge" patch 'resolve', to: "incidents#bulk_resolve" end resources :comments end resources :escalation_series do member do get 'update_escalations' end end resources :escalations resources :shifts resources :notifiers resources :notifier_providers resources :maintenances resources :users, only: [:index, :show, :destroy] do member do patch 'activation' patch 'deactivation' end end resources :topics do member do post 'mailgun' post 'mackerel' post 'alertmanager' post 'slack' end end require 'sidekiq/web' mount Sidekiq::Web => '/sidekiq' root 'home#index' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/boot.rb
config/boot.rb
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' # Set up gems listed in the Gemfile.
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/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 += [:password]
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/initializers/sidekiq.rb
config/initializers/sidekiq.rb
namespace = ENV['REDIS_NAMESPACE'] || "waker-#{Rails.env}" host = ENV['REDIS_HOST'] || 'localhost' port = ENV['REDIS_PORT'] || 6379 Sidekiq.configure_server do |config| config.poll_interval = 5 config.redis = {url: "redis://#{host}:#{port}", namespace: namespace} end Sidekiq.configure_client do |config| config.redis = {url: "redis://#{host}:#{port}", namespace: namespace} end Sidekiq::Logging.logger = Rails.logger
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/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: '_waker_session'
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/initializers/url_options.rb
config/initializers/url_options.rb
if default_host = ENV['DEFAULT_HOST'] Rails.application.routes.default_url_options[:host] = default_host end if default_protocol = ENV['DEFAULT_PROTOCOL'] Rails.application.routes.default_url_options[:protocol] = default_protocol end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/initializers/field_with_errors.rb
config/initializers/field_with_errors.rb
Rails.application.configure do config.action_view.field_error_proc = lambda do |html_tag, instance| %Q{<div class="has-error">#{html_tag}</div>}.html_safe end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/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] if respond_to?(:wrap_parameters) 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
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/initializers/omniauth.rb
config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/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
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/initializers/cookies_serializer.rb
config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/initializers/assets.rb
config/initializers/assets.rb
# Be sure to restart your server when you modify this file. # 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 # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js )
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/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| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/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
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/environments/test.rb
config/environments/test.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure static file server for tests with Cache-Control for performance. config.serve_static_files = true config.static_cache_control = 'public, max-age=3600' # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # 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 # Randomize the order test cases are executed. config.active_support.test_order = :random # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/environments/development.rb
config/environments/development.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. 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.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # 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 # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end Rails.application.routes.default_url_options[:host] = 'localhost:3000'
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/config/environments/production.rb
config/environments/production.rb
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 # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # 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 # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) if log_dir = ENV['LOG_DIR'] config.logger = ::Logger.new(File.expand_path('production.log', log_dir)) end # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new 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 end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/spec/spec_helper.rb
spec/spec_helper.rb
require "mixlib/shellout" require "tmpdir" require "tempfile" require "timeout" # Load everything from spec/support Dir["spec/support/**/*.rb"].each { |f| require File.expand_path(f) } RSpec.configure do |config| config.mock_with :rspec config.filter_run focus: true config.filter_run_excluding external: true # Add jruby filters here config.filter_run_excluding windows_only: true unless windows? config.filter_run_excluding unix_only: true unless unix? config.filter_run_excluding linux_only: true unless linux? config.filter_run_excluding requires_root: true unless root? config.filter_run_excluding ruby: DependencyProc.with(RUBY_VERSION) config.run_all_when_everything_filtered = true config.warnings = true config.expect_with :rspec do |c| c.syntax = :expect end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/spec/support/dependency_helper.rb
spec/support/dependency_helper.rb
class DependencyProc < Proc attr_accessor :present def self.with(present) provided = Gem::Version.new(present.dup) new do |required| !Gem::Requirement.new(required).satisfied_by?(provided) end.tap { |l| l.present = present } end def inspect "\"#{present}\"" end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/spec/support/platform_helpers.rb
spec/support/platform_helpers.rb
def windows? !!(RUBY_PLATFORM =~ /mswin|mingw|windows/) end def unix? !windows? end def linux? !!(RUBY_PLATFORM =~ /linux/) end if windows? LINE_ENDING = "\r\n".freeze ECHO_LC_ALL = "echo %LC_ALL%".freeze else LINE_ENDING = "\n".freeze ECHO_LC_ALL = "echo $LC_ALL".freeze end def root? return false if windows? Process.euid == 0 end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/spec/mixlib/shellout_spec.rb
spec/mixlib/shellout_spec.rb
require "spec_helper" require "etc" require "logger" require "timeout" describe Mixlib::ShellOut do let(:shell_cmd) { options ? shell_cmd_with_options : shell_cmd_without_options } let(:executed_cmd) { shell_cmd.tap(&:run_command) } let(:stdout) { executed_cmd.stdout } let(:stderr) { executed_cmd.stderr } let(:chomped_stdout) { stdout.chomp } let(:stripped_stdout) { stdout.strip } let(:exit_status) { executed_cmd.status.exitstatus } let(:shell_cmd_without_options) { Mixlib::ShellOut.new(cmd) } let(:shell_cmd_with_options) { Mixlib::ShellOut.new(cmd, options) } let(:cmd) { ruby_eval.call(ruby_code) } let(:ruby_code) { raise "define let(:ruby_code)" } let(:options) { nil } let(:ruby_eval) { lambda { |code| "ruby -e '#{code}'" } } context "when instantiating" do subject { shell_cmd } let(:cmd) { "apt-get install chef" } it "should set the command" do expect(subject.command).to eql(cmd) end context "with default settings" do describe "#cwd" do subject { super().cwd } it { is_expected.to be_nil } end describe "#user" do subject { super().user } it { is_expected.to be_nil } end describe "#with_logon" do subject { super().with_logon } it { is_expected.to be_nil } end describe "#login" do subject { super().login } it { is_expected.to be_nil } end describe "#domain" do subject { super().domain } it { is_expected.to be_nil } end describe "#password" do subject { super().password } it { is_expected.to be_nil } end describe "#group" do subject { super().group } it { is_expected.to be_nil } end describe "#umask" do subject { super().umask } it { is_expected.to be_nil } end describe "#timeout" do subject { super().timeout } it { is_expected.to eql(600) } end describe "#valid_exit_codes" do subject { super().valid_exit_codes } it { is_expected.to eql([0]) } end describe "#live_stream" do subject { super().live_stream } it { is_expected.to be_nil } end describe "#input" do subject { super().input } it { is_expected.to be_nil } end describe "#cgroup" do subject { super().input } it { is_expected.to be_nil } end it "should not set any default environmental variables" do expect(shell_cmd.environment).to eq({}) end end context "when setting accessors" do subject { shell_cmd.send(accessor) } let(:shell_cmd) { blank_shell_cmd.tap(&with_overrides) } let(:blank_shell_cmd) { Mixlib::ShellOut.new("apt-get install chef") } let(:with_overrides) { lambda { |shell_cmd| shell_cmd.send("#{accessor}=", value) } } context "when setting user" do let(:accessor) { :user } let(:value) { "root" } it "should set the user" do is_expected.to eql(value) end # TODO add :unix_only context "with an integer value for user" do let(:value) { 0 } it "should use the user-supplied uid" do expect(shell_cmd.uid).to eql(value) end end # TODO add :unix_only context "with string value for user" do let(:value) { username } let(:username) { user_info.name } let(:expected_uid) { user_info.uid } let(:user_info) { Etc.getpwent } it "should compute the uid of the user", :unix_only do expect(shell_cmd.uid).to eql(expected_uid) end end end context "when setting with_logon" do let(:accessor) { :with_logon } let(:value) { "root" } it "should set the with_logon" do is_expected.to eql(value) end end context "when setting login" do let(:accessor) { :login } let(:value) { true } it "should set the login" do is_expected.to eql(value) end end context "when setting domain" do let(:accessor) { :domain } let(:value) { "localhost" } it "should set the domain" do is_expected.to eql(value) end end context "when setting password" do let(:accessor) { :password } let(:value) { "vagrant" } it "should set the password" do is_expected.to eql(value) end end context "when setting group" do let(:accessor) { :group } let(:value) { "wheel" } it "should set the group" do is_expected.to eql(value) end # TODO add :unix_only context "with integer value for group" do let(:value) { 0 } it "should use the user-supplied gid" do expect(shell_cmd.gid).to eql(value) end end context "with string value for group" do let(:value) { groupname } let(:groupname) { group_info.name } let(:expected_gid) { group_info.gid } let(:group_info) { Etc.getgrent } it "should compute the gid of the user", :unix_only do expect(shell_cmd.gid).to eql(expected_gid) end end end context "when setting the umask" do let(:accessor) { :umask } context "with octal integer" do let(:value) { 007555 } it "should set the umask" do is_expected.to eql(value) end end context "with decimal integer" do let(:value) { 2925 } it "should sets the umask" do is_expected.to eql(005555) end end context "with string" do let(:value) { "7777" } it "should sets the umask" do is_expected.to eql(007777) end end end context "when setting read timeout" do let(:accessor) { :timeout } let(:value) { 10 } it "should set the read timeout" do is_expected.to eql(value) end end context "when setting valid exit codes" do let(:accessor) { :valid_exit_codes } let(:value) { [0, 23, 42] } it "should set the valid exit codes" do is_expected.to eql(value) end end context "when setting a live stream" do let(:accessor) { :live_stream } let(:value) { stream } let(:stream) { StringIO.new } before(:each) do shell_cmd.live_stream = stream end it "live stream should return the stream used for live stdout and live stderr" do expect(shell_cmd.live_stream).to eql(stream) end it "should set the live stdout stream" do expect(shell_cmd.live_stderr).to eql(stream) end it "should set the live stderr stream" do expect(shell_cmd.live_stderr).to eql(stream) end end context "when setting the live stdout and live stderr streams separately" do let(:accessor) { :live_stream } let(:stream) { StringIO.new } let(:value) { stream } let(:stdout_stream) { StringIO.new } let(:stderr_stream) { StringIO.new } before(:each) do shell_cmd.live_stdout = stdout_stream shell_cmd.live_stderr = stderr_stream end it "live_stream should return nil" do expect(shell_cmd.live_stream).to be_nil end it "should set the live stdout" do expect(shell_cmd.live_stdout).to eql(stdout_stream) end it "should set the live stderr" do expect(shell_cmd.live_stderr).to eql(stderr_stream) end end context "when setting a live stream and then overriding the live stderr" do let(:accessor) { :live_stream } let(:value) { stream } let(:stream) { StringIO.new } before(:each) do shell_cmd.live_stdout = stream shell_cmd.live_stderr = nil end it "should return nil" do is_expected.to be_nil end it "should set the live stdout" do expect(shell_cmd.live_stdout).to eql(stream) end it "should set the live stderr" do expect(shell_cmd.live_stderr).to eql(nil) end end context "when setting an input" do let(:accessor) { :input } let(:value) { "Random content #{rand(1000000)}" } it "should set the input" do is_expected.to eql(value) end end context "when setting cgroup" do let(:accessor) { :cgroup } let(:value) { "test" } it "should set the cgroup" do is_expected.to eql(value) end end end context "testing login", :unix_only do subject { shell_cmd } let(:uid) { 1005 } let(:gid) { 1002 } let(:shell) { "/bin/money" } let(:dir) { "/home/castle" } let(:path) { "/sbin:/bin:/usr/sbin:/usr/bin" } before :each do shell_cmd.login = true catbert_user = double("Etc::Passwd", name: "catbert", passwd: "x", uid: 1005, gid: 1002, gecos: "Catbert,,,", dir: "/home/castle", shell: "/bin/money") group_double = [ double("Etc::Group", name: "catbert", passwd: "x", gid: 1002, mem: []), double("Etc::Group", name: "sudo", passwd: "x", gid: 52, mem: ["catbert"]), double("Etc::Group", name: "rats", passwd: "x", gid: 43, mem: ["ratbert"]), double("Etc::Group", name: "dilbertpets", passwd: "x", gid: 700, mem: %w{catbert ratbert}), ] allow(Etc).to receive(:getpwuid).with(1005) { catbert_user } allow(Etc).to receive(:getpwnam).with("catbert") { catbert_user } allow(shell_cmd).to receive(:all_seconderies) { group_double } end # Setting the user by name should change the uid context "when setting user by name" do before(:each) { shell_cmd.user = "catbert" } describe "#uid" do subject { super().uid } it { is_expected.to eq(uid) } end end context "when setting user by id" do before(:each) { shell_cmd.user = uid } # Setting the user by uid should change the uid # it 'should set the uid' do describe "#uid" do subject { super().uid } it { is_expected.to eq(uid) } end # end # Setting the user without a different gid should change the gid to 1002 describe "#gid" do subject { super().gid } it { is_expected.to eq(gid) } end # Setting the user and the group (to 43) should change the gid to 43 context "when setting the group manually" do before(:each) { shell_cmd.group = 43 } describe "#gid" do subject { super().gid } it { is_expected.to eq(43) } end end # Setting the user should set the env variables describe "#process_environment" do subject { super().process_environment } it { is_expected.to eq({ "HOME" => dir, "SHELL" => shell, "USER" => "catbert", "LOGNAME" => "catbert", "PATH" => path, "IFS" => "\t\n" }) } end # Setting the user with overriding env variables should override context "when adding environment variables" do before(:each) { shell_cmd.environment = { "PATH" => "/lord:/of/the/dance", "CUSTOM" => "costume" } } it "should preserve custom variables" do expect(shell_cmd.process_environment["PATH"]).to eq("/lord:/of/the/dance") end # Setting the user with additional env variables should have both it "should allow new variables" do expect(shell_cmd.process_environment["CUSTOM"]).to eq("costume") end end # Setting the user should set secondary groups describe "#sgids" do subject { super().sgids } it { is_expected.to match_array([52, 700]) } end end # Setting login with user should throw errors context "when not setting a user id" do it "should fail showing an error" do expect { Mixlib::ShellOut.new("hostname", { login: true }) }.to raise_error(Mixlib::ShellOut::InvalidCommandOption) end end end context "with options hash" do let(:cmd) { "brew install couchdb" } let(:options) do { cwd:, user:, login: true, domain:, password:, group:, umask:, timeout:, environment:, returns: valid_exit_codes, live_stream: stream, input:, cgroup: } end let(:cwd) { "/tmp" } let(:user) { "toor" } let(:with_logon) { user } let(:login) { true } let(:domain) { "localhost" } let(:password) { "vagrant" } let(:group) { "wheel" } let(:umask) { "2222" } let(:timeout) { 5 } let(:environment) { { "RUBY_OPTS" => "-w" } } let(:valid_exit_codes) { [ 0, 1, 42 ] } let(:stream) { StringIO.new } let(:input) { 1.upto(10).map { "Data #{rand(100000)}" }.join("\n") } let(:cgroup) { "test" } it "should set the working directory" do expect(shell_cmd.cwd).to eql(cwd) end it "should set the user" do expect(shell_cmd.user).to eql(user) end it "should set the with_logon" do expect(shell_cmd.with_logon).to eql(with_logon) end it "should set the login" do expect(shell_cmd.login).to eql(login) end it "should set the domain" do expect(shell_cmd.domain).to eql(domain) end it "should set the password" do expect(shell_cmd.password).to eql(password) end it "should set the group" do expect(shell_cmd.group).to eql(group) end it "should set the umask" do expect(shell_cmd.umask).to eql(002222) end it "should set the timeout" do expect(shell_cmd.timeout).to eql(timeout) end it "should add environment settings to the default" do expect(shell_cmd.environment).to eql({ "RUBY_OPTS" => "-w" }) end context "when setting custom environments" do context "when setting the :env option" do let(:options) { { env: environment } } it "should also set the environment" do expect(shell_cmd.environment).to eql({ "RUBY_OPTS" => "-w" }) end end context "when setting environments with symbols" do let(:options) { { environment: { SYMBOL: "cymbal" } } } it "should also set the enviroment" do expect(shell_cmd.environment).to eql({ "SYMBOL" => "cymbal" }) end end context "when :environment is set to nil" do let(:options) { { environment: nil } } it "should not set any environment" do expect(shell_cmd.environment).to eq({}) end end context "when :env is set to nil" do let(:options) { { env: nil } } it "should not set any environment" do expect(shell_cmd.environment).to eql({}) end end end it "should set valid exit codes" do expect(shell_cmd.valid_exit_codes).to eql(valid_exit_codes) end it "should set the live stream" do expect(shell_cmd.live_stream).to eql(stream) end it "should set the input" do expect(shell_cmd.input).to eql(input) end it "should set the cgroup" do expect(shell_cmd.cgroup).to eql(cgroup) end context "with an invalid option" do let(:options) { { frab: :job } } let(:invalid_option_exception) { Mixlib::ShellOut::InvalidCommandOption } let(:exception_message) { "option ':frab' is not a valid option for Mixlib::ShellOut" } it "should raise InvalidCommandOPtion" do expect { shell_cmd }.to raise_error(invalid_option_exception, exception_message) end end end context "with array of command and args" do let(:cmd) { [ "ruby", "-e", %q{'puts "hello"'} ] } context "without options" do let(:options) { nil } it "should set the command to the array of command and args" do expect(shell_cmd.command).to eql(cmd) end end context "with options" do let(:options) { { cwd: "/tmp", user: "nobody", password: "something" } } it "should set the command to the array of command and args" do expect(shell_cmd.command).to eql(cmd) end it "should evaluate the options" do expect(shell_cmd.cwd).to eql("/tmp") expect(shell_cmd.user).to eql("nobody") expect(shell_cmd.password).to eql("something") end end end end context "when executing the command" do let(:dir) { Dir.mktmpdir } let(:dump_file) { "#{dir}/out.txt" } let(:dump_file_content) { stdout; IO.read(dump_file) } context "with a current working directory" do subject { File.expand_path(chomped_stdout) } let(:fully_qualified_cwd) { File.expand_path(cwd) } let(:options) { { cwd: } } context "when running under Unix", :unix_only do # Use /bin for tests only if it is not a symlink. Some # distributions (e.g. Fedora) symlink it to /usr/bin let(:cwd) { File.symlink?("/bin") ? "/tmp" : "/bin" } let(:cmd) { "pwd" } it "should chdir to the working directory" do is_expected.to eql(fully_qualified_cwd) end end context "when running under Windows", :windows_only do let(:cwd) { Dir.tmpdir } let(:cmd) { "echo %cd%" } it "should chdir to the working directory" do is_expected.to eql(fully_qualified_cwd) end end end context "when handling locale" do before do @original_lc_all = ENV["LC_ALL"] ENV["LC_ALL"] = "en_US.UTF-8" end after do ENV["LC_ALL"] = @original_lc_all end subject { stripped_stdout } let(:cmd) { ECHO_LC_ALL } let(:options) { { environment: { "LC_ALL" => locale } } } context "without specifying environment" do let(:options) { nil } it "should no longer use the C locale by default" do is_expected.to eql("en_US.UTF-8") end end context "with locale" do let(:locale) { "es" } it "should use the requested locale" do is_expected.to eql(locale) end end context "with LC_ALL set to nil" do let(:locale) { nil } context "when running under Unix", :unix_only do it "should unset the process's locale" do is_expected.to eql("") end end context "when running under Windows", :windows_only do it "should unset process's locale" do is_expected.to eql("%LC_ALL%") end end end end context "when running under Windows", :windows_only do let(:cmd) { "%windir%/system32/whoami.exe" } let(:running_user) { shell_cmd.run_command.stdout.strip.downcase } context "when no user is set" do # Need to adjust the username and domain if running as local system # to match how whoami returns the information it "should run as current user" do if ENV["USERNAME"] == "#{ENV["COMPUTERNAME"]}$" expected_user = "nt authority\\system" else expected_user = "#{ENV["USERDOMAIN"].downcase}\\#{ENV["USERNAME"].downcase}" end expect(running_user).to eql(expected_user) end end context "when user is specified" do before do expect(system("net user #{user} #{password} /add")).to eq(true) end after do expect(system("net user #{user} /delete")).to eq(true) end let(:user) { "testuser" } let(:password) { "testpass1!" } let(:options) { { user:, password: } } it "should run as specified user" do expect(running_user).to eql("#{ENV["COMPUTERNAME"].downcase}\\#{user}") end context "when an alternate user is passed" do let(:env_list) { ["ALLUSERSPROFILE=C:\\ProgramData", "TEMP=C:\\Windows\\TEMP", "TMP=C:\\Windows\\TEMP", "USERDOMAIN=WIN-G06ENRTTKF9", "USERNAME=testuser", "USERPROFILE=C:\\Users\\Default", "windir=C:\\Windows"] } let(:current_env) { ["ALLUSERSPROFILE=C:\\ProgramData", "TEMP=C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2", "TMP=C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2", "USER=Administrator", "USERDOMAIN=WIN-G06ENRTTKF9", "USERDOMAIN_ROAMINGPROFILE=WIN-G06ENRTTKF9", "USERNAME=Administrator", "USERPROFILE=C:\\Users\\Administrator", "windir=C:\\Windows"] } let(:merged_env) { ["ALLUSERSPROFILE=C:\\ProgramData", "TEMP=C:\\Windows\\TEMP", "TMP=C:\\Windows\\TEMP", "USER=Administrator", "USERDOMAIN=WIN-G06ENRTTKF9", "USERDOMAIN_ROAMINGPROFILE=WIN-G06ENRTTKF9", "USERNAME=testuser", "USERPROFILE=C:\\Users\\Default", "windir=C:\\Windows"] } let(:converted) { { "ALLUSERSPROFILE" => "C:\\ProgramData", "TEMP" => "C:\\Windows\\TEMP", "TMP" => "C:\\Windows\\TEMP", "USERDOMAIN" => "WIN-G06ENRTTKF9", "USERNAME" => "testuser", "USERPROFILE" => "C:\\Users\\Default", "windir" => "C:\\Windows" } } it "merge environment variables" do expect(Process.merge_env_variables(env_list, current_env)).to eql(merged_env) end it "Convert an array to a hash" do expect(Process.environment_list_to_hash(env_list)).to eql(converted) end end context "when :elevated => true" do context "when user and password are passed" do let(:options) { { user:, password:, elevated: true } } it "raises permission related error" do expect { running_user }.to raise_error(/the user has not been granted the requested logon type at this computer/) end end context "when user and password are not passed" do let(:options) { { elevated: true } } it "raises error" do expect { running_user }.to raise_error("`elevated` option should be passed only with `username` and `password`.") end end end end end context "with a live stream" do let(:stream) { StringIO.new } let(:ruby_code) { '$stdout.puts "hello"; $stderr.puts "world"' } let(:options) { { live_stream: stream } } it "should copy the child's stdout to the live stream" do shell_cmd.run_command expect(stream.string).to include("hello#{LINE_ENDING}") end context "with default live stderr" do it "should copy the child's stderr to the live stream" do shell_cmd.run_command expect(stream.string).to include("world#{LINE_ENDING}") end end context "without live stderr" do it "should not copy the child's stderr to the live stream" do shell_cmd.live_stderr = nil shell_cmd.run_command expect(stream.string).not_to include("world#{LINE_ENDING}") end end context "with a separate live stderr" do let(:stderr_stream) { StringIO.new } it "should not copy the child's stderr to the live stream" do shell_cmd.live_stderr = stderr_stream shell_cmd.run_command expect(stream.string).not_to include("world#{LINE_ENDING}") end it "should copy the child's stderr to the live stderr stream" do shell_cmd.live_stderr = stderr_stream shell_cmd.run_command expect(stderr_stream.string).to include("world#{LINE_ENDING}") end end end context "with an input" do subject { stdout } let(:input) { "hello" } let(:ruby_code) { "STDIN.sync = true; STDOUT.sync = true; puts gets" } let(:options) { { input: } } it "should copy the input to the child's stdin" do is_expected.to eql("hello#{LINE_ENDING}") end end context "when running different types of command" do let(:script) { open_file.tap(&write_file).tap(&:close).tap(&make_executable) } let(:file_name) { "#{dir}/Setup Script.cmd" } let(:script_name) { "\"#{script.path}\"" } let(:open_file) { File.open(file_name, "w") } let(:write_file) { lambda { |f| f.write(script_content) } } let(:make_executable) { lambda { |f| File.chmod(0755, f.path) } } context "with spaces in the path" do subject { chomped_stdout } let(:cmd) { script_name } context "when running under Unix", :unix_only do let(:script_content) { "echo blah" } it "should execute" do is_expected.to eql("blah") end end context "when running under Windows", :windows_only do let(:cmd) { "#{script_name} #{argument}" } let(:script_content) { "@echo %1" } let(:argument) { rand(10000).to_s } it "should execute" do is_expected.to eql(argument) end context "with multiple quotes in the command and args" do context "when using a batch file" do let(:argument) { "\"Random #{rand(10000)}\"" } it "should execute" do is_expected.to eql(argument) end end context "when not using a batch file" do let(:cmd) { "#{executable_file_name} -NoProfile -NoLogo -command #{script_content}" } let(:executable_file_name) { "\"#{dir}/Powershell Parser.exe\"".tap(&make_executable!) } let(:make_executable!) { lambda { |filename| Mixlib::ShellOut.new("copy \"c:\\windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe\" #{filename}").run_command } } let(:script_content) { "Write-Host \"#{expected_output}\"" } let(:expected_output) { "Random #{rand(10000)}" } it "should execute" do is_expected.to eql(expected_output) end end end end end context "with lots of long arguments" do subject { chomped_stdout } # This number was chosen because it seems to be an actual maximum # in Windows--somewhere around 6-7K of command line let(:echotext) { 10000.upto(11340).map(&:to_s).join(" ") } let(:cmd) { "echo #{echotext}" } it "should execute" do is_expected.to eql(echotext) end end context "with special characters" do subject { stdout } let(:special_characters) { "<>&|&&||;" } let(:ruby_code) { "print \"#{special_characters}\"" } it "should execute" do is_expected.to eql(special_characters) end end context "with backslashes" do subject { stdout } let(:backslashes) { %q{\\"\\\\} } let(:cmd) { ruby_eval.call("print \"#{backslashes}\"") } it "should execute" do is_expected.to eql("\"\\") end end context "with pipes" do let(:input_script) { "STDOUT.sync = true; STDERR.sync = true; print true; STDERR.print false" } let(:output_script) { "print STDIN.read.length" } let(:cmd) { ruby_eval.call(input_script) + " | " + ruby_eval.call(output_script) } it "should execute" do expect(stdout).to eql("4") end it "should handle stderr" do expect(stderr).to eql("false") end end context "with stdout and stderr file pipes" do let(:code) { "STDOUT.sync = true; STDERR.sync = true; print true; STDERR.print false" } let(:cmd) { ruby_eval.call(code) + " > #{dump_file}" } it "should execute" do expect(stdout).to eql("") end it "should handle stderr" do expect(stderr).to eql("false") end it "should write to file pipe" do expect(dump_file_content).to eql("true") end end context "with stdin file pipe" do let(:code) { "STDIN.sync = true; STDOUT.sync = true; STDERR.sync = true; print gets; STDERR.print false" } let(:cmd) { ruby_eval.call(code) + " < #{dump_file_path}" } let(:file_content) { "Random content #{rand(100000)}" } let(:dump_file_path) { dump_file.path } let(:dump_file) { open_file.tap(&write_file).tap(&:close) } let(:file_name) { "#{dir}/input" } let(:open_file) { File.open(file_name, "w") } let(:write_file) { lambda { |f| f.write(file_content) } } it "should execute" do expect(stdout).to eql(file_content) end it "should handle stderr" do expect(stderr).to eql("false") end end context "with stdout and stderr file pipes" do let(:code) { "STDOUT.sync = true; STDERR.sync = true; print true; STDERR.print false" } let(:cmd) { ruby_eval.call(code) + " > #{dump_file} 2>&1" } it "should execute" do expect(stdout).to eql("") end it "should write to file pipe" do expect(dump_file_content).to eql("truefalse") end end context "with &&" do subject { stdout } let(:cmd) { ruby_eval.call('print "foo"') + " && " + ruby_eval.call('print "bar"') } it "should execute" do is_expected.to eql("foobar") end end context "with ||" do let(:cmd) { ruby_eval.call('print "foo"; exit 1') + " || " + ruby_eval.call('print "bar"') } it "should execute" do expect(stdout).to eql("foobar") end it "should exit with code 0" do expect(exit_status).to eql(0) end end end context "when handling process exit codes" do let(:cmd) { ruby_eval.call("exit #{exit_code}") } context "with normal exit status" do let(:exit_code) { 0 } it "should not raise error" do expect { executed_cmd.error! }.not_to raise_error end it "should set the exit status of the command" do expect(exit_status).to eql(exit_code) end end context "with nonzero exit status" do let(:exit_code) { 2 } let(:exception_message_format) { Regexp.escape(executed_cmd.format_for_exception) } it "should raise ShellCommandFailed" do expect { executed_cmd.error! }.to raise_error(Mixlib::ShellOut::ShellCommandFailed) end it "includes output with exceptions from #error!" do executed_cmd.error! rescue Mixlib::ShellOut::ShellCommandFailed => e expect(e.message).to match(exception_message_format) end it "should set the exit status of the command" do expect(exit_status).to eql(exit_code) end end context "with valid exit codes" do let(:cmd) { ruby_eval.call("exit #{exit_code}" ) } let(:options) { { returns: valid_exit_codes } } context "when exiting with valid code" do let(:valid_exit_codes) { 42 } let(:exit_code) { 42 } it "should not raise error" do expect { executed_cmd.error! }.not_to raise_error end it "should set the exit status of the command" do expect(exit_status).to eql(exit_code) end end context "when exiting with invalid code" do let(:valid_exit_codes) { [ 0, 1, 42 ] } let(:exit_code) { 2 } it "should raise ShellCommandFailed" do expect { executed_cmd.error! }.to raise_error(Mixlib::ShellOut::ShellCommandFailed) end it "should set the exit status of the command" do expect(exit_status).to eql(exit_code) end context "with input data" do let(:options) { { returns: valid_exit_codes, input: } } let(:input) { "Random data #{rand(1000000)}" } it "should raise ShellCommandFailed" do expect { executed_cmd.error! }.to raise_error(Mixlib::ShellOut::ShellCommandFailed) end it "should set the exit status of the command" do expect(exit_status).to eql(exit_code) end end end context "when exiting with invalid code 0" do
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
true
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/spec/mixlib/shellout/helper_spec.rb
spec/mixlib/shellout/helper_spec.rb
require "spec_helper" require "mixlib/shellout/helper" require "logger" # to use this helper you need to either: # 1. use mixlib-log which has a trace level # 2. monkeypatch a trace level into ruby's logger like this # 3. override the __io_for_live_stream method # class Logger module Severity; TRACE = -1; end def trace(progname = nil, &block); add(TRACE, nil, progname, &block); end def trace?; @level <= TRACE; end end describe Mixlib::ShellOut::Helper, ruby: ">= 2.3" do class TestClass include Mixlib::ShellOut::Helper # this is a hash-like object def __config {} end # this is a train transport connection or nil def __transport_connection nil end # this is a logger-like object def __log Logger.new(IO::NULL) end end let(:test_class) { TestClass.new } it "works to run a trivial ruby command" do expect(test_class.shell_out("ruby -e 'exit 0'")).to be_kind_of(Mixlib::ShellOut) end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/spec/mixlib/shellout/windows_spec.rb
spec/mixlib/shellout/windows_spec.rb
require "spec_helper" # FIXME: these are stubby enough unit tests that they almost run under unix, but the # Mixlib::ShellOut object does not mixin the Windows behaviors when running on unix. describe "Mixlib::ShellOut::Windows", :windows_only do describe "Utils" do describe ".should_run_under_cmd?" do subject { Mixlib::ShellOut.new.send(:should_run_under_cmd?, command) } def self.with_command(_command, &example) context "with command: #{_command}" do let(:command) { _command } it(&example) end end context "when unquoted" do with_command(%q{ruby -e 'prints "foobar"'}) { is_expected.not_to be_truthy } # https://github.com/chef/mixlib-shellout/pull/2#issuecomment-4825574 with_command(%q{"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe" /i "C:\Program Files (x86)\NUnit 2.6\bin\framework\nunit.framework.dll"}) { is_expected.not_to be_truthy } with_command(%q{ruby -e 'exit 1' | ruby -e 'exit 0'}) { is_expected.to be_truthy } with_command(%q{ruby -e 'exit 1' > out.txt}) { is_expected.to be_truthy } with_command(%q{ruby -e 'exit 1' > out.txt 2>&1}) { is_expected.to be_truthy } with_command(%q{ruby -e 'exit 1' < in.txt}) { is_expected.to be_truthy } with_command(%q{ruby -e 'exit 1' || ruby -e 'exit 0'}) { is_expected.to be_truthy } with_command(%q{ruby -e 'exit 1' && ruby -e 'exit 0'}) { is_expected.to be_truthy } with_command(%q{@echo TRUE}) { is_expected.to be_truthy } with_command(%q{echo %PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe %A}) { is_expected.to be_falsey } with_command(%q{run.exe B%}) { is_expected.to be_falsey } with_command(%q{run.exe %A B%}) { is_expected.to be_falsey } with_command(%q{run.exe %A B% %PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe %A B% %_PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe %A B% %PATH_EXT%}) { is_expected.to be_truthy } with_command(%q{run.exe %A B% %1%}) { is_expected.to be_falsey } with_command(%q{run.exe %A B% %PATH1%}) { is_expected.to be_truthy } with_command(%q{run.exe %A B% %_PATH1%}) { is_expected.to be_truthy } context "when outside quotes" do with_command(%q{ruby -e "exit 1" | ruby -e "exit 0"}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" > out.txt}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" > out.txt 2>&1}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" < in.txt}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" || ruby -e "exit 0"}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" && ruby -e "exit 0"}) { is_expected.to be_truthy } with_command(%q{@echo "TRUE"}) { is_expected.to be_truthy } context "with unclosed quote" do with_command(%q{ruby -e "exit 1" | ruby -e "exit 0}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" > "out.txt}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" > "out.txt 2>&1}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" < "in.txt}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" || "ruby -e "exit 0"}) { is_expected.to be_truthy } with_command(%q{ruby -e "exit 1" && "ruby -e "exit 0"}) { is_expected.to be_truthy } with_command(%q{@echo "TRUE}) { is_expected.to be_truthy } with_command(%q{echo "%PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A}) { is_expected.to be_falsey } with_command(%q{run.exe "B%}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B%}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B% %PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %_PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %PATH_EXT%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %1%}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B% %PATH1%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %_PATH1%}) { is_expected.to be_truthy } end end end context "when quoted" do with_command(%q{run.exe "ruby -e 'exit 1' || ruby -e 'exit 0'"}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' > out.txt"}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' > out.txt 2>&1"}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' < in.txt"}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' || ruby -e 'exit 0'"}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' && ruby -e 'exit 0'"}) { is_expected.to be_falsey } with_command(%q{run.exe "%PATH%"}) { is_expected.to be_truthy } with_command(%q{run.exe "%A"}) { is_expected.to be_falsey } with_command(%q{run.exe "B%"}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B%"}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B% %PATH%"}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %_PATH%"}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %PATH_EXT%"}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %1%"}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B% %PATH1%"}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %_PATH1%"}) { is_expected.to be_truthy } context "with unclosed quote" do with_command(%q{run.exe "ruby -e 'exit 1' || ruby -e 'exit 0'}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' > out.txt}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' > out.txt 2>&1}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' < in.txt}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' || ruby -e 'exit 0'}) { is_expected.to be_falsey } with_command(%q{run.exe "ruby -e 'exit 1' && ruby -e 'exit 0'}) { is_expected.to be_falsey } with_command(%q{run.exe "%PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A}) { is_expected.to be_falsey } with_command(%q{run.exe "B%}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B%}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B% %PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %_PATH%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %PATH_EXT%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %1%}) { is_expected.to be_falsey } with_command(%q{run.exe "%A B% %PATH1%}) { is_expected.to be_truthy } with_command(%q{run.exe "%A B% %_PATH1%}) { is_expected.to be_truthy } end end end describe ".kill_process_tree" do let(:shell_out) { Mixlib::ShellOut.new } let(:wmi) { Object.new } let(:wmi_ole_object) { Object.new } let(:wmi_process) { Object.new } let(:logger) { Object.new } before do allow(wmi).to receive(:query).and_return([wmi_process]) allow(wmi_process).to receive(:wmi_ole_object).and_return(wmi_ole_object) allow(logger).to receive(:debug) end context "with a protected system process in the process tree" do before do allow(wmi_ole_object).to receive(:name).and_return("csrss.exe") allow(wmi_ole_object).to receive(:processid).and_return(100) end it "does not attempt to kill csrss.exe" do expect(shell_out).to_not receive(:kill_process) shell_out.send(:kill_process_tree, 200, wmi, logger) end end context "with a non-system-critical process in the process tree" do before do allow(wmi_ole_object).to receive(:name).and_return("blah.exe") allow(wmi_ole_object).to receive(:processid).and_return(300) end it "does attempt to kill blah.exe" do expect(shell_out).to receive(:kill_process).with(wmi_process, logger) expect(shell_out).to receive(:kill_process_tree).with(200, wmi, logger).and_call_original expect(shell_out).to receive(:kill_process_tree).with(300, wmi, logger) shell_out.send(:kill_process_tree, 200, wmi, logger) end end end end # Caveat: Private API methods are subject to change without notice. # Monkeypatch at your own risk. context "#command_to_run" do describe "#command_to_run" do subject { shell_out.send(:command_to_run, command) } # @param cmd [String] command string # @param filename [String] the pathname to the executable that will be found (nil to have no pathname match) # @param search [Boolean] false: will setup expectation not to search PATH, true: will setup expectations that it searches the PATH # @param directory [Boolean] true: will setup an expectation that the search strategy will find a directory def self.with_command(cmd, filename: nil, search: false, directory: false, &example) context "with #{cmd}" do let(:shell_out) { Mixlib::ShellOut.new } let(:comspec) { 'C:\Windows\system32\cmd.exe' } let(:command) { cmd } before do if search expect(ENV).to receive(:[]).with("PATH").and_return('C:\Windows\system32') else expect(ENV).not_to receive(:[]).with("PATH") end allow(ENV).to receive(:[]).with("PATHEXT").and_return(".COM;.EXE;.BAT;.CMD") allow(ENV).to receive(:[]).with("COMSPEC").and_return(comspec) allow(File).to receive(:executable?).and_return(false) if filename expect(File).to receive(:executable?).with(filename).and_return(true) expect(File).to receive(:directory?).with(filename).and_return(false) end if directory expect(File).to receive(:executable?).with(cmd).and_return(true) expect(File).to receive(:directory?).with(cmd).and_return(true) end end it(&example) end end # quoted and unquoted commands that have correct bat and cmd extensions with_command("autoexec.bat", filename: "autoexec.bat") do is_expected.to eql([ comspec, 'cmd /c "autoexec.bat"']) end with_command("autoexec.cmd", filename: "autoexec.cmd") do is_expected.to eql([ comspec, 'cmd /c "autoexec.cmd"']) end with_command('"C:\Program Files\autoexec.bat"', filename: 'C:\Program Files\autoexec.bat') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\autoexec.bat""']) end with_command('"C:\Program Files\autoexec.cmd"', filename: 'C:\Program Files\autoexec.cmd') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\autoexec.cmd""']) end # lookups via PATHEXT with_command("autoexec", filename: "autoexec.BAT") do is_expected.to eql([ comspec, 'cmd /c "autoexec"']) end with_command("autoexec", filename: "autoexec.CMD") do is_expected.to eql([ comspec, 'cmd /c "autoexec"']) end # unquoted commands that have "bat" or "cmd" in the wrong place with_command("autoexecbat", filename: "autoexecbat") do is_expected.to eql(%w{autoexecbat autoexecbat}) end with_command("autoexeccmd", filename: "autoexeccmd") do is_expected.to eql(%w{autoexeccmd autoexeccmd}) end with_command("abattoir.exe", filename: "abattoir.exe") do is_expected.to eql([ "abattoir.exe", "abattoir.exe" ]) end with_command("parse_cmd.exe", filename: "parse_cmd.exe") do is_expected.to eql([ "parse_cmd.exe", "parse_cmd.exe" ]) end # quoted commands that have "bat" or "cmd" in the wrong place with_command('"C:\Program Files\autoexecbat"', filename: 'C:\Program Files\autoexecbat') do is_expected.to eql([ 'C:\Program Files\autoexecbat', '"C:\Program Files\autoexecbat"' ]) end with_command('"C:\Program Files\autoexeccmd"', filename: 'C:\Program Files\autoexeccmd') do is_expected.to eql([ 'C:\Program Files\autoexeccmd', '"C:\Program Files\autoexeccmd"']) end with_command('"C:\Program Files\abattoir.exe"', filename: 'C:\Program Files\abattoir.exe') do is_expected.to eql([ 'C:\Program Files\abattoir.exe', '"C:\Program Files\abattoir.exe"' ]) end with_command('"C:\Program Files\parse_cmd.exe"', filename: 'C:\Program Files\parse_cmd.exe') do is_expected.to eql([ 'C:\Program Files\parse_cmd.exe', '"C:\Program Files\parse_cmd.exe"' ]) end # empty command with_command(" ") do expect { subject }.to raise_error(Mixlib::ShellOut::EmptyWindowsCommand) end # extensionless executable with_command("ping", filename: 'C:\Windows\system32/ping.EXE', search: true) do is_expected.to eql([ 'C:\Windows\system32/ping.EXE', "ping" ]) end # it ignores directories with_command("ping", filename: 'C:\Windows\system32/ping.EXE', directory: true, search: true) do is_expected.to eql([ 'C:\Windows\system32/ping.EXE', "ping" ]) end # https://github.com/chef/mixlib-shellout/pull/2 with bat file with_command('"C:\Program Files\Application\Start.bat"', filename: 'C:\Program Files\Application\Start.bat') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\Application\Start.bat""' ]) end with_command('"C:\Program Files\Application\Start.bat" arguments', filename: 'C:\Program Files\Application\Start.bat') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\Application\Start.bat" arguments"' ]) end with_command('"C:\Program Files\Application\Start.bat" /i "C:\Program Files (x86)\NUnit 2.6\bin\framework\nunit.framework.dll"', filename: 'C:\Program Files\Application\Start.bat') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\Application\Start.bat" /i "C:\Program Files (x86)\NUnit 2.6\bin\framework\nunit.framework.dll""' ]) end # https://github.com/chef/mixlib-shellout/pull/2 with cmd file with_command('"C:\Program Files\Application\Start.cmd"', filename: 'C:\Program Files\Application\Start.cmd') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\Application\Start.cmd""' ]) end with_command('"C:\Program Files\Application\Start.cmd" arguments', filename: 'C:\Program Files\Application\Start.cmd') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\Application\Start.cmd" arguments"' ]) end with_command('"C:\Program Files\Application\Start.cmd" /i "C:\Program Files (x86)\NUnit 2.6\bin\framework\nunit.framework.dll"', filename: 'C:\Program Files\Application\Start.cmd') do is_expected.to eql([ comspec, 'cmd /c ""C:\Program Files\Application\Start.cmd" /i "C:\Program Files (x86)\NUnit 2.6\bin\framework\nunit.framework.dll""' ]) end # https://github.com/chef/mixlib-shellout/pull/2 with unquoted exe file with_command('C:\RUBY192\bin\ruby.exe', filename: 'C:\RUBY192\bin\ruby.exe') do is_expected.to eql([ 'C:\RUBY192\bin\ruby.exe', 'C:\RUBY192\bin\ruby.exe' ]) end with_command('C:\RUBY192\bin\ruby.exe arguments', filename: 'C:\RUBY192\bin\ruby.exe') do is_expected.to eql([ 'C:\RUBY192\bin\ruby.exe', 'C:\RUBY192\bin\ruby.exe arguments' ]) end with_command('C:\RUBY192\bin\ruby.exe -e "print \'fee fie foe fum\'"', filename: 'C:\RUBY192\bin\ruby.exe') do is_expected.to eql([ 'C:\RUBY192\bin\ruby.exe', 'C:\RUBY192\bin\ruby.exe -e "print \'fee fie foe fum\'"' ]) end # https://github.com/chef/mixlib-shellout/pull/2 with quoted exe file exe_with_spaces = 'C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe' with_command("\"#{exe_with_spaces}\"", filename: exe_with_spaces) do is_expected.to eql([ exe_with_spaces, "\"#{exe_with_spaces}\"" ]) end with_command("\"#{exe_with_spaces}\" arguments", filename: exe_with_spaces) do is_expected.to eql([ exe_with_spaces, "\"#{exe_with_spaces}\" arguments" ]) end long_options = "/i \"C:\Program Files (x86)\NUnit 2.6\bin\framework\nunit.framework.dll\"" with_command("\"#{exe_with_spaces}\" #{long_options}", filename: exe_with_spaces) do is_expected.to eql([ exe_with_spaces, "\"#{exe_with_spaces}\" #{long_options}" ]) end # shell built in with_command("copy thing1.txt thing2.txt", search: true) do is_expected.to eql([ comspec, 'cmd /c "copy thing1.txt thing2.txt"' ]) end end end context "#combine_args" do let(:shell_out) { Mixlib::ShellOut.new } subject { shell_out.send(:combine_args, *largs) } def self.with_args(*args, &example) context "with command #{args}" do let(:largs) { args } it(&example) end end with_args("echo", "%PATH%") do is_expected.to eql(%q{echo %PATH%}) end with_args("echo %PATH%") do is_expected.to eql(%q{echo %PATH%}) end # Note carefully for the following that single quotes in ruby support '\\' as an escape sequence for a single # literal backslash. It is not mandatory to always use this since '\d' does not escape the 'd' and is literally # a backlash followed by an 'd'. However, in the following all backslashes are escaped for consistency. Otherwise # it becomes prohibitively confusing to track when you need and do not need the escape the backslash (particularly # when the literal string has a trailing backslash such that '\\' must be used instead of '\' which would escape # the intended terminating single quote or %q{\} which escapes the terminating delimiter). with_args("child.exe", "argument1", "argument 2", '\\some\\path with\\spaces') do is_expected.to eql('child.exe argument1 "argument 2" "\\some\\path with\\spaces"') end with_args("child.exe", "argument1", 'she said, "you had me at hello"', '\\some\\path with\\spaces') do is_expected.to eql('child.exe argument1 "she said, \\"you had me at hello\\"" "\\some\\path with\\spaces"') end with_args("child.exe", "argument1", 'argument\\\\"2\\\\"', "argument3", "argument4") do is_expected.to eql('child.exe argument1 "argument\\\\\\\\\\"2\\\\\\\\\\"" argument3 argument4') end with_args("child.exe", '\\some\\directory with\\spaces\\', "argument2") do is_expected.to eql('child.exe "\\some\\directory with\\spaces\\\\" argument2') end with_args("child.exe", '\\some\\directory with\\\\\\spaces\\\\\\', "argument2") do is_expected.to eql('child.exe "\\some\\directory with\\\\\\spaces\\\\\\\\\\\\" argument2') end end context "#run_command" do let(:shell_out) { Mixlib::ShellOut.new(*largs) } subject { shell_out.send(:run_command) } def self.with_args(*args, &example) context "with command #{args}" do let(:largs) { args } it(&example) end end with_args("echo", "FOO") do is_expected.not_to be_error end # Test box is going to have to have c:\program files on it, which is perhaps brittle in principle, but # I don't know enough windows to come up with a less brittle test. Fix it if you've got a better idea. # The tests need to fail though if the argument is not quoted correctly so using `echo` would be poor # because `echo FOO BAR` and `echo "FOO BAR"` aren't any different. with_args('dir c:\\program files') do is_expected.to be_error end with_args('dir "c:\\program files"') do is_expected.not_to be_error end with_args("dir", 'c:\\program files') do is_expected.not_to be_error end with_args("dir", 'c:\\program files\\') do is_expected.not_to be_error end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout.rb
lib/mixlib/shellout.rb
# frozen_string_literal: true #-- # Author:: Daniel DeLeo (<dan@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "etc" unless defined?(Etc) require "tmpdir" unless defined?(Dir.mktmpdir) require "fcntl" require_relative "shellout/exceptions" module Mixlib class ShellOut READ_WAIT_TIME = 0.01 READ_SIZE = 4096 DEFAULT_READ_TIMEOUT = 600 if RUBY_PLATFORM =~ /mswin|mingw|windows/ require_relative "shellout/windows" include ShellOut::Windows else require_relative "shellout/unix" include ShellOut::Unix end # User the command will run as. Normally set via options passed to new attr_accessor :user attr_accessor :domain attr_accessor :password # TODO remove attr_accessor :with_logon # Whether to simulate logon as the user. Normally set via options passed to new # Always enabled on windows attr_accessor :login # Group the command will run as. Normally set via options passed to new attr_accessor :group # Working directory for the subprocess. Normally set via options to new attr_accessor :cwd # An Array of acceptable exit codes. #error? (and #error!) use this list # to determine if the command was successful. Normally set via options to new attr_accessor :valid_exit_codes # When live_stdout is set, the stdout of the subprocess will be copied to it # as the subprocess is running. attr_accessor :live_stdout # When live_stderr is set, the stderr of the subprocess will be copied to it # as the subprocess is running. attr_accessor :live_stderr # ShellOut will push data from :input down the stdin of the subprocess. # Normally set via options passed to new. # Default: nil attr_accessor :input # If a logger is set, ShellOut will log a message before it executes the # command. attr_accessor :logger # The log level at which ShellOut should log. attr_accessor :log_level # A string which will be prepended to the log message. attr_accessor :log_tag # The command to be executed. attr_reader :command # The umask that will be set for the subcommand. attr_reader :umask # Environment variables that will be set for the subcommand. Refer to the # documentation of new to understand how ShellOut interprets this. attr_accessor :environment # The maximum time this command is allowed to run. Usually set via options # to new attr_writer :timeout # The amount of time the subcommand took to execute attr_reader :execution_time # Data written to stdout by the subprocess attr_reader :stdout # Data written to stderr by the subprocess attr_reader :stderr # A Process::Status (or ducktype) object collected when the subprocess is # reaped. attr_reader :status attr_reader :stdin_pipe, :stdout_pipe, :stderr_pipe, :process_status_pipe # Runs windows process with elevated privileges. Required for Powershell commands which need elevated privileges attr_accessor :elevated attr_accessor :sensitive # Path to cgroupv2 that the process should run on attr_accessor :cgroup # === Arguments: # Takes a single command, or a list of command fragments. These are used # as arguments to Kernel.exec. See the Kernel.exec documentation for more # explanation of how arguments are evaluated. The last argument can be an # options Hash. # === Options: # If the last argument is a Hash, it is removed from the list of args passed # to exec and used as an options hash. The following options are available: # * +user+: the user the command should run as. if an integer is given, it is # used as a uid. A string is treated as a username and resolved to a uid # with Etc.getpwnam # * +group+: the group the command should run as. works similarly to +user+ # * +cwd+: the directory to chdir to before running the command # * +umask+: a umask to set before running the command. If given as an Integer, # be sure to use two leading zeros so it's parsed as Octal. A string will # be treated as an octal integer # * +returns+: one or more Integer values to use as valid exit codes for the # subprocess. This only has an effect if you call +error!+ after # +run_command+. # * +environment+: a Hash of environment variables to set before the command # is run. # * +timeout+: a Numeric value for the number of seconds to wait on the # child process before raising an Exception. This is calculated as the # total amount of time that ShellOut waited on the child process without # receiving any output (i.e., IO.select returned nil). Default is 600 # seconds. Note: the stdlib Timeout library is not used. # * +input+: A String of data to be passed to the subcommand. This is # written to the child process' stdin stream before the process is # launched. The child's stdin stream will be a pipe, so the size of input # data should not exceed the system's default pipe capacity (4096 bytes # is a safe value, though on newer Linux systems the capacity is 64k by # default). # * +live_stream+: An IO or Logger-like object (must respond to the append # operator +<<+) that will receive data as ShellOut reads it from the # child process. Generally this is used to copy data from the child to # the parent's stdout so that users may observe the progress of # long-running commands. # * +login+: Whether to simulate a login (set secondary groups, primary group, environment # variables etc) as done by the OS in an actual login # === Examples: # Invoke find(1) to search for .rb files: # find = Mixlib::ShellOut.new("find . -name '*.rb'") # find.run_command # # If all went well, the results are on +stdout+ # puts find.stdout # # find(1) prints diagnostic info to STDERR: # puts "error messages" + find.stderr # # Raise an exception if it didn't exit with 0 # find.error! # Run a command as the +www+ user with no extra ENV settings from +/tmp+ # cmd = Mixlib::ShellOut.new("apachectl", "start", :user => 'www', :env => nil, :cwd => '/tmp') # cmd.run_command # etc. def initialize(*command_args) # Since ruby 4.0 will freeze string literals by default, we are assigning mutable strings here. @stdout, @stderr, @process_status = String.new(""), String.new(""), String.new("") @live_stdout = @live_stderr = nil @input = nil @log_level = :debug @log_tag = nil @environment = {} @cwd = nil @valid_exit_codes = [0] @terminate_reason = nil @timeout = nil @elevated = false @sensitive = false @cgroup = nil if command_args.last.is_a?(Hash) parse_options(command_args.pop) end @command = command_args.size == 1 ? command_args.first : command_args end # Returns the stream that both is being used by both live_stdout and live_stderr, or nil def live_stream live_stdout == live_stderr ? live_stdout : nil end # A shortcut for setting both live_stdout and live_stderr, so that both the # stdout and stderr from the subprocess will be copied to the same stream as # the subprocess is running. def live_stream=(stream) @live_stdout = @live_stderr = stream end # Set the umask that the subprocess will have. If given as a string, it # will be converted to an integer by String#oct. def umask=(new_umask) @umask = (new_umask.respond_to?(:oct) ? new_umask.oct : new_umask.to_i) & 007777 end # The uid that the subprocess will switch to. If the user attribute was # given as a username, it is converted to a uid by Etc.getpwnam # TODO migrate to shellout/unix.rb def uid return nil unless user user.is_a?(Integer) ? user : Etc.getpwnam(user.to_s).uid end # The gid that the subprocess will switch to. If the group attribute is # given as a group name, it is converted to a gid by Etc.getgrnam # TODO migrate to shellout/unix.rb def gid return group.is_a?(Integer) ? group : Etc.getgrnam(group.to_s).gid if group return Etc.getpwuid(uid).gid if using_login? nil end def timeout @timeout || DEFAULT_READ_TIMEOUT end # Creates a String showing the output of the command, including a banner # showing the exact command executed. Used by +invalid!+ to show command # results when the command exited with an unexpected status. def format_for_exception return "Command execution failed. STDOUT/STDERR suppressed for sensitive resource" if sensitive msg = String.new msg << "#{@terminate_reason}\n" if @terminate_reason msg << "---- Begin output of #{command} ----\n" msg << "STDOUT: #{stdout.strip}\n" msg << "STDERR: #{stderr.strip}\n" msg << "---- End output of #{command} ----\n" msg << "Ran #{command} returned #{status.exitstatus}" if status msg end # The exit status of the subprocess. Will be nil if the command is still # running or died without setting an exit status (e.g., terminated by # `kill -9`). def exitstatus @status&.exitstatus end # Run the command, writing the command's standard out and standard error # to +stdout+ and +stderr+, and saving its exit status object to +status+ # === Returns # returns +self+; +stdout+, +stderr+, +status+, and +exitstatus+ will be # populated with results of the command # === Raises # * Errno::EACCES when you are not privileged to execute the command # * Errno::ENOENT when the command is not available on the system (or not # in the current $PATH) # * CommandTimeout when the command does not complete # within +timeout+ seconds (default: 600s) def run_command if logger prefix = log_tag.nil? ? "" : "#{@log_tag} " log_message = prefix + "sh(#{@command})" # log_message = (log_tag.nil? ? "" : "#{@log_tag} ") << "sh(#{@command})" logger.send(log_level, log_message) end super end # Checks the +exitstatus+ against the set of +valid_exit_codes+. # === Returns # +true+ if +exitstatus+ is not in the list of +valid_exit_codes+, false # otherwise. def error? !Array(valid_exit_codes).include?(exitstatus) end # If #error? is true, calls +invalid!+, which raises an Exception. # === Returns # nil::: always returns nil when it does not raise # === Raises # ::ShellCommandFailed::: via +invalid!+ def error! invalid!("Expected process to exit with #{valid_exit_codes.inspect}, but received '#{exitstatus}'") if error? end # Raises a ShellCommandFailed exception, appending the # command's stdout, stderr, and exitstatus to the exception message. # === Arguments # +msg+: A String to use as the basis of the exception message. The # default explanation is very generic, providing a more informative message # is highly encouraged. # === Raises # ShellCommandFailed always def invalid!(msg = nil) msg ||= "Command produced unexpected results" raise ShellCommandFailed, msg + "\n" + format_for_exception end def inspect "<#{self.class.name}##{object_id}: command: '#{@command}' process_status: #{@status.inspect} " + "stdout: '#{stdout.strip}' stderr: '#{stderr.strip}' child_pid: #{@child_pid.inspect} " + "environment: #{@environment.inspect} timeout: #{timeout} user: #{@user} group: #{@group} working_dir: #{@cwd} " + "cgroup: #{@cgroup} >" end private def parse_options(opts) opts.each do |option, setting| case option.to_s when "cwd" self.cwd = setting when "domain" self.domain = setting when "password" self.password = setting when "user" self.user = setting self.with_logon = setting when "group" self.group = setting when "umask" self.umask = setting when "timeout" self.timeout = setting when "returns" self.valid_exit_codes = Array(setting) when "live_stream" self.live_stdout = self.live_stderr = setting.is_a?(String) ? String.new(setting) : setting when "live_stdout" self.live_stdout = setting.is_a?(String) ? String.new(setting) : setting when "live_stderr" self.live_stderr = setting.is_a?(String) ? String.new(setting) : setting when "input" self.input = setting when "logger" self.logger = setting when "log_level" self.log_level = setting when "log_tag" self.log_tag = setting when "environment", "env" if setting self.environment = Hash[setting.map { |(k, v)| [k.to_s, v] }] else self.environment = {} end when "login" self.login = setting when "elevated" self.elevated = setting when "sensitive" self.sensitive = setting when "cgroup" self.cgroup = setting else raise InvalidCommandOption, "option '#{option.inspect}' is not a valid option for #{self.class.name}" end end validate_options(opts) end def validate_options(opts) if login && !user raise InvalidCommandOption, "cannot set login without specifying a user" end super end end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false
chef/mixlib-shellout
https://github.com/chef/mixlib-shellout/blob/08c2734f5f7861603b7a825f162d10ea1cab2582/lib/mixlib/shellout/version.rb
lib/mixlib/shellout/version.rb
module Mixlib class ShellOut VERSION = "3.4.10".freeze end end
ruby
Apache-2.0
08c2734f5f7861603b7a825f162d10ea1cab2582
2026-01-04T17:46:55.301314Z
false