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 |
|---|---|---|---|---|---|---|---|---|
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/tracking_middleware.rb | lib/tracking_middleware.rb | # frozen_string_literal: true
class TrackingMiddleware
TRACKING_PIXEL = File.read(Rails.root.join("app", "assets", "images", "tracking_pixel.png"))
def initialize(app = nil)
@app = app
end
def call(env)
unless env["HTTP_X_POSTAL_TRACK_HOST"].to_i == 1
return @app.call(env)
end
request = Rack::Request.new(env)
case request.path
when /\A\/img\/([a-z0-9-]+)\/([a-z0-9-]+)/i
server_token = ::Regexp.last_match(1)
message_token = ::Regexp.last_match(2)
dispatch_image_request(request, server_token, message_token)
when /\A\/([a-z0-9-]+)\/([a-z0-9-]+)/i
server_token = ::Regexp.last_match(1)
link_token = ::Regexp.last_match(2)
dispatch_redirect_request(request, server_token, link_token)
else
[200, {}, ["Hello."]]
end
end
private
def dispatch_image_request(request, server_token, message_token)
message_db = get_message_db_from_server_token(server_token)
if message_db.nil?
return [404, {}, ["Invalid Server Token"]]
end
begin
message = message_db.message(token: message_token)
message.create_load(request)
rescue Postal::MessageDB::Message::NotFound
# This message has been removed, we'll just continue to serve the image
rescue StandardError => e
# Somethign else went wrong. We don't want to stop the image loading though because
# this is our problem. Log this exception though.
Sentry.capture_exception(e) if defined?(Sentry)
end
source_image = request.params["src"]
case source_image
when nil
headers = {}
headers["Content-Type"] = "image/png"
headers["Content-Length"] = TRACKING_PIXEL.bytesize.to_s
[200, headers, [TRACKING_PIXEL]]
when /\Ahttps?:\/\//
response = Postal::HTTP.get(source_image, timeout: 3)
return [404, {}, ["Not found"]] unless response[:code] == 200
headers = {}
headers["Content-Type"] = response[:headers]["content-type"]&.first
headers["Last-Modified"] = response[:headers]["last-modified"]&.first
headers["Cache-Control"] = response[:headers]["cache-control"]&.first
headers["Etag"] = response[:headers]["etag"]&.first
headers["Content-Length"] = response[:body].bytesize.to_s
[200, headers, [response[:body]]]
else
[400, {}, ["Invalid/missing source image"]]
end
end
def dispatch_redirect_request(request, server_token, link_token)
message_db = get_message_db_from_server_token(server_token)
if message_db.nil?
return [404, {}, ["Invalid Server Token"]]
end
link = message_db.select(:links, where: { token: link_token }, limit: 1).first
if link.nil?
return [404, {}, ["Link not found"]]
end
time = Time.now.to_f
if link["message_id"]
message_db.update(:messages, { clicked: time }, where: { id: link["message_id"] })
message_db.insert(:clicks, {
message_id: link["message_id"],
link_id: link["id"],
ip_address: request.ip,
user_agent: request.user_agent,
timestamp: time
})
begin
message_webhook_hash = message_db.message(link["message_id"]).webhook_hash
WebhookRequest.trigger(message_db.server, "MessageLinkClicked", {
message: message_webhook_hash,
url: link["url"],
token: link["token"],
ip_address: request.ip,
user_agent: request.user_agent
})
rescue Postal::MessageDB::Message::NotFound
# If we can't find the message that this link is associated with, we'll just ignore it
# and not trigger any webhooks.
end
end
[307, { "Location" => link["url"] }, ["Redirected to: #{link['url']}"]]
end
def get_message_db_from_server_token(token)
return unless server = ::Server.find_by_token(token)
server.message_db
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal.rb | lib/postal.rb | # frozen_string_literal: true
module Postal
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/config_schema.rb | lib/postal/config_schema.rb | # frozen_string_literal: true
require "uri"
module Postal
# REMEMBER: If you change the schema, remember to regenerate the configuration docs
# using the rake command below:
#
# rake postal:generate_config_docs
ConfigSchema = Konfig::Schema.draw do
group :postal do
string :web_hostname do
description "The hostname that the Postal web interface runs on"
default "postal.example.com"
end
string :web_protocol do
description "The HTTP protocol to use for the Postal web interface"
default "https"
end
string :smtp_hostname do
description "The hostname that the Postal SMTP server runs on"
default "postal.example.com"
end
boolean :use_ip_pools do
description "Should IP pools be enabled for this installation?"
default false
end
integer :default_maximum_delivery_attempts do
description "The maximum number of delivery attempts"
default 18
end
integer :default_maximum_hold_expiry_days do
description "The number of days to hold a message before they will be expired"
default 7
end
integer :default_suppression_list_automatic_removal_days do
description "The number of days an address will remain in a suppression list before being removed"
default 30
end
integer :default_spam_threshold do
description "The default threshold at which a message should be treated as spam"
default 5
end
integer :default_spam_failure_threshold do
description "The default threshold at which a message should be treated as spam failure"
default 20
end
boolean :use_local_ns_for_domain_verification do
description "Domain verification and checking usually checks with a domain's nameserver. Enable this to check with the server's local nameservers."
default false
end
boolean :use_resent_sender_header do
description "Append a Resend-Sender header to all outgoing e-mails"
default true
end
string :signing_key_path do
description "Path to the private key used for signing"
default "$config-file-root/signing.key"
transform { |v| Postal.substitute_config_file_root(v) }
end
string :smtp_relays do
array
description "An array of SMTP relays in the format of smtp://host:port"
transform do |value|
uri = URI.parse(value)
query = uri.query ? CGI.parse(uri.query) : {}
{
host: uri.host,
port: uri.port || 25,
ssl_mode: query["ssl_mode"]&.first || "Auto"
}
end
end
string :trusted_proxies do
array
description "An array of IP addresses to trust for proxying requests to Postal (in addition to localhost addresses)"
transform { |ip| IPAddr.new(ip) }
end
integer :queued_message_lock_stale_days do
description "The number of days after which to consider a lock as stale. Messages with stale locks will be removed and not retried."
default 1
end
boolean :batch_queued_messages do
description "When enabled queued messages will be de-queued in batches based on their destination"
default true
end
end
group :web_server do
integer :default_port do
description "The default port the web server should listen on unless overriden by the PORT environment variable"
default 5000
end
string :default_bind_address do
description "The default bind address the web server should listen on unless overriden by the BIND_ADDRESS environment variable"
default "127.0.0.1"
end
integer :max_threads do
description "The maximum number of threads which can be used by the web server"
default 5
end
end
group :worker do
integer :default_health_server_port do
description "The default port for the worker health server to listen on"
default 9090
end
string :default_health_server_bind_address do
description "The default bind address for the worker health server to listen on"
default "127.0.0.1"
end
integer :threads do
description "The number of threads to execute within each worker"
default 2
end
end
group :main_db do
string :host do
description "Hostname for the main MariaDB server"
default "localhost"
end
integer :port do
description "The MariaDB port to connect to"
default 3306
end
string :username do
description "The MariaDB username"
default "postal"
end
string :password do
description "The MariaDB password"
end
string :database do
description "The MariaDB database name"
default "postal"
end
integer :pool_size do
description "The maximum size of the MariaDB connection pool"
default 5
end
string :encoding do
description "The encoding to use when connecting to the MariaDB database"
default "utf8mb4"
end
end
group :message_db do
string :host do
description "Hostname for the MariaDB server which stores the mail server databases"
default "localhost"
end
integer :port do
description "The MariaDB port to connect to"
default 3306
end
string :username do
description "The MariaDB username"
default "postal"
end
string :password do
description "The MariaDB password"
end
string :encoding do
description "The encoding to use when connecting to the MariaDB database"
default "utf8mb4"
end
string :database_name_prefix do
description "The MariaDB prefix to add to database names"
default "postal"
end
end
group :logging do
boolean :rails_log_enabled do
description "Enable the default Rails logger"
default false
end
string :sentry_dsn do
description "A DSN which should be used to report exceptions to Sentry"
end
boolean :enabled do
description "Enable the Postal logger to log to STDOUT"
default true
end
boolean :highlighting_enabled do
description "Enable highlighting of log lines"
default false
end
end
group :gelf do
string :host do
description "GELF-capable host to send logs to"
end
integer :port do
description "GELF port to send logs to"
default 12_201
end
string :facility do
description "The facility name to add to all log entries sent to GELF"
default "postal"
end
end
group :smtp_server do
integer :default_port do
description "The default port the SMTP server should listen on unless overriden by the PORT environment variable"
default 25
end
string :default_bind_address do
description "The default bind address the SMTP server should listen on unless overriden by the BIND_ADDRESS environment variable"
default "::"
end
integer :default_health_server_port do
description "The default port for the SMTP server health server to listen on"
default 9091
end
string :default_health_server_bind_address do
description "The default bind address for the SMTP server health server to listen on"
default "127.0.0.1"
end
boolean :tls_enabled do
description "Enable TLS for the SMTP server (requires certificate)"
default false
end
string :tls_certificate_path do
description "The path to the SMTP server's TLS certificate"
default "$config-file-root/smtp.cert"
transform { |v| Postal.substitute_config_file_root(v) }
end
string :tls_private_key_path do
description "The path to the SMTP server's TLS private key"
default "$config-file-root/smtp.key"
transform { |v| Postal.substitute_config_file_root(v) }
end
string :tls_ciphers do
description "Override ciphers to use for SSL"
end
string :ssl_version do
description "The SSL versions which are supported"
default "SSLv23"
end
boolean :proxy_protocol do
description "Enable proxy protocol for use behind some load balancers (supports proxy protocol v1 only)"
default false
end
boolean :log_connections do
description "Enable connection logging"
default false
end
integer :max_message_size do
description "The maximum message size to accept from the SMTP server (in MB)"
default 14
end
string :log_ip_address_exclusion_matcher do
description "A regular expression to use to exclude connections from logging"
end
end
group :dns do
string :mx_records do
description "The names of the default MX records"
array
default ["mx1.postal.example.com", "mx2.postal.example.com"]
end
string :spf_include do
description "The location of the SPF record"
default "spf.postal.example.com"
end
string :return_path_domain do
description "The return path hostname"
default "rp.postal.example.com"
end
string :route_domain do
description "The domain to use for hosting route-specific addresses"
default "routes.postal.example.com"
end
string :track_domain do
description "The CNAME which tracking domains should be pointed to"
default "track.postal.example.com"
end
string :helo_hostname do
description "The hostname to use in HELO/EHLO when connecting to external SMTP servers"
end
string :dkim_identifier do
description "The identifier to use for DKIM keys in DNS records"
default "postal"
end
string :domain_verify_prefix do
description "The prefix to add before TXT record verification string"
default "postal-verification"
end
string :custom_return_path_prefix do
description "The domain to use on external domains which points to the Postal return path domain"
default "psrp"
end
integer :timeout do
description "The timeout to wait for DNS resolution"
default 5
end
string :resolv_conf_path do
description "The path to the resolv.conf file containing addresses for local nameservers"
default "/etc/resolv.conf"
end
end
group :smtp do
string :host do
description "The hostname to send application-level e-mails to"
default "127.0.0.1"
end
integer :port do
description "The port number to send application-level e-mails to"
default 25
end
string :username do
description "The username to use when authentication to the SMTP server"
end
string :password do
description "The password to use when authentication to the SMTP server"
end
string :authentication_type do
description "The type of authentication to use"
default "login"
end
boolean :enable_starttls do
description "Use STARTTLS when connecting to the SMTP server and fail if unsupported"
default false
end
boolean :enable_starttls_auto do
description "Detects if STARTTLS is enabled in the SMTP server and starts to use it"
default true
end
string :openssl_verify_mode do
description "When using TLS, you can set how OpenSSL checks the certificate. Use 'none' for no certificate checking"
default "peer"
end
string :from_name do
description "The name to use as the from name outgoing emails from Postal"
default "Postal"
end
string :from_address do
description "The e-mail to use as the from address outgoing emails from Postal"
default "postal@example.com"
end
end
group :rails do
string :environment do
description "The Rails environment to run the application in"
default "production"
end
string :secret_key do
description "The secret key used to sign and encrypt cookies and session data in the application"
end
end
group :rspamd do
boolean :enabled do
description "Enable rspamd for message inspection"
default false
end
string :host do
description "The hostname of the rspamd server"
default "127.0.0.1"
end
integer :port do
description "The port of the rspamd server"
default 11_334
end
boolean :ssl do
description "Enable SSL for the rspamd connection"
default false
end
string :password do
description "The password for the rspamd server"
end
string :flags do
description "Any flags for the rspamd server"
end
end
group :spamd do
boolean :enabled do
description "Enable SpamAssassin for message inspection"
default false
end
string :host do
description "The hostname for the SpamAssassin server"
default "127.0.0.1"
end
integer :port do
description "The port of the SpamAssassin server"
default 783
end
end
group :clamav do
boolean :enabled do
description "Enable ClamAV for message inspection"
default false
end
string :host do
description "The host of the ClamAV server"
default "127.0.0.1"
end
integer :port do
description "The port of the ClamAV server"
default 2000
end
end
group :smtp_client do
integer :open_timeout do
description "The open timeout for outgoing SMTP connections"
default 30
end
integer :read_timeout do
description "The read timeout for outgoing SMTP connections"
default 30
end
end
group :migration_waiter do
boolean :enabled do
description "Wait for all migrations to run before starting a process"
default false
end
integer :attempts do
description "The number of attempts to try waiting for migrations to complete before start"
default 120
end
integer :sleep_time do
description "The number of seconds to wait between each migration check"
default 2
end
end
group :oidc do
boolean :enabled do
description "Enable OIDC authentication"
default false
end
boolean :local_authentication_enabled do
description "When enabled, users with passwords will still be able to login locally. If disable, only OpenID Connect will be available."
default true
end
string :name do
description "The name of the OIDC provider as shown in the UI"
default "OIDC Provider"
end
string :issuer do
description "The OIDC issuer URL"
end
string :identifier do
description "The client ID for OIDC"
end
string :secret do
description "The client secret for OIDC"
end
string :scopes do
description "Scopes to request from the OIDC server."
array
default ["openid", "email"]
end
string :uid_field do
description "The field to use to determine the user's UID"
default "sub"
end
string :email_address_field do
description "The field to use to determine the user's email address"
default "email"
end
string :name_field do
description "The field to use to determine the user's name"
default "name"
end
boolean :discovery do
description "Enable discovery to determine endpoints from .well-known/openid-configuration from the Issuer"
default true
end
string :authorization_endpoint do
description "The authorize endpoint on the authorization server (only used when discovery is false)"
end
string :token_endpoint do
description "The token endpoint on the authorization server (only used when discovery is false)"
end
string :userinfo_endpoint do
description "The user info endpoint on the authorization server (only used when discovery is false)"
end
string :jwks_uri do
description "The JWKS endpoint on the authorization server (only used when discovery is false)"
end
end
end
class << self
def substitute_config_file_root(string)
return if string.nil?
string.gsub(/\$config-file-root/i, File.dirname(Postal.config_file_path))
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_parser.rb | lib/postal/message_parser.rb | # frozen_string_literal: true
module Postal
class MessageParser
URL_REGEX = /(?<url>(?<protocol>https?):\/\/(?<domain>[A-Za-z0-9\-.:]+)(?<path>\/[A-Za-z0-9.\/+?&\-_%=~:;()\[\]#]*)?+)/
def initialize(message)
@message = message
@actioned = false
@tracked_links = 0
@tracked_images = 0
@domain = @message.server.track_domains.where(domain: @message.domain, dns_status: "OK").first
return unless @domain
@parsed_output = generate.split("\r\n\r\n", 2)
end
attr_reader :tracked_links
attr_reader :tracked_images
def actioned?
@actioned || @tracked_links.positive? || @tracked_images.positive?
end
def new_body
@parsed_output[1]
end
def new_headers
@parsed_output[0]
end
private
def generate
@mail = Mail.new(@message.raw_message)
@original_message = @message.raw_message
if @mail.parts.empty?
if @mail.mime_type
if @mail.mime_type =~ /text\/plain/
@mail.body = parse(@mail.body.decoded.dup, :text)
@mail.content_transfer_encoding = nil
@mail.charset = "UTF-8"
elsif @mail.mime_type =~ /text\/html/
@mail.body = parse(@mail.body.decoded.dup, :html)
@mail.content_transfer_encoding = nil
@mail.charset = "UTF-8"
end
end
else
parse_parts(@mail.parts)
end
@mail.to_s
rescue StandardError => e
raise if Rails.env.development?
if defined?(Sentry)
Sentry.capture_exception(e)
end
@actioned = false
@tracked_links = 0
@tracked_images = 0
@original_message
end
def parse_parts(parts)
parts.each do |part|
case part.content_type
when /text\/html/
part.body = parse(part.body.decoded.dup, :html)
part.content_transfer_encoding = nil
part.charset = "UTF-8"
when /text\/plain/
part.body = parse(part.body.decoded.dup, :text)
part.content_transfer_encoding = nil
part.charset = "UTF-8"
when /multipart\/(alternative|related)/
unless part.parts.empty?
parse_parts(part.parts)
end
end
end
end
def parse(part, type = nil)
if @domain.track_clicks?
part = insert_links(part, type)
end
if @domain.track_loads? && type == :html
part = insert_tracking_image(part)
end
part
end
def insert_links(part, type = nil)
if type == :text
part.gsub!(/(#{URL_REGEX})(?=\s|$)/) do
if track_domain?($~[:domain])
@tracked_links += 1
url = $~[:url]
while url =~ /[^\w]$/
theend = url.size - 2
url = url[0..theend]
end
token = @message.create_link(url)
"#{domain}/#{@message.server.token}/#{token}"
else
::Regexp.last_match(0)
end
end
end
if type == :html
part.gsub!(/href=(['"])(#{URL_REGEX})['"]/) do
if track_domain?($~[:domain])
@tracked_links += 1
url = CGI.unescapeHTML($~[:url])
token = @message.create_link(url)
"href='#{domain}/#{@message.server.token}/#{token}'"
else
::Regexp.last_match(0)
end
end
end
part.gsub!(/(https?)\+notrack:\/\//) do
@actioned = true
"#{::Regexp.last_match(1)}://"
end
part
end
def insert_tracking_image(part)
@tracked_images += 1
container = "<p class='ampimg' style='display:none;visibility:none;margin:0;padding:0;line-height:0;'><img src='#{domain}/img/#{@message.server.token}/#{@message.token}' alt=''></p>"
if part =~ /<\/body>/
part.gsub("</body>", "#{container}</body>")
else
part + container
end
end
def domain
"#{@domain.use_ssl? ? 'https' : 'http'}://#{@domain.full_name}"
end
def track_domain?(domain)
!@domain.excluded_click_domains_array.include?(domain)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/signer.rb | lib/postal/signer.rb | # frozen_string_literal: true
require "base64"
module Postal
class Signer
# Create a new Signer
#
# @param [OpenSSL::PKey::RSA] private_key The private key to use for signing
# @return [Signer]
def initialize(private_key)
@private_key = private_key
end
# Return the private key
#
# @return [OpenSSL::PKey::RSA]
attr_reader :private_key
# Return the public key for the private key
#
# @return [OpenSSL::PKey::RSA]
def public_key
@private_key.public_key
end
# Sign the given data
#
# @param [String] data The data to sign
# @return [String] The signature
def sign(data)
private_key.sign(OpenSSL::Digest.new("SHA256"), data)
end
# Sign the given data and return a Base64-encoded signature
#
# @param [String] data The data to sign
# @return [String] The Base64-encoded signature
def sign64(data)
Base64.strict_encode64(sign(data))
end
# Return a JWK for the private key
#
# @return [JWT::JWK] The JWK
def jwk
@jwk ||= JWT::JWK.new(private_key, { use: "sig", alg: "RS256" })
end
# Sign the given data using SHA1 (for legacy use)
#
# @param [String] data The data to sign
# @return [String] The signature
def sha1_sign(data)
private_key.sign(OpenSSL::Digest.new("SHA1"), data)
end
# Sign the given data using SHA1 (for legacy use) and return a Base64-encoded string
#
# @param [String] data The data to sign
# @return [String] The signature
def sha1_sign64(data)
Base64.strict_encode64(sha1_sign(data))
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_inspection.rb | lib/postal/message_inspection.rb | # frozen_string_literal: true
module Postal
class MessageInspection
attr_reader :message
attr_reader :scope
attr_reader :spam_checks
attr_accessor :threat
attr_accessor :threat_message
def initialize(message, scope)
@message = message
@scope = scope
@spam_checks = []
@threat = false
end
def spam_score
return 0 if @spam_checks.empty?
@spam_checks.sum(&:score)
end
def scan
MessageInspector.inspectors.each do |inspector|
inspector.inspect_message(self)
end
end
class << self
def scan(message, scope)
inspection = new(message, scope)
inspection.scan
inspection
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_inspector.rb | lib/postal/message_inspector.rb | # frozen_string_literal: true
module Postal
class MessageInspector
def initialize(config)
@config = config
end
# Inspect a message and update the inspection with the results
# as appropriate.
def inspect_message(message, scope, inspection)
end
private
def logger
Postal.logger
end
class << self
# Return an array of all inspectors that are available for this
# installation.
def inspectors
[].tap do |inspectors|
if Postal::Config.rspamd.enabled?
inspectors << MessageInspectors::Rspamd.new(Postal::Config.rspamd)
elsif Postal::Config.spamd.enabled?
inspectors << MessageInspectors::SpamAssassin.new(Postal::Config.spamd)
end
if Postal::Config.clamav.enabled?
inspectors << MessageInspectors::Clamav.new(Postal::Config.clamav)
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/helpers.rb | lib/postal/helpers.rb | # frozen_string_literal: true
module Postal
module Helpers
def self.strip_name_from_address(address)
return nil if address.nil?
address.gsub(/.*</, "").gsub(/>.*/, "").gsub(/\(.+?\)/, "").strip
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/http.rb | lib/postal/http.rb | # frozen_string_literal: true
require "net/https"
require "uri"
module Postal
module HTTP
def self.get(url, options = {})
request(Net::HTTP::Get, url, options)
end
def self.post(url, options = {})
request(Net::HTTP::Post, url, options)
end
def self.request(method, url, options = {})
options[:headers] ||= {}
uri = URI.parse(url)
request = method.new((uri.path.empty? ? "/" : uri.path) + (uri.query ? "?" + uri.query : ""))
options[:headers].each { |k, v| request.add_field k, v }
if options[:username] || uri.user
request.basic_auth(options[:username] || uri.user, options[:password] || uri.password)
end
if options[:params].is_a?(Hash)
# If params has been provided, sent it them as form encoded values
request.set_form_data(options[:params])
elsif options[:json].is_a?(String)
# If we have a JSON string, set the content type and body to be the JSON
# data
request.add_field "Content-Type", "application/json"
request.body = options[:json]
elsif options[:text_body]
# Add a plain text body if we have one
request.body = options[:text_body]
end
if options[:sign]
request.add_field "X-Postal-Signature-KID", Postal.signer.jwk.kid
request.add_field "X-Postal-Signature", Postal.signer.sha1_sign64(request.body.to_s)
request.add_field "X-Postal-Signature-256", Postal.signer.sign64(request.body.to_s)
end
request["User-Agent"] = options[:user_agent] || "Postal/#{Postal.version}"
connection = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"
connection.use_ssl = true
connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
ssl = true
else
ssl = false
end
begin
timeout = options[:timeout] || 60
Timeout.timeout(timeout) do
result = connection.request(request)
{
code: result.code.to_i,
body: result.body,
headers: result.to_hash,
secure: ssl
}
end
rescue OpenSSL::SSL::SSLError
{
code: -3,
body: "Invalid SSL certificate",
headers: {},
secure: ssl
}
rescue SocketError, Errno::ECONNRESET, EOFError, Errno::EINVAL, Errno::ENETUNREACH, Errno::EHOSTUNREACH, Errno::ECONNREFUSED => e
{
code: -2,
body: e.message,
headers: {},
secure: ssl
}
rescue Timeout::Error
{
code: -1,
body: "Timed out after #{timeout}s",
headers: {},
secure: ssl
}
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/spam_check.rb | lib/postal/spam_check.rb | # frozen_string_literal: true
module Postal
class SpamCheck
attr_reader :code, :score, :description
def initialize(code, score, description = nil)
@code = code
@score = score
@description = description
end
def to_hash
{
code: code,
score: score,
description: description
}
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/yaml_config_exporter.rb | lib/postal/yaml_config_exporter.rb | # frozen_string_literal: true
require "konfig/exporters/abstract"
module Postal
class YamlConfigExporter < Konfig::Exporters::Abstract
def export
contents = []
contents << "version: 2"
contents << ""
@schema.groups.each do |group_name, group|
contents << "#{group_name}:"
group.attributes.each do |name, attr|
contents << " # #{attr.description}"
if attr.array?
if attr.default.blank?
contents << " #{name}: []"
else
contents << " #{name}:"
attr.transform(attr.default).each do |d|
contents << " - #{d}"
end
end
else
contents << " #{name}: #{attr.default}"
end
end
contents << ""
end
contents.join("\n")
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/config.rb | lib/postal/config.rb | # frozen_string_literal: true
require "erb"
require "yaml"
require "pathname"
require "cgi"
require "openssl"
require "fileutils"
require "konfig"
require "konfig/sources/environment"
require "konfig/sources/yaml"
require "dotenv"
require "klogger"
require_relative "error"
require_relative "config_schema"
require_relative "legacy_config_source"
require_relative "signer"
module Postal
class << self
attr_writer :current_process_type
# Return the path to the config file
#
# @return [String]
def config_file_path
ENV.fetch("POSTAL_CONFIG_FILE_PATH", "config/postal/postal.yml")
end
def initialize_config
sources = []
# Load environment variables to begin with. Any config provided
# by an environment variable will override any provided in the
# config file.
Dotenv.load(".env")
sources << Konfig::Sources::Environment.new(ENV)
silence_config_messages = ENV.fetch("SILENCE_POSTAL_CONFIG_MESSAGES", "false") == "true"
# If a config file exists, we need to load that. Config files can
# either be legacy (v1) or new (v2). Any file without a 'version'
# key is a legacy file whereas new-style config files will include
# the 'version: 2' key/value.
if File.file?(config_file_path)
unless silence_config_messages
warn "Loading config from #{config_file_path}"
end
config_file = File.read(config_file_path)
yaml = YAML.safe_load(config_file)
config_version = yaml["version"] || 1
case config_version
when 1
unless silence_config_messages
warn "WARNING: Using legacy config file format. Upgrade your postal.yml to use"
warn "version 2 of the Postal configuration or configure using environment"
warn "variables. See https://docs.postalserver.io/config-v2 for details."
end
sources << LegacyConfigSource.new(yaml)
when 2
sources << Konfig::Sources::YAML.new(config_file)
else
raise "Invalid version specified in Postal config file. Must be 1 or 2."
end
elsif !silence_config_messages
warn "No configuration file found at #{config_file_path}"
warn "Only using environment variables for configuration"
end
# Build configuration with the provided sources.
Konfig::Config.build(ConfigSchema, sources: sources)
end
def host_with_protocol
@host_with_protocol ||= "#{Config.postal.web_protocol}://#{Config.postal.web_hostname}"
end
def logger
@logger ||= begin
k = Klogger.new(nil, destination: Config.logging.enabled? ? $stdout : "/dev/null", highlight: Config.logging.highlighting_enabled?)
k.add_destination(graylog_logging_destination) if Config.gelf.host.present?
k
end
end
def process_name
@process_name ||= begin
"host:#{Socket.gethostname} pid:#{Process.pid}"
rescue StandardError
"pid:#{Process.pid}"
end
end
def locker_name
string = process_name.dup
string += " job:#{Thread.current[:job_id]}" if Thread.current[:job_id]
string += " thread:#{Thread.current.native_thread_id}"
string
end
def locker_name_with_suffix(suffix)
"#{locker_name} #{suffix}"
end
def signer
@signer ||= begin
key = OpenSSL::PKey::RSA.new(File.read(Config.postal.signing_key_path))
Signer.new(key)
end
end
def rp_dkim_dns_record
public_key = signer.private_key.public_key.to_s.gsub(/-+[A-Z ]+-+\n/, "").gsub(/\n/, "")
"v=DKIM1; t=s; h=sha256; p=#{public_key};"
end
def ip_pools?
Config.postal.use_ip_pools?
end
def graylog_logging_destination
@graylog_logging_destination ||= begin
notifier = GELF::Notifier.new(Config.gelf.host, Config.gelf.port, "WAN")
proc do |_logger, payload, group_ids|
short_message = payload.delete(:message) || "[message missing]"
notifier.notify!(short_message: short_message, **{
facility: Config.gelf.facility,
_environment: Config.rails.environment,
_version: Postal.version.to_s,
_group_ids: group_ids.join(" ")
}.merge(payload.transform_keys { |k| "_#{k}".to_sym }.transform_values(&:to_s)))
end
end
end
# Change the connection pool size to the given size.
#
# @param new_size [Integer]
# @return [void]
def change_database_connection_pool_size(new_size)
ActiveRecord::Base.connection_pool.disconnect!
config = ActiveRecord::Base.configurations
.configs_for(env_name: Config.rails.environment)
.first
.configuration_hash
ActiveRecord::Base.establish_connection(config.merge(pool: new_size))
end
# Return the branch name which created this release
#
# @return [String, nil]
def branch
return @branch if instance_variable_defined?("@branch")
@branch ||= read_version_file("BRANCH")
end
# Return the version
#
# @return [String, nil]
def version
return @version if instance_variable_defined?("@version")
@version ||= read_version_file("VERSION") || "0.0.0"
end
private
def read_version_file(file)
path = File.expand_path("../../../" + file, __FILE__)
return unless File.exist?(path)
value = File.read(path).strip
value.empty? ? nil : value
end
end
Config = initialize_config
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/helm_config_exporter.rb | lib/postal/helm_config_exporter.rb | # frozen_string_literal: true
require "konfig/exporters/abstract"
module Postal
class HelmConfigExporter < Konfig::Exporters::Abstract
def export
contents = []
path = []
@schema.groups.each do |group_name, group|
path << group_name
group.attributes.each do |name, _|
env_var = Konfig::Sources::Environment.path_to_env_var(path + [name])
contents << <<~VAR.strip
{{ include "app.envVar" (dict "name" "#{env_var}" "spec" .Values.postal.#{path.join('.')}.#{name} "root" . ) }}
VAR
end
path.pop
end
contents.join("\n")
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/legacy_config_source.rb | lib/postal/legacy_config_source.rb | # frozen_string_literal: true
require "konfig/sources/abstract"
require "konfig/error"
module Postal
class LegacyConfigSource < Konfig::Sources::Abstract
# This maps all the new configuration values to where they
# exist in the old YAML file. The source will load any YAML
# file that has been provided to this source in order. A
# warning will be generated to the console for configuration
# loaded from this format.
MAPPING = {
"postal.web_hostname" => -> (c) { c.dig("web", "host") },
"postal.web_protocol" => -> (c) { c.dig("web", "protocol") },
"postal.smtp_hostname" => -> (c) { c.dig("dns", "smtp_server_hostname") },
"postal.use_ip_pools" => -> (c) { c.dig("general", "use_ip_pools") },
"logging.sentry_dsn" => -> (c) { c.dig("general", "exception_url") },
"postal.default_maximum_delivery_attempts" => -> (c) { c.dig("general", "maximum_delivery_attempts") },
"postal.default_maximum_hold_expiry_days" => -> (c) { c.dig("general", "maximum_hold_expiry_days") },
"postal.default_suppression_list_automatic_removal_days" => -> (c) { c.dig("general", "suppression_list_removal_delay") },
"postal.use_local_ns_for_domain_verification" => -> (c) { c.dig("general", "use_local_ns_for_domains") },
"postal.default_spam_threshold" => -> (c) { c.dig("general", "default_spam_threshold") },
"postal.default_spam_failure_threshold" => -> (c) { c.dig("general", "default_spam_failure_threshold") },
"postal.use_resent_sender_header" => -> (c) { c.dig("general", "use_resent_sender_header") },
# SMTP relays must be converted to the new URI style format and they'll
# then be transformed back to a hash by the schema transform.
"postal.smtp_relays" => -> (c) { c["smtp_relays"]&.map { |r| "smtp://#{r['hostname']}:#{r['port']}?ssl_mode=#{r['ssl_mode']}" } },
"web_server.default_bind_address" => -> (c) { c.dig("web_server", "bind_address") },
"web_server.default_port" => -> (c) { c.dig("web_server", "port") },
"web_server.max_threads" => -> (c) { c.dig("web_server", "max_threads") },
"main_db.host" => -> (c) { c.dig("main_db", "host") },
"main_db.port" => -> (c) { c.dig("main_db", "port") },
"main_db.username" => -> (c) { c.dig("main_db", "username") },
"main_db.password" => -> (c) { c.dig("main_db", "password") },
"main_db.database" => -> (c) { c.dig("main_db", "database") },
"main_db.pool_size" => -> (c) { c.dig("main_db", "pool_size") },
"main_db.encoding" => -> (c) { c.dig("main_db", "encoding") },
"message_db.host" => -> (c) { c.dig("message_db", "host") },
"message_db.port" => -> (c) { c.dig("message_db", "port") },
"message_db.username" => -> (c) { c.dig("message_db", "username") },
"message_db.password" => -> (c) { c.dig("message_db", "password") },
"message_db.database_name_prefix" => -> (c) { c.dig("message_db", "prefix") },
"logging.rails_log_enabled" => -> (c) { c.dig("logging", "rails_log") },
"gelf.host" => -> (c) { c.dig("logging", "graylog", "host") },
"gelf.port" => -> (c) { c.dig("logging", "graylog", "port") },
"gelf.facility" => -> (c) { c.dig("logging", "graylog", "facility") },
"smtp_server.default_port" => -> (c) { c.dig("smtp_server", "port") },
"smtp_server.default_bind_address" => -> (c) { c.dig("smtp_server", "bind_address") || "::" },
"smtp_server.tls_enabled" => -> (c) { c.dig("smtp_server", "tls_enabled") },
"smtp_server.tls_certificate_path" => -> (c) { c.dig("smtp_server", "tls_certificate_path") },
"smtp_server.tls_private_key_path" => -> (c) { c.dig("smtp_server", "tls_private_key_path") },
"smtp_server.tls_ciphers" => -> (c) { c.dig("smtp_server", "tls_ciphers") },
"smtp_server.ssl_version" => -> (c) { c.dig("smtp_server", "ssl_version") },
"smtp_server.proxy_protocol" => -> (c) { c.dig("smtp_server", "proxy_protocol") },
"smtp_server.log_connections" => -> (c) { c.dig("smtp_server", "log_connect") },
"smtp_server.max_message_size" => -> (c) { c.dig("smtp_server", "max_message_size") },
"dns.mx_records" => -> (c) { c.dig("dns", "mx_records") },
"dns.spf_include" => -> (c) { c.dig("dns", "spf_include") },
"dns.return_path_domain" => -> (c) { c.dig("dns", "return_path") },
"dns.route_domain" => -> (c) { c.dig("dns", "route_domain") },
"dns.track_domain" => -> (c) { c.dig("dns", "track_domain") },
"dns.helo_hostname" => -> (c) { c.dig("dns", "helo_hostname") },
"dns.dkim_identifier" => -> (c) { c.dig("dns", "dkim_identifier") },
"dns.domain_verify_prefix" => -> (c) { c.dig("dns", "domain_verify_prefix") },
"dns.custom_return_path_prefix" => -> (c) { c.dig("dns", "custom_return_path_prefix") },
"smtp.host" => -> (c) { c.dig("smtp", "host") },
"smtp.port" => -> (c) { c.dig("smtp", "port") },
"smtp.username" => -> (c) { c.dig("smtp", "username") },
"smtp.password" => -> (c) { c.dig("smtp", "password") },
"smtp.from_name" => -> (c) { c.dig("smtp", "from_name") },
"smtp.from_address" => -> (c) { c.dig("smtp", "from_address") },
"rails.environment" => -> (c) { c.dig("rails", "environment") },
"rails.secret_key" => -> (c) { c.dig("rails", "secret_key") },
"rspamd.enabled" => -> (c) { c.dig("rspamd", "enabled") },
"rspamd.host" => -> (c) { c.dig("rspamd", "host") },
"rspamd.port" => -> (c) { c.dig("rspamd", "port") },
"rspamd.ssl" => -> (c) { c.dig("rspamd", "ssl") },
"rspamd.password" => -> (c) { c.dig("rspamd", "password") },
"rspamd.flags" => -> (c) { c.dig("rspamd", "flags") },
"spamd.enabled" => -> (c) { c.dig("spamd", "enabled") },
"spamd.host" => -> (c) { c.dig("spamd", "host") },
"spamd.port" => -> (c) { c.dig("spamd", "port") },
"clamav.enabled" => -> (c) { c.dig("clamav", "enabled") },
"clamav.host" => -> (c) { c.dig("clamav", "host") },
"clamav.port" => -> (c) { c.dig("clamav", "port") },
"smtp_client.open_timeout" => -> (c) { c.dig("smtp_client", "open_timeout") },
"smtp_client.read_timeout" => -> (c) { c.dig("smtp_client", "read_timeout") }
}.freeze
def initialize(config)
super()
@config = config
end
def get(path, attribute: nil)
path_string = path.join(".")
raise Konfig::ValueNotPresentError unless MAPPING.key?(path_string)
legacy_value = MAPPING[path_string].call(@config)
raise Konfig::ValueNotPresentError if legacy_value.nil?
legacy_value
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/error.rb | lib/postal/error.rb | # frozen_string_literal: true
module Postal
class Error < StandardError
end
module Errors
class AuthenticationError < Error
attr_reader :error
def initialize(error)
super()
@error = error
end
def to_s
"Authentication Failed: #{@error}"
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/webhooks.rb | lib/postal/message_db/webhooks.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Webhooks
def initialize(database)
@database = database
end
def record(attributes = {})
@database.insert(:webhook_requests, attributes)
end
def list(page = 1)
result = @database.select_with_pagination(:webhook_requests, page, order: :timestamp, direction: "desc")
result[:records] = result[:records].map { |i| Request.new(i) }
result
end
def find(uuid)
request = @database.select(:webhook_requests, where: { uuid: uuid }).first || raise(RequestNotFound, "No request found with UUID '#{uuid}'")
Request.new(request)
end
def prune
return unless last = @database.select(:webhook_requests, where: { timestamp: { less_than: 10.days.ago.to_f } }, order: "timestamp", direction: "desc", limit: 1, fields: ["id"]).first
@database.delete(:webhook_requests, where: { id: { less_than_or_equal_to: last["id"] } })
end
class RequestNotFound < Postal::Error
end
class Request
def initialize(attributes)
@attributes = attributes
end
def [](name)
@attributes[name.to_s]
end
def timestamp
Time.zone.at(@attributes["timestamp"])
end
def event
@attributes["event"]
end
def status_code
@attributes["status_code"]
end
def url
@attributes["url"]
end
def uuid
@attributes["uuid"]
end
def payload
@attributes["payload"]
end
def pretty_payload
@pretty_payload ||= begin
json = JSON.parse(payload)
JSON.pretty_unparse(json)
end
end
def body
@attributes["body"]
end
def attempt
@attributes["attempt"]
end
def will_retry?
@attributes["will_retry"] == 1
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/load.rb | lib/postal/message_db/load.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Load
def initialize(attributes)
@ip_address = attributes["ip_address"]
@user_agent = attributes["user_agent"]
@timestamp = Time.zone.at(attributes["timestamp"])
end
attr_reader :ip_address
attr_reader :user_agent
attr_reader :timestamp
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/statistics.rb | lib/postal/message_db/statistics.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Statistics
def initialize(database)
@database = database
end
STATS_GAPS = { hourly: :hour, daily: :day, monthly: :month, yearly: :year }.freeze
COUNTERS = [:incoming, :outgoing, :spam, :bounces, :held].freeze
#
# Increment an appropriate counter
#
def increment_one(type, field, time = Time.now)
time = time.utc
initial_values = COUNTERS.map do |c|
field.to_sym == c ? 1 : 0
end
time_i = time.send("beginning_of_#{STATS_GAPS[type]}").utc.to_i
sql_query = "INSERT INTO `#{@database.database_name}`.`stats_#{type}` (time, #{COUNTERS.join(', ')})"
sql_query << " VALUES (#{time_i}, #{initial_values.join(', ')})"
sql_query << " ON DUPLICATE KEY UPDATE #{field} = #{field} + 1"
@database.query(sql_query)
end
#
# Increment all stats counters
#
def increment_all(time, field)
STATS_GAPS.each_key do |type|
increment_one(type, field, time)
end
end
#
# Get a statistic (or statistics)
#
def get(type, counters, start_date = Time.now, quantity = 10)
start_date = start_date.utc
items = quantity.times.each_with_object({}) do |i, hash|
hash[(start_date - i.send(STATS_GAPS[type])).send("beginning_of_#{STATS_GAPS[type]}").utc] = counters.each_with_object({}) do |c, h|
h[c] = 0
end
end
@database.select("stats_#{type}", where: { time: items.keys.map(&:to_i) }, fields: [:time] | counters).each do |data|
time = Time.zone.at(data.delete("time"))
data.each do |key, value|
items[time][key.to_sym] = value
end
end
items.to_a.reverse
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/connection_pool.rb | lib/postal/message_db/connection_pool.rb | # frozen_string_literal: true
module Postal
module MessageDB
class ConnectionPool
attr_reader :connections
def initialize
@connections = []
@lock = Mutex.new
end
def use
retried = false
do_not_checkin = false
begin
connection = checkout
yield connection
rescue Mysql2::Error => e
if e.message =~ /(lost connection|gone away|not connected)/i
# If the connection has failed for a connectivity reason
# we won't add it back in to the pool so that it'll reconnect
# next time.
do_not_checkin = true
# If we haven't retried yet, we'll retry the block once more.
if retried == false
retried = true
retry
end
end
raise
ensure
checkin(connection) unless do_not_checkin
end
end
private
def checkout
@lock.synchronize do
return @connections.pop unless @connections.empty?
end
add_new_connection
checkout
end
def checkin(connection)
@lock.synchronize do
@connections << connection
end
end
def add_new_connection
@lock.synchronize do
@connections << establish_connection
end
end
def establish_connection
Mysql2::Client.new(
host: Postal::Config.message_db.host,
username: Postal::Config.message_db.username,
password: Postal::Config.message_db.password,
port: Postal::Config.message_db.port,
encoding: Postal::Config.message_db.encoding
)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/suppression_list.rb | lib/postal/message_db/suppression_list.rb | # frozen_string_literal: true
module Postal
module MessageDB
class SuppressionList
def initialize(database)
@database = database
end
def add(type, address, options = {})
keep_until = (options[:days] || Postal::Config.postal.default_suppression_list_automatic_removal_days).days.from_now.to_f
if existing = @database.select("suppressions", where: { type: type, address: address }, limit: 1).first
reason = options[:reason] || existing["reason"]
@database.update("suppressions", { reason: reason, keep_until: keep_until }, where: { id: existing["id"] })
else
@database.insert("suppressions", { type: type, address: address, reason: options[:reason], timestamp: Time.now.to_f, keep_until: keep_until })
end
true
end
def get(type, address)
@database.select("suppressions", where: { type: type, address: address, keep_until: { greater_than_or_equal_to: Time.now.to_f } }, limit: 1).first
end
def all_with_pagination(page)
@database.select_with_pagination(:suppressions, page, order: :timestamp, direction: "desc")
end
def remove(type, address)
@database.delete("suppressions", where: { type: type, address: address }).positive?
end
def prune
@database.delete("suppressions", where: { keep_until: { less_than: Time.now.to_f } }) || 0
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/message.rb | lib/postal/message_db/message.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Message
class NotFound < Postal::Error
end
def self.find_one(database, query)
query = { id: query.to_i } if query.is_a?(Integer)
raise NotFound, "No message found matching provided query #{query}" unless message = database.select("messages", where: query, limit: 1).first
Message.new(database, message)
end
def self.find(database, options = {})
if messages = database.select("messages", options)
if messages.is_a?(Array)
messages.map { |m| Message.new(database, m) }
else
messages
end
else
[]
end
end
def self.find_with_pagination(database, page, options = {})
messages = database.select_with_pagination("messages", page, options)
messages[:records] = messages[:records].map { |m| Message.new(database, m) }
messages
end
attr_reader :database
def initialize(database, attributes)
@database = database
@attributes = attributes
end
def reload
self.class.find_one(@database, @attributes["id"])
end
#
# Return the server for this message
#
def server
@database.server
end
#
# Return the credential for this message
#
def credential
@credential ||= credential_id ? Credential.find_by_id(credential_id) : nil
end
#
# Return the route for this message
#
def route
@route ||= route_id ? Route.find_by_id(route_id) : nil
end
#
# Return the endpoint for this message
#
def endpoint
if endpoint_type && endpoint_id
@endpoint ||= endpoint_type.constantize.find_by_id(endpoint_id)
elsif route && route.mode == "Endpoint"
@endpoint ||= route.endpoint
end
end
#
# Return the credential for this message
#
def domain
@domain ||= domain_id ? Domain.find_by_id(domain_id) : nil
end
#
# Copy appropriate attributes from the raw message to the message itself
#
def copy_attributes_from_raw_message
return unless raw_message
self.subject = headers["subject"]&.last.to_s[0, 200]
self.message_id = headers["message-id"]&.last
return unless message_id
self.message_id = message_id.gsub(/.*</, "").gsub(/>.*/, "").strip
end
#
# Return the timestamp for this message
#
def timestamp
@timestamp ||= @attributes["timestamp"] ? Time.zone.at(@attributes["timestamp"]) : nil
end
#
# Return the time that the last delivery was attempted
#
def last_delivery_attempt
@last_delivery_attempt ||= @attributes["last_delivery_attempt"] ? Time.zone.at(@attributes["last_delivery_attempt"]) : nil
end
#
# Return the hold expiry for this message
#
def hold_expiry
@hold_expiry ||= @attributes["hold_expiry"] ? Time.zone.at(@attributes["hold_expiry"]) : nil
end
#
# Has this message been read?
#
def read?
!!(loaded || clicked)
end
#
# Add a delivery attempt for this message
#
def create_delivery(status, options = {})
delivery = Delivery.create(self, options.merge(status: status))
hold_expiry = status == "Held" ? Postal::Config.postal.default_maximum_hold_expiry_days.days.from_now.to_f : nil
update(status: status, last_delivery_attempt: delivery.timestamp.to_f, held: status == "Held", hold_expiry: hold_expiry)
delivery
end
#
# Return all deliveries for this object
#
def deliveries
@deliveries ||= @database.select("deliveries", where: { message_id: id }, order: :timestamp).map do |hash|
Delivery.new(self, hash)
end
end
#
# Return all the clicks for this object
#
def clicks
@clicks ||= begin
clicks = @database.select("clicks", where: { message_id: id }, order: :timestamp)
if clicks.empty?
[]
else
links = @database.select("links", where: { id: clicks.map { |c| c["link_id"].to_i } }).group_by { |l| l["id"] }
clicks.map do |hash|
Click.new(hash, links[hash["link_id"]].first)
end
end
end
end
#
# Return all the loads for this object
#
def loads
@loads ||= begin
loads = @database.select("loads", where: { message_id: id }, order: :timestamp)
loads.map do |hash|
Load.new(hash)
end
end
end
#
# Return all activity entries
#
def activity_entries
@activity_entries ||= (deliveries + clicks + loads).sort_by(&:timestamp)
end
#
# Provide access to set and get acceptable attributes
#
def method_missing(name, value = nil, &block)
if @attributes.key?(name.to_s)
@attributes[name.to_s]
elsif name.to_s =~ /=\z/
@attributes[name.to_s.gsub("=", "").to_s] = value
end
end
def respond_to_missing?(name, include_private = false)
name = name.to_s.sub(/=\z/, "")
@attributes.key?(name.to_s)
end
#
# Has this message been persisted to the database yet?
#
def persisted?
!@attributes["id"].nil?
end
#
# Save this message
#
def save(queue_on_create: true)
save_raw_message
persisted? ? _update : _create(queue: queue_on_create)
self
end
#
# Update this message
#
def update(attributes_to_change)
@attributes = @attributes.merge(database.stringify_keys(attributes_to_change))
if persisted?
@database.update("messages", attributes_to_change, where: { id: id })
else
_create
end
end
#
# Delete the message from the database
#
def delete
return unless persisted?
@database.delete("messages", where: { id: id })
end
#
# Return the headers
#
def raw_headers
if raw_table
@raw_headers ||= @database.select(raw_table, where: { id: raw_headers_id }).first&.send(:[], "data") || ""
else
""
end
end
#
# Return the full raw message body for this message.
#
def raw_body
if raw_table
@raw ||= @database.select(raw_table, where: { id: raw_body_id }).first&.send(:[], "data") || ""
else
""
end
end
#
# Return the full raw message for this message
#
def raw_message
@raw_message ||= "#{raw_headers}\r\n\r\n#{raw_body}"
end
#
# Set the raw message ready for saving later
#
def raw_message=(raw)
@pending_raw_message = raw.force_encoding("BINARY")
end
#
# Save the raw message to the database as appropriate
#
def save_raw_message
return unless @pending_raw_message
self.size = @pending_raw_message.bytesize
date = Time.now.utc.to_date
table_name, headers_id, body_id = @database.insert_raw_message(@pending_raw_message, date)
self.raw_table = table_name
self.raw_headers_id = headers_id
self.raw_body_id = body_id
@raw = nil
@raw_headers = nil
@headers = nil
@mail = nil
@pending_raw_message = nil
copy_attributes_from_raw_message
@database.query("UPDATE `#{@database.database_name}`.`raw_message_sizes` SET size = size + #{size} WHERE table_name = '#{table_name}'")
end
#
# Is there a raw message?
#
def raw_message?
!!raw_table
end
#
# Return the plain body for this message
#
def plain_body
mail&.plain_body
end
#
# Return the HTML body for this message
#
def html_body
mail&.html_body
end
#
# Return the HTML body with any tracking links
#
def html_body_without_tracking_image
html_body.gsub(/<p class=['"]ampimg['"].*?<\/p>/, "")
end
#
# Return all attachments for this message
#
def attachments
mail&.attachments || []
end
#
# Return the headers for this message
#
def headers
@headers ||= begin
mail = Mail.new(raw_headers)
mail.header.fields.each_with_object({}) do |field, hash|
hash[field.name.downcase] ||= []
begin
hash[field.name.downcase] << field.decoded
rescue Mail::Field::IncompleteParseError
# Never mind, move on to the next header
end
end
end
end
#
# Return the recipient domain for this message
#
def recipient_domain
rcpt_to&.split("@")&.last
end
#
# Create a new item in the message queue for this message
#
def add_to_message_queue(**options)
QueuedMessage.create!({
message: self,
server_id: @database.server_id,
batch_key: batch_key,
domain: recipient_domain,
route_id: route_id
}.merge(options))
end
#
# Return a suitable batch key for this message
#
def batch_key
case scope
when "outgoing"
key = "outgoing-"
key += recipient_domain.to_s
when "incoming"
key = "incoming-"
key += "rt:#{route_id}-ep:#{endpoint_id}-#{endpoint_type}"
else
key = nil
end
key
end
#
# Return the queued message
#
def queued_message
@queued_message ||= id ? QueuedMessage.where(message_id: id, server_id: @database.server_id).first : nil
end
#
# Return the spam status
#
def spam_status
return "NotChecked" unless inspected
spam ? "Spam" : "NotSpam"
end
#
# Has this message been held?
#
def held?
status == "Held"
end
#
# Does this message have our DKIM header yet?
#
def has_outgoing_headers?
!!(raw_headers =~ /^X-Postal-MsgID:/i)
end
#
# Add dkim header
#
def add_outgoing_headers
headers = []
if domain
dkim = DKIMHeader.new(domain, raw_message)
headers << dkim.dkim_header
end
headers << "X-Postal-MsgID: #{token}"
append_headers(*headers)
end
#
# Append a header to the existing headers
#
def append_headers(*headers)
new_headers = headers.join("\r\n")
new_headers = "#{new_headers}\r\n#{raw_headers}"
@database.update(raw_table, { data: new_headers }, where: { id: raw_headers_id })
@raw_headers = new_headers
@raw_message = nil
@headers = nil
end
#
# Return a suitable
#
def webhook_hash
@webhook_hash ||= {
id: id,
token: token,
direction: scope,
message_id: message_id,
to: rcpt_to,
from: mail_from,
subject: subject,
timestamp: timestamp.to_f,
spam_status: spam_status,
tag: tag
}
end
#
# Mark this message as bounced
#
def bounce!(bounce_message)
create_delivery("Bounced", details: "We've received a bounce message for this e-mail. See <msg:#{bounce_message.id}> for details.")
WebhookRequest.trigger(server, "MessageBounced", {
original_message: webhook_hash,
bounce: bounce_message.webhook_hash
})
end
#
# Should bounces be sent for this message?
#
def send_bounces?
!bounce && mail_from.present?
end
#
# Add a load for this message
#
def create_load(request)
update("loaded" => Time.now.to_f) if loaded.nil?
database.insert(:loads, { message_id: id, ip_address: request.ip, user_agent: request.user_agent, timestamp: Time.now.to_f })
WebhookRequest.trigger(server, "MessageLoaded", {
message: webhook_hash,
ip_address: request.ip,
user_agent: request.user_agent
})
end
#
# Create a new link
#
def create_link(url)
hash = Digest::SHA1.hexdigest(url.to_s)
token = SecureRandom.alphanumeric(16)
database.insert(:links, { message_id: id, hash: hash, url: url, timestamp: Time.now.to_f, token: token })
token
end
#
# Return a message object that this message is a reply to
#
def original_messages
return nil unless bounce
other_message_ids = raw_message.scan(/\X-Postal-MsgID:\s*([a-z0-9]+)/i).flatten
if other_message_ids.empty?
[]
else
database.messages(where: { token: other_message_ids })
end
end
#
# Was thsi message sent to a return path?
#
def rcpt_to_return_path?
!!(rcpt_to =~ /@#{Regexp.escape(Postal::Config.dns.custom_return_path_prefix)}\./)
end
#
# Inspect this message
#
def inspect_message
result = MessageInspection.scan(self, scope&.to_sym)
# Update the messages table with the results of our inspection
update(inspected: true, spam_score: result.spam_score, threat: result.threat, threat_details: result.threat_message)
# Add any spam details into the spam checks database
database.insert_multi(:spam_checks, [:message_id, :code, :score, :description], result.spam_checks.map { |d| [id, d.code, d.score, d.description] })
# Return the result
result
end
#
# Return all spam checks for this message
#
def spam_checks
@spam_checks ||= database.select(:spam_checks, where: { message_id: id })
end
#
# Cancel the hold on this message
#
def cancel_hold
return unless status == "Held"
create_delivery("HoldCancelled", details: "The hold on this message has been removed without action.")
end
#
# Parse the contents of this message
#
def parse_content
parse_result = Postal::MessageParser.new(self)
if parse_result.actioned?
# Somethign was changed, update the raw message
@database.update(raw_table, { data: parse_result.new_body }, where: { id: raw_body_id })
@database.update(raw_table, { data: parse_result.new_headers }, where: { id: raw_headers_id })
@raw = parse_result.new_body
@raw_headers = parse_result.new_headers
@raw_message = nil
end
update("parsed" => 1, "tracked_links" => parse_result.tracked_links, "tracked_images" => parse_result.tracked_images)
end
#
# Has this message been parsed?
#
def parsed?
parsed == 1
end
#
# Should this message be parsed?
#
def should_parse?
parsed? == false && headers["x-amp"] != "skip"
end
private
def _update
@database.update("messages", @attributes.except(:id), where: { id: @attributes["id"] })
end
def _create(queue: true)
self.timestamp = Time.now.to_f if timestamp.blank?
self.status = "Pending" if status.blank?
self.token = SecureRandom.alphanumeric(16) if token.blank?
last_id = @database.insert("messages", @attributes.except(:id))
@attributes["id"] = last_id
@database.statistics.increment_all(timestamp, scope)
Statistic.global.increment!(:total_messages)
Statistic.global.increment!("total_#{scope}".to_sym)
add_to_message_queue if queue
end
def mail
# This version of mail is only used for accessing the bodies.
@mail ||= raw_message? ? Mail.new(raw_message) : nil
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/provisioner.rb | lib/postal/message_db/provisioner.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Provisioner
def initialize(database)
@database = database
end
#
# Provisions a new database
#
def provision
drop
create
migrate(silent: true)
end
#
# Migrate this database
#
def migrate(start_from: @database.schema_version, silent: false)
Postal::MessageDB::Migration.run(@database, start_from: start_from, silent: silent)
end
#
# Does a database already exist?
#
def exists?
!!@database.query("SELECT schema_name FROM `information_schema`.`schemata` WHERE schema_name = '#{@database.database_name}'").first
end
#
# Creates a new empty database
#
def create
@database.query("CREATE DATABASE `#{@database.database_name}` CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;")
true
rescue Mysql2::Error => e
e.message =~ /database exists/ ? false : raise
end
#
# Drops the whole message database
#
def drop
@database.query("DROP DATABASE `#{@database.database_name}`;")
true
rescue Mysql2::Error => e
e.message =~ /doesn't exist/ ? false : raise
end
#
# Create a new table
#
def create_table(table_name, options)
@database.query(create_table_query(table_name, options))
end
#
# Drop a table
#
def drop_table(table_name)
@database.query("DROP TABLE `#{@database.database_name}`.`#{table_name}`")
end
#
# Clean the database. This really only useful in development & testing
# environment and can be quite dangerous in production.
#
def clean
%w[clicks deliveries links live_stats loads messages
raw_message_sizes spam_checks stats_daily stats_hourly
stats_monthly stats_yearly suppressions webhook_requests].each do |table|
@database.query("TRUNCATE `#{@database.database_name}`.`#{table}`")
end
end
#
# Creates a new empty raw message table for the given date. Returns nothing.
#
def create_raw_table(table)
@database.query(create_table_query(table, columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
data: "longblob DEFAULT NULL",
next: "int(11) DEFAULT NULL"
}))
@database.query("INSERT INTO `#{@database.database_name}`.`raw_message_sizes` (table_name, size) VALUES ('#{table}', 0)")
rescue Mysql2::Error => e
# Don't worry if the table already exists, another thread has already run this code.
raise unless e.message =~ /already exists/
end
#
# Return a list of raw message tables that are older than the given date
#
def raw_tables(max_age = 30)
earliest_date = max_age ? Time.now.utc.to_date - max_age : nil
[].tap do |tables|
@database.query("SHOW TABLES FROM `#{@database.database_name}` LIKE 'raw-%'").each do |tbl|
tbl_name = tbl.to_a.first.last
date = Date.parse(tbl_name.gsub(/\Araw-/, ""))
if earliest_date.nil? || date < earliest_date
tables << tbl_name
end
end
end.sort
end
#
# Tidy all messages
#
def remove_raw_tables_older_than(max_age = 30)
raw_tables(max_age).each do |table|
remove_raw_table(table)
end
end
#
# Remove a raw message table
#
def remove_raw_table(table)
@database.query("UPDATE `#{@database.database_name}`.`messages` SET raw_table = NULL, raw_headers_id = NULL, raw_body_id = NULL, size = NULL WHERE raw_table = '#{table}'")
@database.query("DELETE FROM `#{@database.database_name}`.`raw_message_sizes` WHERE table_name = '#{table}'")
drop_table(table)
end
#
# Remove messages from the messages table that are too old to retain
#
def remove_messages(max_age = 60)
time = (Time.now.utc.to_date - max_age.days).to_time.end_of_day
return unless newest_message_to_remove = @database.select(:messages, where: { timestamp: { less_than_or_equal_to: time.to_f } }, limit: 1, order: :id, direction: "DESC", fields: [:id]).first
id = newest_message_to_remove["id"]
@database.query("DELETE FROM `#{@database.database_name}`.`clicks` WHERE `message_id` <= #{id}")
@database.query("DELETE FROM `#{@database.database_name}`.`loads` WHERE `message_id` <= #{id}")
@database.query("DELETE FROM `#{@database.database_name}`.`deliveries` WHERE `message_id` <= #{id}")
@database.query("DELETE FROM `#{@database.database_name}`.`spam_checks` WHERE `message_id` <= #{id}")
@database.query("DELETE FROM `#{@database.database_name}`.`messages` WHERE `id` <= #{id}")
end
#
# Remove raw message tables in order order until size is under the given size (given in MB)
#
def remove_raw_tables_until_less_than_size(size)
tables = raw_tables(nil)
tables_removed = []
until @database.total_size <= size
table = tables.shift
tables_removed << table
remove_raw_table(table)
end
tables_removed
end
private
#
# Build a query to load a table
#
def create_table_query(table_name, options)
String.new.tap do |s|
s << "CREATE TABLE `#{@database.database_name}`.`#{table_name}` ("
s << options[:columns].map do |column_name, column_options|
"`#{column_name}` #{column_options}"
end.join(", ")
if options[:indexes]
s << ", "
s << options[:indexes].map do |index_name, index_options|
"KEY `#{index_name}` (#{index_options}) USING BTREE"
end.join(", ")
end
if options[:unique_indexes]
s << ", "
s << options[:unique_indexes].map do |index_name, index_options|
"UNIQUE KEY `#{index_name}` (#{index_options})"
end.join(", ")
end
if options[:primary_key]
s << ", PRIMARY KEY (#{options[:primary_key]})"
else
s << ", PRIMARY KEY (`id`)"
end
s << ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;"
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/delivery.rb | lib/postal/message_db/delivery.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Delivery
def self.create(message, attributes = {})
attributes = message.database.stringify_keys(attributes)
attributes = attributes.merge("message_id" => message.id, "timestamp" => Time.now.to_f)
# Ensure that output and details don't overflow their columns. We don't need
# these values to store more than 250 characters.
attributes["output"] = attributes["output"][0, 250] if attributes["output"]
attributes["details"] = attributes["details"][0, 250] if attributes["details"]
id = message.database.insert("deliveries", attributes)
delivery = Delivery.new(message, attributes.merge("id" => id))
delivery.update_statistics
delivery.send_webhooks
delivery
end
def initialize(message, attributes)
@message = message
@attributes = attributes.stringify_keys
end
def method_missing(name, value = nil, &block)
return unless @attributes.key?(name.to_s)
@attributes[name.to_s]
end
def respond_to_missing?(name, include_private = false)
@attributes.key?(name.to_s)
end
def timestamp
@timestamp ||= @attributes["timestamp"] ? Time.zone.at(@attributes["timestamp"]) : nil
end
def update_statistics
if status == "Held"
@message.database.statistics.increment_all(timestamp, "held")
end
return unless status == "Bounced" || status == "HardFail"
@message.database.statistics.increment_all(timestamp, "bounces")
end
def send_webhooks
return unless webhook_event
WebhookRequest.trigger(@message.database.server_id, webhook_event, webhook_hash)
end
def webhook_hash
{
message: @message.webhook_hash,
status: status,
details: details,
output: output.to_s.dup.force_encoding("UTF-8").scrub.truncate(512),
sent_with_ssl: sent_with_ssl,
timestamp: @attributes["timestamp"],
time: time
}
end
# rubocop:disable Style/HashLikeCase
def webhook_event
@webhook_event ||= case status
when "Sent" then "MessageSent"
when "SoftFail" then "MessageDelayed"
when "HardFail" then "MessageDeliveryFailed"
when "Held" then "MessageHeld"
end
end
# rubocop:enable Style/HashLikeCase
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/live_stats.rb | lib/postal/message_db/live_stats.rb | # frozen_string_literal: true
module Postal
module MessageDB
class LiveStats
def initialize(database)
@database = database
end
#
# Increment the live stats by one for the current minute
#
def increment(type)
time = Time.now.utc
type = @database.escape(type.to_s)
sql_query = "INSERT INTO `#{@database.database_name}`.`live_stats` (type, minute, timestamp, count)"
sql_query << " VALUES (#{type}, #{time.min}, #{time.to_f}, 1)"
sql_query << " ON DUPLICATE KEY UPDATE count = if(timestamp < #{time.to_f - 1800}, 1, count + 1), timestamp = #{time.to_f}"
@database.query(sql_query)
end
#
# Return the total number of messages for the last 60 minutes
#
def total(minutes, options = {})
if minutes > 60
raise Postal::Error, "Live stats can only return data for the last 60 minutes."
end
options[:types] ||= [:incoming, :outgoing]
raise Postal::Error, "You must provide at least one type to return" if options[:types].empty?
time = minutes.minutes.ago.beginning_of_minute.utc.to_f
types = options[:types].map { |t| @database.escape(t.to_s) }.join(", ")
result = @database.query("SELECT SUM(count) as count FROM `#{@database.database_name}`.`live_stats` WHERE `type` IN (#{types}) AND timestamp > #{time}").first
result["count"] || 0
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migration.rb | lib/postal/message_db/migration.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Migration
def initialize(database)
@database = database
end
def up
end
def self.run(database, start_from: database.schema_version, silent: false)
files = Dir[Rails.root.join("lib", "postal", "message_db", "migrations", "*.rb")]
files = files.map do |f|
id, name = f.split("/").last.split("_", 2)
[id.to_i, name]
end.sort_by(&:first)
latest_version = files.last.first
if latest_version <= start_from
puts "Nothing to do" unless silent
return false
end
unless silent
puts "\e[32mMigrating #{database.database_name} from version #{start_from} => #{files.last.first}\e[0m"
end
files.each do |version, file|
klass_name = file.gsub(/\.rb\z/, "").camelize
next if start_from >= version
puts "\e[45m++ Migrating #{klass_name} (#{version})\e[0m" unless silent
require "postal/message_db/migrations/#{version.to_s.rjust(2, '0')}_#{file}"
klass = Postal::MessageDB::Migrations.const_get(klass_name)
instance = klass.new(database)
instance.up
database.insert(:migrations, version: version)
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/click.rb | lib/postal/message_db/click.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Click
def initialize(attributes, link)
@url = link["url"]
@ip_address = attributes["ip_address"]
@user_agent = attributes["user_agent"]
@timestamp = Time.zone.at(attributes["timestamp"])
end
attr_reader :ip_address
attr_reader :user_agent
attr_reader :timestamp
attr_reader :url
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/database.rb | lib/postal/message_db/database.rb | # frozen_string_literal: true
module Postal
module MessageDB
class Database
class << self
def connection_pool
@connection_pool ||= ConnectionPool.new
end
end
def initialize(organization_id, server_id, database_name: nil)
@organization_id = organization_id
@server_id = server_id
@database_name = database_name
end
attr_reader :organization_id
attr_reader :server_id
#
# Return the server
#
def server
@server ||= Server.find_by_id(@server_id)
end
#
# Return the current schema version
#
def schema_version
@schema_version ||= begin
last_migration = select(:migrations, order: :version, direction: "DESC", limit: 1).first
last_migration ? last_migration["version"] : 0
rescue Mysql2::Error => e
e.message =~ /doesn't exist/ ? 0 : raise
end
end
#
# Return a single message. Accepts an ID or an array of conditions
#
def message(*args)
Message.find_one(self, *args)
end
#
# Return an array or count of messages.
#
def messages(*args)
Message.find(self, *args)
end
def messages_with_pagination(*args)
Message.find_with_pagination(self, *args)
end
#
# Create a new message with the given attributes. This won't be saved to the database
# until it has been 'save'd.
#
def new_message(attributes = {})
Message.new(self, attributes)
end
#
# Return the total size of all stored messages
#
def total_size
query("SELECT SUM(size) AS size FROM `#{database_name}`.`raw_message_sizes`").first["size"] || 0
end
#
# Return the live stats instance
#
def live_stats
@live_stats ||= LiveStats.new(self)
end
#
# Return the statistics instance
#
def statistics
@statistics ||= Statistics.new(self)
end
#
# Return the provisioner instance
#
def provisioner
@provisioner ||= Provisioner.new(self)
end
#
# Return the provisioner instance
#
def suppression_list
@suppression_list ||= SuppressionList.new(self)
end
#
# Return the provisioner instance
#
def webhooks
@webhooks ||= Webhooks.new(self)
end
#
# Return the name for a raw message table for a given date
#
def raw_table_name_for_date(date)
date.strftime("raw-%Y-%m-%d")
end
#
# Insert a new raw message into a table (creating it if needed)
#
def insert_raw_message(data, date = Time.now.utc.to_date)
table_name = raw_table_name_for_date(date)
begin
headers, body = data.split(/\r?\n\r?\n/, 2)
headers_id = insert(table_name, data: headers)
body_id = insert(table_name, data: body)
rescue Mysql2::Error => e
raise unless e.message =~ /doesn't exist/
provisioner.create_raw_table(table_name)
retry
end
[table_name, headers_id, body_id]
end
#
# Selects entries from the database. Accepts a number of options which can be used
# to manipulate the results.
#
# :where => A hash containing the query
# :order => The name of a field to order by
# :direction => The order that should be applied to ordering (ASC or DESC)
# :fields => An array of fields to select
# :limit => Limit the number of results
# :page => Which page number to return
# :per_page => The number of items per page (defaults to 30)
# :count => Return a count of the results instead of the actual data
#
def select(table, options = {})
sql_query = String.new("SELECT")
if options[:count]
sql_query << " COUNT(id) AS count"
elsif options[:fields]
sql_query << (" " + options[:fields].map { |f| "`#{f}`" }.join(", "))
else
sql_query << " *"
end
sql_query << " FROM `#{database_name}`.`#{table}`"
if options[:where].present?
sql_query << (" " + build_where_string(options[:where], " AND "))
end
if options[:order]
direction = (options[:direction] || "ASC").upcase
raise Postal::Error, "Invalid direction #{options[:direction]}" unless %w[ASC DESC].include?(direction)
sql_query << " ORDER BY `#{options[:order]}` #{direction}"
end
if options[:limit]
sql_query << " LIMIT #{options[:limit]}"
end
if options[:offset]
sql_query << " OFFSET #{options[:offset]}"
end
result = query(sql_query)
if options[:count]
result.first["count"]
else
result.to_a
end
end
#
# A paginated version of select
#
def select_with_pagination(table, page, options = {})
page = page.to_i
page = 1 if page <= 0
per_page = options.delete(:per_page) || 30
offset = (page - 1) * per_page
result = {}
result[:total] = select(table, options.merge(count: true))
result[:records] = select(table, options.merge(limit: per_page, offset: offset))
result[:per_page] = per_page
result[:total_pages], remainder = result[:total].divmod(per_page)
result[:total_pages] += 1 if remainder.positive?
result[:page] = page
result
end
#
# Updates a record in the database. Accepts a table name, the attributes to update
# plus some options which are shown below:
#
# :where => The condition to apply to the query
#
# Will return the total number of affected rows.
#
def update(table, attributes, options = {})
sql_query = "UPDATE `#{database_name}`.`#{table}` SET"
sql_query << " #{hash_to_sql(attributes)}"
if options[:where]
sql_query << (" " + build_where_string(options[:where]))
end
with_mysql do |mysql|
query_on_connection(mysql, sql_query)
mysql.affected_rows
end
end
#
# Insert a record into a given table. A hash of attributes is also provided.
# Will return the ID of the new item.
#
def insert(table, attributes)
sql_query = "INSERT INTO `#{database_name}`.`#{table}`"
sql_query << (" (" + attributes.keys.map { |k| "`#{k}`" }.join(", ") + ")")
sql_query << (" VALUES (" + attributes.values.map { |v| escape(v) }.join(", ") + ")")
with_mysql do |mysql|
query_on_connection(mysql, sql_query)
mysql.last_id
end
end
#
# Insert multiple rows at the same time in the same query
#
def insert_multi(table, keys, values)
if values.empty?
nil
else
sql_query = "INSERT INTO `#{database_name}`.`#{table}`"
sql_query << (" (" + keys.map { |k| "`#{k}`" }.join(", ") + ")")
sql_query << " VALUES "
sql_query << values.map { |v| "(" + v.map { |r| escape(r) }.join(", ") + ")" }.join(", ")
query(sql_query)
end
end
#
# Deletes a in the database. Accepts a table name, and some options which
# are shown below:
#
# :where => The condition to apply to the query
#
# Will return the total number of affected rows.
#
def delete(table, options = {})
sql_query = "DELETE FROM `#{database_name}`.`#{table}`"
sql_query << (" " + build_where_string(options[:where], " AND "))
with_mysql do |mysql|
query_on_connection(mysql, sql_query)
mysql.affected_rows
end
end
#
# Return the correct database name
#
def database_name
@database_name ||= "#{Postal::Config.message_db.database_name_prefix}-server-#{@server_id}"
end
#
# Run a query, log it and return the result
#
class ResultForExplainPrinter
attr_reader :columns
attr_reader :rows
def initialize(result)
if result.first
@columns = result.first.keys
@rows = result.map { |row| row.map(&:last) }
else
@columns = []
@rows = []
end
end
end
def stringify_keys(hash)
hash.transform_keys(&:to_s)
end
def escape(value)
with_mysql do |mysql|
if value == true
"1"
elsif value == false
"0"
elsif value.nil? || value.to_s.empty?
"NULL"
else
"'" + mysql.escape(value.to_s) + "'"
end
end
end
def query(query)
with_mysql do |mysql|
query_on_connection(mysql, query)
end
end
private
def query_on_connection(connection, query)
start_time = Time.now.to_f
result = connection.query(query, cast_booleans: true)
time = Time.now.to_f - start_time
logger.debug " \e[4;34mMessageDB Query (#{time.round(2)}s) \e[0m \e[33m#{query}\e[0m"
if time > 0.05 && query =~ /\A(SELECT|UPDATE|DELETE) /
id = SecureRandom.alphanumeric(8)
explain_result = ResultForExplainPrinter.new(connection.query("EXPLAIN #{query}"))
logger.info " [#{id}] EXPLAIN #{query}"
ActiveRecord::ConnectionAdapters::MySQL::ExplainPrettyPrinter.new.pp(explain_result, time).split("\n").each do |line|
logger.info " [#{id}] " + line
end
end
result
end
def logger
defined?(Rails) ? Rails.logger : Logger.new($stdout)
end
def with_mysql(&block)
self.class.connection_pool.use(&block)
end
def build_where_string(attributes, joiner = ", ")
"WHERE #{hash_to_sql(attributes, joiner)}"
end
def hash_to_sql(hash, joiner = ", ")
hash.map do |key, value|
if value.is_a?(Array) && value.all? { |v| v.is_a?(Integer) }
"`#{key}` IN (#{value.join(', ')})"
elsif value.is_a?(Array)
escaped_values = value.map { |v| escape(v) }.join(", ")
"`#{key}` IN (#{escaped_values})"
elsif value.is_a?(Hash)
sql = []
value.each do |operator, inner_value|
case operator
when :less_than
sql << "`#{key}` < #{escape(inner_value)}"
when :greater_than
sql << "`#{key}` > #{escape(inner_value)}"
when :less_than_or_equal_to
sql << "`#{key}` <= #{escape(inner_value)}"
when :greater_than_or_equal_to
sql << "`#{key}` >= #{escape(inner_value)}"
end
end
sql.empty? ? "1=1" : sql.join(joiner)
else
"`#{key}` = #{escape(value)}"
end
end.join(joiner)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/11_add_time_to_deliveries.rb | lib/postal/message_db/migrations/11_add_time_to_deliveries.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class AddTimeToDeliveries < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`deliveries` ADD COLUMN `time` decimal(8,2)")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/08_create_stats.rb | lib/postal/message_db/migrations/08_create_stats.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateStats < Postal::MessageDB::Migration
def up
[:hourly, :daily, :monthly, :yearly].each do |table_name|
@database.provisioner.create_table("stats_#{table_name}",
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
time: "int(11) DEFAULT NULL",
incoming: "bigint DEFAULT NULL",
outgoing: "bigint DEFAULT NULL",
spam: "bigint DEFAULT NULL",
bounces: "bigint DEFAULT NULL",
held: "bigint DEFAULT NULL"
},
unique_indexes: {
on_time: "`time`"
})
end
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/09_create_links.rb | lib/postal/message_db/migrations/09_create_links.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateLinks < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:links,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
message_id: "int(11) DEFAULT NULL",
token: "varchar(255) DEFAULT NULL",
hash: "varchar(255) DEFAULT NULL",
url: "varchar(255) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL"
},
indexes: {
on_message_id: "`message_id`",
on_token: "`token`(8)"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/16_add_url_and_hook_to_webhooks.rb | lib/postal/message_db/migrations/16_add_url_and_hook_to_webhooks.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class AddUrlAndHookToWebhooks < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`webhook_requests` ADD COLUMN `url` varchar(255)")
@database.query("ALTER TABLE `#{@database.database_name}`.`webhook_requests` ADD COLUMN `webhook_id` int(11)")
@database.query("ALTER TABLE `#{@database.database_name}`.`webhook_requests` ADD INDEX `on_webhook_id` (`webhook_id`) USING BTREE")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/01_create_migrations.rb | lib/postal/message_db/migrations/01_create_migrations.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateMigrations < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:migrations,
columns: {
version: "int(11) NOT NULL"
},
primary_key: "`version`")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/14_create_suppressions.rb | lib/postal/message_db/migrations/14_create_suppressions.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateSuppressions < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:suppressions,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
type: "varchar(255) DEFAULT NULL",
address: "varchar(255) DEFAULT NULL",
reason: "varchar(255) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL",
keep_until: "decimal(18,6) DEFAULT NULL"
},
indexes: {
on_address: "`address`(6)",
on_keep_until: "`keep_until`"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/06_create_clicks.rb | lib/postal/message_db/migrations/06_create_clicks.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateClicks < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:clicks,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
message_id: "int(11) DEFAULT NULL",
link_id: "int(11) DEFAULT NULL",
ip_address: "varchar(255) DEFAULT NULL",
country: "varchar(255) DEFAULT NULL",
city: "varchar(255) DEFAULT NULL",
user_agent: "varchar(255) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL"
},
indexes: {
on_message_id: "`message_id`",
on_link_id: "`link_id`"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/04_create_live_stats.rb | lib/postal/message_db/migrations/04_create_live_stats.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateLiveStats < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:live_stats,
columns: {
type: "varchar(20) NOT NULL",
minute: "int(11) NOT NULL",
count: "int(11) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL"
},
primary_key: "`minute`, `type`(8)")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/15_create_webhook_requests.rb | lib/postal/message_db/migrations/15_create_webhook_requests.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateWebhookRequests < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:webhook_requests,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
uuid: "varchar(255) DEFAULT NULL",
event: "varchar(255) DEFAULT NULL",
attempt: "int(11) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL",
status_code: "int(1) DEFAULT NULL",
body: "text DEFAULT NULL",
payload: "text DEFAULT NULL",
will_retry: "tinyint DEFAULT NULL"
},
indexes: {
on_uuid: "`uuid`(8)",
on_event: "`event`(8)",
on_timestamp: "`timestamp`"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/12_add_hold_expiry.rb | lib/postal/message_db/migrations/12_add_hold_expiry.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class AddHoldExpiry < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` ADD COLUMN `hold_expiry` decimal(18,6)")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/02_create_messages.rb | lib/postal/message_db/migrations/02_create_messages.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateMessages < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:messages,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
token: "varchar(255) DEFAULT NULL",
scope: "varchar(10) DEFAULT NULL",
rcpt_to: "varchar(255) DEFAULT NULL",
mail_from: "varchar(255) DEFAULT NULL",
subject: "varchar(255) DEFAULT NULL",
message_id: "varchar(255) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL",
route_id: "int(11) DEFAULT NULL",
domain_id: "int(11) DEFAULT NULL",
credential_id: "int(11) DEFAULT NULL",
status: "varchar(255) DEFAULT NULL",
held: "tinyint(1) DEFAULT 0",
size: "varchar(255) DEFAULT NULL",
last_delivery_attempt: "decimal(18,6) DEFAULT NULL",
raw_table: "varchar(255) DEFAULT NULL",
raw_body_id: "int(11) DEFAULT NULL",
raw_headers_id: "int(11) DEFAULT NULL",
inspected: "tinyint(1) DEFAULT 0",
spam: "tinyint(1) DEFAULT 0",
spam_score: "decimal(8,2) DEFAULT 0",
threat: "tinyint(1) DEFAULT 0",
threat_details: "varchar(255) DEFAULT NULL",
bounce: "tinyint(1) DEFAULT 0",
bounce_for_id: "int(11) DEFAULT 0",
tag: "varchar(255) DEFAULT NULL",
loaded: "decimal(18,6) DEFAULT NULL",
clicked: "decimal(18,6) DEFAULT NULL",
received_with_ssl: "tinyint(1) DEFAULT NULL"
},
indexes: {
on_message_id: "`message_id`(8)",
on_token: "`token`(6)",
on_bounce_for_id: "`bounce_for_id`",
on_held: "`held`",
on_scope_and_status: "`scope`(1), `spam`, `status`(6), `timestamp`",
on_scope_and_tag: "`scope`(1), `spam`, `tag`(8), `timestamp`",
on_scope_and_spam: "`scope`(1), `spam`, `timestamp`",
on_scope_and_thr_status: "`scope`(1), `threat`, `status`(6), `timestamp`",
on_scope_and_threat: "`scope`(1), `threat`, `timestamp`",
on_rcpt_to: "`rcpt_to`(12), `timestamp`",
on_mail_from: "`mail_from`(12), `timestamp`",
on_raw_table: "`raw_table`(14)"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/19_convert_database_to_utf8mb4.rb | lib/postal/message_db/migrations/19_convert_database_to_utf8mb4.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class ConvertDatabaseToUtf8mb4 < Postal::MessageDB::Migration
def up
@database.query("ALTER DATABASE `#{@database.database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`clicks` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`deliveries` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`links` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`live_stats` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`loads` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`migrations` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`raw_message_sizes` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`spam_checks` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`stats_daily` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`stats_hourly` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`stats_monthly` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`stats_yearly` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`suppressions` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
@database.query("ALTER TABLE `#{@database.database_name}`.`webhook_requests` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/13_add_index_to_message_status.rb | lib/postal/message_db/migrations/13_add_index_to_message_status.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class AddIndexToMessageStatus < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` ADD INDEX `on_status` (`status`(8)) USING BTREE")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/03_create_deliveries.rb | lib/postal/message_db/migrations/03_create_deliveries.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateDeliveries < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:deliveries,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
message_id: "int(11) DEFAULT NULL",
status: "varchar(255) DEFAULT NULL",
code: "int(11) DEFAULT NULL",
output: "varchar(512) DEFAULT NULL",
details: "varchar(512) DEFAULT NULL",
sent_with_ssl: "tinyint(1) DEFAULT 0",
log_id: "varchar(100) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL"
},
indexes: {
on_message_id: "`message_id`"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/17_add_replaced_link_count_to_messages.rb | lib/postal/message_db/migrations/17_add_replaced_link_count_to_messages.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class AddReplacedLinkCountToMessages < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` ADD COLUMN `tracked_links` int(11) DEFAULT 0")
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` ADD COLUMN `tracked_images` int(11) DEFAULT 0")
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` ADD COLUMN `parsed` tinyint DEFAULT 0")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/10_create_spam_checks.rb | lib/postal/message_db/migrations/10_create_spam_checks.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateSpamChecks < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:spam_checks,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
message_id: "int(11) DEFAULT NULL",
score: "decimal(8,2) DEFAULT NULL",
code: "varchar(255) DEFAULT NULL",
description: "varchar(255) DEFAULT NULL"
},
indexes: {
on_message_id: "`message_id`",
on_code: "`code`(8)"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/20_increase_links_url_size.rb | lib/postal/message_db/migrations/20_increase_links_url_size.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class IncreaseLinksUrlSize < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`links` MODIFY `url` TEXT")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/18_add_endpoints_to_messages.rb | lib/postal/message_db/migrations/18_add_endpoints_to_messages.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class AddEndpointsToMessages < Postal::MessageDB::Migration
def up
@database.query("ALTER TABLE `#{@database.database_name}`.`messages` ADD COLUMN `endpoint_id` int(11), ADD COLUMN `endpoint_type` varchar(255)")
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/05_create_raw_message_sizes.rb | lib/postal/message_db/migrations/05_create_raw_message_sizes.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateRawMessageSizes < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:raw_message_sizes,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
table_name: "varchar(255) DEFAULT NULL",
size: "bigint DEFAULT NULL"
},
indexes: {
on_table_name: "`table_name`(14)"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_db/migrations/07_create_loads.rb | lib/postal/message_db/migrations/07_create_loads.rb | # frozen_string_literal: true
module Postal
module MessageDB
module Migrations
class CreateLoads < Postal::MessageDB::Migration
def up
@database.provisioner.create_table(:loads,
columns: {
id: "int(11) NOT NULL AUTO_INCREMENT",
message_id: "int(11) DEFAULT NULL",
ip_address: "varchar(255) DEFAULT NULL",
country: "varchar(255) DEFAULT NULL",
city: "varchar(255) DEFAULT NULL",
user_agent: "varchar(255) DEFAULT NULL",
timestamp: "decimal(18,6) DEFAULT NULL"
},
indexes: {
on_message_id: "`message_id`"
})
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_inspectors/clamav.rb | lib/postal/message_inspectors/clamav.rb | # frozen_string_literal: true
module Postal
module MessageInspectors
class Clamav < MessageInspector
def inspect_message(inspection)
raw_message = inspection.message.raw_message
data = nil
Timeout.timeout(10) do
tcp_socket = TCPSocket.new(@config.host, @config.port)
tcp_socket.write("zINSTREAM\0")
tcp_socket.write([raw_message.bytesize].pack("N"))
tcp_socket.write(raw_message)
tcp_socket.write([0].pack("N"))
tcp_socket.close_write
data = tcp_socket.read
end
if data && data =~ /\Astream:\s+(.*?)[\s\0]+?/
if ::Regexp.last_match(1).upcase == "OK"
inspection.threat = false
inspection.threat_message = "No threats found"
else
inspection.threat = true
inspection.threat_message = ::Regexp.last_match(1)
end
else
inspection.threat = false
inspection.threat_message = "Could not scan message"
end
rescue Timeout::Error
inspection.threat = false
inspection.threat_message = "Timed out scanning for threats"
rescue StandardError => e
logger.error "Error talking to clamav: #{e.class} (#{e.message})"
logger.error e.backtrace[0, 5]
inspection.threat = false
inspection.threat_message = "Error when scanning for threats"
ensure
begin
tcp_socket.close
rescue StandardError
nil
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_inspectors/spam_assassin.rb | lib/postal/message_inspectors/spam_assassin.rb | # frozen_string_literal: true
module Postal
module MessageInspectors
class SpamAssassin < MessageInspector
EXCLUSIONS = {
outgoing: ["NO_RECEIVED", "NO_RELAYS", "ALL_TRUSTED", "FREEMAIL_FORGED_REPLYTO", "RDNS_DYNAMIC", "CK_HELO_GENERIC", /^SPF_/, /^HELO_/, /DKIM_/, /^RCVD_IN_/],
incoming: []
}.freeze
def inspect_message(inspection)
data = nil
raw_message = inspection.message.raw_message
Timeout.timeout(15) do
tcp_socket = TCPSocket.new(@config.host, @config.port)
tcp_socket.write("REPORT SPAMC/1.2\r\n")
tcp_socket.write("Content-length: #{raw_message.bytesize}\r\n")
tcp_socket.write("\r\n")
tcp_socket.write(raw_message)
tcp_socket.close_write
data = tcp_socket.read
end
spam_checks = []
total = 0.0
rules = data ? data.split(/^---(.*)\r?\n/).last.split(/\r?\n/) : []
while line = rules.shift
if line =~ /\A([- ]?[\d.]+)\s+(\w+)\s+(.*)/
total += ::Regexp.last_match(1).to_f
spam_checks << SpamCheck.new(::Regexp.last_match(2), ::Regexp.last_match(1).to_f, ::Regexp.last_match(3))
else
spam_checks.last.description << (" " + line.strip)
end
end
checks = spam_checks.reject { |s| EXCLUSIONS[inspection.scope].include?(s.code) }
checks.each do |check|
inspection.spam_checks << check
end
rescue Timeout::Error
inspection.spam_checks << SpamCheck.new("TIMEOUT", 0, "Timed out when scanning for spam")
rescue StandardError => e
logger.error "Error talking to spamd: #{e.class} (#{e.message})"
logger.error e.backtrace[0, 5]
inspection.spam_checks << SpamCheck.new("ERROR", 0, "Error when scanning for spam")
ensure
begin
tcp_socket.close
rescue StandardError
nil
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/lib/postal/message_inspectors/rspamd.rb | lib/postal/message_inspectors/rspamd.rb | # frozen_string_literal: true
require "net/http"
module Postal
module MessageInspectors
class Rspamd < MessageInspector
class Error < StandardError
end
def inspect_message(inspection)
response = request(inspection.message, inspection.scope)
response = JSON.parse(response.body)
return unless response["symbols"].is_a?(Hash)
response["symbols"].each_value do |symbol|
next if symbol["description"].blank?
inspection.spam_checks << SpamCheck.new(symbol["name"], symbol["score"], symbol["description"])
end
rescue Error => e
inspection.spam_checks << SpamCheck.new("ERROR", 0, e.message)
end
private
def request(message, scope)
http = Net::HTTP.new(@config.host, @config.port)
http.use_ssl = true if @config.ssl
http.read_timeout = 10
http.open_timeout = 10
raw_message = message.raw_message
request = Net::HTTP::Post.new("/checkv2")
request.body = raw_message
request["Content-Length"] = raw_message.bytesize.to_s
request["Password"] = @config.password if @config.password
request["Flags"] = @config.flags if @config.flags
request["User-Agent"] = "Postal"
request["Deliver-To"] = message.rcpt_to
request["From"] = message.mail_from
request["Rcpt"] = message.rcpt_to
request["Queue-Id"] = message.token
if scope == :outgoing
request["User"] = ""
# We don't actually know the IP but an empty input here will
# still trigger rspamd to treat this as an outbound email
# and disable certain checks.
# https://rspamd.com/doc/tutorials/scanning_outbound.html
request["Ip"] = ""
end
response = nil
begin
response = http.request(request)
rescue StandardError => e
logger.error "Error talking to rspamd: #{e.class} (#{e.message})"
logger.error e.backtrace[0, 5]
raise Error, "Error when scanning with rspamd (#{e.class})"
end
unless response.is_a?(Net::HTTPOK)
logger.info "Got #{response.code} status from rspamd, wanted 200"
raise Error, "Error when scanning with rspamd (got #{response.code})"
end
response
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/application.rb | config/application.rb | # frozen_string_literal: true
require_relative "boot"
require "rails"
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
gem_groups = Rails.groups
gem_groups << :oidc if Postal::Config.oidc.enabled?
Bundler.require(*gem_groups)
module Postal
class Application < Rails::Application
config.load_defaults 7.0
# Disable most generators
config.generators do |g|
g.orm :active_record
g.test_framework false
g.stylesheets false
g.javascripts false
g.helper false
end
# Include from lib
config.eager_load_paths << Rails.root.join("lib")
# Disable field_with_errors
config.action_view.field_error_proc = proc { |t, _| t }
# Load the tracking server middleware
require "tracking_middleware"
config.middleware.insert_before ActionDispatch::HostAuthorization, TrackingMiddleware
config.hosts << Postal::Config.postal.web_hostname
unless Postal::Config.logging.rails_log_enabled?
config.logger = Logger.new("/dev/null")
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/environment.rb | config/environment.rb | # frozen_string_literal: true
# Load the Rails application.
require_relative "application"
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/puma.rb | config/puma.rb | # frozen_string_literal: true
require_relative "../lib/postal/config"
threads_count = Postal::Config.web_server.max_threads
threads threads_count, threads_count
bind_address = ENV.fetch("BIND_ADDRESS", Postal::Config.web_server.default_bind_address)
bind_port = ENV.fetch("PORT", Postal::Config.web_server.default_port)
bind "tcp://#{bind_address}:#{bind_port}"
environment Postal::Config.rails.environment || "development"
prune_bundler
quiet false
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/routes.rb | config/routes.rb | # frozen_string_literal: true
Rails.application.routes.draw do
# Legacy API Routes
match "/api/v1/send/message" => "legacy_api/send#message", via: [:get, :post, :patch, :put]
match "/api/v1/send/raw" => "legacy_api/send#raw", via: [:get, :post, :patch, :put]
match "/api/v1/messages/message" => "legacy_api/messages#message", via: [:get, :post, :patch, :put]
match "/api/v1/messages/deliveries" => "legacy_api/messages#deliveries", via: [:get, :post, :patch, :put]
scope "org/:org_permalink", as: "organization" do
resources :domains, only: [:index, :new, :create, :destroy] do
match :verify, on: :member, via: [:get, :post]
get :setup, on: :member
post :check, on: :member
end
resources :servers, except: [:index] do
resources :domains, only: [:index, :new, :create, :destroy] do
match :verify, on: :member, via: [:get, :post]
get :setup, on: :member
post :check, on: :member
end
resources :track_domains do
post :toggle_ssl, on: :member
post :check, on: :member
end
resources :credentials
resources :routes
resources :http_endpoints
resources :smtp_endpoints
resources :address_endpoints
resources :ip_pool_rules
resources :messages do
get :incoming, on: :collection
get :outgoing, on: :collection
get :held, on: :collection
get :activity, on: :member
get :plain, on: :member
get :html, on: :member
get :html_raw, on: :member
get :attachments, on: :member
get :headers, on: :member
get :attachment, on: :member
get :download, on: :member
get :spam_checks, on: :member
post :retry, on: :member
post :cancel_hold, on: :member
get :suppressions, on: :collection
delete :remove_from_queue, on: :member
get :deliveries, on: :member
end
resources :webhooks do
get :history, on: :collection
get "history/:uuid", on: :collection, action: "history_request", as: "history_request"
end
get :limits, on: :member
get :retention, on: :member
get :queue, on: :member
get :spam, on: :member
get :delete, on: :member
get "help/outgoing" => "help#outgoing"
get "help/incoming" => "help#incoming"
get :advanced, on: :member
post :suspend, on: :member
post :unsuspend, on: :member
end
resources :ip_pool_rules
resources :ip_pools, controller: "organization_ip_pools" do
put :assignments, on: :collection
end
root "servers#index"
get "settings" => "organizations#edit"
patch "settings" => "organizations#update"
get "delete" => "organizations#delete"
delete "delete" => "organizations#destroy"
end
resources :organizations, except: [:index]
resources :users
resources :ip_pools do
resources :ip_addresses
end
get "settings" => "user#edit"
patch "settings" => "user#update"
post "persist" => "sessions#persist"
get "login" => "sessions#new"
post "login" => "sessions#create"
delete "logout" => "sessions#destroy"
match "login/reset" => "sessions#begin_password_reset", :via => [:get, :post]
match "login/reset/:token" => "sessions#finish_password_reset", :via => [:get, :post]
if Postal::Config.oidc.enabled?
get "auth/oidc/callback", to: "sessions#create_from_oidc"
end
get ".well-known/jwks.json" => "well_known#jwks"
get "ip" => "sessions#ip"
root "organizations#index"
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/boot.rb | config/boot.rb | # frozen_string_literal: true
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
require "bundler/setup" # Set up gems listed in the Gemfile.
require_relative "../lib/postal/config"
ENV["RAILS_ENV"] = Postal::Config.rails.environment || "development"
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/content_security_policy.rb | config/initializers/content_security_policy.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Define an application-wide content security policy.
# See the Securing Rails Applications Guide for more information:
# https://guides.rubyonrails.org/security.html#content-security-policy-header
# Rails.application.configure do
# config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
#
# # Generate session nonces for permitted importmap and inline scripts
# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
# config.content_security_policy_nonce_directives = %w(script-src)
#
# # Report violations without enforcing the policy.
# # config.content_security_policy_report_only = true
# end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/filter_parameter_logging.rb | config/initializers/filter_parameter_logging.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Configure parameters to be filtered from the log file. Use this to limit dissemination of
# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported
# notations and behaviors.
Rails.application.config.filter_parameters += [
:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn,
]
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/application_controller_renderer.rb | config/initializers/application_controller_renderer.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/new_framework_defaults_7_0.rb | config/initializers/new_framework_defaults_7_0.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
#
# This file eases your Rails 7.0 framework defaults upgrade.
#
# Uncomment each configuration one by one to switch to the new default.
# Once your application is ready to run with all new defaults, you can remove
# this file and set the `config.load_defaults` to `7.0`.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# https://guides.rubyonrails.org/upgrading_ruby_on_rails.html
# `button_to` view helper will render `<button>` element, regardless of whether
# or not the content is passed as the first argument or as a block.
# Rails.application.config.action_view.button_to_generates_button_tag = true
# `stylesheet_link_tag` view helper will not render the media attribute by default.
# Rails.application.config.action_view.apply_stylesheet_media_default = false
# Change the digest class for the key generators to `OpenSSL::Digest::SHA256`.
# Changing this default means invalidate all encrypted messages generated by
# your application and, all the encrypted cookies. Only change this after you
# rotated all the messages using the key rotator.
#
# See upgrading guide for more information on how to build a rotator.
# https://guides.rubyonrails.org/v7.0/upgrading_ruby_on_rails.html
# Rails.application.config.active_support.key_generator_hash_digest_class = OpenSSL::Digest::SHA256
# Change the digest class for ActiveSupport::Digest.
# Changing this default means that for example Etags change and
# various cache keys leading to cache invalidation.
# Rails.application.config.active_support.hash_digest_class = OpenSSL::Digest::SHA256
# Don't override ActiveSupport::TimeWithZone.name and use the default Ruby
# implementation.
# Rails.application.config.active_support.remove_deprecated_time_with_zone_name = true
# Calls `Rails.application.executor.wrap` around test cases.
# This makes test cases behave closer to an actual request or job.
# Several features that are normally disabled in test, such as Active Record query cache
# and asynchronous queries will then be enabled.
# Rails.application.config.active_support.executor_around_test_case = true
# Set both the `:open_timeout` and `:read_timeout` values for `:smtp` delivery method.
# Rails.application.config.action_mailer.smtp_timeout = 5
# The ActiveStorage video previewer will now use scene change detection to generate
# better preview images (rather than the previous default of using the first frame
# of the video).
# Rails.application.config.active_storage.video_preview_arguments =
# "-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1' -frames:v 1 -f image2"
# Automatically infer `inverse_of` for associations with a scope.
# Rails.application.config.active_record.automatic_scope_inversing = true
# Raise when running tests if fixtures contained foreign key violations
# Rails.application.config.active_record.verify_foreign_keys_for_fixtures = true
# Disable partial inserts.
# This default means that all columns will be referenced in INSERT queries
# regardless of whether they have a default or not.
# Rails.application.config.active_record.partial_inserts = false
# Protect from open redirect attacks in `redirect_back_or_to` and `redirect_to`.
# Rails.application.config.action_controller.raise_on_open_redirects = true
# Change the variant processor for Active Storage.
# Changing this default means updating all places in your code that
# generate variants to use image processing macros and ruby-vips
# operations. See the upgrading guide for detail on the changes required.
# The `:mini_magick` option is not deprecated; it's fine to keep using it.
# Rails.application.config.active_storage.variant_processor = :vips
# Enable parameter wrapping for JSON.
# Previously this was set in an initializer. It's fine to keep using that initializer if you've customized it.
# To disable parameter wrapping entirely, set this config to `false`.
# Rails.application.config.action_controller.wrap_parameters_by_default = true
# Specifies whether generated namespaced UUIDs follow the RFC 4122 standard for namespace IDs provided as a
# `String` to `Digest::UUID.uuid_v3` or `Digest::UUID.uuid_v5` method calls.
#
# See https://guides.rubyonrails.org/configuring.html#config-active-support-use-rfc4122-namespaced-uuids for
# more information.
# Rails.application.config.active_support.use_rfc4122_namespaced_uuids = true
# Change the default headers to disable browsers' flawed legacy XSS protection.
# Rails.application.config.action_dispatch.default_headers = {
# "X-Frame-Options" => "SAMEORIGIN",
# "X-XSS-Protection" => "0",
# "X-Content-Type-Options" => "nosniff",
# "X-Download-Options" => "noopen",
# "X-Permitted-Cross-Domain-Policies" => "none",
# "Referrer-Policy" => "strict-origin-when-cross-origin"
# }
# ** Please read carefully, this must be configured in config/application.rb **
# Change the format of the cache entry.
# Changing this default means that all new cache entries added to the cache
# will have a different format that is not supported by Rails 6.1 applications.
# Only change this value after your application is fully deployed to Rails 7.0
# and you have no plans to rollback.
# When you're ready to change format, add this to `config/application.rb` (NOT this file):
# config.active_support.cache_format_version = 7.0
# Cookie serializer: 2 options
#
# If you're upgrading and haven't set `cookies_serializer` previously, your cookie serializer
# is `:marshal`. The default for new apps is `:json`.
#
# Rails.application.config.action_dispatch.cookies_serializer = :json
#
#
# To migrate an existing application to the `:json` serializer, use the `:hybrid` option.
#
# Rails transparently deserializes existing (Marshal-serialized) cookies on read and
# re-writes them in the JSON format.
#
# It is fine to use `:hybrid` long term; you should do that until you're confident *all* your cookies
# have been converted to JSON. To keep using `:hybrid` long term, move this config to its own
# initializer or to `config/application.rb`.
#
# Rails.application.config.action_dispatch.cookies_serializer = :hybrid
#
#
# If your cookies can't yet be serialized to JSON, keep using `:marshal` for backward-compatibility.
#
# If you have configured the serializer elsewhere, you can remove this section of the file.
#
# See https://guides.rubyonrails.org/action_controller_overview.html#cookies for more information.
# Change the return value of `ActionDispatch::Request#content_type` to the Content-Type header without modification.
# Rails.application.config.action_dispatch.return_only_request_media_type_on_content_type = false
# Active Storage `has_many_attached` relationships will default to replacing the current collection instead of appending to it.
# Thus, to support submitting an empty collection, the `file_field` helper will render an hidden field `include_hidden` by default when `multiple_file_field_include_hidden` is set to `true`.
# See https://guides.rubyonrails.org/configuring.html#config-active-storage-multiple-file-field-include-hidden for more information.
# Rails.application.config.active_storage.multiple_file_field_include_hidden = true
# ** Please read carefully, this must be configured in config/application.rb (NOT this file) **
# Disables the deprecated #to_s override in some Ruby core classes
# See https://guides.rubyonrails.org/configuring.html#config-active-support-disable-to-s-conversion for more information.
# config.active_support.disable_to_s_conversion = true
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/secure_headers.rb | config/initializers/secure_headers.rb | # frozen_string_literal: true
SecureHeaders::Configuration.default do |config|
config.hsts = SecureHeaders::OPT_OUT
config.csp[:default_src] = []
config.csp[:script_src] = ["'self'"]
config.csp[:child_src] = ["'self'"]
config.csp[:connect_src] = ["'self'"]
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/session_store.rb | config/initializers/session_store.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: "_postal_session"
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/_wait_for_migrations.rb | config/initializers/_wait_for_migrations.rb | # frozen_string_literal: true
require "migration_waiter"
MigrationWaiter.wait_if_appropriate
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/logging.rb | config/initializers/logging.rb | # frozen_string_literal: true
begin
def add_exception_to_payload(payload, event)
return unless exception = event.payload[:exception_object]
payload[:exception_class] = exception.class.name
payload[:exception_message] = exception.message
payload[:exception_backtrace] = exception.backtrace[0, 4].join("\n")
end
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
payload = {
event: "request",
transaction: event.transaction_id,
controller: event.payload[:controller],
action: event.payload[:action],
format: event.payload[:format],
method: event.payload[:method],
path: event.payload[:path],
request_id: event.payload[:request].request_id,
ip_address: event.payload[:request].ip,
status: event.payload[:status],
view_runtime: event.payload[:view_runtime],
db_runtime: event.payload[:db_runtime]
}
add_exception_to_payload(payload, event)
string = "#{payload[:method]} #{payload[:path]} (#{payload[:status]})"
if payload[:exception_class]
Postal.logger.error(string, **payload)
else
Postal.logger.info(string, **payload)
end
end
ActiveSupport::Notifications.subscribe "deliver.action_mailer" do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
Postal.logger.info({
event: "send_email",
transaction: event.transaction_id,
message_id: event.payload[:message_id],
subject: event.payload[:subject],
from: event.payload[:from],
to: event.payload[:to].is_a?(Array) ? event.payload[:to].join(", ") : event.payload[:to].to_s
})
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/trusted_proxies.rb | config/initializers/trusted_proxies.rb | # frozen_string_literal: true
Rack::Request.ip_filter = lambda { |ip|
if Postal::Config.postal.trusted_proxies&.any? { |net| net.include?(ip) } ||
ip.match(/\A127\.0\.0\.1\Z|\A::1\Z|\Afd[0-9a-f]{2}:.+|\Alocalhost\Z|\Aunix\Z|\Aunix:/i)
true
else
false
end
}
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/record_key_for_dom.rb | config/initializers/record_key_for_dom.rb | # frozen_string_literal: true
module ActionView
module RecordIdentifier
def dom_id(record, prefix = nil)
if record.new_record?
dom_class(record, prefix || NEW)
else
id = record.respond_to?(:uuid) ? record.uuid : record.id
"#{dom_class(record, prefix)}#{JOIN}#{id}"
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/wrap_parameters.rb | config/initializers/wrap_parameters.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/omniauth.rb | config/initializers/omniauth.rb | # frozen_string_literal: true
config = Postal::Config.oidc
if config.enabled?
client_options = { identifier: config.identifier, secret: config.secret }
client_options[:redirect_uri] = "#{Postal::Config.postal.web_protocol}://#{Postal::Config.postal.web_hostname}/auth/oidc/callback"
unless config.discovery?
client_options[:authorization_endpoint] = config.authorization_endpoint
client_options[:token_endpoint] = config.token_endpoint
client_options[:userinfo_endpoint] = config.userinfo_endpoint
client_options[:jwks_uri] = config.jwks_uri
end
Rails.application.config.middleware.use OmniAuth::Builder do
provider :openid_connect, name: :oidc,
scope: config.scopes.map(&:to_sym),
uid_field: config.uid_field,
issuer: config.issuer,
discovery: config.discovery?,
client_options: client_options
end
OmniAuth.config.on_failure = proc do |env|
SessionsController.action(:oauth_failure).call(env)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/inflections.rb | config/initializers/inflections.rb | # frozen_string_literal: true
# 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 "DKIM"
inflect.acronym "HTTP"
inflect.acronym "OIDC"
inflect.acronym "SMTP"
inflect.acronym "UUID"
inflect.acronym "API"
inflect.acronym "DNS"
inflect.acronym "SSL"
inflect.acronym "MySQL"
inflect.acronym "DB"
inflect.acronym "IP"
inflect.acronym "MQ"
inflect.acronym "MX"
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/smtp.rb | config/initializers/smtp.rb | # frozen_string_literal: true
require "postal/config"
config = Postal::Config.smtp
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
address: config.host,
user_name: config.username,
password: config.password,
port: config.port,
authentication: config.authentication_type&.to_sym,
enable_starttls: config.enable_starttls?,
enable_starttls_auto: config.enable_starttls_auto?,
openssl_verify_mode: config.openssl_verify_mode
}
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/cookies_serializer.rb | config/initializers/cookies_serializer.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/permissions_policy.rb | config/initializers/permissions_policy.rb | # frozen_string_literal: true
# Define an application-wide HTTP permissions policy. For further
# information see https://developers.google.com/web/updates/2018/06/feature-policy
#
# Rails.application.config.permissions_policy do |f|
# f.camera :none
# f.gyroscope :none
# f.microphone :none
# f.usb :none
# f.fullscreen :self
# f.payment :self, "https://secure.example.com"
# end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/assets.rb | config/initializers/assets.rb | # frozen_string_literal: true
# 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 | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/smtp_extensions.rb | config/initializers/smtp_extensions.rb | # frozen_string_literal: true
module Net
class SMTP
attr_accessor :source_address
def secure_socket?
return false unless @socket
@socket.io.is_a?(OpenSSL::SSL::SSLSocket)
end
#
# We had an issue where a message was sent to a server and was greylisted. It returned
# a Net::SMTPUnknownError error. We then tried to send another message on the same
# connection after running `rset` the next message didn't raise any exceptions because
# net/smtp returns a '200 dummy reply code' and doesn't raise any exceptions.
#
def rset
@error_occurred = false
getok("RSET")
end
def rset_errors
@error_occurred = false
end
private
def tcp_socket(address, port)
TCPSocket.open(address, port, source_address)
end
class Response
def message
@string
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/zeitwerk.rb | config/initializers/zeitwerk.rb | # frozen_string_literal: true
Rails.autoloaders.each do |autoloader|
# Ignore the message DB migrations directory as it doesn't follow
# Zeitwerk's conventions and is always loaded and executed in order.
autoloader.ignore(Rails.root.join("lib/postal/message_db/migrations"))
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/sentry.rb | config/initializers/sentry.rb | # frozen_string_literal: true
require "postal/config"
if Postal::Config.logging.sentry_dsn
Sentry.init do |config|
config.dsn = Postal::Config.logging.sentry_dsn
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # frozen_string_literal: true
# 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 | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # frozen_string_literal: true
# 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 | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/mail_extensions.rb | config/initializers/mail_extensions.rb | # frozen_string_literal: true
require "mail"
module Mail
module Encodings
# Handle windows-1258 as windows-1252 when decoding
def self.q_value_decode(str)
str = str.sub(/=\?windows-?1258\?/i, '\=?windows-1252?')
Utilities.q_value_decode(str)
end
def self.b_value_decode(str)
str = str.sub(/=\?windows-?1258\?/i, '\=?windows-1252?')
Utilities.b_value_decode(str)
end
end
class Message
## Extract plain text body of message
def plain_body
if multipart? && text_part
text_part.decoded
elsif mime_type == "text/plain" || mime_type.nil?
decoded
end
end
## Extract HTML text body of message
def html_body
if multipart? && html_part
html_part.decoded
elsif mime_type == "text/html"
decoded
end
end
private
## Fix bug in basic parsing
def parse_message
self.header, self.body = raw_source.split(/\r?\n\r?\n/m, 2)
end
# Handle attached emails as attachments
# Returns the filename of the attachment (if it exists) or returns nil
# Make up a filename for rfc822 attachments if it isn't specified
def find_attachment
content_type_name = begin
header[:content_type].filename
rescue StandardError
nil
end
content_disp_name = begin
header[:content_disposition].filename
rescue StandardError
nil
end
content_loc_name = begin
header[:content_location].location
rescue StandardError
nil
end
if content_type && content_type_name
filename = content_type_name
elsif content_disposition && content_disp_name
filename = content_disp_name
elsif content_location && content_loc_name
filename = content_loc_name
elsif mime_type == "message/rfc822"
filename = "#{rand(100_000_000)}.eml"
else
filename = nil
end
if filename
# Normal decode
filename = begin
Mail::Encodings.decode_encode(filename, :decode)
rescue StandardError
filename
end
end
filename
end
def decode_body_as_text
body_text = decode_body
charset_tmp = begin
Encoding.find(Utilities.pick_encoding(charset))
rescue StandardError
"ASCII"
end
charset_tmp = "Windows-1252" if charset_tmp.to_s =~ /windows-?1258/i
if charset_tmp == Encoding.find("UTF-7")
body_text.force_encoding("UTF-8")
decoded = body_text.gsub(/\+.*?-/m) { |n| Base64.decode64(n[1..-2] + "===").force_encoding("UTF-16BE").encode("UTF-8") }
else
body_text.force_encoding(charset_tmp)
decoded = body_text.encode("utf-8", invalid: :replace, undef: :replace)
end
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", invalid: :replace, undef: :replace).encode("utf-8")
end
end
# Handle attached emails as attachments
class AttachmentsList < Array
# rubocop:disable Lint/MissingSuper
def initialize(parts_list)
@parts_list = parts_list
@content_disposition_type = "attachment"
parts = parts_list.map do |p|
p.parts.empty? && p.attachment? ? p : p.attachments
end.flatten.compact
parts.each { |a| self << a }
end
# rubocop:enable Lint/MissingSuper
end
end
class Array
def decoded
return nil if empty?
first.decoded
end
end
class NilClass
def decoded
nil
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/secret_key.rb | config/initializers/secret_key.rb | # frozen_string_literal: true
if Postal::Config.rails.secret_key
Rails.application.credentials.secret_key_base = Postal::Config.rails.secret_key
else
warn "No secret key was specified in the Postal config file. Using one for just this session"
Rails.application.credentials.secret_key_base = SecureRandom.hex(128)
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/initializers/postal.rb | config/initializers/postal.rb | # frozen_string_literal: true
require "postal"
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/environments/test.rb | config/environments/test.rb | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.enable_reloading = false
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=3600"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/environments/development.rb | config/environments/development.rb | # frozen_string_literal: true
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.enable_reloading = true
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join("tmp/caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=172800"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = 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
# Suppress logger output for asset requests.
config.assets.quiet = false
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/config/environments/production.rb | config/environments/production.rb | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.enable_reloading = false
# 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
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# 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 = :info
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "deliver_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.raise_delivery_errors = true
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require "pry"
require "simplecov"
SimpleCov.start do
if ENV["CI"]
formatter SimpleCov::Formatter::SimpleFormatter
else
formatter SimpleCov::Formatter::MultiFormatter.new(
[
SimpleCov::Formatter::HTMLFormatter,
SimpleCov::Formatter::SimpleFormatter,
]
)
end
add_filter "vendor/cache"
end
require "tmuxinator"
require "factory_bot"
FactoryBot.find_definitions
# Custom Matchers
require_relative "matchers/pane_matcher"
RSpec.configure do |config|
config.order = "random"
end
# Copied from minitest.
def capture_io
require "stringio"
captured_stdout = StringIO.new
captured_stderr = StringIO.new
orig_stdout = $stdout
orig_stderr = $stderr
$stdout = captured_stdout
$stderr = captured_stderr
yield
[captured_stdout.string, captured_stderr.string]
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
def tmux_config(options = {})
standard_options = [
"assume-paste-time 1",
"bell-action any",
"bell-on-alert off",
]
if base_index = options.fetch(:base_index, 1)
standard_options << "base-index #{base_index}"
end
if pane_base_index = options.fetch(:pane_base_index, 1)
standard_options << "pane-base-index #{pane_base_index}"
end
"echo '#{standard_options.join("\n")}'"
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/factories/projects.rb | spec/factories/projects.rb | # frozen_string_literal: true
def yaml_load(file)
YAML.safe_load(File.read(File.expand_path(file)))
end
FactoryBot.define do
factory :project, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :project_with_force_attach, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/detach.yml") }
end
initialize_with { Tmuxinator::Project.new(file, force_attach: true) }
end
factory :project_with_force_detach, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/detach.yml") }
end
initialize_with { Tmuxinator::Project.new(file, force_detach: true) }
end
factory :project_with_custom_name, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample.yml") }
end
initialize_with { Tmuxinator::Project.new(file, custom_name: "custom") }
end
factory :project_with_number_as_name, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample_number_as_name.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :project_with_emoji_as_name, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample_emoji_as_name.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :project_with_literals_as_window_name, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample_literals_as_window_name.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :project_with_deprecations, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample.deprecations.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :wemux_project, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/sample_wemux.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :noname_project, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/noname.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :noroot_project, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/noroot.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :nowindows_project, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/nowindows.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :nameless_window_project, class: Tmuxinator::Project do
transient do
file { yaml_load("spec/fixtures/nameless_window.yml") }
end
initialize_with { Tmuxinator::Project.new(file) }
end
factory :project_with_alias, class: Tmuxinator::Project do
transient do
file { "spec/fixtures/sample_alias.yml" }
end
initialize_with { Tmuxinator::Project.load(file) }
end
factory :project_with_append, class: Tmuxinator::Project do
transient do
file { "spec/fixtures/sample.yml" }
end
initialize_with { Tmuxinator::Project.load(file, append: true) }
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/matchers/pane_matcher.rb | spec/matchers/pane_matcher.rb | # frozen_string_literal: true
RSpec::Matchers.alias_matcher :be_a_pane, :a_pane
RSpec::Matchers.define :a_pane do
attr_reader :commands
match do
result = is_pane
result && attributes_match if @expected_attrs
result &&= commands_match if commands
result
end
failure_message do |actual|
return "Expected #{actual} to be a Tmuxinator::Pane" unless is_pane
msg = "Actual pane does not match expected"
msg << "\n Expected #{@commands} but has #{actual.commands}" if @commands
msg << "\n Expected pane to have #{@expected_attrs}" if @expected_attrs
end
chain :with do |attrs|
@expected_attrs = attrs
end
chain :with_commands do |*expected|
@commands = expected
end
alias_method :and_commands, :with_commands
private
def attributes_match
expect(@actual).to have_attributes(@expected_attrs)
end
def commands_match
@actual.commands == commands
end
def is_pane
@actual.is_a? Tmuxinator::Pane
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/hooks_spec.rb | spec/lib/tmuxinator/hooks_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Hooks do
describe "#commands_from" do
let(:project) { FactoryBot.build(:project) }
let(:hook_name) { "generic_hook" }
context "config value is string" do
before { project.yaml[hook_name] = "echo 'on hook'" }
it "returns the string" do
expect(subject.commands_from(project, hook_name)).
to eq("echo 'on hook'")
end
end
context "config value is Array" do
before do
project.yaml[hook_name] = [
"echo 'on hook'",
"echo 'another command here'"
]
end
it "joins array using ;" do
expect(subject.commands_from(project, hook_name)).
to eq("echo 'on hook'; echo 'another command here'")
end
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/doctor_spec.rb | spec/lib/tmuxinator/doctor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Doctor do
describe ".installed?" do
context "tmux is installed" do
before do
allow(Kernel).to receive(:system) { true }
end
it "returns true" do
expect(described_class.installed?).to be_truthy
end
end
context "tmux is not installed" do
before do
allow(Kernel).to receive(:system) { false }
end
it "returns false" do
expect(described_class.installed?).to be_falsey
end
end
end
describe ".editor?" do
context "$EDITOR is set" do
before do
allow(ENV).to receive(:[]).with("EDITOR") { "vim" }
end
it "returns true" do
expect(described_class.editor?).to be_truthy
end
end
context "$EDITOR is not set" do
before do
allow(ENV).to receive(:[]).with("EDITOR") { nil }
end
it "returns false" do
expect(described_class.editor?).to be_falsey
end
end
end
describe ".shell?" do
context "$SHELL is set" do
before do
allow(ENV).to receive(:[]).with("SHELL") { "vim" }
end
it "returns true" do
expect(described_class.shell?).to be_truthy
end
end
context "$SHELL is not set" do
before do
allow(ENV).to receive(:[]).with("SHELL") { nil }
end
it "returns false" do
expect(described_class.shell?).to be_falsey
end
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/project_spec.rb | spec/lib/tmuxinator/project_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Project do
let(:project) { FactoryBot.build(:project) }
let(:project_with_custom_name) do
FactoryBot.build(:project_with_custom_name)
end
let(:project_with_number_as_name) do
FactoryBot.build(:project_with_number_as_name)
end
let(:project_with_emoji_as_name) do
FactoryBot.build(:project_with_emoji_as_name)
end
let(:project_with_literals_as_window_name) do
FactoryBot.build(:project_with_literals_as_window_name)
end
let(:project_with_deprecations) do
FactoryBot.build(:project_with_deprecations)
end
let(:project_with_force_attach) do
FactoryBot.build(:project_with_force_attach)
end
let(:project_with_force_detach) do
FactoryBot.build(:project_with_force_detach)
end
let(:wemux_project) { FactoryBot.build(:wemux_project) }
let(:noname_project) { FactoryBot.build(:noname_project) }
let(:noroot_project) { FactoryBot.build(:noroot_project) }
let(:nameless_window_project) do
FactoryBot.build(:nameless_window_project)
end
let(:project_with_alias) do
FactoryBot.build(:project_with_alias)
end
let(:project_with_append) do
FactoryBot.build(:project_with_append)
end
it "should include Hooks" do
expect(project).to be_kind_of(Tmuxinator::Hooks::Project)
end
describe "#initialize" do
context "valid yaml" do
it "creates an instance" do
expect(project).to be_a(Tmuxinator::Project)
end
it "validates append outside a current session" do
Tmuxinator::Project.any_instance.stub(tmux_has_session?: false)
expect { project_with_append }.to(
raise_error(
RuntimeError,
"Cannot append to a session that does not exist"
)
)
end
it "validates append within a current session" do
Tmuxinator::Project.any_instance.stub(tmux_has_session?: true)
expect { project_with_append }.to_not raise_error
end
end
end
describe "#render" do
it "renders the tmux config" do
expect(project.render).to_not be_empty
end
context "wemux" do
it "renders the wemux config" do
expect(wemux_project.render).to_not be_empty
end
end
context "custom name" do
it "renders the tmux config with custom name" do
rendered = project_with_custom_name.render
expect(rendered).to_not be_empty
expect(rendered).to include("custom")
expect(rendered).to_not include("sample")
end
end
context "with alias" do
it "renders the tmux config" do
rendered = project_with_alias.render
expect(rendered).to_not be_empty
expect(rendered).to include("alias_is_working")
end
end
end
describe "#tmux_has_session?" do
context "no active sessions" do
before do
tmux = project.tmux_command
cmd = "#{tmux} -f ~/.tmux.mac.conf -L foo ls 2> /dev/null"
resp = ""
call_tmux_ls = receive(:`).with(cmd).at_least(:once).and_return(resp)
expect(project).to call_tmux_ls
end
it "should return false if no sessions are found" do
expect(project.tmux_has_session?("no server running")).to be false
end
end
context "active sessions" do
before do
cmd = "#{project.tmux} ls 2> /dev/null"
resp = ""\
"foo: 1 window (created Sun May 25 10:12:00 1986) [0x0] (detached)\n"\
"bar: 1 window (created Sat Sept 01 00:00:00 1990) [0x0] (detached)"
call_tmux_ls = receive(:`).with(cmd).at_least(:once).and_return(resp)
expect(project).to call_tmux_ls
end
it "should return true only when `tmux ls` has the named session" do
expect(project.tmux_has_session?("foo")).to be true
expect(project.tmux_has_session?("bar")).to be true
expect(project.tmux_has_session?("quux")).to be false
end
it "should return false if a partial (prefix) match is found" do
expect(project.tmux_has_session?("foobar")).to be false
end
end
end
describe "#windows" do
context "without deprecations" do
it "gets the list of windows" do
expect(project.windows).to_not be_empty
end
end
context "with deprecations" do
it "still gets the list of windows" do
expect(project_with_deprecations.windows).to_not be_empty
end
end
end
describe "#root" do
context "without deprecations" do
it "gets the root" do
expect(project.root).to include("test")
end
end
context "with deprecations" do
it "still gets the root" do
expect(project_with_deprecations.root).to include("test")
end
end
context "without root" do
it "doesn't throw an error" do
expect { noroot_project.root }.to_not raise_error
end
end
end
describe "#name" do
context "without deprecations" do
it "gets the name" do
expect(project.name).to eq "sample"
end
end
context "with deprecations" do
it "still gets the name" do
expect(project_with_deprecations.name).to eq "sample"
end
end
context "wemux" do
it "is wemux" do
expect(wemux_project.name).to eq "wemux"
end
end
context "without name" do
it "displays error message" do
expect { noname_project.name }.to_not raise_error
end
end
context "as number" do
it "will gracefully handle a name given as a number" do
rendered = project_with_number_as_name
expect(rendered.name.to_i).to_not equal 0
end
end
context "as emoji" do
it "will gracefully handle a name given as an emoji" do
rendered = project_with_emoji_as_name
# needs to allow for \\ present in shellescape'd project name
expect(rendered.name).to match(/^\\*🍩/)
end
end
context "window as non-string literal" do
it "will gracefully handle a window name given as a non-string literal" do
rendered = project_with_literals_as_window_name
expect(rendered.windows.map(&:name)).to match_array(
%w(222 222333 111222333444555666777 222.3 4e5 4E5
true false nil // /sample/)
)
end
end
end
describe "#pre_window" do
subject(:pre_window) { project.pre_window }
context "pre_window in yaml is string" do
before { project.yaml["pre_window"] = "mysql.server start" }
it "returns the string" do
expect(pre_window).to eq("mysql.server start")
end
end
context "pre_window in yaml is Array" do
before do
project.yaml["pre_window"] = [
"mysql.server start",
"memcached -d"
]
end
it "joins array using ;" do
expect(pre_window).to eq("mysql.server start; memcached -d")
end
end
context "with deprecations" do
context "rbenv option is present" do
before do
allow(project).to receive_messages(rbenv?: true)
allow(project).to \
receive_message_chain(:yaml, :[]).and_return("2.0.0-p247")
end
it "still gets the correct pre_window command" do
expect(project.pre_window).to eq "rbenv shell 2.0.0-p247"
end
end
context "rvm option is present" do
before do
allow(project).to receive_messages(rbenv?: false)
allow(project).to \
receive_message_chain(:yaml, :[]).and_return("ruby-2.0.0-p247")
end
it "still gets the correct pre_window command" do
expect(project.pre_window).to eq "rvm use ruby-2.0.0-p247"
end
end
context "pre_tab is present" do
before do
allow(project).to receive_messages(rbenv?: false)
allow(project).to receive_messages(pre_tab?: true)
end
it "still gets the correct pre_window command" do
expect(project.pre_window).to be_nil
end
end
end
context "no_pre_window option is true" do
before do
allow(project).to receive_messages(no_pre_window: true)
end
it "returns nil" do
expect(pre_window).to be_nil
end
end
end
describe "#socket" do
context "socket path is present" do
before do
allow(project).to receive_messages(socket_path: "/tmp")
end
it "gets the socket path" do
expect(project.socket).to eq " -S /tmp"
end
end
end
describe "#tmux_command" do
context "tmux_command specified" do
before do
project.yaml["tmux_command"] = "byobu"
end
it "gets the custom tmux command" do
expect(project.tmux_command).to eq "byobu"
end
end
context "tmux_command is not specified" do
it "returns the default" do
expect(project.tmux_command).to eq "tmux"
end
end
end
describe "#tmux_options" do
context "no tmux options" do
before do
allow(project).to receive_messages(tmux_options?: false)
end
it "returns nothing" do
expect(project.tmux_options).to eq ""
end
end
context "with deprecations" do
before do
allow(project_with_deprecations).to receive_messages(cli_args?: true)
end
it "still gets the tmux options" do
expect(project_with_deprecations.tmux_options).to \
eq " -f ~/.tmux.mac.conf"
end
end
end
describe "#get_pane_base_index" do
it "extracts pane-base-index from the global tmux window options" do
allow_any_instance_of(Kernel).to receive(:`).
with(Regexp.new("tmux.+ show-window-option -g pane-base-index")).
and_return("pane-base-index 3\n")
expect(project.get_pane_base_index).to eq("3")
end
end
describe "#get_base_index" do
it "extracts base-index from the global tmux options" do
allow_any_instance_of(Kernel).to receive(:`).
with(Regexp.new("tmux.+ show-option -g base-index")).
and_return("base-index 1\n")
expect(project.get_base_index).to eq("1")
end
end
describe "#base_index" do
context "when pane_base_index is 1 and base_index is unset" do
before do
allow(project).to receive_messages(get_pane_base_index: "1")
allow(project).to receive_messages(get_base_index: nil)
end
it "gets the tmux default of 0" do
expect(project.base_index).to eq(0)
end
end
context "base index present" do
before do
allow(project).to receive_messages(get_base_index: "1")
end
it "gets the base index" do
expect(project.base_index).to eq 1
end
end
context "base index not present" do
before do
allow(project).to receive_messages(get_base_index: nil)
end
it "defaults to 0" do
expect(project.base_index).to eq 0
end
end
context "with append set" do
before do
Tmuxinator::Project.any_instance.stub(tmux_has_session?: true)
project_with_append.stub(last_window_index: 3)
end
it "defaults to the next window index" do
expect(project_with_append.base_index).to eq 4
end
end
end
describe "#startup_window" do
context "startup window specified" do
it "gets the startup window from project config" do
project.yaml["startup_window"] = "logs"
expect(project.startup_window).to eq("sample:logs")
end
end
context "startup window not specified" do
it "returns base index instead" do
allow(project).to receive_messages(base_index: 8)
expect(project.startup_window).to eq("sample:8")
end
end
end
describe "#startup_pane" do
context "startup pane specified" do
it "get the startup pane index from project config" do
project.yaml["startup_pane"] = 1
expect(project.startup_pane).to eq("sample:0.1")
end
end
context "startup pane not specified" do
it "returns the base pane instead" do
allow(project).to receive_messages(pane_base_index: 4)
expect(project.startup_pane).to eq("sample:0.4")
end
end
end
describe "#window" do
it "gets the window and index for tmux" do
expect(project.window(1)).to eq "sample:1"
end
context "with append set" do
it "excludes the session name" do
Tmuxinator::Project.any_instance.stub(tmux_has_session?: true)
expect(project_with_append.window(1)).to eq ":1"
end
end
end
describe "#name?" do
context "name is present" do
it "returns true" do
expect(project.name?).to be_truthy
end
end
end
describe "#windows?" do
context "windows are present" do
it "returns true" do
expect(project.windows?).to be_truthy
end
end
end
describe "#root?" do
context "root are present" do
it "returns true" do
expect(project.root?).to be_truthy
end
end
end
describe "#send_keys" do
context "no command for window" do
it "returns empty string" do
expect(project.send_keys("", 1)).to be_empty
end
end
context "command for window is not empty" do
it "returns the tmux command" do
expect(project.send_keys("vim", 1)).to \
eq "tmux -f ~/.tmux.mac.conf -L foo send-keys -t sample:1 vim C-m"
end
end
end
describe "#send_pane_command" do
context "no command for pane" do
it "returns empty string" do
expect(project.send_pane_command("", 0, 0)).to be_empty
end
end
context "command for pane is not empty" do
it "returns the tmux command" do
expect(project.send_pane_command("vim", 1, 0)).to \
eq "tmux -f ~/.tmux.mac.conf -L foo send-keys -t sample:1 vim C-m"
end
end
end
describe "#deprecations" do
context "without deprecations" do
it "is empty" do
expect(project.deprecations).to be_empty
end
end
context "with deprecations" do
it "is not empty" do
expect(project_with_deprecations.deprecations).to_not be_empty
end
end
end
describe "#commands" do
let(:window) { project.windows.keep_if { |w| w.name == "shell" }.first }
it "splits commands into an array" do
commands = [
"tmux -f ~/.tmux.mac.conf -L foo send-keys -t sample:1 git\\ pull C-m",
"tmux -f ~/.tmux.mac.conf -L foo send-keys -t sample:1 git\\ merge C-m"
]
expect(window.commands).to eq(commands)
end
end
describe "#pre" do
subject(:pre) { project.pre }
context "pre in yaml is string" do
before { project.yaml["pre"] = "mysql.server start" }
it "returns the string" do
expect(pre).to eq("mysql.server start")
end
end
context "pre in yaml is Array" do
before do
project.yaml["pre"] = [
"mysql.server start",
"memcached -d"
]
end
it "joins array using ;" do
expect(pre).to eq("mysql.server start; memcached -d")
end
end
end
describe "#attach?" do
context "attach is true in yaml" do
before { project.yaml["attach"] = true }
it "returns true" do
expect(project.attach?).to be_truthy
end
end
context "attach is not defined in yaml" do
it "returns true" do
expect(project.attach?).to be_truthy
end
end
context "attach is false in yaml" do
before { project.yaml["attach"] = false }
it "returns false" do
expect(project.attach?).to be_falsey
end
end
context "attach is true in yaml, but command line forces detach" do
before { project_with_force_attach.yaml["attach"] = true }
it "returns false" do
expect(project_with_force_detach.attach?).to be_falsey
end
end
context "attach is false in yaml, but command line forces attach" do
before { project_with_force_detach.yaml["attach"] = false }
it "returns true" do
expect(project_with_force_attach.attach?).to be_truthy
end
end
end
describe "tmux_new_session_command" do
let(:command) { "#{executable} new-session -d -s #{session} -n #{window}" }
let(:executable) { project.tmux }
let(:session) { project.name }
let(:window) { project.windows.first.name }
context "when first window has a name" do
it "returns command to start a new detached session" do
expect(project.tmux_new_session_command).to eq command
end
end
context "when first window is nameless" do
let(:project) { nameless_window_project }
let(:command) { "#{project.tmux} new-session -d -s #{project.name} " }
it "returns command to for new detached session without a window name" do
expect(project.tmux_new_session_command).to eq command
end
end
context "with append set" do
it "returns nothing" do
Tmuxinator::Project.any_instance.stub(tmux_has_session?: true)
expect(project_with_append.tmux_new_session_command).to be_nil
end
end
end
describe "tmux_kill_session_command" do
let(:command) { "#{executable} kill-session -t #{session}" }
let(:executable) { project.tmux }
let(:session) { project.name }
context "when first window has a name" do
it "returns command to start a new detached session" do
expect(project.tmux_kill_session_command).to eq command
end
end
end
describe "::load" do
let(:path) { File.expand_path("../../fixtures/sample.yml", __dir__) }
let(:options) { {} }
it "should raise if the project file doesn't parse" do
bad_yaml = <<-Y
name: "foo"
subkey:
Y
expect(File).to receive(:read).with(path) { bad_yaml }
expect do
described_class.load(path, options)
end.to raise_error RuntimeError, /\AFailed to parse config file: .+\z/
end
it "should return an instance of the class if the file loads" do
expect(described_class.load(path, options)).to be_a Tmuxinator::Project
end
end
describe "::parse_settings" do
let(:args) { ["one", "two=three", "four=five=six"] }
it "returns settings in a hash" do
expect(described_class.parse_settings(args)["two"]).to eq("three")
end
it "removes settings from args" do
described_class.parse_settings(args)
expect(args).to eq(["one"])
end
it "handles equals signs in values" do
expect(described_class.parse_settings(args)["four"]).to eq("five=six")
end
end
describe "#validate!" do
it "should raise if there are no windows defined" do
nowindows_project = FactoryBot.build(:nowindows_project)
expect do
nowindows_project.validate!
end.to raise_error RuntimeError, %r{should.include.some.windows}
end
it "should raise if there is not a project name" do
expect do
noname_project.validate!
end.to raise_error RuntimeError, %r{didn't.specify.a.'project_name'}
end
end
describe "#pane_titles" do
before do
allow(project).to receive(:tmux).and_return "tmux"
end
context "pane_titles not enabled" do
before { project.yaml["enable_pane_titles"] = false }
it "returns false" do
expect(project.enable_pane_titles?).to be false
end
end
context "pane_titles enabled" do
before { project.yaml["enable_pane_titles"] = true }
it "returns true" do
expect(project.enable_pane_titles?).to be true
end
end
context "pane_title_position not configured" do
before { project.yaml["pane_title_position"] = nil }
it "configures a default position of top" do
expect(project.tmux_set_pane_title_position("x")).to eq(
"tmux set-window-option -t x pane-border-status top"
)
end
end
context "pane_title_position configured" do
before { project.yaml["pane_title_position"] = "bottom" }
it "configures a position of bottom" do
expect(project.tmux_set_pane_title_position("x")).to eq(
"tmux set-window-option -t x pane-border-status bottom"
)
end
end
context "pane_title_position invalid" do
before { project.yaml["pane_title_position"] = "other" }
it "configures the default position" do
expect(project.tmux_set_pane_title_position("x")).to eq(
"tmux set-window-option -t x pane-border-status top"
)
end
end
context "pane_title_format not configured" do
before { project.yaml["pane_title_format"] = nil }
it "configures a default format" do
resp = ""\
"tmux set-window-option -t x pane-border-format"\
" \"\#{pane_index}: \#{pane_title}\""
expect(project.tmux_set_pane_title_format("x")).to eq(resp)
end
end
context "pane_title_format configured" do
before { project.yaml["pane_title_format"] = " [ #T ] " }
it "configures the provided format" do
expect(project.tmux_set_pane_title_format("x")).to eq(
'tmux set-window-option -t x pane-border-format " [ #T ] "'
)
end
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/pane_spec.rb | spec/lib/tmuxinator/pane_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Pane do
let(:klass) { described_class }
let(:instance) { klass.new(index, project, window, *commands) }
let(:instance_with_title) do
klass.new(index, project, window, *commands, title: title)
end
let(:index) { 0 }
let(:project) { double }
let(:window) { double }
let(:commands) { ["vim", "bash"] }
let(:title) { "test (a test)" }
before do
allow(project).to receive(:name).and_return "foo"
allow(project).to receive(:base_index).and_return 0
allow(project).to receive(:pane_base_index).and_return 1
allow(project).to receive(:tmux).and_return "tmux"
allow(window).to receive(:project).and_return project
allow(window).to receive(:index).and_return 0
end
subject { instance }
it "creates an instance" do
expect(subject).to be_a(Tmuxinator::Pane)
end
it { expect(subject.tmux_window_and_pane_target).to eql "foo:0.1" }
it "does not set pane title" do
expect(subject.tmux_set_title).to be_nil
end
context "when title is provided" do
subject { instance_with_title }
it "sets pane title" do
expect(subject.tmux_set_title).to eql(
"tmux select-pane -t foo:0.1 -T test\\ \\(a\\ test\\)"
)
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/cli_spec.rb | spec/lib/tmuxinator/cli_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Cli do
shared_context :local_project_setup do
let(:local_project_config) { ".tmuxinator.yml" }
let(:content_fixture) { "../../fixtures/sample.yml" }
let(:content_relpath) { File.join(File.dirname(__FILE__), content_fixture) }
let(:content_path) { File.expand_path(content_relpath) }
let(:content) { File.read(content_path) }
let(:working_dir) { FileUtils.pwd }
let(:local_project_relpath) { File.join(working_dir, local_project_config) }
let(:local_project_path) { File.expand_path(local_project_relpath) }
before do
File.new(local_project_path, "w").tap do |f|
f.write content
end.close
expect(File.exist?(local_project_path)).to be_truthy
expect(File.read(local_project_path)).to eq content
end
after do
File.delete(local_project_path)
end
end
subject(:cli) { described_class }
let(:fixtures_dir) { File.expand_path("../../fixtures", __dir__) }
let(:project) { FactoryBot.build(:project) }
let(:project_config) do
File.join(fixtures_dir, "sample_with_project_config.yml")
end
before do
ARGV.clear
allow(Kernel).to receive(:system)
allow(FileUtils).to receive(:copy_file)
allow(FileUtils).to receive(:rm)
allow(FileUtils).to receive(:remove_dir)
end
context "no arguments" do
it "runs without error" do
_, err = capture_io { cli.start }
expect(err).to be_empty
end
end
context "base thor functionality" do
shared_examples_for :base_thor_functionality do
it "supports -v" do
out, err = capture_io { cli.bootstrap(["-v"]) }
expect(err).to eq ""
expect(out).to include(Tmuxinator::VERSION)
end
it "supports help" do
out, err = capture_io { cli.bootstrap(["help"]) }
expect(err).to eq ""
expect(out).to include("tmuxinator commands:")
end
end
it_should_behave_like :base_thor_functionality
context "with a local project config" do
include_context :local_project_setup
it_should_behave_like :base_thor_functionality
end
end
describe "::bootstrap" do
subject { cli.bootstrap(args) }
let(:args) { [] }
shared_examples_for :bootstrap_with_arguments do
let(:args) { [arg1] }
context "and the first arg is a tmuxinator command" do
let(:arg1) { "list" }
it "should call ::start" do
expect(cli).to receive(:start).with(args)
subject
end
end
context "and the first arg is" do
let(:arg1) { "sample" }
context "a tmuxinator project name" do
before do
expect(Tmuxinator::Config).to \
receive(:exist?).with(name: arg1) { true }
end
it "should call #start" do
expect(cli).to receive(:start).with([:start, *args])
subject
end
context "and the append option is passed" do
let(:args) { ["sample", "--append"] }
it "should call #start" do
expect(cli).to receive(:start).with([:start, *args])
subject
end
end
end
context "a thor command" do
context "(-v)" do
let(:arg1) { "-v" }
it "should call ::start" do
expect(cli).to receive(:start).with(args)
subject
end
end
context "(help)" do
let(:arg1) { "help" }
it "should call ::start" do
expect(cli).to receive(:start).with(args)
subject
end
end
end
context "something else" do
before do
expect(Tmuxinator::Config).to \
receive(:exist?).with(name: arg1) { false }
end
it "should call ::start" do
expect(cli).to receive(:start).with(args)
subject
end
end
end
end
context "and there is a local project config" do
include_context :local_project_setup
context "when no args are supplied" do
it "should call #local" do
instance = instance_double(cli)
expect(cli).to receive(:new).and_return(instance)
expect(instance).to receive(:local)
subject
end
end
context "when one or more args are supplied" do
it_should_behave_like :bootstrap_with_arguments
end
end
context "and there is no local project config" do
context "when no args are supplied" do
it "should call ::start" do
expect(cli).to receive(:start).with([])
subject
end
end
context "when one or more args are supplied" do
it_should_behave_like :bootstrap_with_arguments
end
end
end
describe "#completions" do
before do
ARGV.replace(["completions", "start"])
allow(Tmuxinator::Config).to receive_messages(configs: ["test.yml",
"foo.yml"])
end
it "gets completions" do
out, _err = capture_io { cli.start }
expect(out).to include("test.yml\nfoo.yml")
end
end
describe "#commands" do
before do
ARGV.replace(["commands"])
end
it "lists the commands" do
out, _err = capture_io { cli.start }
expected = %w(
commands
completions
copy
debug
delete
doctor
edit
help
implode
local
list
new
open
start
stop
stop_all
version
)
expect(out).to eq "#{expected.join("\n")}\n"
end
end
shared_examples_for :unsupported_version_message do |*args|
before do
ARGV.replace([*args])
end
context "unsupported version" do
before do
allow($stdin).to receive_messages(getc: "y")
allow(Tmuxinator::TmuxVersion).to receive(:supported?).and_return(false)
end
it "prints the warning" do
out, _err = capture_io { cli.start }
expect(out).to include "WARNING"
end
context "with --suppress-tmux-version-warning flag" do
before do
ARGV.replace([*args, "--suppress-tmux-version-warning"])
end
it "does not print the warning" do
out, _err = capture_io { cli.start }
expect(out).not_to include "WARNING"
end
end
end
context "supported version" do
before do
allow($stdin).to receive_messages(getc: "y")
allow(Tmuxinator::TmuxVersion).to receive(:supported?).and_return(true)
end
it "does not print the warning" do
out, _err = capture_io { cli.start }
expect(out).not_to include "WARNING"
end
end
end
describe "#start" do
before do
ARGV.replace(["start", "foo"])
allow(Tmuxinator::Config).to receive_messages(validate: project)
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
allow(Kernel).to receive(:exec)
end
context "no deprecations" do
it "starts the project" do
expect(Kernel).to receive(:exec)
capture_io { cli.start }
end
it "accepts a flag for alternate name" do
ARGV.replace(["start", "foo", "--name=bar"])
expect(Kernel).to receive(:exec)
capture_io { cli.start }
end
it "accepts a project config file flag" do
ARGV.replace(["start", "foo", "--project-config=sample.yml"])
expect(Kernel).to receive(:exec)
capture_io { cli.start }
end
it "accepts additional arguments" do
ARGV.replace(["start", "foo", "bar", "three=four"])
expect(Kernel).to receive(:exec)
capture_io { cli.start }
end
end
context "with --help flag" do
it "shows help instead of starting project" do
ARGV.replace(["start", "--help"])
expect(Kernel).not_to receive(:exec)
out, _err = capture_io { cli.start }
expect(out).to include("start [PROJECT] [ARGS]")
expect(out).to include("Options:")
end
it "shows help with -h flag" do
ARGV.replace(["start", "-h"])
expect(Kernel).not_to receive(:exec)
out, _err = capture_io { cli.start }
expect(out).to include("start [PROJECT] [ARGS]")
expect(out).to include("Options:")
end
end
context "deprecations" do
before do
allow($stdin).to receive_messages(getc: "y")
end
let(:project) { FactoryBot.build(:project_with_deprecations) }
it "prints the deprecations" do
out, _err = capture_io { cli.start }
expect(out).to include "DEPRECATION"
end
end
include_examples :unsupported_version_message, :start, :foo
end
describe "#stop" do
before do
allow(Tmuxinator::Config).to receive_messages(validate: project)
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
allow(Kernel).to receive(:exec)
end
context "with project name" do
it "stops the project" do
ARGV.replace(["stop", "foo"])
expect(Kernel).to receive(:exec)
out, err = capture_io { cli.start }
expect(err).to eq ""
expect(out).to eq ""
end
end
context "without project name" do
it "stops the project using .tmuxinator.yml" do
ARGV.replace(["stop"])
expect(Kernel).to receive(:exec)
out, err = capture_io { cli.start }
expect(err).to eq ""
expect(out).to eq ""
end
end
context "with --help flag" do
it "shows help instead of stopping project" do
ARGV.replace(["stop", "--help"])
expect(Kernel).not_to receive(:exec)
out, _err = capture_io { cli.start }
expect(out).to include("stop [PROJECT]")
expect(out).to include("Options:")
end
end
include_examples :unsupported_version_message, :stop, :foo
end
describe "#stop(with project config file)" do
before do
allow(Tmuxinator::Config).to receive(:validate).and_call_original
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
allow(Kernel).to receive(:exec)
end
it "stops the project" do
ARGV.replace(["stop", "--project-config=#{project_config}"])
expect(Tmuxinator::Config).to receive_messages(validate: project)
expect(Kernel).to receive(:exec)
out, err = capture_io { cli.start }
expect(err).to eq ""
expect(out).to eq ""
end
it "does not stop the project if given a bogus project config file" do
ARGV.replace(["stop", "--project-config=bogus.yml"])
expect(Kernel).not_to receive(:exec)
expect { capture_io { cli.start } }.to raise_error(SystemExit)
end
it "does not set the project name" do
ARGV.replace(["stop", "--project-config=#{project_config}"])
expect(Tmuxinator::Config).
to(receive(:validate).
with(hash_including(name: nil)))
capture_io { cli.start }
end
it "does not set the project name even when set" do
ARGV.replace(["stop", "bar", "--project-config=#{project_config}"])
expect(Tmuxinator::Config).
to(receive(:validate).
with(hash_including(name: nil)))
capture_io { cli.start }
end
end
describe "#stop_all" do
before do
allow(Tmuxinator::Config).to receive_messages(validate: project)
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
end
it "stops all projects" do
ARGV.replace(["stop-all", "--noconfirm"])
out, err = capture_io { cli.start }
expect(err).to eq ""
expect(out).to eq ""
end
end
describe "#local" do
before do
allow(Tmuxinator::Config).to receive_messages(validate: project)
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
allow(Kernel).to receive(:exec)
end
shared_examples_for :local_project do
it "starts the project" do
expect(Kernel).to receive(:exec)
out, err = capture_io { cli.start }
expect(err).to eq ""
expect(out).to eq ""
end
end
context "when the command used is 'local'" do
before do
ARGV.replace ["local"]
end
it_should_behave_like :local_project
end
context "when the command used is '.'" do
before do
ARGV.replace ["."]
end
it_should_behave_like :local_project
end
include_examples :unsupported_version_message, :local
end
describe "#start(custom_name)" do
before do
ARGV.replace(["start", "foo", "bar"])
allow(Tmuxinator::Config).to receive_messages(validate: project)
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
allow(Kernel).to receive(:exec)
end
context "no deprecations" do
it "starts the project" do
expect(Kernel).to receive(:exec)
capture_io { cli.start }
end
end
end
describe "#start(with project config file)" do
before do
allow(Tmuxinator::Config).to receive(:validate).and_call_original
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
allow(Kernel).to receive(:exec)
end
context "no deprecations" do
it "starts the project if given a valid project config file" do
ARGV.replace(["start", "--project-config=#{project_config}"])
expect(Kernel).to receive(:exec)
capture_io { cli.start }
end
it "does not start the project if given a bogus project config file" do
ARGV.replace(["start", "--project-config=bogus.yml"])
expect(Kernel).not_to receive(:exec)
expect { capture_io { cli.start } }.to raise_error(SystemExit)
end
it "passes additional arguments through" do
ARGV.replace(["start", "--project-config=#{project_config}", "extra"])
expect(Tmuxinator::Config).
to(receive(:validate).
with(hash_including(args: array_including("extra"))))
capture_io { cli.start }
end
it "does not set the project name" do
ARGV.replace(["start", "--project-config=#{project_config}"])
expect(Tmuxinator::Config).
to(receive(:validate).
with(hash_including(name: nil)))
capture_io { cli.start }
end
end
end
describe "#edit" do
let(:file) { StringIO.new }
let(:name) { "test" }
let(:path) { Tmuxinator::Config.default_project(name) }
context "when the project file _does_ already exist" do
let(:extra) { " - extra: echo 'foobar'" }
before do
# make sure that no project file exists initially
FileUtils.remove_file(path) if File.exist?(path)
expect(File).not_to exist(path)
# now generate a project file
expect(described_class.new.generate_project_file(name, path)).to eq path
expect(File).to exist path
# add some content to the project file
File.open(path, "w") do |f|
f.write(extra)
f.flush
end
expect(File.read(path)).to match %r{#{extra}}
# get ready to run `tmuxinator edit #{name}`
ARGV.replace ["edit", name]
end
it "should _not_ generate a new project file" do
capture_io { cli.start }
expect(File.read(path)).to match %r{#{extra}}
end
end
end
describe "#new" do
let(:file) { StringIO.new }
let(:name) { "test" }
before do
allow(File).to receive(:open) { |&block| block.yield file }
end
context "with --help flag" do
it "shows help instead of creating project" do
ARGV.replace(["new", "--help"])
out, _err = capture_io { cli.start }
expect(out).to include("new [PROJECT]")
expect(out).to include("Options:")
end
end
context "without the --local option" do
before do
ARGV.replace(["new", name])
end
context "existing project doesn't exist" do
before do
expect(File).to receive_messages(exist?: false)
end
it "creates a new tmuxinator project file" do
capture_io { cli.start }
expect(file.string).to_not be_empty
end
end
context "file exists" do
let(:project_path) { Tmuxinator::Config.project(name).to_s }
before do
allow(File).to receive(:exist?).with(anything).and_return(false)
expect(File).to receive(:exist?).with(project_path).and_return(true)
end
it "just opens the file" do
expect(Kernel).to receive(:system).with(%r{#{project_path}})
capture_io { cli.start }
end
end
end
context "with the --local option" do
before do
ARGV.replace ["new", name, "--local"]
end
context "existing project doesn't exist" do
before do
allow(File).to receive(:exist?).at_least(:once) do
false
end
end
it "creates a new tmuxinator project file" do
capture_io { cli.start }
expect(file.string).to_not be_empty
end
end
context "file exists" do
let(:path) { Tmuxinator::Config::LOCAL_DEFAULTS[0] }
before do
expect(File).to receive(:exist?).with(path) { true }
end
it "just opens the file" do
expect(Kernel).to receive(:system).with(%r{#{path}})
capture_io { cli.start }
end
end
end
# this command variant only works for tmux version 1.6 and up.
context "from a session" do
context "with tmux >= 1.6", if: Tmuxinator::Config.version >= 1.6 do
before do
# Necessary to make `Doctor.installed?` work in specs
allow(Tmuxinator::Doctor).to receive(:installed?).and_return(true)
end
context "session exists" do
before(:all) do
# Can't add variables through `let` in `before :all`.
@session = "for-testing-tmuxinator"
# Pass the -d option, so that the session is not attached.
Kernel.system "tmux new-session -d -s #{@session}"
end
before do
ARGV.replace ["new", name, @session]
end
after(:all) do
puts @session
Kernel.system "tmux kill-session -t #{@session}"
end
it "creates a project file" do
capture_io { cli.start }
expect(file.string).to_not be_empty
# make sure the output is valid YAML
expect { YAML.parse file.string }.to_not raise_error
end
end
context "session doesn't exist" do
before do
ARGV.replace ["new", name, "sessiondoesnotexist"]
end
it "fails" do
expect { cli.start }.to raise_error RuntimeError
end
end
end
context "with tmux < 1.6" do
before do
ARGV.replace ["new", name, "sessionname"]
allow(Tmuxinator::Config).to receive(:version).and_return(1.5)
end
it "is unsupported" do
expect { cli.start }.to raise_error RuntimeError
end
end
end
end
describe "#copy" do
before do
ARGV.replace(["copy", "foo", "bar"])
allow(Tmuxinator::Config).to receive(:exist?) { true }
end
context "with --help flag" do
it "shows help instead of copying project" do
ARGV.replace(["copy", "--help"])
expect(FileUtils).not_to receive(:copy_file)
out, _err = capture_io { cli.start }
expect(out).to include("copy [EXISTING] [NEW]")
expect(out).to include("Options:")
end
it "shows help with -h flag" do
ARGV.replace(["copy", "-h"])
expect(FileUtils).not_to receive(:copy_file)
out, _err = capture_io { cli.start }
expect(out).to include("copy [EXISTING] [NEW]")
expect(out).to include("Options:")
end
it "shows help when only one argument provided" do
ARGV.replace(["copy", "foo"])
expect(FileUtils).not_to receive(:copy_file)
out, _err = capture_io { cli.start }
expect(out).to include("copy [EXISTING] [NEW]")
end
end
context "new project already exists" do
before do
allow(Thor::LineEditor).to receive_messages(readline: "y")
end
it "prompts user to confirm overwrite" do
expect(FileUtils).to receive(:copy_file)
capture_io { cli.start }
end
end
context "existing project doesn't exist" do
before do
allow(Tmuxinator::Config).to receive(:exist?) { false }
end
it "exit with error code" do
expect { capture_io { cli.start } }.to raise_error SystemExit
end
end
end
describe "#debug" do
context "named project" do
let(:project_with_force_attach) do
FactoryBot.build(:project_with_force_attach)
end
let(:project_with_force_detach) do
FactoryBot.build(:project_with_force_detach)
end
before do
allow(Tmuxinator::Config).to receive_messages(validate: project)
expect(project).to receive(:render)
end
it "renders the project" do
ARGV.replace(["debug", "foo"])
capture_io { cli.start }
end
it "force attach renders the project with attach code" do
ARGV.replace(["debug", "--attach=true", "sample"])
capture_io { cli.start }
# Currently no project is rendered at all,
# because the project file is not found
# expect(out).to include "attach-session"
end
it "force detach renders the project without attach code" do
ARGV.replace(["debug", "--attach=false", "sample"])
capture_io { cli.start }
# Currently no project is rendered at all
# expect(out).to_not include "attach-session"
end
it "renders the project with custom session" do
ARGV.replace(["debug", "sample", "bar"])
capture_io { cli.start }
end
end
context "project config file" do
before do
allow(Tmuxinator::Config).to receive_messages(version: 1.9)
expect(Tmuxinator::Config).to receive(:validate).and_call_original
end
it "renders the project if given a valid project config file" do
ARGV.replace(["debug", "--project-config=#{project_config}"])
expect { cli.start }.to output(/sample_with_project_config/).to_stdout
end
it "does not render the project if given a bogus project config file" do
ARGV.replace(["debug", "--project-config=bogus.yml"])
expect { capture_io { cli.start } }.to raise_error(SystemExit)
end
end
end
describe "#delete" do
context "with --help flag" do
it "shows help instead of deleting project" do
ARGV.replace(["delete", "--help"])
expect(FileUtils).not_to receive(:rm)
out, _err = capture_io { cli.start }
expect(out).to include("delete [PROJECT1] [PROJECT2]")
expect(out).to include("Options:")
end
it "shows help with -h flag" do
ARGV.replace(["delete", "-h"])
expect(FileUtils).not_to receive(:rm)
out, _err = capture_io { cli.start }
expect(out).to include("delete [PROJECT1] [PROJECT2]")
expect(out).to include("Options:")
end
it "shows help when no arguments provided" do
ARGV.replace(["delete"])
expect(FileUtils).not_to receive(:rm)
out, _err = capture_io { cli.start }
expect(out).to include("delete [PROJECT1] [PROJECT2]")
end
end
context "with a single argument" do
before do
ARGV.replace(["delete", "foo"])
allow(Thor::LineEditor).to receive_messages(readline: "y")
end
context "project exists" do
before do
allow(Tmuxinator::Config).to receive(:exist?) { true }
end
it "deletes the project" do
expect(FileUtils).to receive(:rm)
capture_io { cli.start }
end
end
context "local project exists" do
before do
allow(Tmuxinator::Config).to receive(:exist?) { true }
expect(Tmuxinator::Config).to receive(:project) { "local" }
end
it "deletes the local project" do
expect(FileUtils).to receive(:rm).with("local")
capture_io { cli.start }
end
end
context "project doesn't exist" do
before do
allow(Tmuxinator::Config).to receive(:exist?) { false }
end
it "outputs an error message" do
expect(capture_io { cli.start }[0]).to match(/foo does not exist!/)
end
end
end
context "with multiple arguments" do
before do
ARGV.replace(["delete", "foo", "bar"])
allow(Thor::LineEditor).to receive_messages(readline: "y")
end
context "all projects exist" do
before do
allow(Tmuxinator::Config).to receive(:exist?).and_return(true)
end
it "deletes the projects" do
expect(FileUtils).to receive(:rm).exactly(2).times
capture_io { cli.start }
end
end
context "only one project exists" do
before do
allow(Tmuxinator::Config).to receive(:exist?).with(name: "foo") {
true
}
allow(Tmuxinator::Config).to receive(:exist?).with(name: "bar") {
false
}
end
it "deletes one project" do
expect(FileUtils).to receive(:rm)
capture_io { cli.start }
end
it "outputs an error message" do
expect(capture_io { cli.start }[0]).to match(/bar does not exist!/)
end
end
context "all projects do not exist" do
before do
allow(Tmuxinator::Config).to receive(:exist?).and_return(false)
end
it "outputs multiple error messages" do
expect(capture_io { cli.start }[0]).
to match(/foo does not exist!\nbar does not exist!/)
end
end
end
end
describe "#implode" do
before do
ARGV.replace(["implode"])
allow(Thor::LineEditor).to receive_messages(readline: "y")
end
it "confirms deletion of all projects" do
expect(Thor::LineEditor).to receive(:readline).and_return("y")
capture_io { cli.start }
end
it "deletes the configuration directory(s)" do
allow(Tmuxinator::Config).to receive(:directories) \
{ [Tmuxinator::Config.xdg, Tmuxinator::Config.home] }
expect(FileUtils).to receive(:remove_dir).once.
with(Tmuxinator::Config.xdg)
expect(FileUtils).to receive(:remove_dir).once.
with(Tmuxinator::Config.home)
expect(FileUtils).to receive(:remove_dir).never
capture_io { cli.start }
end
context "$TMUXINATOR_CONFIG specified" do
it "only deletes projects in that directory" do
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").and_return "dir"
allow(File).to receive(:directory?).with("dir").and_return true
expect(FileUtils).to receive(:remove_dir).once.with("dir")
expect(FileUtils).to receive(:remove_dir).never
capture_io { cli.start }
end
end
end
describe "#list" do
before do
allow(Dir).to receive_messages(:[] => ["/path/to/project.yml"])
end
context "set --newline flag " do
ARGV.replace(["list --newline"])
it "force output to be one entry per line" do
expect { capture_io { cli.start } }.to_not raise_error
end
end
context "set --active flag " do
ARGV.replace(["list", "--active"])
it "is a valid option" do
expect { capture_io { cli.start } }.to_not raise_error
end
end
context "no arguments are given" do
ARGV.replace(["list"])
it "lists all projects " do
expect { capture_io { cli.start } }.to_not raise_error
end
end
end
describe "#version" do
before do
ARGV.replace(["version"])
end
it "prints the current version" do
out, _err = capture_io { cli.start }
expect(out).to eq "tmuxinator #{Tmuxinator::VERSION}\n"
end
end
describe "#doctor" do
before do
ARGV.replace(["doctor"])
end
it "checks requirements" do
expect(Tmuxinator::Doctor).to receive(:installed?)
expect(Tmuxinator::Doctor).to receive(:editor?)
expect(Tmuxinator::Doctor).to receive(:shell?)
capture_io { cli.start }
end
end
describe "#find_project_file" do
let(:name) { "foobar" }
let(:path) { Tmuxinator::Config.default_project(name) }
after(:each) do
FileUtils.remove_file(path) if File.exist?(path)
end
context "when the project file does not already exist" do
before do
expect(File).not_to exist(path), "expected file at #{path} not to exist"
end
it "should generate a project file" do
new_path = described_class.new.find_project_file(name, local: false)
expect(new_path).to eq path
expect(File).to exist new_path
end
end
context "when the project file _does_ already exist" do
let(:extra) { " - extra: echo 'foobar'" }
before do
expect(File).not_to exist(path), "expected file at #{path} not to exist"
expect(described_class.new.generate_project_file(name, path)).to eq path
expect(File).to exist path
File.open(path, "w") do |f|
f.write(extra)
f.flush
end
expect(File.read(path)).to match %r{#{extra}}
end
it "should _not_ generate a new project file" do
new_path = described_class.new.find_project_file(name, local: false)
expect(new_path).to eq path
expect(File).to exist new_path
expect(File.read(new_path)).to match %r{#{extra}}
end
end
end
describe "#generate_project_file" do
let(:name) { "foobar-#{Time.now.to_i}" }
it "should always generate a project file" do
Dir.mktmpdir do |dir|
path = "#{dir}/#{name}.yml"
expect(File).not_to exist(path), "expected file at #{path} not to exist"
new_path = described_class.new.generate_project_file(name, path)
expect(new_path).to eq path
expect(File).to exist new_path
end
end
it "should generate a project file using the correct project file path" do
file = StringIO.new
allow(File).to receive(:open) { |&block| block.yield file }
Dir.mktmpdir do |dir|
path = "#{dir}/#{name}.yml"
_ = described_class.new.generate_project_file(name, path)
expect(file.string).to match %r{\A# #{path}$}
end
end
end
describe "#create_project" do
before do
allow(Tmuxinator::Config).to receive_messages(directory: path)
end
let(:name) { "sample" }
let(:custom_name) { nil }
let(:cli_options) { {} }
let(:path) { File.expand_path("../../fixtures", __dir__) }
shared_examples_for :a_proper_project do
it "should create a valid project" do
expect(subject).to be_a Tmuxinator::Project
expect(subject.name).to eq name
end
end
context "when creating a traditional named project" do
let(:params) do
{
name: name,
custom_name: custom_name
}
end
subject { described_class.new.create_project(params) }
it_should_behave_like :a_proper_project
end
context "attach option" do
describe "detach" do
it "sets force_detach to false when no attach argument is provided" do
project = described_class.new.create_project(name: name)
expect(project.force_detach).to eq(false)
end
it "sets force_detach to true when 'attach: false' is provided" do
project = described_class.new.create_project(attach: false,
name: name)
expect(project.force_detach).to eq(true)
end
it "sets force_detach to false when 'attach: true' is provided" do
project = described_class.new.create_project(attach: true,
name: name)
expect(project.force_detach).to eq(false)
end
end
describe "attach" do
it "sets force_attach to false when no attach argument is provided" do
project = described_class.new.create_project(name: name)
expect(project.force_attach).to eq(false)
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | true |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/util_spec.rb | spec/lib/tmuxinator/util_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Util do
let(:util) { Object.new.extend(Tmuxinator::Util) }
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/wemux_support_spec.rb | spec/lib/tmuxinator/wemux_support_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::WemuxSupport do
let(:klass) { Class.new }
let(:instance) { klass.new }
before { instance.extend Tmuxinator::WemuxSupport }
describe "#render" do
it "renders the template" do
expect(File).to receive(:read).at_least(:once) { "wemux ls 2>/dev/null" }
expect(instance.render).to match %r{wemux.ls.2>/dev/null}
end
end
describe "#name" do
it { expect(instance.name).to eq "wemux" }
end
describe "#tmux" do
it { expect(instance.tmux).to eq "wemux" }
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/config_spec.rb | spec/lib/tmuxinator/config_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Config do
let(:fixtures_dir) { File.expand_path("../../fixtures", __dir__) }
let(:xdg_config_dir) { "#{fixtures_dir}/xdg-tmuxinator" }
let(:home_config_dir) { "#{fixtures_dir}/dot-tmuxinator" }
describe "#directory" do
context "environment variable $TMUXINATOR_CONFIG non-blank" do
it "is $TMUXINATOR_CONFIG" do
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").
and_return "expected"
allow(File).to receive(:directory?).and_return true
expect(described_class.directory).to eq "expected"
end
end
context "only ~/.tmuxinator exists" do
it "is ~/.tmuxinator" do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).to receive(:xdg?).and_return false
allow(described_class).to receive(:home?).and_return true
expect(described_class.directory).to eq described_class.home
end
end
context "only $XDG_CONFIG_HOME/tmuxinator exists" do
it "is #xdg" do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).to receive(:xdg?).and_return true
allow(described_class).to receive(:home?).and_return false
expect(described_class.directory).to eq described_class.xdg
end
end
context "both $XDG_CONFIG_HOME/tmuxinator and ~/.tmuxinator exist" do
it "is #xdg" do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).to receive(:xdg?).and_return true
allow(described_class).to receive(:home?).and_return true
expect(described_class.directory).to eq described_class.xdg
end
end
context "defaulting to xdg with parent directory(s) that do not exist" do
it "creates parent directories if required" do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).to receive(:xdg?).and_return false
allow(described_class).to receive(:home?).and_return false
Dir.mktmpdir do |dir|
config_parent = "#{dir}/non_existent_parent/s"
allow(ENV).to receive(:fetch).with("XDG_CONFIG_HOME", "~/.config").
and_return config_parent
expect(described_class.directory).
to eq "#{config_parent}/tmuxinator"
expect(File.directory?("#{config_parent}/tmuxinator")).to be true
end
end
end
end
describe "#environment" do
context "environment variable $TMUXINATOR_CONFIG is not empty" do
it "is $TMUXINATOR_CONFIG" do
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").
and_return "expected"
allow(File).to receive(:directory?).and_return true
expect(described_class.environment).to eq "expected"
end
end
context "environment variable $TMUXINATOR_CONFIG is nil" do
it "is an empty string" do
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").
and_return nil
# allow(XDG).to receive(:[]).with("CONFIG").and_return nil
allow(File).to receive(:directory?).and_return true
expect(described_class.environment).to eq ""
end
end
context "environment variable $TMUXINATOR_CONFIG is set and empty" do
it "is an empty string" do
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").and_return ""
expect(described_class.environment).to eq ""
end
end
end
describe "#directories" do
context "without TMUXINATOR_CONFIG environment" do
before do
allow(described_class).to receive(:environment?).and_return false
end
it "is empty if no configuration directories exist" do
allow(File).to receive(:directory?).and_return false
expect(described_class.directories).to eq []
end
it "contains #xdg before #home" do
allow(described_class).to receive(:xdg).and_return "XDG"
allow(described_class).to receive(:home).and_return "HOME"
allow(File).to receive(:directory?).and_return true
expect(described_class.directories).to eq \
["XDG", "HOME"]
end
end
context "with TMUXINATOR_CONFIG environment" do
before do
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").
and_return "TMUXINATOR_CONFIG"
end
it "is only [$TMUXINATOR_CONFIG] if set" do
allow(File).to receive(:directory?).and_return true
expect(described_class.directories).to eq ["TMUXINATOR_CONFIG"]
end
end
end
describe "#home" do
it "is ~/.tmuxinator" do
expect(described_class.home).to eq "#{ENV['HOME']}/.tmuxinator"
end
end
describe "#xdg" do
it "is $XDG_CONFIG_HOME/tmuxinator" do
expect(described_class.xdg).to eq File.expand_path("~/.config/tmuxinator")
end
end
describe "#sample" do
it "gets the path of the sample project" do
expect(described_class.sample).to include("sample.yml")
end
end
describe "#default" do
it "gets the path of the default config" do
expect(described_class.default).to include("default.yml")
end
end
describe "#default_or_sample" do
context "with default? true" do
before do
allow(described_class).to receive(:default?).and_return true
allow(described_class).to receive(:default).and_return("default_path")
end
it "gets the default config when it exists" do
expect(described_class.default_or_sample).to eq "default_path"
end
end
context "with default? false" do
before do
allow(described_class).to receive(:default?)
allow(described_class).to receive(:sample).and_return("sample_path")
end
it "falls back to the sample config when the default is missing" do
expect(described_class.default_or_sample).to eq "sample_path"
end
end
end
describe "#version" do
subject { described_class.version }
before do
expect(Tmuxinator::Doctor).to receive(:installed?).and_return(true)
allow_any_instance_of(Kernel).to receive(:`).
with(/tmux\s-V/).
and_return("tmux #{version}")
end
version_mapping = {
"0.8" => 0.8,
"1.0" => 1.0,
"1.9" => 1.9,
"1.9a" => 1.9,
"2.4" => 2.4,
"2.9a" => 2.9,
"3.0-rc5" => 3.0,
"next-3.1" => 3.1,
"master" => Float::INFINITY,
# Failsafes
"foobar" => 0.0,
"-123-" => 123.0,
"5935" => 5935.0,
"" => 0.0,
"!@#^%" => 0.0,
"2.9ä" => 2.9,
"v3.5" => 3.5,
"v3.6" => 3.6,
"v3.6a" => 3.6,
"v3.12.0" => 3.12,
"v3.12.5" => 3.12
}.freeze
version_mapping.each do |string_version, parsed_numeric_version|
context "when reported version is '#{string_version}'" do
let(:version) { string_version }
it { is_expected.to eq parsed_numeric_version }
end
end
end
describe "#default_path_option" do
context ">= 1.8" do
before do
allow(described_class).to receive(:version).and_return(1.8)
end
it "returns -c" do
expect(described_class.default_path_option).to eq "-c"
end
end
context "< 1.8" do
before do
allow(described_class).to receive(:version).and_return(1.7)
end
it "returns default-path" do
expect(described_class.default_path_option).to eq "default-path"
end
end
end
describe "#default?" do
let(:directory) { described_class.directory }
let(:local_yml_default) { described_class::LOCAL_DEFAULTS[0] }
let(:local_yaml_default) { described_class::LOCAL_DEFAULTS[1] }
let(:proj_default) { described_class.default }
context "when the file exists" do
before do
allow(File).to receive(:exist?).with(local_yml_default) { false }
allow(File).to receive(:exist?).with(local_yaml_default) { false }
allow(File).to receive(:exist?).with(proj_default) { true }
end
it "returns true" do
expect(described_class.default?).to be_truthy
end
end
context "when the file doesn't exist" do
before do
allow(File).to receive(:exist?).with(local_yml_default) { false }
allow(File).to receive(:exist?).with(local_yaml_default) { false }
allow(File).to receive(:exist?).with(proj_default) { false }
end
it "returns true" do
expect(described_class.default?).to be_falsey
end
end
end
describe "#configs" do
before do
allow(described_class).to receive_messages(xdg: xdg_config_dir)
allow(described_class).to receive_messages(home: home_config_dir)
end
it "gets a sorted list of all projects" do
allow(described_class).to receive(:environment?).and_return false
expect(described_class.configs).
to eq ["both", "both", "dup/local-dup", "home", "local-dup", "xdg"]
end
it "gets a sorted list of all active projects" do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).
to receive(:active_sessions).
and_return ["both", "home"]
expect(described_class.configs(active: true)).
to eq ["both", "home"]
end
it "gets a sorted list excluding active projects" do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).
to receive(:active_sessions).
and_return ["both", "home"]
expect(described_class.configs(active: false)).
to eq ["dup/local-dup", "local-dup", "xdg"]
end
it "lists only projects in $TMUXINATOR_CONFIG when set" do
allow(ENV).to receive(:[]).with("TMUXINATOR_CONFIG").
and_return "#{fixtures_dir}/TMUXINATOR_CONFIG"
expect(described_class.configs).to eq ["TMUXINATOR_CONFIG"]
end
end
describe "#exist?" do
before do
allow(File).to receive_messages(exist?: true)
allow(described_class).to receive_messages(project: "")
end
it "checks if the given project exists" do
expect(described_class.exist?(name: "test")).to be_truthy
end
end
describe "#global_project" do
let(:directory) { described_class.directory }
let(:base) { "#{directory}/sample.yml" }
let(:first_dup) { "#{home_config_dir}/dup/local-dup.yml" }
let(:yaml) { "#{directory}/yaml.yaml" }
before do
allow(described_class).to receive(:environment?).and_return false
allow(described_class).to receive(:xdg).and_return fixtures_dir
allow(described_class).to receive(:home).and_return fixtures_dir
end
context "with project yml" do
it "gets the project as path to the yml file" do
expect(described_class.global_project("sample")).to eq base
end
end
context "with project yaml" do
it "gets the project as path to the yaml file" do
expect(Tmuxinator::Config.global_project("yaml")).to eq yaml
end
end
context "without project yml" do
it "gets the project as path to the yml file" do
expect(described_class.global_project("new-project")).to be_nil
end
end
context "with duplicate project files" do
it "is the first .yml file found" do
expect(described_class.global_project("local-dup")).to eq first_dup
end
end
end
describe "#local?" do
it "checks if the given project exists" do
path = described_class::LOCAL_DEFAULTS[0]
expect(File).to receive(:exist?).with(path) { true }
expect(described_class.local?).to be_truthy
end
end
describe "#local_project" do
let(:default) { described_class::LOCAL_DEFAULTS[0] }
context "with a project yml" do
it "gets the project as path to the yml file" do
expect(File).to receive(:exist?).with(default) { true }
expect(described_class.local_project).to eq default
end
end
context "without project yml" do
it "gets the project as path to the yml file" do
expect(described_class.local_project).to be_nil
end
end
end
describe "#project" do
let(:directory) { described_class.directory }
let(:default) { described_class::LOCAL_DEFAULTS[0] }
context "with an non-local project yml" do
before do
allow(described_class).to receive_messages(directory: fixtures_dir)
end
it "gets the project as path to the yml file" do
expect(described_class.project("sample")).
to eq "#{directory}/sample.yml"
end
end
context "with a local project, but no global project" do
it "gets the project as path to the yml file" do
expect(File).to receive(:exist?).with(default) { true }
expect(described_class.project("sample")).to eq "./.tmuxinator.yml"
end
end
context "without project yml" do
let(:expected) { "#{directory}/new-project.yml" }
it "gets the project as path to the yml file" do
expect(described_class.project("new-project")).to eq expected
end
end
end
describe "#validate" do
let(:local_yml_default) { described_class::LOCAL_DEFAULTS[0] }
let(:local_yaml_default) { described_class::LOCAL_DEFAULTS[1] }
context "when a project config file is provided" do
it "should raise if the project config file can't be found" do
project_config = "dont-exist.yml"
regex = /Project config \(#{project_config}\) doesn't exist\./
expect do
described_class.validate(project_config: project_config)
end.to raise_error RuntimeError, regex
end
it "should load and validate the project" do
project_config = File.join(fixtures_dir, "sample.yml")
expect(described_class.validate(project_config: project_config)).to \
be_a Tmuxinator::Project
end
it "should take precedence over a named project" do
allow(described_class).to receive_messages(directory: fixtures_dir)
project_config = File.join(fixtures_dir, "sample_number_as_name.yml")
project = described_class.validate(name: "sample",
project_config: project_config)
expect(project.name).to eq("222")
end
it "should take precedence over a local project" do
expect(described_class).not_to receive(:local?)
project_config = File.join(fixtures_dir, "sample_number_as_name.yml")
project = described_class.validate(project_config: project_config)
expect(project.name).to eq("222")
end
end
context "when a project name is provided" do
it "should raise if the project file can't be found" do
expect do
described_class.validate(name: "sample")
end.to raise_error RuntimeError, %r{Project.+doesn't.exist}
end
it "should load and validate the project" do
expect(described_class).to receive_messages(directory: fixtures_dir)
expect(described_class.validate(name: "sample")).to \
be_a Tmuxinator::Project
end
end
context "when no project name is provided" do
it "should raise if the local project file doesn't exist" do
expect(File).to receive(:exist?).with(local_yml_default) { false }
expect(File).to receive(:exist?).with(local_yaml_default) { false }
expect do
described_class.validate
end.to raise_error RuntimeError, %r{Project.+doesn't.exist}
end
context "and tmuxinator.yml exists" do
it "should load and validate the local project" do
content = File.read(File.join(fixtures_dir, "sample.yml"))
expect(File).to receive(:exist?).
with(local_yml_default).
at_least(:once) { true }
expect(File).to receive(:read).
with(local_yml_default).
and_return(content)
expect(described_class.validate).to be_a Tmuxinator::Project
end
end
context "and tmuxinator.yaml exists" do
it "should load and validate the local project" do
content = File.read(File.join(fixtures_dir, "sample.yml"))
expect(File).to receive(:exist?).
with(local_yml_default).
at_least(:once) { false }
expect(File).to receive(:exist?).
with(local_yaml_default).
at_least(:once) { true }
expect(File).to receive(:read).
with(local_yaml_default).
and_return(content)
expect(described_class.validate).to be_a Tmuxinator::Project
end
end
end
context "when no project can be found" do
it "should raise with NO_PROJECT_FOUND_MSG" do
expect(described_class).to receive_messages(
valid_project_config?: false,
valid_local_project?: false,
valid_standard_project?: false
)
expect do
described_class.validate
end.to raise_error RuntimeError, %r{Project could not be found\.}
end
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/window_spec.rb | spec/lib/tmuxinator/window_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Tmuxinator::Window do
let(:project) { double }
let(:panes) { ["vim", nil, "top"] }
let(:window_name) { "editor" }
let(:synchronize) { false }
let(:root) {}
let(:root?) { root }
let(:yaml) do
{
window_name => {
"pre" => [
"echo 'I get run in each pane. Before each pane command!'",
nil
],
"synchronize" => synchronize,
"layout" => "main-vertical",
"panes" => panes,
"root" => root,
"root?" => root?,
}
}
end
let(:window) { described_class.new(yaml, 0, project) }
shared_context "window command context" do
let(:project) { double(:project) }
let(:window) { described_class.new(yaml, 0, project) }
let(:root?) { true }
let(:root) { "/project/tmuxinator" }
before do
allow(project).to receive_messages(
name: "test",
tmux: "tmux",
root: root,
root?: root?,
base_index: 1
)
end
let(:tmux_part) { project.tmux }
end
before do
allow(project).to receive_messages(
tmux: "tmux",
name: "test",
base_index: 1,
pane_base_index: 0,
root: "/project/tmuxinator",
root?: true
)
end
describe "#initialize" do
it "creates an instance" do
expect(window).to be_a(Tmuxinator::Window)
end
end
describe "#root" do
context "without window root" do
it "gets the project root" do
expect(window.root).to include("/project/tmuxinator")
end
end
context "with absolute window root" do
let(:root) { "/project/override" }
it "gets the window root" do
expect(window.root).to include("/project/override")
end
end
context "with relative window root" do
let(:root) { "relative" }
it "joins the project root" do
expect(window.root).to include("/project/tmuxinator/relative")
end
end
end
describe "#panes" do
context "with a three element Array" do
let(:panes) { ["vim", "ls", "top"] }
it "creates three panes" do
expect(Tmuxinator::Pane).to receive(:new).exactly(3).times
window.panes
end
it "returns three panes" do
expect(window.panes).to all be_a_pane.with(
project: project, tab: window
)
expect(window.panes).to match(
[
a_pane.with(index: 0).and_commands("vim"),
a_pane.with(index: 1).and_commands("ls"),
a_pane.with(index: 2).and_commands("top")
]
)
end
end
context "with a String" do
let(:panes) { "vim" }
it "returns one pane in an Array" do
expect(window.panes.first).to be_a_pane.
with(index: 0).and_commands("vim")
end
end
context "with nil" do
let(:panes) { nil }
it "returns an empty Array" do
expect(window.panes).to be_empty
end
end
context "titled panes" do
let(:panes) do
[
{ "editor" => ["vim"] },
{ "run" => ["cmd1", "cmd2"] },
"top"
]
end
it "creates panes with titles" do
expect(window.panes).to match(
[
a_pane.with(index: 0, title: "editor").and_commands("vim"),
a_pane.with(index: 1, title: "run").and_commands("cmd1", "cmd2"),
a_pane.with(index: 2, title: nil).and_commands("top")
]
)
end
end
context "nested collections" do
let(:command1) { "cd /tmp/" }
let(:command2) { "ls" }
let(:panes) { ["vim", nested_collection] }
context "with nested hash" do
let(:nested_collection) { { pane2: [command1, command2] } }
it "returns two panes in an Array" do
expect(window.panes).to match [
a_pane.with(index: 0).and_commands("vim"),
a_pane.with(index: 1).and_commands(command1, command2)
]
end
end
context "with nested array" do
let(:nested_collection) { [command1, command2] }
it "returns two panes in an Array" do
expect(window.panes).to match [
a_pane.with(index: 0).and_commands("vim"),
a_pane.with(index: 1).and_commands(command1, command2)
]
end
end
end
end
describe "#pre" do
context "pre is a string" do
before do
yaml["editor"]["pre"] = "vim"
end
it "returns the pre command" do
expect(window.pre).to eq "vim"
end
end
context "pre is not present" do
before do
yaml["editor"].delete("pre")
end
it "returns nil" do
expect(window.pre).to be_nil
end
end
end
describe "#build_commands" do
context "command is an array" do
before do
yaml["editor"] = ["git fetch", "git status"]
end
it "returns the flattened command" do
expect(window.commands).to eq [
"tmux send-keys -t test:1 git\\ fetch C-m",
"tmux send-keys -t test:1 git\\ status C-m"
]
end
end
context "command is a string" do
before do
yaml["editor"] = "vim"
end
it "returns the command" do
expect(window.commands).to eq ["tmux send-keys -t test:1 vim C-m"]
end
end
context "command is empty" do
before do
yaml["editor"] = ""
end
it "returns an empty array" do
expect(window.commands).to be_empty
end
end
context "command is a hash" do
before do
yaml["editor"] = { "layout" => "main-horizontal", "panes" => [nil] }
end
it "returns an empty array" do
expect(window.commands).to be_empty
end
end
end
describe "#name_options" do
context "with a name" do
let(:window_name) { "editor" }
it "specifies name with tmux name option" do
expect(window.tmux_window_name_option).to eq "-n #{window_name}"
end
end
context "without a name" do
let(:window_name) { nil }
it "specifies no tmux name option" do
expect(window.tmux_window_name_option).to be_empty
end
end
end
describe "#synchronize_before?" do
subject { window.synchronize_before? }
context "synchronize is 'before'" do
let(:synchronize) { "before" }
it { is_expected.to be true }
end
context "synchronize is true" do
let(:synchronize) { true }
it { is_expected.to be true }
end
context "synchronize is 'after'" do
let(:synchronize) { "after" }
it { is_expected.to be false }
end
context "synchronization disabled" do
let(:synchronize) { false }
it { is_expected.to be false }
end
context "synchronization not specified" do
it { is_expected.to be false }
end
end
describe "#synchronize_after?" do
subject { window.synchronize_after? }
context "synchronization is 'after'" do
let(:synchronize) { "after" }
it { is_expected.to be true }
end
context "synchronization is true" do
let(:synchronize) { true }
it { is_expected.to be false }
end
context "synchronization is 'before'" do
let(:synchronize) { "before" }
it { is_expected.to be false }
end
context "synchronization disabled" do
let(:synchronize) { false }
it { is_expected.to be false }
end
context "synchronization not specified" do
it { is_expected.to be false }
end
end
describe "#tmux_synchronize_panes" do
include_context "window command context"
let(:window_option_set_part) { "set-window-option" }
let(:target_part) { "-t #{window.tmux_window_target}" }
let(:synchronize_panes_part) { "synchronize-panes" }
context "synchronization enabled" do
let(:synchronize) { true }
let(:enabled) { "on" }
let(:full_command) do
"#{tmux_part} #{window_option_set_part} #{target_part} #{synchronize_panes_part} #{enabled}"
end
it "should set the synchronize-panes window option on" do
expect(window.tmux_synchronize_panes).to eq full_command
end
end
end
describe "#tmux_new_window_command" do
include_context "window command context"
let(:window_part) { "new-window" }
let(:name_part) { window.tmux_window_name_option }
let(:target_part) { "-k -t #{window.tmux_window_target}" }
let(:path_part) { "#{path_option} #{project.root}" }
let(:path_option) { "-c" }
let(:full_command) do
"#{tmux_part} #{window_part} #{path_part} #{target_part} #{name_part}"
end
before do
allow(Tmuxinator::Config).to receive(:default_path_option) { path_option }
end
it "constructs window command with path, target, and name options" do
expect(window.tmux_new_window_command).to eq full_command
end
context "root not set" do
let(:root?) { false }
let(:root) { nil }
let(:path_part) { nil }
it "has an extra space instead of path_part" do
expect(window.tmux_new_window_command).to eq full_command
end
end
context "name not set" do
let(:window_name) { nil }
let(:full_command) do
"#{tmux_part} #{window_part} #{path_part} #{target_part} "
end
it "does not set name option" do
expect(window.tmux_new_window_command).to eq full_command
end
end
end
describe "#tmux_select_first_pane" do
it "targets the pane based on the configured pane_base_index" do
expect(window.tmux_select_first_pane).to eq("tmux select-pane -t test:1.0")
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/spec/lib/tmuxinator/hooks/project_spec.rb | spec/lib/tmuxinator/hooks/project_spec.rb | # frozen_string_literal: true
require "spec_helper"
shared_examples_for "a project hook" do
let(:project) { FactoryBot.build(:project) }
it "calls Hooks.commands_from" do
expect(Tmuxinator::Hooks).to receive(:commands_from).
with(kind_of(Tmuxinator::Project), hook_name).once
project.send("hook_#{hook_name}")
end
context "hook value is string" do
before { project.yaml[hook_name] = "echo 'on hook'" }
it "returns the string" do
expect(project.send("hook_#{hook_name}")).to eq("echo 'on hook'")
end
end
context "hook value is Array" do
before do
project.yaml[hook_name] = [
"echo 'on hook'",
"echo 'another command here'"
]
end
it "joins array using ;" do
expect(project.send("hook_#{hook_name}")).
to eq("echo 'on hook'; echo 'another command here'")
end
end
end
describe Tmuxinator::Hooks::Project do
let(:project) { FactoryBot.build(:project) }
describe "#hook_on_project_start" do
it_should_behave_like "a project hook" do
let(:hook_name) { "on_project_start" }
end
end
describe "#hook_on_project_first_start" do
it_should_behave_like "a project hook" do
let(:hook_name) { "on_project_first_start" }
end
end
describe "#hook_on_project_restart" do
it_should_behave_like "a project hook" do
let(:hook_name) { "on_project_restart" }
end
end
describe "#hook_on_project_exit" do
it_should_behave_like "a project hook" do
let(:hook_name) { "on_project_exit" }
end
end
describe "#hook_on_project_stop" do
it_should_behave_like "a project hook" do
let(:hook_name) { "on_project_stop" }
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator.rb | lib/tmuxinator.rb | # frozen_string_literal: true
require "erubi"
require "fileutils"
require "shellwords"
require "thor"
require "thor/version"
require "yaml"
module Tmuxinator
end
require "tmuxinator/tmux_version"
require "tmuxinator/util"
require "tmuxinator/deprecations"
require "tmuxinator/wemux_support"
require "tmuxinator/cli"
require "tmuxinator/config"
require "tmuxinator/doctor"
require "tmuxinator/hooks"
require "tmuxinator/hooks/project"
require "tmuxinator/pane"
require "tmuxinator/project"
require "tmuxinator/window"
require "tmuxinator/version"
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/version.rb | lib/tmuxinator/version.rb | # frozen_string_literal: true
module Tmuxinator
VERSION = "3.3.7"
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/project.rb | lib/tmuxinator/project.rb | # frozen_string_literal: true
module Tmuxinator
class Project
include Tmuxinator::Util
include Tmuxinator::Deprecations
include Tmuxinator::Hooks::Project
RBENVRVM_DEP_MSG = <<-M
DEPRECATION: rbenv/rvm-specific options have been replaced by the
`pre_tab` option and will not be supported in 0.8.0.
M
TABS_DEP_MSG = <<-M
DEPRECATION: The tabs option has been replaced by the `windows` option
and will not be supported in 0.8.0.
M
CLIARGS_DEP_MSG = <<-M
DEPRECATION: The `cli_args` option has been replaced by the `tmux_options`
option and will not be supported in 0.8.0.
M
SYNC_DEP_MSG = <<-M
DEPRECATION: The `synchronize` option's current default behaviour is to
enable pane synchronization before running commands. In a future release,
the default synchronization option will be `after`, i.e. synchronization of
panes will occur after the commands described in each of the panes
have run. At that time, the current behavior will need to be explicitly
enabled, using the `synchronize: before` option. To use this behaviour
now, use the 'synchronize: after' option.
M
PRE_DEP_MSG = <<-M
DEPRECATION: The `pre` option has been replaced by project hooks (`on_project_start` and
`on_project_restart`) and will be removed in a future release.
M
POST_DEP_MSG = <<-M
DEPRECATION: The `post` option has been replaced by project hooks (`on_project_stop` and
`on_project_exit`) and will be removed in a future release.
M
attr_reader :yaml, :force_attach, :force_detach, :custom_name,
:no_pre_window
class << self
include Tmuxinator::Util
def load(path, options = {})
yaml = begin
args = options[:args] || []
@settings = parse_settings(args)
@args = args
content = render_template(path, binding)
YAML.safe_load(content, aliases: true)
rescue SyntaxError, StandardError => e
raise "Failed to parse config file: #{e.message}"
end
new(yaml, options)
end
def parse_settings(args)
settings = args.select { |x| x.match(/.*=.*/) }
args.reject! { |x| x.match(/.*=.*/) }
settings.map! do |setting|
parts = setting.split("=", 2)
[parts[0], parts[1]]
end
Hash[settings]
end
def active
Tmuxinator::Config.configs(active: true).
map { |config| Config.validate(name: config) }
end
def stop_all
active.
sort_by { |project| project.name == current_session_name ? 1 : 0 }.
each { |project| Kernel.system(project.kill) }
end
end
def validate!
raise "Your project file should include some windows." \
unless windows?
raise "Your project file didn't specify a 'project_name'" \
unless name?
self
end
def initialize(yaml, options = {})
options[:force_attach] = false if options[:force_attach].nil?
options[:force_detach] = false if options[:force_detach].nil?
@yaml = yaml
set_instance_variables_from_options(options)
validate_options
extend Tmuxinator::WemuxSupport if wemux?
end
def set_instance_variables_from_options(options)
@custom_name = options[:custom_name]
@force_attach = options[:force_attach]
@force_detach = options[:force_detach]
@append = options[:append]
@no_pre_window = options[:no_pre_window]
end
def validate_options
if @force_attach && @force_detach
raise "Cannot force_attach and force_detach at the same time"
end
if append? && !tmux_has_session?(name)
raise "Cannot append to a session that does not exist"
end
end
def render
self.class.render_template(Tmuxinator::Config.template, binding)
end
def kill
self.class.render_template(Tmuxinator::Config.stop_template, binding)
end
def self.render_template(template, bndg)
content = File.read(template)
bndg.eval(Erubi::Engine.new(content).src)
end
def windows
windows_yml = yaml["tabs"] || yaml["windows"]
@windows ||= (windows_yml || {}).map.with_index do |window_yml, index|
Tmuxinator::Window.new(window_yml, index, self)
end
end
def root
root = yaml["project_root"] || yaml["root"]
blank?(root) ? nil : File.expand_path(root).shellescape
end
def name
name =
if append?
current_session_name
else
custom_name || yaml["project_name"] || yaml["name"]
end
blank?(name) ? nil : name.to_s.shellescape
end
def append?
@append
end
def pre
pre_config = yaml["pre"]
parsed_parameters(pre_config)
end
def attach?
yaml_attach = yaml["attach"].nil? || yaml["attach"]
force_attach || !force_detach && yaml_attach
end
def pre_window
return if no_pre_window
params = if rbenv?
"rbenv shell #{yaml['rbenv']}"
elsif rvm?
"rvm use #{yaml['rvm']}"
elsif pre_tab?
yaml["pre_tab"]
else
yaml["pre_window"]
end
parsed_parameters(params)
end
def post
post_config = yaml["post"]
parsed_parameters(post_config)
end
def tmux
"#{tmux_command}#{tmux_options}#{socket}"
end
def tmux_command
yaml["tmux_command"] || "tmux"
end
def tmux_has_session?(name)
return false unless name
# Redirect stderr to /dev/null in order to prevent "failed to connect
# to server: Connection refused" error message and non-zero exit status
# if no tmux sessions exist.
# Please see issues #402 and #414.
sessions = `#{tmux} ls 2> /dev/null`
# Remove any escape sequences added by `shellescape` in Project#name.
# Escapes can result in: "ArgumentError: invalid multibyte character"
# when attempting to match `name` against `sessions`.
# Please see issue #564.
unescaped_name = name.shellsplit.join("")
!(sessions !~ /^#{unescaped_name}:/)
end
def socket
if socket_path
" -S #{socket_path}"
elsif socket_name
" -L #{socket_name}"
end
end
def socket_name
yaml["socket_name"]
end
def socket_path
yaml["socket_path"]
end
def tmux_options
if cli_args?
" #{yaml['cli_args'].to_s.strip}"
elsif tmux_options?
" #{yaml['tmux_options'].to_s.strip}"
else
""
end
end
def last_window_index
`tmux list-windows -F '#I'`.split.last.to_i
end
def base_index
return last_window_index + 1 if append?
get_base_index.to_i
end
def pane_base_index
get_pane_base_index.to_i
end
def startup_window
"#{name}:#{yaml['startup_window'] || base_index}"
end
def startup_pane
"#{startup_window}.#{yaml['startup_pane'] || pane_base_index}"
end
def tmux_options?
yaml["tmux_options"]
end
def windows?
windows.any?
end
def root?
!root.nil?
end
def name?
!name.nil?
end
def window(index)
append? ? ":#{index}" : "#{name}:#{index}"
end
def send_pane_command(cmd, window_index, _pane_index)
send_keys(cmd, window_index)
end
def send_keys(cmd, window_index)
if cmd.empty?
""
else
"#{tmux} send-keys -t #{window(window_index)} #{cmd.shellescape} C-m"
end
end
def deprecations
deprecation_checks.zip(deprecation_messages).
inject([]) do |deps, (chk, msg)|
deps << msg if chk
deps
end
end
def deprecation_checks
[
rvm_or_rbenv?,
tabs?,
cli_args?,
legacy_synchronize?,
pre?,
post?
]
end
def deprecation_messages
[
RBENVRVM_DEP_MSG,
TABS_DEP_MSG,
CLIARGS_DEP_MSG,
SYNC_DEP_MSG,
PRE_DEP_MSG,
POST_DEP_MSG
]
end
def rbenv?
yaml["rbenv"]
end
def rvm?
yaml["rvm"]
end
def rvm_or_rbenv?
rvm? || rbenv?
end
def tabs?
yaml["tabs"]
end
def cli_args?
yaml["cli_args"]
end
def pre?
yaml["pre"]
end
def post?
yaml["post"]
end
def get_pane_base_index
tmux_config["pane-base-index"]
end
def get_base_index
tmux_config["base-index"]
end
def show_tmux_options
"#{tmux} start-server\\; " \
"show-option -g base-index\\; " \
"show-window-option -g pane-base-index\\;"
end
def tmux_new_session_command
return if append?
window = windows.first.tmux_window_name_option
"#{tmux} new-session -d -s #{name} #{window}"
end
def tmux_kill_session_command
"#{tmux} kill-session -t #{name}"
end
def enable_pane_titles?
yaml["enable_pane_titles"]
end
def tmux_set_pane_title_position(tmux_window_target)
command = set_window_option(tmux_window_target)
if pane_title_position? && pane_title_position_valid?
"#{command} pane-border-status #{yaml['pane_title_position']}"
else
"#{command} pane-border-status top"
end
end
def tmux_set_pane_title_format(tmux_window_target)
command = set_window_option(tmux_window_target)
if pane_title_format?
"#{command} pane-border-format \"#{yaml['pane_title_format']}\""
else
"#{command} pane-border-format \"\#{pane_index}: \#{pane_title}\""
end
end
def pane_title_position_not_valid_warning
print_warning(
"The specified pane title position '#{yaml['pane_title_position']}' " \
"is not valid. Please choose one of: top, bottom, or off."
)
end
def pane_titles_not_supported_warning
print_warning(
"You have enabled pane titles in your configuration, but the " \
"feature is not supported by your version of tmux.\nPlease consider " \
"upgrading to a version that supports it (tmux >=2.6)."
)
end
private
def blank?(object)
(object.respond_to?(:empty?) && object.empty?) || !object
end
def tmux_config
@tmux_config ||= extract_tmux_config
end
def extract_tmux_config
options_hash = {}
`#{show_tmux_options}`.
encode("UTF-8", invalid: :replace).
split("\n").
map do |entry|
key, value = entry.split("\s")
options_hash[key] = value
options_hash
end
options_hash
end
def legacy_synchronize?
(synchronize_options & [true, "before"]).any?
end
def synchronize_options
window_options.map do |option|
option["synchronize"] if option.is_a?(Hash)
end
end
def window_options
yaml["windows"].map(&:values).flatten
end
def parsed_parameters(parameters)
parameters.is_a?(Array) ? parameters.join("; ") : parameters
end
def wemux?
yaml["tmux_command"] == "wemux"
end
def pane_title_position?
yaml["pane_title_position"]
end
def pane_title_position_valid?
["top", "bottom", "off"].include? yaml["pane_title_position"]
end
def pane_title_format?
yaml["pane_title_format"]
end
def print_warning(message)
yellow = '\033[1;33m'
no_color = '\033[0m'
msg = "WARNING: #{message}\n"
"printf \"#{yellow}#{msg}#{no_color}\""
end
def set_window_option(tmux_window_target)
"#{tmux} set-window-option -t #{tmux_window_target}"
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
tmuxinator/tmuxinator | https://github.com/tmuxinator/tmuxinator/blob/8f8a4687c229b4d0ed725451057b32f14b476ebd/lib/tmuxinator/doctor.rb | lib/tmuxinator/doctor.rb | # frozen_string_literal: true
module Tmuxinator
class Doctor
class << self
def editor?
!ENV["EDITOR"].nil? && !ENV["EDITOR"].empty?
end
def installed?
Kernel.system("type tmux > /dev/null")
end
def shell?
!ENV["SHELL"].nil? && !ENV["SHELL"].empty?
end
end
end
end
| ruby | MIT | 8f8a4687c229b4d0ed725451057b32f14b476ebd | 2026-01-04T15:37:31.204874Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.