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
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/rake_compat.rb
lib/vendor/thor/lib/thor/rake_compat.rb
require 'rake' require 'rake/dsl_definition' class Thor # Adds a compatibility layer to your Thor classes which allows you to use # rake package tasks. For example, to use rspec rake tasks, one can do: # # require 'thor/rake_compat' # require 'rspec/core/rake_task' # # class Default < Thor # include Thor::RakeCompat # # RSpec::Core::RakeTask.new(:spec) do |t| # t.spec_opts = ['--options', "./.rspec"] # t.spec_files = FileList['spec/**/*_spec.rb'] # end # end # module RakeCompat include Rake::DSL if defined?(Rake::DSL) def self.rake_classes @rake_classes ||= [] end def self.included(base) # Hack. Make rakefile point to invoker, so rdoc task is generated properly. rakefile = File.basename(caller[0].match(/(.*):\d+/)[1]) Rake.application.instance_variable_set(:@rakefile, rakefile) self.rake_classes << base end end end # override task on (main), for compatibility with Rake 0.9 self.instance_eval do alias rake_namespace namespace def task(*) task = super if klass = Thor::RakeCompat.rake_classes.last non_namespaced_name = task.name.split(':').last description = non_namespaced_name description << task.arg_names.map{ |n| n.to_s.upcase }.join(' ') description.strip! klass.desc description, Rake.application.last_description || non_namespaced_name Rake.application.last_description = nil klass.send :define_method, non_namespaced_name do |*args| Rake::Task[task.name.to_sym].invoke(*args) end end task end def namespace(name) if klass = Thor::RakeCompat.rake_classes.last const_name = Thor::Util.camel_case(name.to_s).to_sym klass.const_set(const_name, Class.new(Thor)) new_klass = klass.const_get(const_name) Thor::RakeCompat.rake_classes << new_klass end super Thor::RakeCompat.rake_classes.pop end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/group.rb
lib/vendor/thor/lib/thor/group.rb
require 'thor/base' # Thor has a special class called Thor::Group. The main difference to Thor class # is that it invokes all commands at once. It also include some methods that allows # invocations to be done at the class method, which are not available to Thor # commands. class Thor::Group class << self # The description for this Thor::Group. If none is provided, but a source root # exists, tries to find the USAGE one folder above it, otherwise searches # in the superclass. # # ==== Parameters # description<String>:: The description for this Thor::Group. # def desc(description=nil) @desc = case description when nil @desc || from_superclass(:desc, nil) else description end end # Prints help information. # # ==== Options # short:: When true, shows only usage. # def help(shell) shell.say "Usage:" shell.say " #{banner}\n" shell.say class_options_help(shell) shell.say self.desc if self.desc end # Stores invocations for this class merging with superclass values. # def invocations #:nodoc: @invocations ||= from_superclass(:invocations, {}) end # Stores invocation blocks used on invoke_from_option. # def invocation_blocks #:nodoc: @invocation_blocks ||= from_superclass(:invocation_blocks, {}) end # Invoke the given namespace or class given. It adds an instance # method that will invoke the klass and command. You can give a block to # configure how it will be invoked. # # The namespace/class given will have its options showed on the help # usage. Check invoke_from_option for more information. # def invoke(*names, &block) options = names.last.is_a?(Hash) ? names.pop : {} verbose = options.fetch(:verbose, true) names.each do |name| invocations[name] = false invocation_blocks[name] = block if block_given? class_eval <<-METHOD, __FILE__, __LINE__ def _invoke_#{name.to_s.gsub(/\W/, '_')} klass, command = self.class.prepare_for_invocation(nil, #{name.inspect}) if klass say_status :invoke, #{name.inspect}, #{verbose.inspect} block = self.class.invocation_blocks[#{name.inspect}] _invoke_for_class_method klass, command, &block else say_status :error, %(#{name.inspect} [not found]), :red end end METHOD end end # Invoke a thor class based on the value supplied by the user to the # given option named "name". A class option must be created before this # method is invoked for each name given. # # ==== Examples # # class GemGenerator < Thor::Group # class_option :test_framework, :type => :string # invoke_from_option :test_framework # end # # ==== Boolean options # # In some cases, you want to invoke a thor class if some option is true or # false. This is automatically handled by invoke_from_option. Then the # option name is used to invoke the generator. # # ==== Preparing for invocation # # In some cases you want to customize how a specified hook is going to be # invoked. You can do that by overwriting the class method # prepare_for_invocation. The class method must necessarily return a klass # and an optional command. # # ==== Custom invocations # # You can also supply a block to customize how the option is going to be # invoked. The block receives two parameters, an instance of the current # class and the klass to be invoked. # def invoke_from_option(*names, &block) options = names.last.is_a?(Hash) ? names.pop : {} verbose = options.fetch(:verbose, :white) names.each do |name| unless class_options.key?(name) raise ArgumentError, "You have to define the option #{name.inspect} " << "before setting invoke_from_option." end invocations[name] = true invocation_blocks[name] = block if block_given? class_eval <<-METHOD, __FILE__, __LINE__ def _invoke_from_option_#{name.to_s.gsub(/\W/, '_')} return unless options[#{name.inspect}] value = options[#{name.inspect}] value = #{name.inspect} if TrueClass === value klass, command = self.class.prepare_for_invocation(#{name.inspect}, value) if klass say_status :invoke, value, #{verbose.inspect} block = self.class.invocation_blocks[#{name.inspect}] _invoke_for_class_method klass, command, &block else say_status :error, %(\#{value} [not found]), :red end end METHOD end end # Remove a previously added invocation. # # ==== Examples # # remove_invocation :test_framework # def remove_invocation(*names) names.each do |name| remove_command(name) remove_class_option(name) invocations.delete(name) invocation_blocks.delete(name) end end # Overwrite class options help to allow invoked generators options to be # shown recursively when invoking a generator. # def class_options_help(shell, groups={}) #:nodoc: get_options_from_invocations(groups, class_options) do |klass| klass.send(:get_options_from_invocations, groups, class_options) end super(shell, groups) end # Get invocations array and merge options from invocations. Those # options are added to group_options hash. Options that already exists # in base_options are not added twice. # def get_options_from_invocations(group_options, base_options) #:nodoc: invocations.each do |name, from_option| value = if from_option option = class_options[name] option.type == :boolean ? name : option.default else name end next unless value klass, _ = prepare_for_invocation(name, value) next unless klass && klass.respond_to?(:class_options) value = value.to_s human_name = value.respond_to?(:classify) ? value.classify : value group_options[human_name] ||= [] group_options[human_name] += klass.class_options.values.select do |class_option| base_options[class_option.name.to_sym].nil? && class_option.group.nil? && !group_options.values.flatten.any? { |i| i.name == class_option.name } end yield klass if block_given? end end # Returns commands ready to be printed. def printable_commands(*) item = [] item << banner item << (desc ? "# #{desc.gsub(/\s+/m,' ')}" : "") [item] end alias printable_tasks printable_commands def handle_argument_error(command, error, args, arity) #:nodoc: msg = "#{basename} #{command.name} takes #{arity} argument" msg << "s" if arity > 1 msg << ", but it should not." raise error, msg end protected # The method responsible for dispatching given the args. def dispatch(command, given_args, given_opts, config) #:nodoc: if Thor::HELP_MAPPINGS.include?(given_args.first) help(config[:shell]) return end args, opts = Thor::Options.split(given_args) opts = given_opts || opts instance = new(args, opts, config) yield instance if block_given? if command instance.invoke_command(all_commands[command]) else instance.invoke_all end end # The banner for this class. You can customize it if you are invoking the # thor class by another ways which is not the Thor::Runner. def banner "#{basename} #{self_command.formatted_usage(self, false)}" end # Represents the whole class as a command. def self_command #:nodoc: Thor::DynamicCommand.new(self.namespace, class_options) end alias self_task self_command def baseclass #:nodoc: Thor::Group end def create_command(meth) #:nodoc: commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil) true end alias create_task create_command end include Thor::Base protected # Shortcut to invoke with padding and block handling. Use internally by # invoke and invoke_from_option class methods. def _invoke_for_class_method(klass, command=nil, *args, &block) #:nodoc: with_padding do if block case block.arity when 3 block.call(self, klass, command) when 2 block.call(self, klass) when 1 instance_exec(klass, &block) end else invoke klass, command, *args end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/parser.rb
lib/vendor/thor/lib/thor/parser.rb
require 'thor/parser/argument' require 'thor/parser/arguments' require 'thor/parser/option' require 'thor/parser/options'
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/base.rb
lib/vendor/thor/lib/thor/base.rb
require 'thor/command' require 'thor/core_ext/hash_with_indifferent_access' require 'thor/core_ext/ordered_hash' require 'thor/error' require 'thor/invocation' require 'thor/parser' require 'thor/shell' require 'thor/util' class Thor autoload :Actions, 'thor/actions' autoload :RakeCompat, 'thor/rake_compat' autoload :Group, 'thor/group' # Shortcuts for help. HELP_MAPPINGS = %w(-h -? --help -D) # Thor methods that should not be overwritten by the user. THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root action add_file create_file in_root inside run run_ruby_script) module Base attr_accessor :options, :parent_options, :args # It receives arguments in an Array and two hashes, one for options and # other for configuration. # # Notice that it does not check if all required arguments were supplied. # It should be done by the parser. # # ==== Parameters # args<Array[Object]>:: An array of objects. The objects are applied to their # respective accessors declared with <tt>argument</tt>. # # options<Hash>:: An options hash that will be available as self.options. # The hash given is converted to a hash with indifferent # access, magic predicates (options.skip?) and then frozen. # # config<Hash>:: Configuration for this Thor class. # def initialize(args=[], options={}, config={}) parse_options = self.class.class_options # The start method splits inbound arguments at the first argument # that looks like an option (starts with - or --). It then calls # new, passing in the two halves of the arguments Array as the # first two parameters. if options.is_a?(Array) command_options = config.delete(:command_options) # hook for start parse_options = parse_options.merge(command_options) if command_options array_options, hash_options = options, {} else # Handle the case where the class was explicitly instantiated # with pre-parsed options. array_options, hash_options = [], options end # Let Thor::Options parse the options first, so it can remove # declared options from the array. This will leave us with # a list of arguments that weren't declared. stop_on_unknown = self.class.stop_on_unknown_option? config[:current_command] opts = Thor::Options.new(parse_options, hash_options, stop_on_unknown) self.options = opts.parse(array_options) self.options = config[:class_options].merge(self.options) if config[:class_options] # If unknown options are disallowed, make sure that none of the # remaining arguments looks like an option. opts.check_unknown! if self.class.check_unknown_options?(config) # Add the remaining arguments from the options parser to the # arguments passed in to initialize. Then remove any positional # arguments declared using #argument (this is primarily used # by Thor::Group). Tis will leave us with the remaining # positional arguments. to_parse = args to_parse += opts.remaining unless self.class.strict_args_position?(config) thor_args = Thor::Arguments.new(self.class.arguments) thor_args.parse(to_parse).each { |k,v| __send__("#{k}=", v) } @args = thor_args.remaining end class << self def included(base) #:nodoc: base.send :extend, ClassMethods base.send :include, Invocation base.send :include, Shell end # Returns the classes that inherits from Thor or Thor::Group. # # ==== Returns # Array[Class] # def subclasses @subclasses ||= [] end # Returns the files where the subclasses are kept. # # ==== Returns # Hash[path<String> => Class] # def subclass_files @subclass_files ||= Hash.new{ |h,k| h[k] = [] } end # Whenever a class inherits from Thor or Thor::Group, we should track the # class and the file on Thor::Base. This is the method responsable for it. # def register_klass_file(klass) #:nodoc: file = caller[1].match(/(.*):\d+/)[1] Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass) file_subclasses = Thor::Base.subclass_files[File.expand_path(file)] file_subclasses << klass unless file_subclasses.include?(klass) end end module ClassMethods def attr_reader(*) #:nodoc: no_commands { super } end def attr_writer(*) #:nodoc: no_commands { super } end def attr_accessor(*) #:nodoc: no_commands { super } end # If you want to raise an error for unknown options, call check_unknown_options! # This is disabled by default to allow dynamic invocations. def check_unknown_options! @check_unknown_options = true end def check_unknown_options #:nodoc: @check_unknown_options ||= from_superclass(:check_unknown_options, false) end def check_unknown_options?(config) #:nodoc: !!check_unknown_options end # If true, option parsing is suspended as soon as an unknown option or a # regular argument is encountered. All remaining arguments are passed to # the command as regular arguments. def stop_on_unknown_option?(command_name) #:nodoc: false end # If you want only strict string args (useful when cascading thor classes), # call strict_args_position! This is disabled by default to allow dynamic # invocations. def strict_args_position! @strict_args_position = true end def strict_args_position #:nodoc: @strict_args_position ||= from_superclass(:strict_args_position, false) end def strict_args_position?(config) #:nodoc: !!strict_args_position end # Adds an argument to the class and creates an attr_accessor for it. # # Arguments are different from options in several aspects. The first one # is how they are parsed from the command line, arguments are retrieved # from position: # # thor command NAME # # Instead of: # # thor command --name=NAME # # Besides, arguments are used inside your code as an accessor (self.argument), # while options are all kept in a hash (self.options). # # Finally, arguments cannot have type :default or :boolean but can be # optional (supplying :optional => :true or :required => false), although # you cannot have a required argument after a non-required argument. If you # try it, an error is raised. # # ==== Parameters # name<Symbol>:: The name of the argument. # options<Hash>:: Described below. # # ==== Options # :desc - Description for the argument. # :required - If the argument is required or not. # :optional - If the argument is optional or not. # :type - The type of the argument, can be :string, :hash, :array, :numeric. # :default - Default value for this argument. It cannot be required and have default values. # :banner - String to show on usage notes. # # ==== Errors # ArgumentError:: Raised if you supply a required argument after a non required one. # def argument(name, options={}) is_thor_reserved_word?(name, :argument) no_commands { attr_accessor name } required = if options.key?(:optional) !options[:optional] elsif options.key?(:required) options[:required] else options[:default].nil? end remove_argument name arguments.each do |argument| next if argument.required? raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " << "the non-required argument #{argument.human_name.inspect}." end if required options[:required] = required arguments << Thor::Argument.new(name, options) end # Returns this class arguments, looking up in the ancestors chain. # # ==== Returns # Array[Thor::Argument] # def arguments @arguments ||= from_superclass(:arguments, []) end # Adds a bunch of options to the set of class options. # # class_options :foo => false, :bar => :required, :baz => :string # # If you prefer more detailed declaration, check class_option. # # ==== Parameters # Hash[Symbol => Object] # def class_options(options=nil) @class_options ||= from_superclass(:class_options, {}) build_options(options, @class_options) if options @class_options end # Adds an option to the set of class options # # ==== Parameters # name<Symbol>:: The name of the argument. # options<Hash>:: Described below. # # ==== Options # :desc:: -- Description for the argument. # :required:: -- If the argument is required or not. # :default:: -- Default value for this argument. # :group:: -- The group for this options. Use by class options to output options in different levels. # :aliases:: -- Aliases for this option. <b>Note:</b> Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wouldn't be parsed; use either "\--something" or "-s" instead. # :type:: -- The type of the argument, can be :string, :hash, :array, :numeric or :boolean. # :banner:: -- String to show on usage notes. # :hide:: -- If you want to hide this option from the help. # def class_option(name, options={}) build_option(name, options, class_options) end # Removes a previous defined argument. If :undefine is given, undefine # accessors as well. # # ==== Parameters # names<Array>:: Arguments to be removed # # ==== Examples # # remove_argument :foo # remove_argument :foo, :bar, :baz, :undefine => true # def remove_argument(*names) options = names.last.is_a?(Hash) ? names.pop : {} names.each do |name| arguments.delete_if { |a| a.name == name.to_s } undef_method name, "#{name}=" if options[:undefine] end end # Removes a previous defined class option. # # ==== Parameters # names<Array>:: Class options to be removed # # ==== Examples # # remove_class_option :foo # remove_class_option :foo, :bar, :baz # def remove_class_option(*names) names.each do |name| class_options.delete(name) end end # Defines the group. This is used when thor list is invoked so you can specify # that only commands from a pre-defined group will be shown. Defaults to standard. # # ==== Parameters # name<String|Symbol> # def group(name=nil) @group = case name when nil @group || from_superclass(:group, 'standard') else name.to_s end end # Returns the commands for this Thor class. # # ==== Returns # OrderedHash:: An ordered hash with commands names as keys and Thor::Command # objects as values. # def commands @commands ||= Thor::CoreExt::OrderedHash.new end alias tasks commands # Returns the commands for this Thor class and all subclasses. # # ==== Returns # OrderedHash:: An ordered hash with commands names as keys and Thor::Command # objects as values. # def all_commands @all_commands ||= from_superclass(:all_commands, Thor::CoreExt::OrderedHash.new) @all_commands.merge(commands) end alias all_tasks all_commands # Removes a given command from this Thor class. This is usually done if you # are inheriting from another class and don't want it to be available # anymore. # # By default it only remove the mapping to the command. But you can supply # :undefine => true to undefine the method from the class as well. # # ==== Parameters # name<Symbol|String>:: The name of the command to be removed # options<Hash>:: You can give :undefine => true if you want commands the method # to be undefined from the class as well. # def remove_command(*names) options = names.last.is_a?(Hash) ? names.pop : {} names.each do |name| commands.delete(name.to_s) all_commands.delete(name.to_s) undef_method name if options[:undefine] end end alias remove_task remove_command # All methods defined inside the given block are not added as commands. # # So you can do: # # class MyScript < Thor # no_commands do # def this_is_not_a_command # end # end # end # # You can also add the method and remove it from the command list: # # class MyScript < Thor # def this_is_not_a_command # end # remove_command :this_is_not_a_command # end # def no_commands @no_commands = true yield ensure @no_commands = false end alias no_tasks no_commands # Sets the namespace for the Thor or Thor::Group class. By default the # namespace is retrieved from the class name. If your Thor class is named # Scripts::MyScript, the help method, for example, will be called as: # # thor scripts:my_script -h # # If you change the namespace: # # namespace :my_scripts # # You change how your commands are invoked: # # thor my_scripts -h # # Finally, if you change your namespace to default: # # namespace :default # # Your commands can be invoked with a shortcut. Instead of: # # thor :my_command # def namespace(name=nil) @namespace = case name when nil @namespace || Thor::Util.namespace_from_thor_class(self) else @namespace = name.to_s end end # Parses the command and options from the given args, instantiate the class # and invoke the command. This method is used when the arguments must be parsed # from an array. If you are inside Ruby and want to use a Thor class, you # can simply initialize it: # # script = MyScript.new(args, options, config) # script.invoke(:command, first_arg, second_arg, third_arg) # def start(given_args=ARGV, config={}) config[:shell] ||= Thor::Base.shell.new dispatch(nil, given_args.dup, nil, config) rescue Thor::Error => e ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message) exit(1) if exit_on_failure? rescue Errno::EPIPE # This happens if a thor command is piped to something like `head`, # which closes the pipe when it's done reading. This will also # mean that if the pipe is closed, further unnecessary # computation will not occur. exit(0) end # Allows to use private methods from parent in child classes as commands. # # ==== Parameters # names<Array>:: Method names to be used as commands # # ==== Examples # # public_command :foo # public_command :foo, :bar, :baz # def public_command(*names) names.each do |name| class_eval "def #{name}(*); super end" end end alias public_task public_command def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc: if has_namespace raise UndefinedCommandError, "Could not find command #{command.inspect} in #{namespace.inspect} namespace." else raise UndefinedCommandError, "Could not find command #{command.inspect}." end end alias handle_no_task_error handle_no_command_error def handle_argument_error(command, error, args, arity) #:nodoc: msg = "ERROR: #{basename} #{command.name} was called with " msg << 'no arguments' if args.empty? msg << 'arguments ' << args.inspect if !args.empty? msg << "\nUsage: #{self.banner(command).inspect}." raise InvocationError, msg end protected # Prints the class options per group. If an option does not belong to # any group, it's printed as Class option. # def class_options_help(shell, groups={}) #:nodoc: # Group options by group class_options.each do |_, value| groups[value.group] ||= [] groups[value.group] << value end # Deal with default group global_options = groups.delete(nil) || [] print_options(shell, global_options) # Print all others groups.each do |group_name, options| print_options(shell, options, group_name) end end # Receives a set of options and print them. def print_options(shell, options, group_name=nil) return if options.empty? list = [] padding = options.collect{ |o| o.aliases.size }.max.to_i * 4 options.each do |option| unless option.hide item = [ option.usage(padding) ] item.push(option.description ? "# #{option.description}" : "") list << item list << [ "", "# Default: #{option.default}" ] if option.show_default? list << [ "", "# Possible values: #{option.enum.join(', ')}" ] if option.enum end end shell.say(group_name ? "#{group_name} options:" : "Options:") shell.print_table(list, :indent => 2) shell.say "" end # Raises an error if the word given is a Thor reserved word. def is_thor_reserved_word?(word, type) #:nodoc: return false unless THOR_RESERVED_WORDS.include?(word.to_s) raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}" end # Build an option and adds it to the given scope. # # ==== Parameters # name<Symbol>:: The name of the argument. # options<Hash>:: Described in both class_option and method_option. # scope<Hash>:: Options hash that is being built up def build_option(name, options, scope) #:nodoc: scope[name] = Thor::Option.new(name, options) end # Receives a hash of options, parse them and add to the scope. This is a # fast way to set a bunch of options: # # build_options :foo => true, :bar => :required, :baz => :string # # ==== Parameters # Hash[Symbol => Object] def build_options(options, scope) #:nodoc: options.each do |key, value| scope[key] = Thor::Option.parse(key, value) end end # Finds a command with the given name. If the command belongs to the current # class, just return it, otherwise dup it and add the fresh copy to the # current command hash. def find_and_refresh_command(name) #:nodoc: command = if command = commands[name.to_s] command elsif command = all_commands[name.to_s] commands[name.to_s] = command.clone else raise ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found." end end alias find_and_refresh_task find_and_refresh_command # Everytime someone inherits from a Thor class, register the klass # and file into baseclass. def inherited(klass) Thor::Base.register_klass_file(klass) klass.instance_variable_set(:@no_commands, false) end # Fire this callback whenever a method is added. Added methods are # tracked as commands by invoking the create_command method. def method_added(meth) meth = meth.to_s if meth == "initialize" initialize_added return end # Return if it's not a public instance method return unless public_method_defined?(meth.to_sym) return if @no_commands || !create_command(meth) is_thor_reserved_word?(meth, :command) Thor::Base.register_klass_file(self) end # Retrieves a value from superclass. If it reaches the baseclass, # returns default. def from_superclass(method, default=nil) if self == baseclass || !superclass.respond_to?(method, true) default else value = superclass.send(method) if value if value.is_a?(TrueClass) || value.is_a?(Symbol) value else value.dup end end end end # A flag that makes the process exit with status 1 if any error happens. def exit_on_failure? false end # # The basename of the program invoking the thor class. # def basename File.basename($0).split(' ').first end # SIGNATURE: Sets the baseclass. This is where the superclass lookup # finishes. def baseclass #:nodoc: end # SIGNATURE: Creates a new command if valid_command? is true. This method is # called when a new method is added to the class. def create_command(meth) #:nodoc: end alias create_task create_command # SIGNATURE: Defines behavior when the initialize method is added to the # class. def initialize_added #:nodoc: end # SIGNATURE: The hook invoked by start. def dispatch(command, given_args, given_opts, config) #:nodoc: raise NotImplementedError end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/runner.rb
lib/vendor/thor/lib/thor/runner.rb
require 'thor' require 'thor/group' require 'thor/core_ext/io_binary_read' require 'fileutils' require 'open-uri' require 'yaml' require 'digest/md5' require 'pathname' class Thor::Runner < Thor #:nodoc: map "-T" => :list, "-i" => :install, "-u" => :update, "-v" => :version # Override Thor#help so it can give information about any class and any method. # def help(meth = nil) if meth && !self.respond_to?(meth) initialize_thorfiles(meth) klass, command = Thor::Util.find_class_and_command_by_namespace(meth) self.class.handle_no_command_error(command, false) if klass.nil? klass.start(["-h", command].compact, :shell => self.shell) else super end end # If a command is not found on Thor::Runner, method missing is invoked and # Thor::Runner is then responsible for finding the command in all classes. # def method_missing(meth, *args) meth = meth.to_s initialize_thorfiles(meth) klass, command = Thor::Util.find_class_and_command_by_namespace(meth) self.class.handle_no_command_error(command, false) if klass.nil? args.unshift(command) if command klass.start(args, :shell => self.shell) end desc "install NAME", "Install an optionally named Thor file into your system commands" method_options :as => :string, :relative => :boolean, :force => :boolean def install(name) initialize_thorfiles # If a directory name is provided as the argument, look for a 'main.thor' # command in said directory. begin if File.directory?(File.expand_path(name)) base, package = File.join(name, "main.thor"), :directory contents = open(base) {|input| input.read } else base, package = name, :file contents = open(name) {|input| input.read } end rescue OpenURI::HTTPError raise Error, "Error opening URI '#{name}'" rescue Errno::ENOENT raise Error, "Error opening file '#{name}'" end say "Your Thorfile contains:" say contents unless options["force"] return false if no?("Do you wish to continue [y/N]?") end as = options["as"] || begin first_line = contents.split("\n")[0] (match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil end unless as basename = File.basename(name) as = ask("Please specify a name for #{name} in the system repository [#{basename}]:") as = basename if as.empty? end location = if options[:relative] || name =~ /^https?:\/\// name else File.expand_path(name) end thor_yaml[as] = { :filename => Digest::MD5.hexdigest(name + as), :location => location, :namespaces => Thor::Util.namespaces_in_content(contents, base) } save_yaml(thor_yaml) say "Storing thor file in your system repository" destination = File.join(thor_root, thor_yaml[as][:filename]) if package == :file File.open(destination, "w") { |f| f.puts contents } else FileUtils.cp_r(name, destination) end thor_yaml[as][:filename] # Indicate success end desc "version", "Show Thor version" def version require 'thor/version' say "Thor #{Thor::VERSION}" end desc "uninstall NAME", "Uninstall a named Thor module" def uninstall(name) raise Error, "Can't find module '#{name}'" unless thor_yaml[name] say "Uninstalling #{name}." FileUtils.rm_rf(File.join(thor_root, "#{thor_yaml[name][:filename]}")) thor_yaml.delete(name) save_yaml(thor_yaml) puts "Done." end desc "update NAME", "Update a Thor file from its original location" def update(name) raise Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location] say "Updating '#{name}' from #{thor_yaml[name][:location]}" old_filename = thor_yaml[name][:filename] self.options = self.options.merge("as" => name) if File.directory? File.expand_path(name) FileUtils.rm_rf(File.join(thor_root, old_filename)) thor_yaml.delete(old_filename) save_yaml(thor_yaml) filename = install(name) else filename = install(thor_yaml[name][:location]) end unless filename == old_filename File.delete(File.join(thor_root, old_filename)) end end desc "installed", "List the installed Thor modules and commands" method_options :internal => :boolean def installed initialize_thorfiles(nil, true) display_klasses(true, options["internal"]) end desc "list [SEARCH]", "List the available thor commands (--substring means .*SEARCH)" method_options :substring => :boolean, :group => :string, :all => :boolean, :debug => :boolean def list(search="") initialize_thorfiles search = ".*#{search}" if options["substring"] search = /^#{search}.*/i group = options[:group] || "standard" klasses = Thor::Base.subclasses.select do |k| (options[:all] || k.group == group) && k.namespace =~ search end display_klasses(false, false, klasses) end private def self.banner(command, all = false, subcommand = false) "thor " + command.formatted_usage(self, all, subcommand) end def thor_root Thor::Util.thor_root end def thor_yaml @thor_yaml ||= begin yaml_file = File.join(thor_root, "thor.yml") yaml = YAML.load_file(yaml_file) if File.exists?(yaml_file) yaml || {} end end # Save the yaml file. If none exists in thor root, creates one. # def save_yaml(yaml) yaml_file = File.join(thor_root, "thor.yml") unless File.exists?(yaml_file) FileUtils.mkdir_p(thor_root) yaml_file = File.join(thor_root, "thor.yml") FileUtils.touch(yaml_file) end File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml } end def self.exit_on_failure? true end # Load the Thorfiles. If relevant_to is supplied, looks for specific files # in the thor_root instead of loading them all. # # By default, it also traverses the current path until find Thor files, as # described in thorfiles. This look up can be skipped by suppliying # skip_lookup true. # def initialize_thorfiles(relevant_to=nil, skip_lookup=false) thorfiles(relevant_to, skip_lookup).each do |f| Thor::Util.load_thorfile(f, nil, options[:debug]) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f)) end end # Finds Thorfiles by traversing from your current directory down to the root # directory of your system. If at any time we find a Thor file, we stop. # # We also ensure that system-wide Thorfiles are loaded first, so local # Thorfiles can override them. # # ==== Example # # If we start at /Users/wycats/dev/thor ... # # 1. /Users/wycats/dev/thor # 2. /Users/wycats/dev # 3. /Users/wycats <-- we find a Thorfile here, so we stop # # Suppose we start at c:\Documents and Settings\james\dev\thor ... # # 1. c:\Documents and Settings\james\dev\thor # 2. c:\Documents and Settings\james\dev # 3. c:\Documents and Settings\james # 4. c:\Documents and Settings # 5. c:\ <-- no Thorfiles found! # def thorfiles(relevant_to=nil, skip_lookup=false) thorfiles = [] unless skip_lookup Pathname.pwd.ascend do |path| thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten break unless thorfiles.empty? end end files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob) files += thorfiles files -= ["#{thor_root}/thor.yml"] files.map! do |file| File.directory?(file) ? File.join(file, "main.thor") : file end end # Load Thorfiles relevant to the given method. If you provide "foo:bar" it # will load all thor files in the thor.yaml that has "foo" e "foo:bar" # namespaces registered. # def thorfiles_relevant_to(meth) lookup = [ meth, meth.split(":")[0...-1].join(":") ] files = thor_yaml.select do |k, v| v[:namespaces] && !(v[:namespaces] & lookup).empty? end files.map { |k, v| File.join(thor_root, "#{v[:filename]}") } end # Display information about the given klasses. If with_module is given, # it shows a table with information extracted from the yaml file. # def display_klasses(with_modules=false, show_internal=false, klasses=Thor::Base.subclasses) klasses -= [Thor, Thor::Runner, Thor::Group] unless show_internal raise Error, "No Thor commands available" if klasses.empty? show_modules if with_modules && !thor_yaml.empty? list = Hash.new { |h,k| h[k] = [] } groups = klasses.select { |k| k.ancestors.include?(Thor::Group) } # Get classes which inherit from Thor (klasses - groups).each { |k| list[k.namespace.split(":").first] += k.printable_commands(false) } # Get classes which inherit from Thor::Base groups.map! { |k| k.printable_commands(false).first } list["root"] = groups # Order namespaces with default coming first list = list.sort{ |a,b| a[0].sub(/^default/, '') <=> b[0].sub(/^default/, '') } list.each { |n, commands| display_commands(n, commands) unless commands.empty? } end def display_commands(namespace, list) #:nodoc: list.sort!{ |a,b| a[0] <=> b[0] } say shell.set_color(namespace, :blue, true) say "-" * namespace.size print_table(list, :truncate => true) say end alias display_tasks display_commands def show_modules #:nodoc: info = [] labels = ["Modules", "Namespaces"] info << labels info << [ "-" * labels[0].size, "-" * labels[1].size ] thor_yaml.each do |name, hash| info << [ name, hash[:namespaces].join(", ") ] end print_table info say "" end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/shell.rb
lib/vendor/thor/lib/thor/shell.rb
require 'rbconfig' class Thor module Base # Returns the shell used in all Thor classes. If you are in a Unix platform # it will use a colored log, otherwise it will use a basic one without color. # def self.shell @shell ||= if ENV['THOR_SHELL'] && ENV['THOR_SHELL'].size > 0 Thor::Shell.const_get(ENV['THOR_SHELL']) elsif ((RbConfig::CONFIG['host_os'] =~ /mswin|mingw/) && !(ENV['ANSICON'])) Thor::Shell::Basic else Thor::Shell::Color end end # Sets the shell used in all Thor classes. # def self.shell=(klass) @shell = klass end end module Shell SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width] autoload :Basic, 'thor/shell/basic' autoload :Color, 'thor/shell/color' autoload :HTML, 'thor/shell/html' # Add shell to initialize config values. # # ==== Configuration # shell<Object>:: An instance of the shell to be used. # # ==== Examples # # class MyScript < Thor # argument :first, :type => :numeric # end # # MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new # def initialize(args=[], options={}, config={}) super self.shell = config[:shell] self.shell.base ||= self if self.shell.respond_to?(:base) end # Holds the shell for the given Thor instance. If no shell is given, # it gets a default shell from Thor::Base.shell. def shell @shell ||= Thor::Base.shell.new end # Sets the shell for this thor class. def shell=(shell) @shell = shell end # Common methods that are delegated to the shell. SHELL_DELEGATED_METHODS.each do |method| module_eval <<-METHOD, __FILE__, __LINE__ def #{method}(*args,&block) shell.#{method}(*args,&block) end METHOD end # Yields the given block with padding. def with_padding shell.padding += 1 yield ensure shell.padding -= 1 end protected # Allow shell to be shared between invocations. # def _shared_configuration #:nodoc: super.merge!(:shell => self.shell) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/invocation.rb
lib/vendor/thor/lib/thor/invocation.rb
class Thor module Invocation def self.included(base) #:nodoc: base.extend ClassMethods end module ClassMethods # This method is responsible for receiving a name and find the proper # class and command for it. The key is an optional parameter which is # available only in class methods invocations (i.e. in Thor::Group). def prepare_for_invocation(key, name) #:nodoc: case name when Symbol, String Thor::Util.find_class_and_command_by_namespace(name.to_s, !key) else name end end end # Make initializer aware of invocations and the initialization args. def initialize(args=[], options={}, config={}, &block) #:nodoc: @_invocations = config[:invocations] || Hash.new { |h,k| h[k] = [] } @_initializer = [ args, options, config ] super end # Receives a name and invokes it. The name can be a string (either "command" or # "namespace:command"), a Thor::Command, a Class or a Thor instance. If the # command cannot be guessed by name, it can also be supplied as second argument. # # You can also supply the arguments, options and configuration values for # the command to be invoked, if none is given, the same values used to # initialize the invoker are used to initialize the invoked. # # When no name is given, it will invoke the default command of the current class. # # ==== Examples # # class A < Thor # def foo # invoke :bar # invoke "b:hello", ["José"] # end # # def bar # invoke "b:hello", ["José"] # end # end # # class B < Thor # def hello(name) # puts "hello #{name}" # end # end # # You can notice that the method "foo" above invokes two commands: "bar", # which belongs to the same class and "hello" which belongs to the class B. # # By using an invocation system you ensure that a command is invoked only once. # In the example above, invoking "foo" will invoke "b:hello" just once, even # if it's invoked later by "bar" method. # # When class A invokes class B, all arguments used on A initialization are # supplied to B. This allows lazy parse of options. Let's suppose you have # some rspec commands: # # class Rspec < Thor::Group # class_option :mock_framework, :type => :string, :default => :rr # # def invoke_mock_framework # invoke "rspec:#{options[:mock_framework]}" # end # end # # As you noticed, it invokes the given mock framework, which might have its # own options: # # class Rspec::RR < Thor::Group # class_option :style, :type => :string, :default => :mock # end # # Since it's not rspec concern to parse mock framework options, when RR # is invoked all options are parsed again, so RR can extract only the options # that it's going to use. # # If you want Rspec::RR to be initialized with its own set of options, you # have to do that explicitly: # # invoke "rspec:rr", [], :style => :foo # # Besides giving an instance, you can also give a class to invoke: # # invoke Rspec::RR, [], :style => :foo # def invoke(name=nil, *args) if name.nil? warn "[Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}" return invoke_all end args.unshift(nil) if Array === args.first || NilClass === args.first command, args, opts, config = args klass, command = _retrieve_class_and_command(name, command) raise "Expected Thor class, got #{klass}" unless klass <= Thor::Base args, opts, config = _parse_initialization_options(args, opts, config) klass.send(:dispatch, command, args, opts, config) do |instance| instance.parent_options = options end end # Invoke the given command if the given args. def invoke_command(command, *args) #:nodoc: current = @_invocations[self.class] unless current.include?(command.name) current << command.name command.run(self, *args) end end alias invoke_task invoke_command # Invoke all commands for the current instance. def invoke_all #:nodoc: self.class.all_commands.map { |_, command| invoke_command(command) } end # Invokes using shell padding. def invoke_with_padding(*args) with_padding { invoke(*args) } end protected # Configuration values that are shared between invocations. def _shared_configuration #:nodoc: { :invocations => @_invocations } end # This method simply retrieves the class and command to be invoked. # If the name is nil or the given name is a command in the current class, # use the given name and return self as class. Otherwise, call # prepare_for_invocation in the current class. def _retrieve_class_and_command(name, sent_command=nil) #:nodoc: case when name.nil? [self.class, nil] when self.class.all_commands[name.to_s] [self.class, name.to_s] else klass, command = self.class.prepare_for_invocation(nil, name) [klass, command || sent_command] end end alias _retrieve_class_and_task _retrieve_class_and_command # Initialize klass using values stored in the @_initializer. def _parse_initialization_options(args, opts, config) #:nodoc: stored_args, stored_opts, stored_config = @_initializer args ||= stored_args.dup opts ||= stored_opts.dup config ||= {} config = stored_config.merge(_shared_configuration).merge!(config) [ args, opts, config ] end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/error.rb
lib/vendor/thor/lib/thor/error.rb
class Thor # Thor::Error is raised when it's caused by wrong usage of thor classes. Those # errors have their backtrace suppressed and are nicely shown to the user. # # Errors that are caused by the developer, like declaring a method which # overwrites a thor keyword, it SHOULD NOT raise a Thor::Error. This way, we # ensure that developer errors are shown with full backtrace. class Error < StandardError end # Raised when a command was not found. class UndefinedCommandError < Error end UndefinedTaskError = UndefinedCommandError # Raised when a command was found, but not invoked properly. class InvocationError < Error end class UnknownArgumentError < Error end class RequiredArgumentMissingError < InvocationError end class MalformattedArgumentError < InvocationError end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/util.rb
lib/vendor/thor/lib/thor/util.rb
require 'rbconfig' class Thor module Sandbox #:nodoc: end # This module holds several utilities: # # 1) Methods to convert thor namespaces to constants and vice-versa. # # Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz" # # 2) Loading thor files and sandboxing: # # Thor::Util.load_thorfile("~/.thor/foo") # module Util class << self # Receives a namespace and search for it in the Thor::Base subclasses. # # ==== Parameters # namespace<String>:: The namespace to search for. # def find_by_namespace(namespace) namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/ Thor::Base.subclasses.find { |klass| klass.namespace == namespace } end # Receives a constant and converts it to a Thor namespace. Since Thor # commands can be added to a sandbox, this method is also responsable for # removing the sandbox namespace. # # This method should not be used in general because it's used to deal with # older versions of Thor. On current versions, if you need to get the # namespace from a class, just call namespace on it. # # ==== Parameters # constant<Object>:: The constant to be converted to the thor path. # # ==== Returns # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz" # def namespace_from_thor_class(constant) constant = constant.to_s.gsub(/^Thor::Sandbox::/, "") constant = snake_case(constant).squeeze(":") constant end # Given the contents, evaluate it inside the sandbox and returns the # namespaces defined in the sandbox. # # ==== Parameters # contents<String> # # ==== Returns # Array[Object] # def namespaces_in_content(contents, file=__FILE__) old_constants = Thor::Base.subclasses.dup Thor::Base.subclasses.clear load_thorfile(file, contents) new_constants = Thor::Base.subclasses.dup Thor::Base.subclasses.replace(old_constants) new_constants.map!{ |c| c.namespace } new_constants.compact! new_constants end # Returns the thor classes declared inside the given class. # def thor_classes_in(klass) stringfied_constants = klass.constants.map { |c| c.to_s } Thor::Base.subclasses.select do |subclass| next unless subclass.name stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", '')) end end # Receives a string and convert it to snake case. SnakeCase returns snake_case. # # ==== Parameters # String # # ==== Returns # String # def snake_case(str) return str.downcase if str =~ /^[A-Z_]+$/ str.gsub(/\B[A-Z]/, '_\&').squeeze('_') =~ /_*(.*)/ return $+.downcase end # Receives a string and convert it to camel case. camel_case returns CamelCase. # # ==== Parameters # String # # ==== Returns # String # def camel_case(str) return str if str !~ /_/ && str =~ /[A-Z]+.*/ str.split('_').map { |i| i.capitalize }.join end # Receives a namespace and tries to retrieve a Thor or Thor::Group class # from it. It first searches for a class using the all the given namespace, # if it's not found, removes the highest entry and searches for the class # again. If found, returns the highest entry as the class name. # # ==== Examples # # class Foo::Bar < Thor # def baz # end # end # # class Baz::Foo < Thor::Group # end # # Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default command # Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil # Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz" # # ==== Parameters # namespace<String> # def find_class_and_command_by_namespace(namespace, fallback = true) if namespace.include?(?:) # look for a namespaced command pieces = namespace.split(":") command = pieces.pop klass = Thor::Util.find_by_namespace(pieces.join(":")) end unless klass # look for a Thor::Group with the right name klass, command = Thor::Util.find_by_namespace(namespace), nil end if !klass && fallback # try a command in the default namespace command = namespace klass = Thor::Util.find_by_namespace('') end return klass, command end alias find_class_and_task_by_namespace find_class_and_command_by_namespace # Receives a path and load the thor file in the path. The file is evaluated # inside the sandbox to avoid namespacing conflicts. # def load_thorfile(path, content=nil, debug=false) content ||= File.binread(path) begin Thor::Sandbox.class_eval(content, path) rescue Exception => e $stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}") if debug $stderr.puts(*e.backtrace) else $stderr.puts(e.backtrace.first) end end end def user_home @@user_home ||= if ENV["HOME"] ENV["HOME"] elsif ENV["USERPROFILE"] ENV["USERPROFILE"] elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"] File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"]) elsif ENV["APPDATA"] ENV["APPDATA"] else begin File.expand_path("~") rescue if File::ALT_SEPARATOR "C:/" else "/" end end end end # Returns the root where thor files are located, depending on the OS. # def thor_root File.join(user_home, ".thor").gsub(/\\/, '/') end # Returns the files in the thor root. On Windows thor_root will be something # like this: # # C:\Documents and Settings\james\.thor # # If we don't #gsub the \ character, Dir.glob will fail. # def thor_root_glob files = Dir["#{escape_globs(thor_root)}/*"] files.map! do |file| File.directory?(file) ? File.join(file, "main.thor") : file end end # Where to look for Thor files. # def globs_for(path) path = escape_globs(path) ["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"] end # Return the path to the ruby interpreter taking into account multiple # installations and windows extensions. # def ruby_command @ruby_command ||= begin ruby_name = RbConfig::CONFIG['ruby_install_name'] ruby = File.join(RbConfig::CONFIG['bindir'], ruby_name) ruby << RbConfig::CONFIG['EXEEXT'] # avoid using different name than ruby (on platforms supporting links) if ruby_name != 'ruby' && File.respond_to?(:readlink) begin alternate_ruby = File.join(RbConfig::CONFIG['bindir'], 'ruby') alternate_ruby << RbConfig::CONFIG['EXEEXT'] # ruby is a symlink if File.symlink? alternate_ruby linked_ruby = File.readlink alternate_ruby # symlink points to 'ruby_install_name' ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby end rescue NotImplementedError # just ignore on windows end end # escape string in case path to ruby executable contain spaces. ruby.sub!(/.*\s.*/m, '"\&"') ruby end end # Returns a string that has had any glob characters escaped. # The glob characters are `* ? { } [ ]`. # # ==== Examples # # Thor::Util.escape_globs('[apps]') # => '\[apps\]' # # ==== Parameters # String # # ==== Returns # String # def escape_globs(path) path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&') end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions/directory.rb
lib/vendor/thor/lib/thor/actions/directory.rb
require 'thor/actions/empty_directory' class Thor module Actions # Copies recursively the files from source directory to root directory. # If any of the files finishes with .tt, it's considered to be a template # and is placed in the destination without the extension .tt. If any # empty directory is found, it's copied and all .empty_directory files are # ignored. If any file name is wrapped within % signs, the text within # the % signs will be executed as a method and replaced with the returned # value. Let's suppose a doc directory with the following files: # # doc/ # components/.empty_directory # README # rdoc.rb.tt # %app_name%.rb # # When invoked as: # # directory "doc" # # It will create a doc directory in the destination with the following # files (assuming that the `app_name` method returns the value "blog"): # # doc/ # components/ # README # rdoc.rb # blog.rb # # <b>Encoded path note:</b> Since Thor internals use Object#respond_to? to check if it can # expand %something%, this `something` should be a public method in the class calling # #directory. If a method is private, Thor stack raises PrivateMethodEncodedError. # # ==== Parameters # source<String>:: the relative path to the source root. # destination<String>:: the relative path to the destination root. # config<Hash>:: give :verbose => false to not log the status. # If :recursive => false, does not look for paths recursively. # If :mode => :preserve, preserve the file mode from the source. # If :exclude_pattern => /regexp/, prevents copying files that match that regexp. # # ==== Examples # # directory "doc" # directory "doc", "docs", :recursive => false # def directory(source, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} destination = args.first || source action Directory.new(self, source, destination || source, config, &block) end class Directory < EmptyDirectory #:nodoc: attr_reader :source def initialize(base, source, destination=nil, config={}, &block) @source = File.expand_path(base.find_in_source_paths(source.to_s)) @block = block super(base, destination, { :recursive => true }.merge(config)) end def invoke! base.empty_directory given_destination, config execute! end def revoke! execute! end protected def execute! lookup = Util.escape_globs(source) lookup = config[:recursive] ? File.join(lookup, '**') : lookup lookup = file_level_lookup(lookup) files(lookup).sort.each do |file_source| next if File.directory?(file_source) next if config[:exclude_pattern] && file_source.match(config[:exclude_pattern]) file_destination = File.join(given_destination, file_source.gsub(source, '.')) file_destination.gsub!('/./', '/') case file_source when /\.empty_directory$/ dirname = File.dirname(file_destination).gsub(/\/\.$/, '') next if dirname == given_destination base.empty_directory(dirname, config) when /\.tt$/ destination = base.template(file_source, file_destination[0..-4], config, &@block) else destination = base.copy_file(file_source, file_destination, config, &@block) end end end if RUBY_VERSION < '2.0' def file_level_lookup(previous_lookup) File.join(previous_lookup, '{*,.[a-z]*}') end def files(lookup) Dir[lookup] end else def file_level_lookup(previous_lookup) File.join(previous_lookup, '*') end def files(lookup) Dir.glob(lookup, File::FNM_DOTMATCH) end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions/create_link.rb
lib/vendor/thor/lib/thor/actions/create_link.rb
require 'thor/actions/create_file' class Thor module Actions # Create a new file relative to the destination root from the given source. # # ==== Parameters # destination<String>:: the relative path to the destination root. # source<String|NilClass>:: the relative path to the source root. # config<Hash>:: give :verbose => false to not log the status. # :: give :symbolic => false for hard link. # # ==== Examples # # create_link "config/apache.conf", "/etc/apache.conf" # def create_link(destination, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} source = args.first action CreateLink.new(self, destination, source, config) end alias :add_link :create_link # CreateLink is a subset of CreateFile, which instead of taking a block of # data, just takes a source string from the user. # class CreateLink < CreateFile #:nodoc: attr_reader :data # Checks if the content of the file at the destination is identical to the rendered result. # # ==== Returns # Boolean:: true if it is identical, false otherwise. # def identical? exists? && File.identical?(render, destination) end def invoke! invoke_with_conflict_check do FileUtils.mkdir_p(File.dirname(destination)) # Create a symlink by default config[:symbolic] = true if config[:symbolic].nil? File.unlink(destination) if exists? if config[:symbolic] File.symlink(render, destination) else File.link(render, destination) end end given_destination end def exists? super || File.symlink?(destination) end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions/create_file.rb
lib/vendor/thor/lib/thor/actions/create_file.rb
require 'thor/actions/empty_directory' class Thor module Actions # Create a new file relative to the destination root with the given data, # which is the return value of a block or a data string. # # ==== Parameters # destination<String>:: the relative path to the destination root. # data<String|NilClass>:: the data to append to the file. # config<Hash>:: give :verbose => false to not log the status. # # ==== Examples # # create_file "lib/fun_party.rb" do # hostname = ask("What is the virtual hostname I should use?") # "vhost.name = #{hostname}" # end # # create_file "config/apache.conf", "your apache config" # def create_file(destination, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} data = args.first action CreateFile.new(self, destination, block || data.to_s, config) end alias :add_file :create_file # CreateFile is a subset of Template, which instead of rendering a file with # ERB, it gets the content from the user. # class CreateFile < EmptyDirectory #:nodoc: attr_reader :data def initialize(base, destination, data, config={}) @data = data super(base, destination, config) end # Checks if the content of the file at the destination is identical to the rendered result. # # ==== Returns # Boolean:: true if it is identical, false otherwise. # def identical? exists? && File.binread(destination) == render end # Holds the content to be added to the file. # def render @render ||= if data.is_a?(Proc) data.call else data end end def invoke! invoke_with_conflict_check do FileUtils.mkdir_p(File.dirname(destination)) File.open(destination, 'wb') { |f| f.write render } end given_destination end protected # Now on conflict we check if the file is identical or not. # def on_conflict_behavior(&block) if identical? say_status :identical, :blue else options = base.options.merge(config) force_or_skip_or_conflict(options[:force], options[:skip], &block) end end # If force is true, run the action, otherwise check if it's not being # skipped. If both are false, show the file_collision menu, if the menu # returns true, force it, otherwise skip. # def force_or_skip_or_conflict(force, skip, &block) if force say_status :force, :yellow block.call unless pretend? elsif skip say_status :skip, :yellow else say_status :conflict, :red force_or_skip_or_conflict(force_on_collision?, true, &block) end end # Shows the file collision menu to the user and gets the result. # def force_on_collision? base.shell.file_collision(destination){ render } end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions/file_manipulation.rb
lib/vendor/thor/lib/thor/actions/file_manipulation.rb
require 'erb' require 'open-uri' class Thor module Actions # Copies the file from the relative source to the relative destination. If # the destination is not given it's assumed to be equal to the source. # # ==== Parameters # source<String>:: the relative path to the source root. # destination<String>:: the relative path to the destination root. # config<Hash>:: give :verbose => false to not log the status, and # :mode => :preserve, to preserve the file mode from the source. # # ==== Examples # # copy_file "README", "doc/README" # # copy_file "doc/README" # def copy_file(source, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} destination = args.first || source source = File.expand_path(find_in_source_paths(source.to_s)) create_file destination, nil, config do content = File.binread(source) content = block.call(content) if block content end if config[:mode] == :preserve mode = File.stat(source).mode chmod(destination, mode, config) end end # Links the file from the relative source to the relative destination. If # the destination is not given it's assumed to be equal to the source. # # ==== Parameters # source<String>:: the relative path to the source root. # destination<String>:: the relative path to the destination root. # config<Hash>:: give :verbose => false to not log the status. # # ==== Examples # # link_file "README", "doc/README" # # link_file "doc/README" # def link_file(source, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} destination = args.first || source source = File.expand_path(find_in_source_paths(source.to_s)) create_link destination, source, config end # Gets the content at the given address and places it at the given relative # destination. If a block is given instead of destination, the content of # the url is yielded and used as location. # # ==== Parameters # source<String>:: the address of the given content. # destination<String>:: the relative path to the destination root. # config<Hash>:: give :verbose => false to not log the status. # # ==== Examples # # get "http://gist.github.com/103208", "doc/README" # # get "http://gist.github.com/103208" do |content| # content.split("\n").first # end # def get(source, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} destination = args.first source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ /^https?\:\/\// render = open(source) {|input| input.binmode.read } destination ||= if block_given? block.arity == 1 ? block.call(render) : block.call else File.basename(source) end create_file destination, render, config end # Gets an ERB template at the relative source, executes it and makes a copy # at the relative destination. If the destination is not given it's assumed # to be equal to the source removing .tt from the filename. # # ==== Parameters # source<String>:: the relative path to the source root. # destination<String>:: the relative path to the destination root. # config<Hash>:: give :verbose => false to not log the status. # # ==== Examples # # template "README", "doc/README" # # template "doc/README" # def template(source, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} destination = args.first || source.sub(/\.tt$/, '') source = File.expand_path(find_in_source_paths(source.to_s)) context = instance_eval('binding') create_file destination, nil, config do content = ERB.new(::File.binread(source), nil, '-', '@output_buffer').result(context) content = block.call(content) if block content end end # Changes the mode of the given file or directory. # # ==== Parameters # mode<Integer>:: the file mode # path<String>:: the name of the file to change mode # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # chmod "script/server", 0755 # def chmod(path, mode, config={}) return unless behavior == :invoke path = File.expand_path(path, destination_root) say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true) FileUtils.chmod_R(mode, path) unless options[:pretend] end # Prepend text to a file. Since it depends on insert_into_file, it's reversible. # # ==== Parameters # path<String>:: path of the file to be changed # data<String>:: the data to prepend to the file, can be also given as a block. # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # prepend_to_file 'config/environments/test.rb', 'config.gem "rspec"' # # prepend_to_file 'config/environments/test.rb' do # 'config.gem "rspec"' # end # def prepend_to_file(path, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} config.merge!(:after => /\A/) insert_into_file(path, *(args << config), &block) end alias_method :prepend_file, :prepend_to_file # Append text to a file. Since it depends on insert_into_file, it's reversible. # # ==== Parameters # path<String>:: path of the file to be changed # data<String>:: the data to append to the file, can be also given as a block. # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # append_to_file 'config/environments/test.rb', 'config.gem "rspec"' # # append_to_file 'config/environments/test.rb' do # 'config.gem "rspec"' # end # def append_to_file(path, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} config.merge!(:before => /\z/) insert_into_file(path, *(args << config), &block) end alias_method :append_file, :append_to_file # Injects text right after the class definition. Since it depends on # insert_into_file, it's reversible. # # ==== Parameters # path<String>:: path of the file to be changed # klass<String|Class>:: the class to be manipulated # data<String>:: the data to append to the class, can be also given as a block. # config<Hash>:: give :verbose => false to not log the status. # # ==== Examples # # inject_into_class "app/controllers/application_controller.rb", ApplicationController, " filter_parameter :password\n" # # inject_into_class "app/controllers/application_controller.rb", ApplicationController do # " filter_parameter :password\n" # end # def inject_into_class(path, klass, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} config.merge!(:after => /class #{klass}\n|class #{klass} .*\n/) insert_into_file(path, *(args << config), &block) end # Run a regular expression replacement on a file. # # ==== Parameters # path<String>:: path of the file to be changed # flag<Regexp|String>:: the regexp or string to be replaced # replacement<String>:: the replacement, can be also given as a block # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1' # # gsub_file 'README', /rake/, :green do |match| # match << " no more. Use thor!" # end # def gsub_file(path, flag, *args, &block) return unless behavior == :invoke config = args.last.is_a?(Hash) ? args.pop : {} path = File.expand_path(path, destination_root) say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true) unless options[:pretend] content = File.binread(path) content.gsub!(flag, *args, &block) File.open(path, 'wb') { |file| file.write(content) } end end # Uncomment all lines matching a given regex. It will leave the space # which existed before the comment hash in tact but will remove any spacing # between the comment hash and the beginning of the line. # # ==== Parameters # path<String>:: path of the file to be changed # flag<Regexp|String>:: the regexp or string used to decide which lines to uncomment # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # uncomment_lines 'config/initializers/session_store.rb', /active_record/ # def uncomment_lines(path, flag, *args) flag = flag.respond_to?(:source) ? flag.source : flag gsub_file(path, /^(\s*)#[[:blank:]]*(.*#{flag})/, '\1\2', *args) end # Comment all lines matching a given regex. It will leave the space # which existed before the beginning of the line in tact and will insert # a single space after the comment hash. # # ==== Parameters # path<String>:: path of the file to be changed # flag<Regexp|String>:: the regexp or string used to decide which lines to comment # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # comment_lines 'config/initializers/session_store.rb', /cookie_store/ # def comment_lines(path, flag, *args) flag = flag.respond_to?(:source) ? flag.source : flag gsub_file(path, /^(\s*)([^#|\n]*#{flag})/, '\1# \2', *args) end # Removes a file at the given location. # # ==== Parameters # path<String>:: path of the file to be changed # config<Hash>:: give :verbose => false to not log the status. # # ==== Example # # remove_file 'README' # remove_file 'app/controllers/application_controller.rb' # def remove_file(path, config={}) return unless behavior == :invoke path = File.expand_path(path, destination_root) say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true) ::FileUtils.rm_rf(path) if !options[:pretend] && File.exists?(path) end alias :remove_dir :remove_file private attr_accessor :output_buffer def concat(string) @output_buffer.concat(string) end def capture(*args, &block) with_output_buffer { block.call(*args) } end def with_output_buffer(buf = '') #:nodoc: self.output_buffer, old_buffer = buf, output_buffer yield output_buffer ensure self.output_buffer = old_buffer end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions/inject_into_file.rb
lib/vendor/thor/lib/thor/actions/inject_into_file.rb
require 'thor/actions/empty_directory' class Thor module Actions # Injects the given content into a file. Different from gsub_file, this # method is reversible. # # ==== Parameters # destination<String>:: Relative path to the destination root # data<String>:: Data to add to the file. Can be given as a block. # config<Hash>:: give :verbose => false to not log the status and the flag # for injection (:after or :before) or :force => true for # insert two or more times the same content. # # ==== Examples # # insert_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n" # # insert_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do # gems = ask "Which gems would you like to add?" # gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n") # end # def insert_into_file(destination, *args, &block) if block_given? data, config = block, args.shift else data, config = args.shift, args.shift end action InjectIntoFile.new(self, destination, data, config) end alias_method :inject_into_file, :insert_into_file class InjectIntoFile < EmptyDirectory #:nodoc: attr_reader :replacement, :flag, :behavior def initialize(base, destination, data, config) super(base, destination, { :verbose => true }.merge(config)) @behavior, @flag = if @config.key?(:after) [:after, @config.delete(:after)] else [:before, @config.delete(:before)] end @replacement = data.is_a?(Proc) ? data.call : data @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp) end def invoke! say_status :invoke content = if @behavior == :after '\0' + replacement else replacement + '\0' end replace!(/#{flag}/, content, config[:force]) end def revoke! say_status :revoke regexp = if @behavior == :after content = '\1\2' /(#{flag})(.*)(#{Regexp.escape(replacement)})/m else content = '\2\3' /(#{Regexp.escape(replacement)})(.*)(#{flag})/m end replace!(regexp, content, true) end protected def say_status(behavior) status = if behavior == :invoke if flag == /\A/ :prepend elsif flag == /\z/ :append else :insert end else :subtract end super(status, config[:verbose]) end # Adds the content to the file. # def replace!(regexp, string, force) unless base.options[:pretend] content = File.binread(destination) if force || !content.include?(replacement) content.gsub!(regexp, string) File.open(destination, 'wb') { |file| file.write(content) } end end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions/empty_directory.rb
lib/vendor/thor/lib/thor/actions/empty_directory.rb
class Thor module Actions # Creates an empty directory. # # ==== Parameters # destination<String>:: the relative path to the destination root. # config<Hash>:: give :verbose => false to not log the status. # # ==== Examples # # empty_directory "doc" # def empty_directory(destination, config={}) action EmptyDirectory.new(self, destination, config) end # Class which holds create directory logic. This is the base class for # other actions like create_file and directory. # # This implementation is based in Templater actions, created by Jonas Nicklas # and Michael S. Klishin under MIT LICENSE. # class EmptyDirectory #:nodoc: attr_reader :base, :destination, :given_destination, :relative_destination, :config # Initializes given the source and destination. # # ==== Parameters # base<Thor::Base>:: A Thor::Base instance # source<String>:: Relative path to the source of this file # destination<String>:: Relative path to the destination of this file # config<Hash>:: give :verbose => false to not log the status. # def initialize(base, destination, config={}) @base, @config = base, { :verbose => true }.merge(config) self.destination = destination end # Checks if the destination file already exists. # # ==== Returns # Boolean:: true if the file exists, false otherwise. # def exists? ::File.exists?(destination) end def invoke! invoke_with_conflict_check do ::FileUtils.mkdir_p(destination) end end def revoke! say_status :remove, :red ::FileUtils.rm_rf(destination) if !pretend? && exists? given_destination end protected # Shortcut for pretend. # def pretend? base.options[:pretend] end # Sets the absolute destination value from a relative destination value. # It also stores the given and relative destination. Let's suppose our # script is being executed on "dest", it sets the destination root to # "dest". The destination, given_destination and relative_destination # are related in the following way: # # inside "bar" do # empty_directory "baz" # end # # destination #=> dest/bar/baz # relative_destination #=> bar/baz # given_destination #=> baz # def destination=(destination) if destination @given_destination = convert_encoded_instructions(destination.to_s) @destination = ::File.expand_path(@given_destination, base.destination_root) @relative_destination = base.relative_to_original_destination_root(@destination) end end # Filenames in the encoded form are converted. If you have a file: # # %file_name%.rb # # It calls #file_name from the base and replaces %-string with the # return value (should be String) of #file_name: # # user.rb # # The method referenced can be either public or private. # def convert_encoded_instructions(filename) filename.gsub(/%(.*?)%/) do |initial_string| method = $1.strip base.respond_to?(method, true) ? base.send(method) : initial_string end end # Receives a hash of options and just execute the block if some # conditions are met. # def invoke_with_conflict_check(&block) if exists? on_conflict_behavior(&block) else say_status :create, :green block.call unless pretend? end destination end # What to do when the destination file already exists. # def on_conflict_behavior(&block) say_status :exist, :blue end # Shortcut to say_status shell method. # def say_status(status, color) base.shell.say_status status, relative_destination, color if config[:verbose] end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/core_ext/ordered_hash.rb
lib/vendor/thor/lib/thor/core_ext/ordered_hash.rb
class Thor module CoreExt #:nodoc: if RUBY_VERSION >= '1.9' class OrderedHash < ::Hash end else # This class is based on the Ruby 1.9 ordered hashes. # # It keeps the semantics and most of the efficiency of normal hashes # while also keeping track of the order in which elements were set. # class OrderedHash #:nodoc: include Enumerable Node = Struct.new(:key, :value, :next, :prev) def initialize @hash = {} end def [](key) @hash[key] && @hash[key].value end def []=(key, value) if node = @hash[key] node.value = value else node = Node.new(key, value) if @first.nil? @first = @last = node else node.prev = @last @last.next = node @last = node end end @hash[key] = node value end def delete(key) if node = @hash[key] prev_node = node.prev next_node = node.next next_node.prev = prev_node if next_node prev_node.next = next_node if prev_node @first = next_node if @first == node @last = prev_node if @last == node value = node.value end @hash.delete(key) value end def keys self.map { |k, v| k } end def values self.map { |k, v| v } end def each return unless @first yield [@first.key, @first.value] node = @first yield [node.key, node.value] while node = node.next self end def merge(other) hash = self.class.new self.each do |key, value| hash[key] = value end other.each do |key, value| hash[key] = value end hash end def empty? @hash.empty? end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/core_ext/hash_with_indifferent_access.rb
lib/vendor/thor/lib/thor/core_ext/hash_with_indifferent_access.rb
class Thor module CoreExt #:nodoc: # A hash with indifferent access and magic predicates. # # hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true # # hash[:foo] #=> 'bar' # hash['foo'] #=> 'bar' # hash.foo? #=> true # class HashWithIndifferentAccess < ::Hash #:nodoc: def initialize(hash={}) super() hash.each do |key, value| self[convert_key(key)] = value end end def [](key) super(convert_key(key)) end def []=(key, value) super(convert_key(key), value) end def delete(key) super(convert_key(key)) end def values_at(*indices) indices.collect { |key| self[convert_key(key)] } end def merge(other) dup.merge!(other) end def merge!(other) other.each do |key, value| self[convert_key(key)] = value end self end # Convert to a Hash with String keys. def to_hash Hash.new(default).merge!(self) end protected def convert_key(key) key.is_a?(Symbol) ? key.to_s : key end # Magic predicates. For instance: # # options.force? # => !!options['force'] # options.shebang # => "/usr/lib/local/ruby" # options.test_framework?(:rspec) # => options[:test_framework] == :rspec # def method_missing(method, *args, &block) method = method.to_s if method =~ /^(\w+)\?$/ if args.empty? !!self[$1] else self[$1] == args.first end else self[method] end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/core_ext/io_binary_read.rb
lib/vendor/thor/lib/thor/core_ext/io_binary_read.rb
class IO #:nodoc: class << self def binread(file, *args) raise ArgumentError, "wrong number of arguments (#{1 + args.size} for 1..3)" unless args.size < 3 File.open(file, 'rb') do |f| f.read(*args) end end unless method_defined? :binread end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/shell/color.rb
lib/vendor/thor/lib/thor/shell/color.rb
require 'thor/shell/basic' class Thor module Shell # Inherit from Thor::Shell::Basic and add set_color behavior. Check # Thor::Shell::Basic to see all available methods. # class Color < Basic # Embed in a String to clear all previous ANSI sequences. CLEAR = "\e[0m" # The start of an ANSI bold sequence. BOLD = "\e[1m" # Set the terminal's foreground ANSI color to black. BLACK = "\e[30m" # Set the terminal's foreground ANSI color to red. RED = "\e[31m" # Set the terminal's foreground ANSI color to green. GREEN = "\e[32m" # Set the terminal's foreground ANSI color to yellow. YELLOW = "\e[33m" # Set the terminal's foreground ANSI color to blue. BLUE = "\e[34m" # Set the terminal's foreground ANSI color to magenta. MAGENTA = "\e[35m" # Set the terminal's foreground ANSI color to cyan. CYAN = "\e[36m" # Set the terminal's foreground ANSI color to white. WHITE = "\e[37m" # Set the terminal's background ANSI color to black. ON_BLACK = "\e[40m" # Set the terminal's background ANSI color to red. ON_RED = "\e[41m" # Set the terminal's background ANSI color to green. ON_GREEN = "\e[42m" # Set the terminal's background ANSI color to yellow. ON_YELLOW = "\e[43m" # Set the terminal's background ANSI color to blue. ON_BLUE = "\e[44m" # Set the terminal's background ANSI color to magenta. ON_MAGENTA = "\e[45m" # Set the terminal's background ANSI color to cyan. ON_CYAN = "\e[46m" # Set the terminal's background ANSI color to white. ON_WHITE = "\e[47m" # Set color by using a string or one of the defined constants. If a third # option is set to true, it also adds bold to the string. This is based # on Highline implementation and it automatically appends CLEAR to the end # of the returned String. # # Pass foreground, background and bold options to this method as # symbols. # # Example: # # set_color "Hi!", :red, :on_white, :bold # # The available colors are: # # :bold # :black # :red # :green # :yellow # :blue # :magenta # :cyan # :white # :on_black # :on_red # :on_green # :on_yellow # :on_blue # :on_magenta # :on_cyan # :on_white def set_color(string, *colors) if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) } ansi_colors = colors.map { |color| lookup_color(color) } "#{ansi_colors.join}#{string}#{CLEAR}" else # The old API was `set_color(color, bold=boolean)`. We # continue to support the old API because you should never # break old APIs unnecessarily :P foreground, bold = colors foreground = self.class.const_get(foreground.to_s.upcase) if foreground.is_a?(Symbol) bold = bold ? BOLD : "" "#{bold}#{foreground}#{string}#{CLEAR}" end end protected def can_display_colors? stdout.tty? end # Overwrite show_diff to show diff with colors if Diff::LCS is # available. # def show_diff(destination, content) #:nodoc: if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil? actual = File.binread(destination).to_s.split("\n") content = content.to_s.split("\n") Diff::LCS.sdiff(actual, content).each do |diff| output_diff_line(diff) end else super end end def output_diff_line(diff) #:nodoc: case diff.action when '-' say "- #{diff.old_element.chomp}", :red, true when '+' say "+ #{diff.new_element.chomp}", :green, true when '!' say "- #{diff.old_element.chomp}", :red, true say "+ #{diff.new_element.chomp}", :green, true else say " #{diff.old_element.chomp}", nil, true end end # Check if Diff::LCS is loaded. If it is, use it to create pretty output # for diff. # def diff_lcs_loaded? #:nodoc: return true if defined?(Diff::LCS) return @diff_lcs_loaded unless @diff_lcs_loaded.nil? @diff_lcs_loaded = begin require 'diff/lcs' true rescue LoadError false end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/shell/basic.rb
lib/vendor/thor/lib/thor/shell/basic.rb
require 'tempfile' class Thor module Shell class Basic attr_accessor :base attr_reader :padding # Initialize base, mute and padding to nil. # def initialize #:nodoc: @base, @mute, @padding = nil, false, 0 end # Mute everything that's inside given block # def mute @mute = true yield ensure @mute = false end # Check if base is muted # def mute? @mute end # Sets the output padding, not allowing less than zero values. # def padding=(value) @padding = [0, value].max end # Asks something to the user and receives a response. # # If asked to limit the correct responses, you can pass in an # array of acceptable answers. If one of those is not supplied, # they will be shown a message stating that one of those answers # must be given and re-asked the question. # # ==== Example # ask("What is your name?") # # ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"]) # def ask(statement, *args) options = args.last.is_a?(Hash) ? args.pop : {} options[:limited_to] ? ask_filtered(statement, options[:limited_to], *args) : ask_simply(statement, *args) end # Say (print) something to the user. If the sentence ends with a whitespace # or tab character, a new line is not appended (print + flush). Otherwise # are passed straight to puts (behavior got from Highline). # # ==== Example # say("I know you knew that.") # def say(message="", color=nil, force_new_line=(message.to_s !~ /( |\t)\Z/)) message = message.to_s message = set_color(message, *color) if color && can_display_colors? spaces = " " * padding if force_new_line stdout.puts(spaces + message) else stdout.print(spaces + message) end stdout.flush end # Say a status with the given color and appends the message. Since this # method is used frequently by actions, it allows nil or false to be given # in log_status, avoiding the message from being shown. If a Symbol is # given in log_status, it's used as the color. # def say_status(status, message, log_status=true) return if quiet? || log_status == false spaces = " " * (padding + 1) color = log_status.is_a?(Symbol) ? log_status : :green status = status.to_s.rjust(12) status = set_color status, color, true if color stdout.puts "#{status}#{spaces}#{message}" stdout.flush end # Make a question the to user and returns true if the user replies "y" or # "yes". # def yes?(statement, color=nil) !!(ask(statement, color) =~ is?(:yes)) end # Make a question the to user and returns true if the user replies "n" or # "no". # def no?(statement, color=nil) !yes?(statement, color) end # Prints values in columns # # ==== Parameters # Array[String, String, ...] # def print_in_columns(array) return if array.empty? colwidth = (array.map{|el| el.to_s.size}.max || 0) + 2 array.each_with_index do |value, index| # Don't output trailing spaces when printing the last column if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length stdout.puts value else stdout.printf("%-#{colwidth}s", value) end end end # Prints a table. # # ==== Parameters # Array[Array[String, String, ...]] # # ==== Options # indent<Integer>:: Indent the first column by indent value. # colwidth<Integer>:: Force the first column to colwidth spaces wide. # def print_table(array, options={}) return if array.empty? formats, indent, colwidth = [], options[:indent].to_i, options[:colwidth] options[:truncate] = terminal_width if options[:truncate] == true formats << "%-#{colwidth + 2}s" if colwidth start = colwidth ? 1 : 0 colcount = array.max{|a,b| a.size <=> b.size }.size maximas = [] start.upto(colcount - 1) do |index| maxima = array.map {|row| row[index] ? row[index].to_s.size : 0 }.max maximas << maxima if index == colcount - 1 # Don't output 2 trailing spaces when printing the last column formats << "%-s" else formats << "%-#{maxima + 2}s" end end formats[0] = formats[0].insert(0, " " * indent) formats << "%s" array.each do |row| sentence = "" row.each_with_index do |column, index| maxima = maximas[index] if column.is_a?(Numeric) if index == row.size - 1 # Don't output 2 trailing spaces when printing the last column f = "%#{maxima}s" else f = "%#{maxima}s " end else f = formats[index] end sentence << f % column.to_s end sentence = truncate(sentence, options[:truncate]) if options[:truncate] stdout.puts sentence end end # Prints a long string, word-wrapping the text to the current width of the # terminal display. Ideal for printing heredocs. # # ==== Parameters # String # # ==== Options # indent<Integer>:: Indent each line of the printed paragraph by indent value. # def print_wrapped(message, options={}) indent = options[:indent] || 0 width = terminal_width - indent paras = message.split("\n\n") paras.map! do |unwrapped| unwrapped.strip.gsub(/\n/, " ").squeeze(" "). gsub(/.{1,#{width}}(?:\s|\Z)/){($& + 5.chr). gsub(/\n\005/,"\n").gsub(/\005/,"\n")} end paras.each do |para| para.split("\n").each do |line| stdout.puts line.insert(0, " " * indent) end stdout.puts unless para == paras.last end end # Deals with file collision and returns true if the file should be # overwritten and false otherwise. If a block is given, it uses the block # response as the content for the diff. # # ==== Parameters # destination<String>:: the destination file to solve conflicts # block<Proc>:: an optional block that returns the value to be used in diff # def file_collision(destination) return true if @always_force options = block_given? ? "[Ynaqdh]" : "[Ynaqh]" while true answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}] case answer when is?(:yes), is?(:force), "" return true when is?(:no), is?(:skip) return false when is?(:always) return @always_force = true when is?(:quit) say 'Aborting...' raise SystemExit when is?(:diff) show_diff(destination, yield) if block_given? say 'Retrying...' else say file_collision_help end end end # This code was copied from Rake, available under MIT-LICENSE # Copyright (c) 2003, 2004 Jim Weirich def terminal_width if ENV['THOR_COLUMNS'] result = ENV['THOR_COLUMNS'].to_i else result = unix? ? dynamic_width : 80 end (result < 10) ? 80 : result rescue 80 end # Called if something goes wrong during the execution. This is used by Thor # internally and should not be used inside your scripts. If something went # wrong, you can always raise an exception. If you raise a Thor::Error, it # will be rescued and wrapped in the method below. # def error(statement) stderr.puts statement end # Apply color to the given string with optional bold. Disabled in the # Thor::Shell::Basic class. # def set_color(string, *args) #:nodoc: string end protected def can_display_colors? false end def lookup_color(color) return color unless color.is_a?(Symbol) self.class.const_get(color.to_s.upcase) end def stdout $stdout end def stdin $stdin end def stderr $stderr end def is?(value) #:nodoc: value = value.to_s if value.size == 1 /\A#{value}\z/i else /\A(#{value}|#{value[0,1]})\z/i end end def file_collision_help #:nodoc: <<HELP Y - yes, overwrite n - no, do not overwrite a - all, overwrite this and all others q - quit, abort d - diff, show the differences between the old and the new h - help, show this help HELP end def show_diff(destination, content) #:nodoc: diff_cmd = ENV['THOR_DIFF'] || ENV['RAILS_DIFF'] || 'diff -u' Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp| temp.write content temp.rewind system %(#{diff_cmd} "#{destination}" "#{temp.path}") end end def quiet? #:nodoc: mute? || (base && base.options[:quiet]) end # Calculate the dynamic width of the terminal def dynamic_width @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput) end def dynamic_width_stty %x{stty size 2>/dev/null}.split[1].to_i end def dynamic_width_tput %x{tput cols 2>/dev/null}.to_i end def unix? RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i end def truncate(string, width) as_unicode do chars = string.chars.to_a if chars.length <= width chars.join else ( chars[0, width-3].join ) + "..." end end end if "".respond_to?(:encode) def as_unicode yield end else def as_unicode old, $KCODE = $KCODE, "U" yield ensure $KCODE = old end end def ask_simply(statement, color=nil) say("#{statement} ", color) stdin.gets.tap{|text| text.strip! if text} end def ask_filtered(statement, answer_set, *args) correct_answer = nil until correct_answer answer = ask_simply("#{statement} #{answer_set.inspect}", *args) correct_answer = answer_set.include?(answer) ? answer : nil answers = answer_set.map(&:inspect).join(", ") say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer end correct_answer end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/shell/html.rb
lib/vendor/thor/lib/thor/shell/html.rb
require 'thor/shell/basic' class Thor module Shell # Inherit from Thor::Shell::Basic and add set_color behavior. Check # Thor::Shell::Basic to see all available methods. # class HTML < Basic # The start of an HTML bold sequence. BOLD = "font-weight: bold" # Set the terminal's foreground HTML color to black. BLACK = 'color: black' # Set the terminal's foreground HTML color to red. RED = 'color: red' # Set the terminal's foreground HTML color to green. GREEN = 'color: green' # Set the terminal's foreground HTML color to yellow. YELLOW = 'color: yellow' # Set the terminal's foreground HTML color to blue. BLUE = 'color: blue' # Set the terminal's foreground HTML color to magenta. MAGENTA = 'color: magenta' # Set the terminal's foreground HTML color to cyan. CYAN = 'color: cyan' # Set the terminal's foreground HTML color to white. WHITE = 'color: white' # Set the terminal's background HTML color to black. ON_BLACK = 'background-color: black' # Set the terminal's background HTML color to red. ON_RED = 'background-color: red' # Set the terminal's background HTML color to green. ON_GREEN = 'background-color: green' # Set the terminal's background HTML color to yellow. ON_YELLOW = 'background-color: yellow' # Set the terminal's background HTML color to blue. ON_BLUE = 'background-color: blue' # Set the terminal's background HTML color to magenta. ON_MAGENTA = 'background-color: magenta' # Set the terminal's background HTML color to cyan. ON_CYAN = 'background-color: cyan' # Set the terminal's background HTML color to white. ON_WHITE = 'background-color: white' # Set color by using a string or one of the defined constants. If a third # option is set to true, it also adds bold to the string. This is based # on Highline implementation and it automatically appends CLEAR to the end # of the returned String. # def set_color(string, *colors) if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) } html_colors = colors.map { |color| lookup_color(color) } "<span style=\"#{html_colors.join("; ")};\">#{string}</span>" else color, bold = colors html_color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) styles = [html_color] styles << BOLD if bold "<span style=\"#{styles.join("; ")};\">#{string}</span>" end end # Ask something to the user and receives a response. # # ==== Example # ask("What is your name?") # # TODO: Implement #ask for Thor::Shell::HTML def ask(statement, color=nil) raise NotImplementedError, "Implement #ask for Thor::Shell::HTML" end protected def can_display_colors? true end # Overwrite show_diff to show diff with colors if Diff::LCS is # available. # def show_diff(destination, content) #:nodoc: if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil? actual = File.binread(destination).to_s.split("\n") content = content.to_s.split("\n") Diff::LCS.sdiff(actual, content).each do |diff| output_diff_line(diff) end else super end end def output_diff_line(diff) #:nodoc: case diff.action when '-' say "- #{diff.old_element.chomp}", :red, true when '+' say "+ #{diff.new_element.chomp}", :green, true when '!' say "- #{diff.old_element.chomp}", :red, true say "+ #{diff.new_element.chomp}", :green, true else say " #{diff.old_element.chomp}", nil, true end end # Check if Diff::LCS is loaded. If it is, use it to create pretty output # for diff. # def diff_lcs_loaded? #:nodoc: return true if defined?(Diff::LCS) return @diff_lcs_loaded unless @diff_lcs_loaded.nil? @diff_lcs_loaded = begin require 'diff/lcs' true rescue LoadError false end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/parser/options.rb
lib/vendor/thor/lib/thor/parser/options.rb
class Thor class Options < Arguments #:nodoc: LONG_RE = /^(--\w+(?:-\w+)*)$/ SHORT_RE = /^(-[a-z])$/i EQ_RE = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i OPTS_END = '--'.freeze # Receives a hash and makes it switches. def self.to_switches(options) options.map do |key, value| case value when true "--#{key}" when Array "--#{key} #{value.map{ |v| v.inspect }.join(' ')}" when Hash "--#{key} #{value.map{ |k,v| "#{k}:#{v}" }.join(' ')}" when nil, false "" else "--#{key} #{value.inspect}" end end.join(" ") end # Takes a hash of Thor::Option and a hash with defaults. # # If +stop_on_unknown+ is true, #parse will stop as soon as it encounters # an unknown option or a regular argument. def initialize(hash_options={}, defaults={}, stop_on_unknown=false) @stop_on_unknown = stop_on_unknown options = hash_options.values super(options) # Add defaults defaults.each do |key, value| @assigns[key.to_s] = value @non_assigned_required.delete(hash_options[key]) end @shorts, @switches, @extra = {}, {}, [] options.each do |option| @switches[option.switch_name] = option option.aliases.each do |short| name = short.to_s.sub(/^(?!\-)/, '-') @shorts[name] ||= option.switch_name end end end def remaining @extra end def peek return super unless @parsing_options result = super if result == OPTS_END shift @parsing_options = false super else result end end def parse(args) @pile = args.dup @parsing_options = true while peek if parsing_options? match, is_switch = current_is_switch? shifted = shift if is_switch case shifted when SHORT_SQ_RE unshift($1.split('').map { |f| "-#{f}" }) next when EQ_RE, SHORT_NUM unshift($2) switch = $1 when LONG_RE, SHORT_RE switch = $1 end switch = normalize_switch(switch) option = switch_option(switch) @assigns[option.human_name] = parse_peek(switch, option) elsif @stop_on_unknown @parsing_options = false @extra << shifted @extra << shift while peek break elsif match @extra << shifted @extra << shift while peek && peek !~ /^-/ else @extra << shifted end else @extra << shift end end check_requirement! assigns = Thor::CoreExt::HashWithIndifferentAccess.new(@assigns) assigns.freeze assigns end def check_unknown! # an unknown option starts with - or -- and has no more --'s afterward. unknown = @extra.select { |str| str =~ /^--?(?:(?!--).)*$/ } raise UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty? end protected # Check if the current value in peek is a registered switch. # # Two booleans are returned. The first is true if the current value # starts with a hyphen; the second is true if it is a registered switch. def current_is_switch? case peek when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM [true, switch?($1)] when SHORT_SQ_RE [true, $1.split('').any? { |f| switch?("-#{f}") }] else [false, false] end end def current_is_switch_formatted? case peek when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE true else false end end def current_is_value? peek && (!parsing_options? || super) end def switch?(arg) switch_option(normalize_switch(arg)) end def switch_option(arg) if match = no_or_skip?(arg) @switches[arg] || @switches["--#{match}"] else @switches[arg] end end # Check if the given argument is actually a shortcut. # def normalize_switch(arg) (@shorts[arg] || arg).tr('_', '-') end def parsing_options? peek @parsing_options end # Parse boolean values which can be given as --foo=true, --foo or --no-foo. # def parse_boolean(switch) if current_is_value? if ["true", "TRUE", "t", "T", true].include?(peek) shift true elsif ["false", "FALSE", "f", "F", false].include?(peek) shift false else true end else @switches.key?(switch) || !no_or_skip?(switch) end end # Parse the value at the peek analyzing if it requires an input or not. # def parse_peek(switch, option) if parsing_options? && (current_is_switch_formatted? || last?) if option.boolean? # No problem for boolean types elsif no_or_skip?(switch) return nil # User set value to nil elsif option.string? && !option.required? # Return the default if there is one, else the human name return option.lazy_default || option.default || option.human_name elsif option.lazy_default return option.lazy_default else raise MalformattedArgumentError, "No value provided for option '#{switch}'" end end @non_assigned_required.delete(option) send(:"parse_#{option.type}", switch) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/parser/arguments.rb
lib/vendor/thor/lib/thor/parser/arguments.rb
class Thor class Arguments #:nodoc: NUMERIC = /(\d*\.\d+|\d+)/ # Receives an array of args and returns two arrays, one with arguments # and one with switches. # def self.split(args) arguments = [] args.each do |item| break if item =~ /^-/ arguments << item end return arguments, args[Range.new(arguments.size, -1)] end def self.parse(*args) to_parse = args.pop new(*args).parse(to_parse) end # Takes an array of Thor::Argument objects. # def initialize(arguments=[]) @assigns, @non_assigned_required = {}, [] @switches = arguments arguments.each do |argument| if argument.default != nil @assigns[argument.human_name] = argument.default elsif argument.required? @non_assigned_required << argument end end end def parse(args) @pile = args.dup @switches.each do |argument| break unless peek @non_assigned_required.delete(argument) @assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name) end check_requirement! @assigns end def remaining @pile end private def no_or_skip?(arg) arg =~ /^--(no|skip)-([-\w]+)$/ $2 end def last? @pile.empty? end def peek @pile.first end def shift @pile.shift end def unshift(arg) unless arg.kind_of?(Array) @pile.unshift(arg) else @pile = arg + @pile end end def current_is_value? peek && peek.to_s !~ /^-/ end # Runs through the argument array getting strings that contains ":" and # mark it as a hash: # # [ "name:string", "age:integer" ] # # Becomes: # # { "name" => "string", "age" => "integer" } # def parse_hash(name) return shift if peek.is_a?(Hash) hash = {} while current_is_value? && peek.include?(?:) key, value = shift.split(':',2) hash[key] = value end hash end # Runs through the argument array getting all strings until no string is # found or a switch is found. # # ["a", "b", "c"] # # And returns it as an array: # # ["a", "b", "c"] # def parse_array(name) return shift if peek.is_a?(Array) array = [] while current_is_value? array << shift end array end # Check if the peek is numeric format and return a Float or Integer. # Otherwise raises an error. # def parse_numeric(name) return shift if peek.is_a?(Numeric) unless peek =~ NUMERIC && $& == peek raise MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}" end $&.index('.') ? shift.to_f : shift.to_i end # Parse string: # for --string-arg, just return the current value in the pile # for --no-string-arg, nil # def parse_string(name) if no_or_skip?(name) nil else value = shift if @switches.is_a?(Hash) && switch = @switches[name] if switch.enum && !switch.enum.include?(value) raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}" end end value end end # Raises an error if @non_assigned_required array is not empty. # def check_requirement! unless @non_assigned_required.empty? names = @non_assigned_required.map do |o| o.respond_to?(:switch_name) ? o.switch_name : o.human_name end.join("', '") class_name = self.class.name.split('::').last.downcase raise RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'" end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/parser/option.rb
lib/vendor/thor/lib/thor/parser/option.rb
class Thor class Option < Argument #:nodoc: attr_reader :aliases, :group, :lazy_default, :hide VALID_TYPES = [:boolean, :numeric, :hash, :array, :string] def initialize(name, options={}) options[:required] = false unless options.key?(:required) super @lazy_default = options[:lazy_default] @group = options[:group].to_s.capitalize if options[:group] @aliases = Array(options[:aliases]) @hide = options[:hide] end # This parse quick options given as method_options. It makes several # assumptions, but you can be more specific using the option method. # # parse :foo => "bar" # #=> Option foo with default value bar # # parse [:foo, :baz] => "bar" # #=> Option foo with default value bar and alias :baz # # parse :foo => :required # #=> Required option foo without default value # # parse :foo => 2 # #=> Option foo with default value 2 and type numeric # # parse :foo => :numeric # #=> Option foo without default value and type numeric # # parse :foo => true # #=> Option foo with default value true and type boolean # # The valid types are :boolean, :numeric, :hash, :array and :string. If none # is given a default type is assumed. This default type accepts arguments as # string (--foo=value) or booleans (just --foo). # # By default all options are optional, unless :required is given. # def self.parse(key, value) if key.is_a?(Array) name, *aliases = key else name, aliases = key, [] end name = name.to_s default = value type = case value when Symbol default = nil if VALID_TYPES.include?(value) value elsif required = (value == :required) :string end when TrueClass, FalseClass :boolean when Numeric :numeric when Hash, Array, String value.class.name.downcase.to_sym end self.new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases) end def switch_name @switch_name ||= dasherized? ? name : dasherize(name) end def human_name @human_name ||= dasherized? ? undasherize(name) : name end def usage(padding=0) sample = if banner && !banner.to_s.empty? "#{switch_name}=#{banner}" else switch_name end sample = "[#{sample}]" unless required? if aliases.empty? (" " * padding) << sample else "#{aliases.join(', ')}, #{sample}" end end VALID_TYPES.each do |type| class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{type}? self.type == #{type.inspect} end RUBY end protected def validate! raise ArgumentError, "An option cannot be boolean and required." if boolean? && required? end def dasherized? name.index('-') == 0 end def undasherize(str) str.sub(/^-{1,2}/, '') end def dasherize(str) (str.length > 1 ? "--" : "-") + str.gsub('_', '-') end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/parser/argument.rb
lib/vendor/thor/lib/thor/parser/argument.rb
class Thor class Argument #:nodoc: VALID_TYPES = [ :numeric, :hash, :array, :string ] attr_reader :name, :description, :enum, :required, :type, :default, :banner alias :human_name :name def initialize(name, options={}) class_name = self.class.name.split("::").last type = options[:type] raise ArgumentError, "#{class_name} name can't be nil." if name.nil? raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type) @name = name.to_s @description = options[:desc] @required = options.key?(:required) ? options[:required] : true @type = (type || :string).to_sym @default = options[:default] @banner = options[:banner] || default_banner @enum = options[:enum] validate! # Trigger specific validations end def usage required? ? banner : "[#{banner}]" end def required? required end def show_default? case default when Array, String, Hash !default.empty? else default end end protected def validate! if required? && !default.nil? raise ArgumentError, "An argument cannot be required and have default value." elsif @enum && !@enum.is_a?(Array) raise ArgumentError, "An argument cannot have an enum other than an array." end end def valid_type?(type) self.class::VALID_TYPES.include?(type.to_sym) end def default_banner case type when :boolean nil when :string, :default human_name.upcase when :numeric "N" when :hash "key:value" when :array "one two three" end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/deploy_config.rb
lib/engineyard/deploy_config.rb
module EY class DeployConfig MIGRATE = 'rake db:migrate --trace' def initialize(cli_opts, env_config, repo, ui) @cli_opts = cli_opts @env_config = env_config @repo = repo @ui = ui end def ref @ref ||= decide_ref end def migrate @migrate ||= @cli_opts.fetch('migrate') do if in_repo? @env_config.migrate else raise RefAndMigrateRequiredOutsideRepo.new(@cli_opts) end end end def migrate_command return @command if defined? @command if migrate @command = migrate.respond_to?(:to_str) && migrate.to_str @command ||= in_repo? ? @env_config.migration_command : MIGRATE else @command = nil end @command end def verbose @cli_opts.fetch('verbose') { in_repo? && @env_config.verbose } end def extra_config @cli_opts.fetch('config', {}) end private # passing an app means we assume PWD is not the app. def in_repo? @cli_opts['app'].nil? || @cli_opts['app'] == '' end def decide_ref ref_decider = EY::DeployConfig::Ref.new(@cli_opts, @env_config, @repo, @ui) if in_repo? ref_decider.when_inside_repo else ref_decider.when_outside_repo end end end end require 'engineyard/deploy_config/ref'
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/serverside_runner.rb
lib/engineyard/serverside_runner.rb
require 'escape' require 'net/ssh' require 'engineyard-serverside-adapter' module EY class ServersideRunner def initialize(options) @verbose = options[:verbose] || !!ENV['DEBUG'] @hostname = options[:bridge] env = options[:environment] @adapter = load_adapter(@hostname, options[:app], env, @verbose, options[:serverside_version]) @username = env.username @hierarchy_name = env.hierarchy_name @command = nil end def deploy(&block) @command = @adapter.deploy(&block) self end def rollback(&block) @command = @adapter.rollback(&block) self end def restart(&block) @command = @adapter.restart(&block) self end def put_up_maintenance_page(&block) @command = @adapter.enable_maintenance(&block) self end def take_down_maintenance_page(&block) @command = @adapter.disable_maintenance(&block) self end def call(out, err) raise "No command!" unless @command @command.call do |cmd| run cmd, out, err end end private def load_adapter(bridge, app, environment, verbose, serverside_version) EY::Serverside::Adapter.new("/usr/local/ey_resin/ruby/bin") do |args| args.serverside_version = serverside_version args.app = app.name args.git = app.repository_uri args.instances = instances_data(environment.deploy_to_instances, bridge) args.stack = environment.app_server_stack_name args.framework_env = environment.framework_env args.environment_name = environment.name args.account_name = app.account.name args.verbose = verbose end end # If we tell engineyard-serverside to use 'localhost', it'll run # commands on the instance directly (#system). If we give it the # instance's actual hostname, it'll SSH to itself. # # Using 'localhost' instead of its EC2 hostname speeds up # deploys on solos and single-app-server clusters significantly. def instances_data(instances, bridge) instances.map do |i| { hostname: i.hostname == bridge ? 'localhost' : i.hostname, roles: [i.role], name: i.name, } end end def run(remote_command, out, err) cmd = Escape.shell_command(['bash', '-lc', remote_command]) if cmd.respond_to?(:encoding) && cmd.respond_to?(:force_encoding) out << "Encoding: #{cmd.encoding.name}" if @verbose cmd.force_encoding('binary') out << " => #{cmd.encoding.name}; __ENCODING__: #{__ENCODING__.name}; LANG: #{ENV['LANG']}; LC_CTYPE: #{ENV['LC_CTYPE']}\n" if @verbose end out << "Running command on #{@username}@#{@hostname}.\n" out << cmd << "\n" if @verbose || ENV['PRINT_CMD'] if ENV["NO_SSH"] out << "NO_SSH is set. No output.\n" true else begin ssh(cmd, @hostname, @username, out, err) rescue Net::SSH::AuthenticationFailed raise EY::Error, <<-ERROR Authentication Failed. Things to fix: 1. Add your SSH key to your local SSH agent with `ssh-add path/to/key`. 2. Add your SSH key to #{@hierarchy_name} on Engine Yard Cloud and apply the changes. (https://support.cloud.engineyard.com/entries/20996846-set-up-ssh-keys) ERROR end end end def net_ssh_options level = :fatal # default in Net::SSH if debug = ENV["DEBUG"] level = :info if %w[debug info warn error fatal].include?(debug.downcase) level = debug.downcase.to_sym end end {paranoid: false, verbose: level, keepalive: true, keepalive_interval: 60} end def ssh(cmd, hostname, username, out, err) exit_code = 1 Net::SSH.start(hostname, username, net_ssh_options) do |net_ssh| net_ssh.open_channel do |channel| channel.exec cmd do |_, success| unless success err << "Remote command execution failed" return false end channel.on_data do |_, data| out << data end channel.on_extended_data do |_, _, data| err << data end channel.on_request("exit-status") do |_, data| exit_code = data.read_long end channel.on_request("exit-signal") do |_, data| exit_code = 255 end # sending eof declares no more data coming from this end (close stdin) channel.eof! end end net_ssh.loop end exit_code.zero? end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/version.rb
lib/engineyard/version.rb
module EY VERSION = '4.0.0.pre1' ENGINEYARD_SERVERSIDE_VERSION = ENV['ENGINEYARD_SERVERSIDE_VERSION'] || '2.6.10' end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/templates.rb
lib/engineyard/templates.rb
module EY module Templates end end require 'engineyard/templates/ey_yml'
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/cli.rb
lib/engineyard/cli.rb
require 'engineyard' require 'engineyard/error' require 'engineyard/thor' require 'engineyard/deploy_config' require 'engineyard/serverside_runner' require 'launchy' require 'fileutils' module EY class CLI < EY::Thor require 'engineyard/cli/recipes' require 'engineyard/cli/web' require 'engineyard/cli/api' require 'engineyard/cli/ui' require 'engineyard/error' require 'engineyard-cloud-client/errors' include Thor::Actions def self.start(given_args=ARGV, config={}) Thor::Base.shell = EY::CLI::UI ui = EY::CLI::UI.new super(given_args, {shell: ui}.merge(config)) rescue Thor::Error, EY::Error, EY::CloudClient::Error => e ui.print_exception(e) raise rescue Interrupt => e puts ui.print_exception(e) ui.say("Quitting...") raise rescue SystemExit, Errno::EPIPE # don't print a message for safe exits raise rescue Exception => e ui.print_exception(e) raise end class_option :api_token, type: :string, desc: "Use API_TOKEN to authenticate this command" class_option :serverside_version, type: :string, desc: "Please use with care! Override deploy system version (same as ENV variable ENGINEYARD_SERVERSIDE_VERSION)" class_option :quiet, aliases: %w[-q], type: :boolean, desc: "Quieter CLI output." desc "init", "Initialize the current directory with an ey.yml configuration file." long_desc <<-DESC Initialize the current directory with an ey.yml configuration file. Please read the generated file and make adjustments. Many applications will need only the default behavior. For reference, many available options are explained in the generated file. IMPORTANT: THE GENERATED FILE '#{EY::Config.pathname_for_write}' MUST BE COMMITTED TO YOUR REPOSITORY OR OPTIONS WILL NOT BE LOADED. DESC method_option :path, type: :string, aliases: %w(-p), desc: "Path for ey.yml (supported paths: #{EY::Config::CONFIG_FILES.join(', ')})" def init unless EY::Repo.exist? raise EY::Error, "Working directory is not a repository. Aborting." end path = Pathname.new(options['path'] || EY::Config.pathname_for_write) existing = {} if path.exist? ui.warn "Reinitializing existing file: #{path}" existing = EY::Config.load_config end template = EY::Templates::EyYml.new(existing) template.write(path) ui.info <<-GIT Configuration generated: #{path} Go look at it, then add it to your repository! \tgit add #{path} \tgit commit -m "Add generated #{path} from ey init" GIT end desc "deploy [--environment ENVIRONMENT] [--ref GIT-REF]", "Deploy specified branch, tag, or sha to specified environment." long_desc <<-DESC This command must be run with the current directory containing the app to be deployed. If ey.yml specifies a default branch then the ref parameter can be omitted. Furthermore, if a default branch is specified but a different command is supplied the deploy will fail unless -R or --force-ref is used. Migrations are run based on the settings in your ey.yml file. With each deploy the default migration setting can be overriden by specifying --migrate or --migrate 'rake db:migrate'. Migrations can also be skipped by using --no-migrate. DESC method_option :ignore_bad_master, type: :boolean, aliases: %w(--ignore-bad-bridge), desc: "Force a deploy even if the master is in a bad state" method_option :migrate, type: :string, aliases: %w(-m), lazy_default: true, desc: "Run migrations via [MIGRATE]; use --no-migrate to avoid running migrations" method_option :ref, type: :string, aliases: %w(-r --branch --tag), required: true, default: '', desc: "Git ref to deploy. May be a branch, a tag, or a SHA. Use -R to deploy a different ref if a default is set." method_option :force_ref, type: :string, aliases: %w(--ignore-default-branch -R), lazy_default: true, desc: "Force a deploy of the specified git ref even if a default is set in ey.yml." method_option :environment, type: :string, aliases: %w(-e), required: true, default: false, desc: "Environment in which to deploy this application" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application to deploy" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :verbose, type: :boolean, aliases: %w(-v), desc: "Be verbose" method_option :config, type: :hash, default: {}, aliases: %w(--extra-deploy-hook-options), desc: "Hash made available in deploy hooks (in the 'config' hash), can also override some ey.yml settings." def deploy app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) env_config = config.environment_config(app_env.environment_name) deploy_config = EY::DeployConfig.new(options, env_config, repo, ui) deployment = app_env.new_deployment({ ref: deploy_config.ref, migrate: deploy_config.migrate, migrate_command: deploy_config.migrate_command, extra_config: deploy_config.extra_config, serverside_version: serverside_version, }) runner = serverside_runner(app_env, deploy_config.verbose, deployment.serverside_version, options[:ignore_bad_master]) out = EY::CLI::UI::Tee.new(ui.out, deployment.output) err = EY::CLI::UI::Tee.new(ui.err, deployment.output) ui.info "Beginning deploy...", :green begin deployment.start rescue ui.error "Error encountered before deploy. Deploy not started." raise end begin ui.show_deployment(deployment) out << "Deploy initiated.\n" runner.deploy do |args| args.config = deployment.config if deployment.config if deployment.migrate args.migrate = deployment.migrate_command else args.migrate = false end args.ref = deployment.resolved_ref end deployment.successful = runner.call(out, err) rescue Interrupt Signal.trap(:INT) { # The fingers you have used to dial are too fat... ui.info "\nRun `ey timeout-deploy` to mark an unfinished deployment as failed." exit 1 } err << "Interrupted. Deployment halted.\n" ui.warn <<-WARN Recording interruption of this unfinished deployment in Engine Yard Cloud... WARNING: Interrupting again may prevent Engine Yard Cloud from recording this failed deployment. Unfinished deployments can block future deploys. WARN raise rescue StandardError => e deployment.err << "Error encountered during deploy.\n#{e.class} #{e}\n" ui.print_exception(e) raise ensure ui.info "Saving log... ", :green deployment.finished if deployment.successful? ui.info "Successful deployment recorded on Engine Yard Cloud.", :green ui.info "Run `ey launch` to open the application in a browser." else ui.info "Failed deployment recorded on Engine Yard Cloud", :green raise EY::Error, "Deploy failed" end end end desc "timeout-deploy [--environment ENVIRONMENT]", "Fail a stuck unfinished deployment." long_desc <<-DESC NOTICE: Timing out a deploy does not stop currently running deploy processes. This command must be run in the current directory containing the app. The latest running deployment will be marked as failed, allowing a new deployment to be run. It is possible to mark a potentially successful deployment as failed. Only run this when a deployment is known to be wrongly unfinished/stuck and when further deployments are blocked. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: false, desc: "Environment in which to deploy this application" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application to deploy" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" def timeout_deploy app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) deployment = app_env.last_deployment if deployment && !deployment.finished? begin ui.info "Marking last deployment failed...", :green deployment.timeout ui.deployment_status(deployment) rescue EY::CloudClient::RequestFailed => e ui.error "Error encountered attempting to timeout previous deployment." raise end else raise EY::Error, "No unfinished deployment was found for #{app_env.hierarchy_name}." end end desc "status", "Show the deployment status of the app" long_desc <<-DESC Show the current status of most recent deployment of the specified application and environment. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment where the application is deployed" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the application can be found" def status app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) deployment = app_env.last_deployment if deployment ui.deployment_status(deployment) else raise EY::Error, "Application #{app_env.app.name} has not been deployed on #{app_env.environment.name}." end end desc "environments [--all]", "List environments for this app; use --all to list all environments." long_desc <<-DESC By default, environments for this app are displayed. The --all option will display all environments, including those for this app. DESC method_option :all, type: :boolean, aliases: %(-A), desc: "Show all environments (ignores --app, --account, and --environment arguments)" method_option :simple, type: :boolean, aliases: %(-s), desc: "Display one environment per line with no extra output" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Show environments for this application" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Show environments in this account" method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Show environments matching environment name" def environments if options[:all] && options[:simple] ui.print_simple_envs api.environments elsif options[:all] ui.print_envs api.apps else remotes = nil if options[:app] == '' repo.fail_on_no_remotes! remotes = repo.remotes end resolver = api.resolve_app_environments({ account_name: options[:account], app_name: options[:app], environment_name: options[:environment], remotes: remotes, }) resolver.no_matches do |errors| messages = errors messages << "Use #{self.class.send(:banner_base)} environments --all to see all environments." raise EY::NoMatchesError.new(messages.join("\n")) end apps = resolver.matches.map { |app_env| app_env.app }.uniq if options[:simple] if apps.size > 1 message = "# This app matches multiple Applications in Engine Yard Cloud:\n" apps.each { |app| message << "#\t#{app.name}\n" } message << "# The following environments contain those applications:\n\n" ui.warn(message) end ui.print_simple_envs(apps.map{ |app| app.environments }.flatten) else ui.print_envs(apps, config.default_environment) end end end map "envs" => :environments desc "servers", "List servers for an environment." long_desc <<-DESC Display a list of all servers on an environment. Specify -s (--simple) to make parsing the output easier or -uS (--user --host) to output bash loop friendly "user@hostname" DESC method_option :simple, type: :boolean, aliases: %(-s), desc: "Display all information in a simplified format without extra text or column alignment" method_option :host, type: :boolean, aliases: %(-S), desc: "Display only hostnames, one per newline (use options -uS (--user --host) for user@hostname)" method_option :user, type: :boolean, aliases: %w(-u), desc: "Include the ssh username in front of the hostname for easy SSH scripting" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Find environment in this account" method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Show servers in environment matching environment name" method_option :all, type: :boolean, aliases: %(-A), desc: "Show all servers (for compatibility only, this is the default for this command)" method_option :app_master, type: :boolean, desc: "Show only app master server" method_option :app_servers, type: :boolean, aliases: %w(--app), desc: "Show only application servers" method_option :db_servers, type: :boolean, aliases: %w(--db), desc: "Show only database servers" method_option :db_master, type: :boolean, desc: "Show only the master database server" method_option :db_slaves, type: :boolean, desc: "Show only the slave database servers" method_option :utilities, type: :array, lazy_default: true, aliases: %w(--util), desc: "Show only utility servers or only utility servers with the given names" def servers if options[:environment] == '' && options[:account] == '' repo.fail_on_no_remotes! end environment = nil ui.mute_if(options[:simple] || options[:host]) do environment = fetch_environment(options[:environment], options[:account]) end username = options[:user] && environment.username servers = filter_servers(environment, options, default: {all: true}) if options[:host] ui.print_hostnames(servers, username) elsif options[:simple] ui.print_simple_servers(servers, username) else ui.print_servers(servers, environment.hierarchy_name, username) end end desc "rebuild [--environment ENVIRONMENT]", "Rebuild specified environment." long_desc <<-DESC Engine Yard's main configuration run occurs on all servers. Mainly used to fix failed configuration of new or existing servers, or to update servers to latest Engine Yard stack (e.g. to apply an Engine Yard supplied security patch). Note that uploaded recipes are also run after the main configuration run has successfully completed. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment to rebuild" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" def rebuild environment = fetch_environment(options[:environment], options[:account]) ui.info "Updating instances on #{environment.hierarchy_name}" environment.rebuild end map "update" => :rebuild desc "rollback [--environment ENVIRONMENT]", "Rollback to the previous deploy." long_desc <<-DESC Uses code from previous deploy in the "/data/APP_NAME/releases" directory on remote server(s) to restart application servers. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment in which to roll back the application" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application to roll back" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :verbose, type: :boolean, aliases: %w(-v), desc: "Be verbose" method_option :config, type: :hash, default: {}, aliases: %w(--extra-deploy-hook-options), desc: "Hash made available in deploy hooks (in the 'config' hash), can also override some ey.yml settings." def rollback app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) env_config = config.environment_config(app_env.environment_name) deploy_config = EY::DeployConfig.new(options, env_config, repo, ui) ui.info "Rolling back #{app_env.hierarchy_name}" runner = serverside_runner(app_env, deploy_config.verbose) runner.rollback do |args| args.config = {'deployed_by' => api.current_user.name, 'input_ref' => 'N/A'}.merge(deploy_config.extra_config || {}) end if runner.call(ui.out, ui.err) ui.info "Rollback complete" else raise EY::Error, "Rollback failed" end end desc "ssh [COMMAND] [--all] [--environment ENVIRONMENT]", "Open an ssh session to the master app server, or run a command." long_desc <<-DESC If a command is supplied, it will be run, otherwise a session will be opened. The bridge server (app master) is used for environments with multiple instances. Option --all requires a command to be supplied and runs it on all servers or pass --each to connect to each server one after another. Note: this command is a bit picky about its ordering. To run a command with arguments on all servers, like "rm -f /some/file", you need to order it like so: $ #{banner_base} ssh "rm -f /some/file" -e my-environment --all DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment to ssh into" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :all, type: :boolean, aliases: %(-A), desc: "Run command on all servers" method_option :app_servers, type: :boolean, desc: "Run command on all application servers" method_option :db_servers, type: :boolean, desc: "Run command on the database servers" method_option :db_master, type: :boolean, desc: "Run command on the master database server" method_option :db_slaves, type: :boolean, desc: "Run command on the slave database servers" method_option :utilities, type: :array, lazy_default: true, desc: "Run command on the utility servers with the given names. If no names are given, run on all utility servers." method_option :shell, type: :string, default: 'bash', aliases: %w(-s), desc: "Run command in a shell other than bash. Use --no-shell to run the command without a shell." method_option :pty, type: :boolean, default: false, aliases: %w(-t), desc: "If a command is given, run in a pty. Required for interactive commands like sudo." method_option :bind_address, type: :string, aliases: %w(-L), desc: "When a command is not given, pass -L to the ssh command." method_option :each, type: :boolean, default: false, desc: "If no command is given, connect to multiple servers each one after another, instead of exiting with an error." def ssh(cmd=nil) environment = fetch_environment(options[:environment], options[:account]) instances = filter_servers(environment, options, default: {app_master: true}) user = environment.username ssh_opts = [] if cmd if options[:shell] cmd = Escape.shell_command([options[:shell],'-lc',cmd]) end if options[:pty] ssh_opts = ["-t"] elsif cmd =~ /sudo/ ui.warn "sudo commands often need a tty to run correctly. Use -t option to spawn a tty." end else if instances.size != 1 && options[:each] == false raise NoCommandError.new end if options[:bind_address] ssh_opts = ["-L", options[:bind_address]] end end ssh_cmd = ["ssh"] ssh_cmd += ssh_opts trap(:INT) { abort "Aborting..." } exits = [] instances.each do |instance| host = instance.public_hostname name = instance.name ? "#{instance.role} (#{instance.name})" : instance.role ui.info "\nConnecting to #{name} #{host}..." unless cmd ui.info "Ctrl + C to abort" sleep 1.3 end sshcmd = Escape.shell_command((ssh_cmd + ["#{user}@#{host}"] + [cmd]).compact) ui.debug "$ #{sshcmd}" system sshcmd exits << $?.exitstatus end exit exits.detect {|status| status != 0 } || 0 end desc "console [--app APP] [--environment ENVIRONMENT] [--account ACCOUNT]", "Open a Rails console session to the master app server." long_desc <<-DESC Opens a Rails console session on app master. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment to console into" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" def console app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) instances = filter_servers(app_env.environment, options, default: {app_master: true}) user = app_env.environment.username cmd = "cd /data/#{app_env.app.name}/current && bundle exec rails console" cmd = Escape.shell_command(['bash','-lc',cmd]) ssh_cmd = ["ssh"] ssh_cmd += ["-t"] trap(:INT) { abort "Aborting..." } exits = [] instances.each do |instance| host = instance.public_hostname name = instance.name ? "#{instance.role} (#{instance.name})" : instance.role ui.info "\nConnecting to #{name} #{host}..." unless cmd ui.info "Ctrl + C to abort" sleep 1.3 end sshcmd = Escape.shell_command((ssh_cmd + ["#{user}@#{host}"] + [cmd]).compact) ui.debug "$ #{sshcmd}" system sshcmd exits << $?.exitstatus end exit exits.detect {|status| status != 0 } || 0 end desc "scp [FROM_PATH] [TO_PATH] [--all] [--environment ENVIRONMENT]", "scp a file to/from multiple servers in an environment" long_desc <<-DESC Use the system `scp` command to copy files to some or all of the servers. If `HOST:` is found in the FROM_PATH or TO_PATH, the server name will be substituted in place of `HOST:` when scp is run. This allows you to scp in either direction by putting `HOST:` in the FROM_PATH or TO_PATH, as follows: $ #{banner_base} scp example.json HOST:/data/app_name/current/config/ -e env --app-servers $ #{banner_base} scp HOST:/data/app_name/current/config/example.json ./ -e env --app-servers If `HOST:` is not specified, TO_PATH will be used as the remote path. Be sure to escape shell words so they don't expand locally (e.g. '~'). Note: this command is a bit picky about its ordering. FROM_PATH TO_PATH must follow immediately after `ey scp` with no flags in between. DESC method_option :environment, :type => :string, :aliases => %w(-e), :required => true, :default => '', :desc => "Name of the destination environment" method_option :account, :type => :string, :aliases => %w(-c), :required => true, :default => '', :desc => "Name of the account in which the environment can be found" method_option :all, :type => :boolean, :aliases => %(-A), :desc => "scp to all servers" method_option :app_servers, :type => :boolean, :desc => "scp to all application servers" method_option :db_servers, :type => :boolean, :desc => "scp to database servers" method_option :db_master, :type => :boolean, :desc => "scp to the master database server" method_option :db_slaves, :type => :boolean, :desc => "scp to the slave database servers" method_option :utilities, :type => :array, :lazy_default => true, :desc => "scp to all utility servers or only those with the given names" def scp(from_path, to_path) environment = fetch_environment(options[:environment], options[:account]) instances = filter_servers(environment, options, default: {app_master: true}) user = environment.username ui.info "Copying '#{from_path}' to '#{to_path}' on #{instances.count} server#{instances.count == 1 ? '' : 's'} serially..." # default to `scp FROM_PATH HOST:TO_PATH` unless [from_path, to_path].detect { |path| path =~ /HOST:/ } to_path = "HOST:#{to_path}" end exits = [] instances.each do |instance| host = instance.public_hostname authority = "#{user}@#{host}:" name = instance.name ? "#{instance.role} (#{instance.name})" : instance.role ui.info "# #{name} #{host}" from = from_path.sub(/^HOST:/, authority) to = to_path.sub(/^HOST:/, authority) cmd = Escape.shell_command(["scp", from, to]) ui.debug "$ #{cmd}" system cmd exits << $?.exitstatus end exit exits.detect {|status| status != 0 } || 0 end no_tasks do OPT_TO_ROLES = { all: %w[all], app_master: %w[solo app_master], app_servers: %w[solo app app_master], db_servers: %w[solo db_master db_slave], db_master: %w[solo db_master], db_slaves: %w[db_slave], utilities: %w[util], } def filter_servers(environment, cli_opts, filter_opts) if (cli_opts.keys.map(&:to_sym) & OPT_TO_ROLES.keys).any? options = cli_opts.dup else options = filter_opts[:default].dup end options.keep_if {|k,v| OPT_TO_ROLES.has_key?(k.to_sym) } if options[:all] instances = environment.instances else roles = {} options.each do |cli_opt,cli_val| if cli_val && OPT_TO_ROLES.has_key?(cli_opt.to_sym) OPT_TO_ROLES[cli_opt.to_sym].each do |role| roles[role] = cli_val # val is true or an array of strings end end end instances = environment.select_instances(roles) end if instances.empty? raise NoInstancesError.new(environment.name) end return instances end end desc "logs [--environment ENVIRONMENT]", "Retrieve the latest logs for an environment." long_desc <<-DESC Displays Engine Yard configuration logs for all servers in the environment. If recipes were uploaded to the environment & run, their logs will also be displayed beneath the main configuration logs. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment with the interesting logs" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" def logs environment = fetch_environment(options[:environment], options[:account]) environment.logs.each do |log| ui.say "Instance: #{log.instance_name}" if log.main ui.say "Main logs for #{environment.name}:", :green ui.say log.main end if log.custom ui.say "Custom logs for #{environment.name}:", :green ui.say log.custom end end end desc "recipes", "Commands related to chef recipes." subcommand "recipes", EY::CLI::Recipes desc "web", "Commands related to maintenance pages." subcommand "web", EY::CLI::Web desc "version", "Print version number." def version ui.say %{engineyard version #{EY::VERSION}} end map ["-v", "--version"] => :version desc "help [COMMAND]", "Describe all commands or one specific command." def help(*cmds) if cmds.empty? base = self.class.send(:banner_base) list = self.class.printable_tasks ui.say "Usage:" ui.say " #{base} [--help] [--version] COMMAND [ARGS]" ui.say ui.say "Deploy commands:" deploy_cmds = %w(deploy environments logs rebuild rollback status) deploy_cmds.map! do |name| list.find{|task| task[0] =~ /^#{base} #{name}/ } end list -= deploy_cmds ui.print_help(deploy_cmds) ui.say self.class.subcommands.each do |name| klass = self.class.subcommand_class_for(name) list.reject!{|cmd| cmd[0] =~ /^#{base} #{name}/} ui.say "#{name.capitalize} commands:" tasks = klass.printable_tasks.reject{|t| t[0] =~ /help$/ } ui.print_help(tasks) ui.say end %w(help version).each{|n| list.reject!{|c| c[0] =~ /^#{base} #{n}/ } } if list.any? ui.say "Other commands:" ui.print_help(list) ui.say end self.class.send(:class_options_help, shell) ui.say "See '#{base} help COMMAND' for more information on a specific command." elsif klass = self.class.subcommand_class_for(cmds.first) klass.new.help(*cmds[1..-1]) else super end end desc "launch [--app APP] [--environment ENVIRONMENT] [--account ACCOUNT]", "Open application in browser." method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment where the application is deployed" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the application can be found" def launch app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) Launchy.open(app_env.uri) end desc "whoami", "Who am I logged in as?" def whoami current_user = api.current_user ui.say "#{current_user.name} (#{current_user.email})" end desc "login", "Log in and verify access to Engine Yard Cloud." long_desc <<-DESC You may run this command to log in to EY Cloud without performing any other action. Once you are logged in, a file will be stored at ~/.eyrc with your API token. You may override the location of this file using the $EYRC environment variable. Instead of logging in, you may specify a token on the command line with --api-token or using the $ENGINEYARD_API_TOKEN environment variable. DESC def login whoami end desc "logout", "Remove the current API key from ~/.eyrc or env variable $EYRC" def logout eyrc = EYRC.load if eyrc.delete_api_token ui.info "API token removed: #{eyrc.path}" ui.info "Run any other command to login again." else ui.info "Already logged out. Run any other command to login again." end end end # CLI end # EY
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/thor.rb
lib/engineyard/thor.rb
$:.unshift(File.expand_path('../vendor/thor/lib/', File.dirname(__FILE__))) require 'thor' module EY module UtilityMethods protected def api @api ||= EY::CLI::API.new(config.endpoint, ui, options[:api_token]) end def config @config ||= EY::Config.new end # engineyard gem uses ui everywhere, thore supplies shell def ui shell end def in_repo? EY::Repo.exist? end def repo @repo ||= EY::Repo.new end def serverside_version respond_to?(:options) && options[:serverside_version] || EY::ENGINEYARD_SERVERSIDE_VERSION end def serverside_runner(app_env, verbose, serverside_version = serverside_version(), ignore_bad_bridge = false) ServersideRunner.new({ bridge: app_env.environment.bridge!(ignore_bad_bridge).hostname, app: app_env.app, environment: app_env.environment, verbose: verbose, serverside_version: serverside_version }) end def use_default_environment if env = config.default_environment ui.info "Using default environment #{config.default_environment.inspect} from ey.yml." env end end def fetch_environment(environment_name, account_name) ui.info "Loading application data from Engine Yard Cloud..." environment_name ||= use_default_environment remotes = repo.remotes if in_repo? constraints = { environment_name: environment_name, account_name: account_name, remotes: remotes, } resolver = api.resolve_environments(constraints) resolver.one_match { |match| return match } resolver.no_matches do |errors, suggestions| raise_no_matches(errors, suggestions) end resolver.many_matches do |matches| if environment_name message = "Multiple environments possible, please be more specific:\n\n" matches.each do |env| message << "\t#{env.name.ljust(25)} # ey <command> --environment='#{env.name}' --account='#{env.account.name}'\n" end raise EY::MultipleMatchesError.new(message) else raise EY::AmbiguousEnvironmentGitUriError.new(matches) end end end def fetch_app_environment(app_name, environment_name, account_name) ui.info "Loading application data from Engine Yard Cloud..." environment_name ||= use_default_environment remotes = repo.remotes if in_repo? constraints = { app_name: app_name, environment_name: environment_name, account_name: account_name, remotes: remotes, } if constraints.all? { |k,v| v.nil? || v.empty? || v.to_s.empty? } raise EY::NoMatchesError.new <<-ERROR Unable to find application without a git remote URI or app name. Please specify --app=app_name or add this application at #{config.endpoint}" ERROR end resolver = api.resolve_app_environments(constraints) resolver.one_match { |match| return match } resolver.no_matches do |errors, suggestions| raise_no_matches(errors, suggestions) end resolver.many_matches do |app_envs| raise EY::MultipleMatchesError.new(too_many_app_environments_error(app_envs)) end end def raise_no_matches(errors, suggestions) message = "We found the following suggestions:\n" if suggestions.any? suggestions.each do |suggest| message << " # ey <command> --account='#{suggest['account_name']}' --app='#{suggest['app_name']}' --environment='#{suggest['env_name']}'\n" end raise EY::NoMatchesError.new([errors,message].compact.join("\n").strip) end def too_many_app_environments_error(app_envs) message = "Multiple application environments possible, please be more specific:\n\n" app_envs.group_by do |app_env| [app_env.account_name, app_env.app_name] end.sort_by { |k,v| k.join }.each do |(account_name, app_name), grouped_app_envs| message << "\n" message << account_name << "/" << app_name << "\n" grouped_app_envs.map { |ae| ae.environment_name }.uniq.sort.each do |env_name| message << "\t#{env_name.ljust(25)}" message << " # ey <command> --account='#{account_name}' --app='#{app_name}' --environment='#{env_name}'\n" end end message end end # UtilityMethods class Thor < ::Thor include UtilityMethods check_unknown_options! no_tasks do def self.subcommand_help(cmd) desc "#{cmd} help [COMMAND]", "Describe all subcommands or one specific subcommand." class_eval <<-RUBY def help(*args) if args.empty? ui.say "usage: #{banner_base} #{cmd} COMMAND" ui.say subcommands = self.class.printable_tasks.sort_by{|s| s[0] } subcommands.reject!{|t| t[0] =~ /#{cmd} help$/} ui.print_help(subcommands) ui.say self.class.send(:class_options_help, ui) ui.say "See #{banner_base} #{cmd} help COMMAND" + " for more information on a specific subcommand." if args.empty? else super end end RUBY end def self.banner_base "ey" end def self.banner(task, task_help = false, subcommand = false) subcommand_banner = to_s.split(/::/).map{|s| s.downcase}[2..-1] subcommand_banner = if subcommand_banner.size > 0 subcommand_banner.join(' ') else nil end task = (task_help ? task.formatted_usage(self, false, subcommand) : task.name) [banner_base, subcommand_banner, task].compact.join(" ") end def self.handle_no_task_error(task) raise UndefinedTaskError, "Could not find command #{task.inspect}." end def self.subcommand(name, klass) @@subcommand_class_for ||= {} @@subcommand_class_for[name] = klass super end def self.subcommand_class_for(name) @@subcommand_class_for ||= {} @@subcommand_class_for[name] end end protected def self.exit_on_failure? true end end # patch handle_no_method_error? to work with rubinius' error text. class ::Thor::Task def handle_no_method_error?(instance, error, caller) not_debugging?(instance) && ( error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/ || error.message =~ /undefined method `#{name}' on an instance of #{Regexp.escape(instance.class.name)}/ ) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/config.rb
lib/engineyard/config.rb
require 'uri' require 'yaml' require 'pathname' require 'engineyard/error' module EY class Config # This order is important. CONFIG_FILES = ["config/ey.yml", "ey.yml"].map {|path| Pathname.new(path)}.freeze TEMPLATE_PATHNAME = Pathname.new(__FILE__).dirname.join('templates','ey.yml').freeze def self.pathname_for_write pathname || CONFIG_FILES.find{|pathname| pathname.dirname.exist? } end def self.pathname CONFIG_FILES.find{|pathname| pathname.exist? } end def self.template_pathname TEMPLATE_PATHNAME end def self.load_config(path = pathname) config = YAML.load_file(path.to_s) if path && path.exist? config ||= {} # load_file returns `false' when the file is empty unless Hash === config raise "ey.yml load error: Expected a Hash but a #{config.class.name} was returned." end config end attr_reader :path def initialize(file = nil) @path = file ? Pathname.new(file) : self.class.pathname @config = self.class.load_config(@path) @config["environments"] ||= {} end def method_missing(meth, *args, &blk) key = meth.to_s.downcase if @config.key?(key) @config[key] else super end end def respond_to?(meth) key = meth.to_s.downcase @config.key?(key) || super end def fetch(key, default = nil, &block) block ? @config.fetch(key.to_s, &block) : @config.fetch(key.to_s, default) end def fetch_from_defaults(key, default=nil, &block) block ? defaults.fetch(key.to_s, &block) : defaults.fetch(key.to_s, default) end def [](key) @config[key.to_s.downcase] end def endpoint env_var_endpoint || default_endpoint end def env_var_endpoint ENV["CLOUD_URL"] end def default_endpoint "https://cloud.engineyard.com/" end def default_endpoint? default_endpoint == endpoint end def default_environment d = environments.find do |name, env| env && env["default"] end d && d.first end def defaults @config['defaults'] ||= {} end def environment_config(environment_name) environments[environment_name] ||= {} EnvironmentConfig.new(environments[environment_name], environment_name, self) end class EnvironmentConfig attr_reader :name def initialize(config, name, parent) @config = config || {} @name = name @parent = parent end def path @parent.path end def ensure_exists unless path && path.exist? raise EY::Error, "Please initialize this application with the following command:\n\tey init" end end def fetch(key, default = nil, &block) @config.fetch(key.to_s) do @parent.fetch_from_defaults(key.to_s, default, &block) end end def branch fetch('branch', nil) end def migrate ensure_exists fetch('migrate') do raise EY::Error, "'migrate' not found in #{path}. Reinitialize with:\n\tey init" end end def migration_command ensure_exists fetch('migration_command') do raise EY::Error, "'migration_command' not found in #{path}. Reinitialize with:\n\tey init" end end alias migrate_command migration_command def verbose fetch('verbose', false) end end private class ConfigurationError < EY::Error def initialize(key, value, source, message=nil) super %|"#{key}" from #{source} has invalid value: #{value.inspect}#{": #{message}" if message}| end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/repo.rb
lib/engineyard/repo.rb
require 'engineyard/error' require 'pathname' module EY class Repo class NotAGitRepository < EY::Error attr_reader :dir def initialize(output) @dir = File.expand_path(ENV['GIT_DIR'] || ENV['GIT_WORK_TREE'] || '.') super("#{output} (#{@dir})") end end class NoRemotesError < EY::Error def initialize(path) super "fatal: No git remotes found in #{path}" end end def self.exist? `git rev-parse --git-dir 2>&1` $?.success? end attr_reader :root # $GIT_DIR is what git uses to override the location of the .git dir. # $GIT_WORK_TREE is the working tree for git, which we'll use after $GIT_DIR. # # We use this to specify which repo we should look at, since it would also # specify where any git commands are directed, thus fooling commands we # run anyway. def initialize end def root @root ||= begin out = `git rev-parse --show-toplevel 2>&1`.strip if $?.success? && !out.empty? Pathname.new(out) else raise EY::Repo::NotAGitRepository.new(out) end end end def ensure_repository! root end def has_committed_file?(file) ensure_repository! `git ls-files --full-name #{file}`.strip == file && $?.success? end def has_file?(file) ensure_repository! has_committed_file?(file) || root.join(file).exist? end # Read the committed version at HEAD (or ref) of a file using the git working tree relative filename. # If the file is not committed, but does exist, a warning will be displayed # and the file will be read anyway. # If the file does not exist, returns nil. # # Example: # # read_file('config/ey.yml') # will read $GIT_WORK_TREE/config/ey.yml # def read_file(file, ref = 'HEAD') ensure_repository! if has_committed_file?(file) # TODO warn if there are unstaged changes. `git show #{ref}:#{file}` else EY.ui.warn <<-WARN Warn: #{file} is not committed to this git repository: \t#{root} This can prevent ey deploy from loading this file for certain server side deploy-time operations. Commit this file to fix this warning. WARN root.join(file).read end end def current_branch ensure_repository! branch = `git symbolic-ref -q HEAD`.chomp.gsub("refs/heads/", "") branch.empty? ? nil : branch end def remotes ensure_repository! @remotes ||= `git remote -v`.scan(/\t[^\s]+\s/).map { |c| c.strip }.uniq end def fail_on_no_remotes! if remotes.empty? raise EY::Repo::NoRemotesError.new(root) end end end # Repo end # EY
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/eyrc.rb
lib/engineyard/eyrc.rb
module EY class EYRC attr_reader :path DEFAULT_PATH = "~/.eyrc" def self.load new(ENV['EYRC'] || DEFAULT_PATH) end def initialize(path) @path = Pathname.new(path).expand_path end def exist? path.exist? end def delete_api_token delete('api_token') end def api_token self['api_token'] end def api_token=(token) self['api_token'] = token end private def [](key) read_data[key.to_s] end def []=(key,val) new_data = read_data.merge(key.to_s => val) write_data new_data val end def delete(key) data = read_data.dup res = data.delete(key) write_data data res end def read_data exist? && YAML.load(path.read) || {} end def write_data(new_data) path.open("w") {|f| YAML.dump(new_data, f) } end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/error.rb
lib/engineyard/error.rb
module EY class Error < RuntimeError end class NoCommandError < EY::Error def initialize super "Specify a command to run via ssh or use --each to cycle through each server one at a time." end end class NoInstancesError < EY::Error def initialize(env_name) super "The environment '#{env_name}' does not have any matching instances." end end class ResolverError < Error; end class NoMatchesError < ResolverError; end class MultipleMatchesError < ResolverError; end class AmbiguousEnvironmentGitUriError < ResolverError def initialize(environments) message = "The repository url in this directory is ambiguous.\n" message << "Please use -e <envname> to specify one of the following environments:\n" environments.sort do |a, b| if a.account == b.account a.name <=> b.name else a.account.name <=> b.account.name end end.each { |env| message << "\t#{env.name} (#{env.account.name})\n" } super message end end class DeployArgumentError < EY::Error; end class BranchMismatchError < DeployArgumentError def initialize(default, ref) super <<-ERR Your default branch is set to #{default.inspect} in ey.yml. To deploy #{ref.inspect} you can: * Delete the line 'branch: #{default}' in ey.yml OR * Use the -R [REF] or --force-ref [REF] options as follows: Usage: ey deploy -R #{ref} ey deploy --force-ref #{ref} ERR end end class RefAndMigrateRequiredOutsideRepo < DeployArgumentError def initialize(options) super <<-ERR Because defaults are stored in a file in your application dir, when specifying --app you must also specify the --ref and the --migrate or --no-migrate options. Usage: ey deploy --app #{options[:app]} --ref [ref] --migrate [COMMAND] ey deploy --app #{options[:app]} --ref [branch] --no-migrate ERR end end class RefRequired < DeployArgumentError def initialize(options) super <<-ERR Unable to determine the branch or ref to deploy Usage: ey deploy --ref [ref] ERR end end class MigrateRequired < DeployArgumentError def initialize(options) super <<-ERR Unable to determine migration choice. ey deploy no longer migrates by default. Usage: ey deploy --migrate ey deploy --no-migrate ERR end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/deploy_config/ref.rb
lib/engineyard/deploy_config/ref.rb
require 'engineyard/error' module EY class DeployConfig class Ref def initialize(cli_opts, env_config, repo, ui) @cli_opts = cli_opts @default = env_config.branch @repo = repo @force_ref = @cli_opts.fetch('force_ref', false) @ui = ui if @force_ref.kind_of?(String) @ref, @force_ref = @force_ref, true else @ref = @cli_opts.fetch('ref', nil) @ref = nil if @ref == '' end end def when_inside_repo if !@force_ref && @ref && @default && @ref != @default raise BranchMismatchError.new(@default, @ref) elsif @force_ref && @ref && @default @ui.say "Default ref overridden with #{@ref.inspect}." end @ref || use_default || use_current_branch || raise(RefRequired.new(@cli_opts)) end def use_default if @default @ui.say "Using default branch #{@default.inspect} from ey.yml." @default end end def use_current_branch if current = @repo.current_branch @ui.say "Using current HEAD branch #{current.inspect}." current end end # a.k.a. not in the correct repo # # returns the ref if it was passed in the cli opts. # or raise def when_outside_repo @ref or raise RefAndMigrateRequiredOutsideRepo.new(@cli_opts) end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/templates/ey_yml.rb
lib/engineyard/templates/ey_yml.rb
require 'erb' module EY module Templates class EyYml PATH = Pathname.new(__FILE__).dirname.join('ey.yml.erb').freeze attr_reader :existing_config, :existing, :config, :template def initialize(existing, template=PATH) @template = template @existing = existing.dup @environments = @existing.delete('environments') || {} @existing_config = @existing.delete('defaults') || {} @config = defaults.merge(@existing_config) fix_config! end def to_str ERB.new(template.read, 0, "<>").result(binding) end alias to_s to_str def write(dest) dest = Pathname.new(dest) dir = dest.dirname temp = dir.join("ey.yml.tmp") # generate first so we don't overwrite with a failed generation output = to_str temp.open('w') { |f| f << output } FileUtils.mv(dest, dir.join("ey.yml.backup")) if dest.exist? FileUtils.mv(temp, dest) end protected def fix_config! if config['migrate'] == nil && existing_config['migration_command'] config['migrate'] = true end end def defaults { "migrate" => Pathname.new('db/migrate').exist?, "migration_command" => "rake db:migrate --trace", "precompile_assets" => Pathname.new('app/assets').exist?, "precompile_assets_task" => "assets:precompile", "asset_dependencies" => nil, # %w[app/assets lib/assets vendor/assets Gemfile.lock config/application.rb config/routes.rb], "asset_strategy" => "shifting", "precompile_unchanged_assets" => false, "bundle_without" => nil, "bundle_options" => nil, "maintenance_on_migrate" => true, "maintenance_on_restart" => nil, "verbose" => false, "ignore_database_adapter_warning" => false, } end def option_unless_default(key) value = config[key] if value != nil && value != defaults[key] option(key, value) else commented_option key end end def option(key, value = nil) value ||= config[key] dump_indented_yaml key => value end def commented_option(key) data = {key => defaults[key]} " ##{dump_indented_yaml(data, 0)}" end def extra_root_options out = "" extra_defaults = config.reject { |k,v| defaults.key?(k) } extra_defaults.each do |key,val| out << option(key, val) << "\n" end unless existing.empty? out << dump_indented_yaml(existing, 0) end out end def environment_options if @environments && !@environments.empty? dump_indented_yaml(@environments) end end def dump_indented_yaml(data, indent=2) YAML.dump(data).sub(/^---/, '').lstrip.gsub(/^/,' '*indent) end def string_to_boolean(str) case str when "true" then true when "false" then false else str end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/cli/ui.rb
lib/engineyard/cli/ui.rb
require 'highline' module EY class CLI class UI < Thor::Base.shell class Tee def initialize(*ios) @ios = ios end def <<(str) @ios.each { |io| io << str } self end end class Prompter def self.add_answer(arg) @answers ||= [] @answers << arg end def self.questions @questions end def self.enable_mock! @questions = [] @answers = [] @mock = true end def self.highline @highline ||= HighLine.new($stdin) end def self.interactive? @mock || ($stdout && $stdout.tty?) end def self.ask(question, password = false, default = nil) if @mock @questions ||= [] @questions << question answer = @answers.shift (answer == '' && default) ? default : answer else timeout_if_not_interactive do highline.ask(question) do |q| q.echo = "*" if password q.default = default if default end.to_s end end end def self.agree(question, default) if @mock @questions ||= [] @questions << question answer = @answers.shift answer == '' ? default : %w[y yes].include?(answer) else timeout_if_not_interactive do answer = highline.agree(question) {|q| q.default = default ? 'Y/n' : 'N/y' } case answer when 'Y/n' then true when 'N/y' then false else answer end end end end def self.timeout_if_not_interactive(&block) if interactive? block.call else Timeout.timeout(2, &block) end end end def error(name, message = nil) $stdout = $stderr say_with_status(name, message, :red) ensure $stdout = STDOUT end def warn(name, message = nil) say_with_status(name, message, :yellow) end def info(message, color = nil) return if quiet? say_with_status(message, nil, color) end def debug(name, message = nil) if ENV["DEBUG"] name = name.inspect unless name.nil? or name.is_a?(String) message = message.inspect unless message.nil? or message.is_a?(String) say_with_status(name, message, :blue) end end def say_with_status(name, message=nil, color=nil) if message say_status name, message, color elsif name say name, color end end def interactive? Prompter.interactive? end def agree(message, default) Prompter.agree(message, default) end def ask(message, password = false, default = nil) Prompter.ask(message, password, default) rescue EOFError return '' end def mute_if(bool, &block) bool ? mute(&block) : yield end def server_tuples(servers, username=nil) user = username && "#{username}@" servers.map do |server| host = "#{user}#{server.hostname}" [host, server.amazon_id, server.role, server.name] end end private :server_tuples def print_hostnames(servers, username=nil) server_tuples(servers, username).each do |server_tuple| puts server_tuple.first end end def print_simple_servers(servers, username=nil) server_tuples(servers, username).each do |server_tuple| puts server_tuple.join("\t") end end def print_servers(servers, name, username=nil) tuples = server_tuples(servers, username) count = tuples.size puts "# #{count} server#{count == 1 ? '' : 's'} on #{name}" host_width = tuples.map {|s| s[0].length }.max host_format = "%-#{host_width}s" # "%-10s" left align role_width = tuples.map {|s| s[2].length }.max role_format = "%-#{role_width}s" # "%-10s" left align tuples.each do |server_tuple| puts "#{host_format}\t%s\t#{role_format}\t%s" % server_tuple end end def print_simple_envs(envs) puts envs.map{|env| env.name }.uniq.sort end def print_envs(apps, default_env_name = nil) apps.sort_by {|app| "#{app.account.name}/#{app.name}" }.each do |app| puts "#{app.account.name}/#{app.name}" if app.environments.any? app.environments.sort_by {|env| env.name }.each do |env| icount = env.instances_count iname = case icount when 0 then "(stopped)" when 1 then "1 instance" else "#{icount} instances" end name = env.name == default_env_name ? "#{env.name} (default)" : env.name framework_env = env.framework_env && "[#{env.framework_env.center(12)}]" puts " #{name.ljust(30)} #{framework_env} #{iname}" end else puts " (No environments)" end puts "" end end def deployment_status(deployment) unless quiet? say "# Status of last deployment of #{deployment.app_environment.hierarchy_name}:" say "#" show_deployment(deployment) say "#" end deployment_result(deployment) end def show_deployment(dep) return if quiet? output = [] output << ["Account", dep.app.account.name] output << ["Application", dep.app.name] output << ["Environment", dep.environment.name] output << ["Input Ref", dep.ref] output << ["Resolved Ref", dep.resolved_ref] output << ["Commit", dep.commit || '(not resolved)'] output << ["Migrate", dep.migrate] output << ["Migrate command", dep.migrate_command] if dep.migrate output << ["Deployed by", dep.deployed_by] output << ["Started at", dep.created_at] if dep.created_at output << ["Finished at", dep.finished_at] if dep.finished_at output.each do |att, val| puts "#\t%-16s %s" % ["#{att}:", val.to_s] end end def deployment_result(dep) if dep.successful? say 'Deployment was successful.', :green elsif dep.finished_at.nil? say 'Deployment is not finished.', :yellow else say 'Deployment failed.', :red end end def print_exception(e) if e.message.empty? || (e.message == e.class.to_s) message = nil else message = e.message end if ENV["DEBUG"] error(e.class, message) e.backtrace.each{|l| say(" "*3 + l) } else error(message || e.class.to_s) end end def print_help(table) print_table(table, ident: 2, truncate: true, colwidth: 20) end def set_color(string, color, bold=false) ($stdout.tty? || ENV['THOR_SHELL']) ? super : string end def err $stderr end def out $stdout end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/cli/recipes.rb
lib/engineyard/cli/recipes.rb
require 'tempfile' module EY class CLI class Recipes < EY::Thor desc "apply [--environment ENVIRONMENT]", "Run chef recipes uploaded by '#{banner_base} recipes upload' on the specified environment." long_desc <<-DESC This is similar to '#{banner_base} rebuild' except Engine Yard's main configuration step is skipped. The cookbook uploaded by the '#{banner_base} recipes upload' command will be run when you run '#{banner_base} recipes apply'. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment in which to apply recipes" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" def apply environment = fetch_environment(options[:environment], options[:account]) apply_recipes(environment) end desc "upload [--environment ENVIRONMENT]", "Upload custom chef recipes to specified environment so they can be applied." long_desc <<-DESC Make an archive of the "cookbooks/" subdirectory in your current working directory and upload it to Engine Yard Cloud's recipe storage. Alternatively, specify a .tgz of a cookbooks/ directory yourself as follows: $ #{banner_base} recipes upload -f path/to/recipes.tgz The uploaded cookbooks will be run when executing '#{banner_base} recipes apply' and also automatically each time you update/rebuild your instances. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment that will receive the recipes" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :apply, type: :boolean, desc: "Apply the recipes immediately after they are uploaded" method_option :file, type: :string, aliases: %w(-f), required: true, default: '', desc: "Specify a gzipped tar file (.tgz) for upload instead of cookbooks/ directory" def upload environment = fetch_environment(options[:environment], options[:account]) upload_recipes(environment, options[:file]) if options[:apply] apply_recipes(environment) end end no_tasks do def apply_recipes(environment) environment.run_custom_recipes ui.info "Uploaded recipes started for #{environment.name}" end def upload_recipes(environment, filename) if filename && filename != '' environment.upload_recipes_at_path(filename) ui.info "Recipes file #{filename} uploaded successfully for #{environment.name}" else path = cookbooks_dir_archive_path environment.upload_recipes_at_path(path) ui.info "Recipes in cookbooks/ uploaded successfully for #{environment.name}" end end def cookbooks_dir_archive_path unless FileTest.exist?("cookbooks") raise EY::Error, "Could not find chef recipes. Please run from the root of your recipes repo." end recipes_file = Tempfile.new("recipes") cmd = "tar czf '#{recipes_file.path}' cookbooks/" if FileTest.exist?("data_bags") cmd = cmd + " data_bags/" end unless system(cmd) raise EY::Error, "Could not archive recipes.\nCommand `#{cmd}` exited with an error." end recipes_file.path end end desc "download [--environment ENVIRONMENT]", "Download a copy of the custom chef recipes from this environment into the current directory." long_desc <<-DESC The recipes will be unpacked into a directory called "cookbooks" in the current directory. This is the opposite of 'recipes upload'. If the cookbooks directory already exists, an error will be raised. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment for which to download the recipes" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" def download if File.exist?('cookbooks') raise EY::Error, "Cannot download recipes, cookbooks directory already exists." end environment = fetch_environment(options[:environment], options[:account]) recipes = environment.download_recipes cmd = "tar xzf '#{recipes.path}' cookbooks" if system(cmd) ui.info "Recipes downloaded successfully for #{environment.name}" else raise EY::Error, "Could not unarchive recipes.\nCommand `#{cmd}` exited with an error." end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/cli/api.rb
lib/engineyard/cli/api.rb
require 'highline' require 'engineyard-cloud-client' require 'engineyard/eyrc' module EY class CLI class API USER_AGENT = "EngineYard/#{EY::VERSION}" attr_reader :token def initialize(endpoint, ui, token = nil) @client = EY::CloudClient.new(endpoint: endpoint, output: ui.out, user_agent: USER_AGENT) @ui = ui @eyrc = EY::EYRC.load token_from('--api-token') { token } || token_from('$ENGINEYARD_API_TOKEN') { ENV['ENGINEYARD_API_TOKEN'] } || token_from(@eyrc.path, false) { @eyrc.api_token } || authenticate || token_not_loaded end def respond_to?(*a) super or @client.respond_to?(*a) end protected def method_missing(meth, *args, &block) if @client.respond_to?(meth) with_reauthentication { @client.send(meth, *args, &block) } else super end end def with_reauthentication begin yield rescue EY::CloudClient::InvalidCredentials if @specified || !@ui.interactive? # If the token is specified, we raise immediately if it is rejected. raise EY::Error, "Authentication failed: Invalid #{@source}." else @ui.warn "Authentication failed: Invalid #{@source}." authenticate retry end end end # Get the token from the provided block, saving it if it works. # Specified will help us know what to do if loading the token fails. # Returns true if it gets a token. # Returns false if there is no token. def token_from(source, specified = true) token = yield if token @client.token = token @specified = specified @source = "token from #{source}" @token = token true else false end end # Load the token from EY Cloud if interactive and # token wasn't explicitly specified previously. def authenticate if @specified return false end @source = "credentials" @specified = false @ui.info "We need to fetch your API token; please log in." begin email = @ui.ask("Email: ") passwd = @ui.ask("Password: ", true) @token = @client.authenticate!(email, passwd) @eyrc.api_token = @token true rescue EY::CloudClient::InvalidCredentials @ui.warn "Authentication failed. Please try again." retry end end # Occurs when all avenues for getting the token are exhausted. def token_not_loaded raise EY::Error, "Sorry, we couldn't get your API token." end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard/cli/web.rb
lib/engineyard/cli/web.rb
module EY class CLI class Web < EY::Thor desc "enable [--environment/-e ENVIRONMENT]", "Remove the maintenance page for this application in the given environment." method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment on which to take down the maintenance page" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application whose maintenance page will be removed" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :verbose, type: :boolean, aliases: %w(-v), desc: "Be verbose" def enable app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) ui.info "Taking down maintenance page for '#{app_env.app.name}' in '#{app_env.environment.name}'" serverside_runner(app_env, options[:verbose]).take_down_maintenance_page.call(ui.out, ui.err) end desc "disable [--environment/-e ENVIRONMENT]", "Put up the maintenance page for this application in the given environment." long_desc <<-DESC The maintenance page is taken from the app currently being deployed. This means that you can customize maintenance pages to tell users the reason for downtime on every particular deploy. Maintenance pages searched for in order of decreasing priority: * public/maintenance.html.custom * public/maintenance.html.tmp * public/maintenance.html * public/system/maintenance.html.default DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: '', desc: "Environment on which to put up the maintenance page" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application whose maintenance page will be put up" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :verbose, type: :boolean, aliases: %w(-v), desc: "Be verbose" def disable app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) ui.info "Putting up maintenance page for '#{app_env.app.name}' in '#{app_env.environment.name}'" serverside_runner(app_env, options[:verbose]).put_up_maintenance_page.call(ui.out, ui.err) end desc "restart [--environment ENVIRONMENT]", "Restart the application servers without deploying." long_desc <<-DESC Restarts the application servers (e.g. Passenger, Unicorn, etc). Respects the maintenance_on_restart settings in the application's ey.yml. Note: Uses the version of the ey.yml currently checked out on the servers. DESC method_option :environment, type: :string, aliases: %w(-e), required: true, default: false, desc: "Environment in which to deploy this application" method_option :app, type: :string, aliases: %w(-a), required: true, default: '', desc: "Name of the application to deploy" method_option :account, type: :string, aliases: %w(-c), required: true, default: '', desc: "Name of the account in which the environment can be found" method_option :verbose, type: :boolean, aliases: %w(-v), desc: "Be verbose" def restart app_env = fetch_app_environment(options[:app], options[:environment], options[:account]) ui.info "Restarting servers on #{app_env.hierarchy_name}" if serverside_runner(app_env, options[:verbose]).restart.call(ui.out, ui.err) ui.info "Restart complete" else raise EY::Error, "Restart failed" end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/markdown_lint.rb
markdown_lint.rb
# enable all linting rules by default, then override below all # Some files hard-wrap lines to around 80 characters, others do not. We don't # have a definitive guide in the GDS Way, so we shouldn't enforce either way here. exclude_rule "line-length" # Middleman starts .md files with Frontmatter (https://middlemanapp.com/basics/frontmatter/) # which describe the title of the page, category, review date and so on. # Thus we don't need to define the title of the page with a header. exclude_rule "first-line-h1" exclude_rule "first-header-h1" # Some documents may want to be explicit about the step numbers so that they # can refer to them later. For example, "go back to step 3 and repeat". # In those cases, forcing every item to be prefixed with `1` is unhelpful. exclude_rule "ol-prefix" # Sometimes we use code blocks to show example log file content or console # output, so a particular syntax highlight would not be appropriate. We should # leave it to the developer to decide whether or not a code language should # be provided. exclude_rule "fenced-code-language" # We've historically been inconsistent in avoiding the leading `$` in shell # examples: some have the extraneous `$` and some don't. exclude_rule "commands-show-output" # At time of writing, this rule is quite buggy. # # 1. # - Foo # - Bar # # ...and then later on in the doc: # # - Baz # # ...it will complain that the `-` isn't at the same indentation level as the ones # encountered earlier. But this is deliberate because the previous hyphens were # sublists within the `1.` numbered list. # # So, better to turn the rule off for now. exclude_rule "list-indent" # Some pages, such as the "Architectural deep-dive of GOV.UK", break into # sections which all follow the same format, e.g. # # ## Foo # ### Problem # ### Solution # ## Bar # ### Problem # ### Solution # # This seems a reasonable thing to be able to do and so we leave it up to # developers' discretion. exclude_rule "no-duplicate-header" # This is quite an opinionated rule that disallows characters like # !, ? or : at the end of headings. # We use these in various places and it's not clear what benefit there is # to disallowing them. exclude_rule "no-trailing-punctuation" # This rule should be triggered when blockquotes have more than one space # after the blockquote (>) symbol. However, it's a bit buggy, and fails for # markdown like this: # # > Foo # > [bar](https://example.com) baz # # ...so best to disable it. exclude_rule "no-multiple-space-blockquote" # This rule errors if it encounters a bare URL, e.g. https://example.com, # which is neither in markdown form (`[link](https://example.com`) nor # wrapped in `<https://example.com>`. # # This is a good rule to enable, however we have numerous use cases where # it isn't appropriate to make the URL linkable. For example, when # describing dynamic portions of the URL, which the reader should # substitute for their own use case: # # - https://example.com/{YOUR_ORGANISATION_ID}/bla # # So, unfortunately, we'll have to exclude the rule. exclude_rule "no-bare-urls" # This rule is a little buggy, treating the following URL markdown # as HTML: # <https://www.direct.gov.uk/__canary__> # We also have some legitimate use cases for inline HTML: for instance, # embedding an iframe on the architecture page. # So, we'll need to disable the rule. Keep an eye on the 'inline ignore' # issue: https://github.com/markdownlint/markdownlint/issues/16 # If that is implemented, we'll be able to override the rule only # in the places we want to allow inline HTML. exclude_rule "no-inline-html" # This rule stops us from having correctly rendered nested unordered # lists within an ordered list. # It is a known issue with this gem: # https://github.com/markdownlint/markdownlint/issues/296 exclude_rule "ul-indent"
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/config.rb
config.rb
require "govuk_tech_docs" require_relative "./app/requires" GovukTechDocs.configure(self) set :markdown, renderer: DeveloperDocsRenderer.new( with_toc_data: true, api: true, context: self, ), fenced_code_blocks: true, tables: true, no_intra_emphasis: true, hard_wrap: false configure :development do # Disable Google Analytics in development config[:tech_docs][:ga_tracking_id] = nil end # Configure the sitemap for Google set :url_root, config[:tech_docs][:host] activate :search_engine_sitemap, default_change_frequency: "weekly" # Load all the `dist/` directories from direct dependencies specified in package.json package = JSON.parse(File.read("package.json")) package.fetch("dependencies", []).each_key do |dep| sprockets.append_path File.join(__dir__, "node_modules", dep, "dist") end helpers do def dashboard Dashboard.new end def manual Manual.new(sitemap) end def related_things @related_things ||= RelatedThings.new(manual, current_page) end def section_url StringToId.convert(current_page.data.section) end def page_title (defined?(locals) && locals[:title]) || [current_page.data.title, current_page.data.section].compact.join(" - ") end def sanitize(contents) ActionController::Base.helpers.sanitize(contents) end end ignore "templates/*" unless ENV["SKIP_PROXY_PAGES"] == "true" ProxyPages.resources.each do |resource| proxy resource[:path], resource[:template], resource[:frontmatter] end end # Configuration for Analytics pages ignore "analytics/templates/*" page "analytics/*", layout: :analytics_layout data.analytics.events.each do |event| event_name = event["name"].downcase.gsub(" ", "_") proxy "analytics/event_#{event_name}.html", "analytics/templates/event.html", locals: { event: } end data.analytics.attributes.each do |attribute| attribute_name = attribute["name"].downcase.gsub(" ", "_") proxy "analytics/attribute_#{attribute_name}.html", "analytics/templates/attribute.html", locals: { attribute:, variant: nil } next unless attribute.variants attribute.variants.each do |variant| variant_name = variant["event_name"].downcase.gsub(" ", "_") proxy "analytics/attribute_#{attribute_name}/variant_#{variant_name}.html", "analytics/templates/attribute.html", locals: { attribute:, variant: } end end data.analytics.trackers.each do |tracker| tracker_name = tracker["name"].downcase.gsub(" ", "_") proxy "analytics/tracker_#{tracker_name}.html", "analytics/templates/tracker.html", locals: { tracker: } end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/repos_csv.rb
app/repos_csv.rb
require "csv" class ReposCSV attr_reader :hash def initialize(repos) @repos = repos end def to_csv CSV.generate do |csv| csv << ["Name", "Team", "Dependencies Team", "Docs URL", "Repo URL", "Hosted On"] @repos.each do |repo| csv << [ repo.repo_name, repo.team, repo.alerts_team, repo.html_url, repo.repo_url, repo.production_hosted_on, ] end end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/snippet.rb
app/snippet.rb
require "sanitize" class Snippet HEADINGS = %i[h1 h2 h3 h4 h5 h6].freeze def self.generate(html) # Discard first heading and everything before it. fragment = html.partition("</h1>")[2] remove_headings = Sanitize::Config.merge( Sanitize::Config::DEFAULT, remove_contents: Sanitize::Config::DEFAULT[:remove_contents] + HEADINGS, ) snippet = Sanitize.fragment(fragment, remove_headings) Nokogiri::HTML.parse(snippet).text # Avoid double-encoding. .squish .truncate(300) # https://stackoverflow.com/a/8916327 end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/repo_data.rb
app/repo_data.rb
class RepoData SEARCH_URL = "https://www.gov.uk/api/search.json?facet_publishing_app=100,examples:10,example_scope:global&facet_rendering_app=100,examples:10,example_scope:global&count=0".freeze def self.publishing_examples @publishing_examples ||= extract_examples_from_search_result("publishing_app") end def self.rendering_examples @rendering_examples ||= extract_examples_from_search_result("rendering_app") end def self.result @result ||= JSON.parse(Faraday.get(SEARCH_URL).body) end def self.extract_examples_from_search_result(facet_name) result.dig("facets", facet_name, "options").each_with_object({}) do |option, hash| hash[option.dig("value", "slug")] = option.dig("value", "example_info", "examples") end end private_class_method :result, :extract_examples_from_search_result end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/dashboard.rb
app/dashboard.rb
# View model for the dashboard. class Dashboard def chapters YAML.load_file("data/dashboard.yml", aliases: true).map do |chapter| Chapter.new(chapter) end end class Thing attr_reader :data def initialize(data) @data = data end def name data.fetch("name") end def id data.fetch("name").parameterize end def description data["description"] end end class Chapter < Thing def sections data["sections"].map { |section| Section.new(section) } end end class Section < Thing def entries from_application_page + repos + sites end private # Pull the applications from repos.yml into the first categories def from_application_page applications_in_this_section = Repos.active_apps.select do |app| app.type == name end applications_in_this_section.map do |app| App.new("name" => app.repo_name, "description" => app.description) end end def repos data["repos"].to_a.map do |repo_name| repo = GitHubRepoFetcher.instance.repo(repo_name) Repo.new(repo) end end def sites data["sites"].to_a.map do |site_data| Site.new(site_data) end end end class Site < Thing def url data.fetch("url") end end class Repo < Thing def name data.owner.login == "alphagov" ? data.name : data.full_name end def url data.html_url end end class App < Thing def url "/repos/#{id}.html" end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/proxy_pages.rb
app/proxy_pages.rb
class ProxyPages def self.resources repo_docs + govuk_schema_names + repo_overviews + repo_overviews_json + document_types + supertypes end def self.repo_docs docs = Repos.with_docs.map do |repo| docs_for_repo = GitHubRepoFetcher.instance.docs(repo.repo_name) || [] docs_for_repo.map do |page| { path: page[:path], template: "templates/external_doc_template.html", frontmatter: { title: "#{repo.repo_name}: #{page[:title]}", locals: { title: "#{repo.repo_name}: #{page[:title]}", markdown: page[:markdown], repo:, relative_path: page[:relative_path], }, data: { repo_name: repo.repo_name, source_url: page[:source_url], latest_commit: page[:latest_commit], }, }, } end end docs.flatten.compact end def self.govuk_schema_names GovukSchemas::Schema.schema_names.map do |schema_name| schema = ContentSchema.new(schema_name) { path: "/content-schemas/#{schema_name}.html", template: "templates/schema_template.html", frontmatter: { title: "Schema: #{schema.schema_name}", content: "", locals: { title: "Schema: #{schema.schema_name}", description: "Everything about the '#{schema.schema_name}' schema", schema:, }, }, } end end def self.repo_overviews Repos.all.map do |repo| { path: "/repos/#{repo.app_name}.html", template: "templates/repo_template.html", frontmatter: { title: repo.page_title, locals: { title: repo.page_title, description: "Everything about #{repo.app_name} (#{repo.description})", repo:, }, }, } end end def self.repo_overviews_json Repos.all.map do |repo| { path: "/repos/#{repo.repo_name}.json", template: "templates/json_response.json", frontmatter: { locals: { payload: repo.api_payload, }, }, } end end def self.document_types DocumentTypes.pages.map do |document_type| { path: "/document-types/#{document_type.name}.html", template: "templates/document_type_template.html", frontmatter: { title: "Document type: #{document_type.name}", content: "", locals: { title: "Document type: #{document_type.name}", description: "Everything about the '#{document_type.name}' document type", page: document_type, }, }, } end end def self.supertypes Supertypes.all.map do |supertype| { path: "/document-types/#{supertype.id}.html", template: "templates/supertype_template.html", frontmatter: { title: "#{supertype.name} supertype", content: "", locals: { title: "#{supertype.name} supertype", description: supertype.description, supertype:, }, }, } end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/source_url.rb
app/source_url.rb
class SourceUrl attr_reader :locals, :current_page def initialize(locals, current_page) @locals = locals @current_page = current_page end def source_url override_from_page || source_from_yaml_file || source_from_file end private # If a `page` local exists, see if it has a `source_url`. This is used by the # pages that are created by the proxy system because they can't use frontmatter def override_from_page locals.key?(:page) ? locals[:page].try(:source_url) : false end # In the frontmatter we can specify a `source_url`. Use this if the actual # source of the page is in another GitHub repo. def source_from_yaml_file current_page.data.source_url end # As the last fallback link to the source file in this repository. def source_from_file "https://github.com/alphagov/govuk-developer-docs/blob/main/source/#{current_page.file_descriptor[:relative_path]}" end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/supertypes.rb
app/supertypes.rb
class Supertypes def self.all data.map { |id, config| Supertype.new(id, config) } end def self.data @data ||= HTTP.get_yaml("https://raw.githubusercontent.com/alphagov/govuk_document_types/master/data/supertypes.yml") end class Supertype attr_reader :id, :name, :description, :default, :items def initialize(id, config) @id = id @name = config.fetch("name") @description = config.fetch("description") @default = config.fetch("default") @items = config.fetch("items") end def for_document_type(document_type) document_type_item = items.find { |item| item.fetch("document_types").include?(document_type) } document_type_item ? document_type_item["id"] : default end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/related_things.rb
app/related_things.rb
class RelatedThings attr_reader :manual, :current_page def initialize(manual, current_page) @manual = manual @current_page = current_page end def related_repos @related_repos ||= current_page.data.related_repos.to_a.map do |repo_name| [repo_name, "/repos/#{repo_name}.html"] end end def any_related_pages? (related_learning_pages + related_task_pages + related_alerts).any? end def related_learning_pages manual.other_pages_from_section(current_page).select do |page| page.data.type == "learn" end end def related_task_pages manual.other_pages_from_section(current_page).select do |page| page.data.type.nil? end end def related_alerts manual.other_alerts_from_subsection(current_page) end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/github_repo_fetcher.rb
app/github_repo_fetcher.rb
require "octokit" class GitHubRepoFetcher # The cache is only used locally, as GitHub Pages rebuilds the site # with an empty cache every hour and when new commits are merged. # # Setting a high cache duration below hastens local development, as # you don't have to keep pulling down lots of content from GitHub. # If you want to work with the very latest data, run `rm -r .cache` # before starting the server. # # TODO: we should supply a command line option to automate the # cache clearing step above. LOCAL_CACHE_DURATION = 1.week def self.instance @instance ||= new end # Fetch a repo from GitHub def repo(repo_name) all_alphagov_repos.find { |repo| repo.name == repo_name } || raise("alphagov/#{repo_name} not found") end # Fetch a README for an alphagov application and cache it. # Note that it is cached as pure markdown and requires further processing. def readme(repo_name) return nil if repo(repo_name).private_repo? CACHE.fetch("alphagov/#{repo_name} README", expires_in: LOCAL_CACHE_DURATION) do default_branch = repo(repo_name).default_branch HTTP.get("https://raw.githubusercontent.com/alphagov/#{repo_name}/#{default_branch}/README.md") rescue Octokit::NotFound nil end end # Fetch all markdown files under the repo's 'docs' folder def docs(repo_name) return nil if repo(repo_name).private_repo? CACHE.fetch("alphagov/#{repo_name} docs", expires_in: LOCAL_CACHE_DURATION) do recursively_fetch_files(repo_name, "docs") rescue Octokit::NotFound nil end end private def all_alphagov_repos @all_alphagov_repos ||= CACHE.fetch("all-repos", expires_in: LOCAL_CACHE_DURATION) do client.repos("alphagov") end end def latest_commit(repo_name, path) latest_commit = client.commits("alphagov/#{repo_name}", repo(repo_name).default_branch, path:).first { sha: latest_commit.sha, timestamp: latest_commit.commit.author.date, } end def recursively_fetch_files(repo_name, path) docs = client.contents("alphagov/#{repo_name}", path:) top_level_files = docs.select { |doc| doc.path.end_with?(".md") }.map do |doc| data_for_github_doc(doc, repo_name) end docs.select { |doc| doc.type == "dir" }.each_with_object(top_level_files) do |dir, files| files.concat(recursively_fetch_files(repo_name, dir.path)) end end def data_for_github_doc(doc, repo_name) contents = HTTP.get(doc.download_url) docs_path = doc.path.sub("docs/", "").match(/(.+)\..+$/)[1] filename = docs_path.split("/")[-1] title = ExternalDoc.title(contents) || filename { path: "/repos/#{repo_name}/#{docs_path}.html", title: title.to_s.force_encoding("UTF-8"), markdown: contents.to_s.force_encoding("UTF-8"), relative_path: doc.path, source_url: doc.html_url, latest_commit: latest_commit(repo_name, doc.path), } end def client @client ||= begin stack = Faraday::RackBuilder.new do |builder| builder.response :logger, nil, { headers: false } builder.use Faraday::HttpCache, serializer: Marshal, shared_cache: false builder.use Octokit::Response::RaiseError builder.use Faraday::Request::Retry, exceptions: Faraday::Request::Retry::DEFAULT_EXCEPTIONS + [Octokit::ServerError] builder.adapter Faraday.default_adapter end Octokit.middleware = stack Octokit.default_media_type = "application/vnd.github.mercy-preview+json" github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) github_client.auto_paginate = true github_client end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/search_api_docs.rb
app/search_api_docs.rb
class SearchApiReference def self.fetch_field_definitions contents = HTTP.get( field_definitions_url, ) fields = JSON.parse(contents) fields.sort_by { |name, definition| [definition["type"], name] } end def self.field_definitions_url "https://raw.githubusercontent.com/alphagov/search-api/main/config/schema/field_definitions.json" end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/requires.rb
app/requires.rb
require "active_support/all" require "tilt" require "middleman-core" require "yaml" require "json" CACHE = ActiveSupport::Cache::FileStore.new(".cache") Dir["#{File.dirname(__FILE__)}/../lib/*.rb"].sort.each { |file| require file } Dir["#{File.dirname(__FILE__)}/**/*.rb"].sort.each { |file| require file }
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/document_types.rb
app/document_types.rb
class DocumentTypes FACET_QUERY = "https://www.gov.uk/api/search.json?facet_content_store_document_type=500,examples:10,example_scope:global&count=0".freeze DOCUMENT_TYPES_URL = "https://raw.githubusercontent.com/alphagov/publishing-api/main/content_schemas/allowed_document_types.yml".freeze def self.pages known_from_search = facet_query.dig("facets", "content_store_document_type", "options").map do |o| Page.new( name: o.dig("value", "slug"), total_count: o["documents"], examples: o.dig("value", "example_info", "examples"), ) end all_document_types.map do |document_type| from_search = known_from_search.find { |p| p.name == document_type } from_search || Page.new(name: document_type, total_count: 0, examples: []) end end def self.to_csv DocumentTypesCsv.new(pages).to_csv end def self.facet_query @facet_query ||= HTTP.get(FACET_QUERY) end def self.all_document_types @all_document_types ||= HTTP.get_yaml(DOCUMENT_TYPES_URL).sort end def self.rendering_apps_from_content_store YAML.load_file("data/rendering-apps.yml", aliases: true) end def self.schema_names_by_document_type @schema_names_by_document_type ||= GovukSchemas::Schema.schema_names.each_with_object({}) do |schema_name, memo| # Notification schema is used as that is the only schema type that is currently generated for every type schema = GovukSchemas::Schema.find(notification_schema: schema_name) document_types = schema.dig("properties", "document_type", "enum") raise "Expected #{schema_name} to have a document_type property with an enum" unless document_types document_types.each do |document_type| memo[document_type] ||= [] memo[document_type] << schema_name end end end class Page attr_reader :name, :total_count, :examples def initialize(name:, total_count:, examples:) @name = name @total_count = total_count @examples = examples end def url "https://docs.publishing.service.gov.uk/document-types/#{name}.html" end def rendering_apps entry = DocumentTypes.rendering_apps_from_content_store.find { |el| el[:name] == name } entry.to_h[:apps].to_a.compact end def search_url "https://www.gov.uk/api/search.json?filter_content_store_document_type=#{name}&count=10" end def schemas shift_low_value_schemas(DocumentTypes.schema_names_by_document_type[name]) || [] end def shift_low_value_schemas(schemas) %w[ generic generic_with_external_links placeholder ].each do |low_value_schema| raise "Error building document-types page. Is ~/govuk/publishing-api is up to date?" if schemas.nil? if schemas.include?(low_value_schema) schemas.delete(low_value_schema) schemas.append(low_value_schema) end end schemas end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/string_to_id.rb
app/string_to_id.rb
require "sanitize" class StringToId def self.convert(string) Sanitize.fragment(string) .downcase .gsub(/&(amp|gt|lt);/, "") .tr(" .", "-") .tr("^a-z0-9_-", "") .gsub(/--+/, "-") end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/external_doc.rb
app/external_doc.rb
require "html/pipeline" require "uri" require_relative "./string_to_id" class ExternalDoc def self.parse(markdown, repository: "", path: "") context = { repository:, # Turn off hardbreaks as they behave different to github rendering gfm: false, base_url: URI.join( "https://github.com", "alphagov/#{repository}/blob/main/", ), image_base_url: URI.join( "https://raw.githubusercontent.com", "alphagov/#{repository}/main/", ), } context[:subpage_url] = URI.join(context[:base_url], File.join(".", File.dirname(path), "/")) context[:image_subpage_url] = URI.join(context[:image_base_url], File.join(".", File.dirname(path), "/")) filters = [ HTML::Pipeline::MarkdownFilter, HTML::Pipeline::AbsoluteSourceFilter, PrimaryHeadingFilter, HeadingFilter, AbsoluteLinkFilter, MarkdownLinkFilter, ] markdown = "" if markdown.nil? HTML::Pipeline .new(filters) .to_html(markdown.to_s.force_encoding("UTF-8"), context) end def self.title(markdown) markdown_title = markdown.split("\n")[0].to_s.match(/#(.+)/) return nil unless markdown_title markdown_title[1].strip end # When we import external documentation it can contain relative links to # source files within the repository that the documentation resides. We need # to filter out these types of links and make them absolute so that they # continue to work when rendered as part of GOV.UK Developer Docs. # # For example a link to `lib/link_expansion.rb` would be rewritten to # https://github.com/alphagov/publishing-api/blob/main/lib/link_expansion.rb class AbsoluteLinkFilter < HTML::Pipeline::Filter def call doc.search("a").each do |element| next if element["href"].nil? || element["href"].empty? href = element["href"].strip uri = begin URI.parse(href) rescue URI::InvalidURIError element.replace(element.children) nil end next if uri.nil? || uri.scheme || href.start_with?("#") element["href"] = if href.start_with?("/") # This is an absolute path. # By default, this would make the link relative to github.com, # e.g. github.com/foo.txt, when really we need it to be # github.com/alphagov/REPO_NAME/foo.txt. # So remove the preceding "/" to turn into a relative link, # then combine with the base repository URL. href = href[1..] URI.join(context[:base_url], href).to_s else # This is a relative path. # Rather than join to the base repository URL, we want to be # context-aware, so that if we're parsing a `./bar.txt` URL # from within the `docs/` folder, we get a `docs/bar.txt` result, # not a `alphagov/REPO_NAME/bar.txt` result. URI.join(context[:subpage_url], href).to_s end end doc end end # When we import external documentation formatted with Markdown it can # contain links to other pages of documentation also formatted with Markdown. # When the documentation is rendered as part of GOV.UK Developer Docs we # render it as HTML so we need to rewrite the links so that they have a .html # extension to match our routing. # # For example a link to `link-expansion.md` would be rewritten to # `link-expansion.html` class MarkdownLinkFilter < HTML::Pipeline::Filter def call doc.search("a").each do |element| next if element["href"].nil? || element["href"].empty? href = element["href"].strip uri = URI.parse(href) if is_github_link?(uri.host) doc_name = internal_doc_name(repository, uri.path) element["href"] = internal_doc_path(repository, doc_name) if doc_name end end doc end private def is_github_link?(host) host == "github.com" end def internal_doc_name(repository, uri_path = "") internal_doc = uri_path.match(/^\/alphagov\/#{repository}\/blob\/(?:main|master)\/docs\/([^\/]+)\.md$/) internal_doc.is_a?(MatchData) ? internal_doc[1] : nil end def internal_doc_path(repository, doc_name) "/repos/#{repository}/#{doc_name}.html" end end # Removes the H1 from the page so that we can choose our own title class PrimaryHeadingFilter < HTML::Pipeline::Filter def call h1 = doc.at("h1:first-of-type") h1.unlink if h1.present? doc end end # This adds a unique ID to each header element so that we can reference # each section of the document when we build our table of contents navigation. class HeadingFilter < HTML::Pipeline::Filter def call headers = Hash.new(0) doc.css("h1, h2, h3, h4, h5, h6").each do |node| text = node.text id = StringToId.convert(text) headers[id] += 1 if node.children.first node[:id] = id end end doc end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/http.rb
app/http.rb
require "faraday-http-cache" require "faraday_middleware" module HTTP def self.get_yaml(url) YAML.load(get(url), aliases: true) end def self.get(url) CACHE.fetch url, expires_in: 1.hour do get_without_cache(url) end end def self.get_without_cache(url) uri = URI.parse(url) faraday = Faraday.new(url: uri) do |conn| conn.response :logger, nil, { headers: false } conn.use Faraday::HttpCache, serializer: Marshal, shared_cache: false conn.use Octokit::Response::RaiseError conn.response :json, content_type: /\bjson$/ conn.adapter Faraday.default_adapter end response = faraday.get(uri.path) response.body end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/document_types_csv.rb
app/document_types_csv.rb
require "csv" class DocumentTypesCsv def initialize(pages) @pages = pages end def to_csv CSV.generate do |csv| row = [ "Name", "Docs URL", "Number of pages", "Example URL", "Rendering apps", ] Supertypes.all.each do |supertype| row << supertype.name end csv << row @pages.each do |page| example_url = page.examples.first ? "https://www.gov.uk#{page.examples.first['link']}" : nil row = [ page.name, page.url, page.total_count, example_url, page.rendering_apps.join(", "), ] Supertypes.all.each do |supertype| row << supertype.for_document_type(page.name) end csv << row end end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/repos.rb
app/repos.rb
class Repos UNKNOWN = "unknown".freeze def self.all @all ||= YAML.load_file("data/repos.yml", aliases: true) .map { |repo_data| Repo.new(repo_data) } .sort_by(&:repo_name) end def self.public Repos.all.reject(&:private_repo?) end def self.active Repos.all.reject(&:retired?).uniq(&:repo_name) end def self.active_gems Repos.all.reject(&:retired?).select(&:is_gem?).uniq(&:repo_name) end def self.active_public Repos.active.reject(&:private_repo?) end def self.with_docs Repos.active_public.reject(&:skip_docs?) end def self.active_apps Repos.all.reject(&:retired?).select(&:is_app?) end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/content_schema.rb
app/content_schema.rb
require "govuk_schemas" class ContentSchema attr_reader :schema_name, :seed def initialize(schema_name, seed = 777) @schema_name = schema_name @seed = seed end def frontend_schema FrontendSchema.new(schema_name, seed) rescue Errno::ENOENT nil end def publisher_content_schema PublisherContentSchema.new(schema_name, seed) rescue Errno::ENOENT nil end def publisher_links_schema PublisherLinksSchema.new(schema_name, seed) rescue Errno::ENOENT nil end class FrontendSchema attr_reader :schema_name def initialize(schema_name, seed) @schema_name = schema_name @seed = seed raw_schema end def link_to_github "https://github.com/alphagov/publishing-api/blob/main/content_schemas/dist/formats/#{schema_name}/frontend/schema.json" end def random_example GovukSchemas::RandomExample.new(schema: raw_schema, seed: @seed).payload end def properties Utils.inline_definitions(raw_schema["properties"], raw_schema["definitions"]) end private def raw_schema @raw_schema ||= GovukSchemas::Schema.find(frontend_schema: schema_name) end end class PublisherContentSchema attr_reader :schema_name def initialize(schema_name, seed) @schema_name = schema_name @seed = seed raw_schema end def link_to_github "https://github.com/alphagov/publishing-api/blob/main/content_schemas/dist/formats/#{schema_name}/publisher_v2/schema.json" end def random_example GovukSchemas::RandomExample.new(schema: raw_schema, seed: @seed).payload end def properties Utils.inline_definitions(raw_schema["properties"], raw_schema["definitions"]) end private def raw_schema @raw_schema ||= GovukSchemas::Schema.find(publisher_schema: schema_name) end end class PublisherLinksSchema attr_reader :schema_name def initialize(schema_name, seed) @schema_name = schema_name @seed = seed raw_schema end def link_to_github "https://github.com/alphagov/publishing-api/blob/main/content_schemas/dist/formats/#{schema_name}/publisher_v2/links.json" end def random_example GovukSchemas::RandomExample.new(schema: raw_schema, seed: @seed).payload end def properties Utils.inline_definitions(raw_schema["properties"], raw_schema["definitions"]) end private def raw_schema @raw_schema ||= GovukSchemas::Schema.find(links_schema: schema_name) end end module Utils # Inline any keys that use definitions def self.inline_definitions(original_properties, definitions) original_properties.to_h.each do |k, v| next unless v["$ref"] original_properties[k] = definitions[v["$ref"].gsub("#/definitions/", "")] end # Inline any keys that use definitions if original_properties.to_h.dig("details", "properties") original_properties["details"]["properties"].each do |k, v| next unless v["$ref"] definition_name = v["$ref"].gsub("#/definitions/", "") original_properties["details"]["properties"][k] = definitions.fetch(definition_name) end end # Sort by keyname Hash[original_properties.to_h.sort_by(&:first)] end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/developer_docs_renderer.rb
app/developer_docs_renderer.rb
require_relative "./string_to_id" class DeveloperDocsRenderer < GovukTechDocs::TechDocsHTMLRenderer def header(text, header_level) anchor = StringToId.convert(text) tag = "h#{header_level}" "<#{tag} id='#{anchor}'>#{text}</#{tag}>" end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/manual.rb
app/manual.rb
class Manual ICINGA_ALERTS = "Icinga alerts".freeze attr_reader :sitemap def initialize(sitemap) @sitemap = sitemap end def manual_pages_grouped_by_section grouped = manual_pages .group_by { |page| page.data.section || "Uncategorised" } .sort_by { |group| group.first.downcase } [["Common tasks", most_important_pages]] + grouped end def manual_pages_about_learning_things manual_pages .select { |page| page.data.type == "learn" } .group_by { |page| page.data.section || "Uncategorised" } .sort_by { |group| group.first.downcase } end def pages_for_repo(repo_name) manual_pages.select { |page| page.data.related_repos.to_a.include?(repo_name) } end def other_pages_from_section(other_page) manual_pages.select { |page| page.data.section == other_page.data.section } - [other_page] end def other_alerts_from_subsection(current_page) return [] if current_page.data.subsection.nil? sitemap.resources .select { |page| page.data.section == ICINGA_ALERTS } .select { |page| page.data.subsection == current_page.data.subsection } .sort_by { |page| page.data.title.downcase } - [current_page] end private def most_important_pages manual_pages.select { |page| page.data.important } end def manual_pages sitemap.resources .reject { |page| page.data.section == ICINGA_ALERTS } .select { |page| page.path.start_with?("manual/") && page.path.end_with?(".html") && page.data.title } .sort_by { |page| [page.data.type || "how to", page.data.title.downcase] } end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/run_rake_task.rb
app/run_rake_task.rb
require "padrino-helpers" class RunRakeTask def self.links(application, rake_task = "") app_name = if application.respond_to?(:repo_name) application.repo_name else application end rake_task_name = rake_task.presence || "<rake task>".freeze <<~END_OF_MARKDOWN ```sh k exec deploy/#{app_name} -- rake #{rake_task_name} ``` END_OF_MARKDOWN end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/repo.rb
app/repo.rb
class Repo attr_reader :repo_data def initialize(repo_data) @repo_data = repo_data end def api_payload { app_name:, # beware renaming the key - it's used here: https://github.com/alphagov/seal/blob/36a897b099943713ea14fa2cfe1abff8b25a83a7/lib/team_builder.rb#L97 team:, alerts_team:, shortname:, production_hosted_on:, links: { self: "https://docs.publishing.service.gov.uk/repos/#{app_name}.json", html_url:, repo_url:, sentry_url:, }, } end def production_hosted_on_eks? production_hosted_on == "eks" end def production_hosted_on_aws? false end def production_hosted_on repo_data["production_hosted_on"] end def is_app? !production_hosted_on.nil? end def html_url "https://docs.publishing.service.gov.uk/repos/#{app_name}.html" end def retired? repo_data["retired"] end def is_gem? repo_data["type"] == "Gems" end def private_repo? repo_data["private_repo"] end def page_title type = is_app? ? "Application" : "Repository" if retired? "#{type}: #{app_name} (retired)" else "#{type}: #{app_name}" end end def app_name repo_data["app_name"] || repo_name end def repo_name repo_data.fetch("repo_name") end def example_published_pages RepoData.publishing_examples[repo_name] end def example_rendered_pages RepoData.rendering_examples[repo_name] end def management_url repo_data["management_url"] end def repo_url repo_data["repo_url"] || "https://github.com/alphagov/#{repo_name}" end def sentry_url if repo_data["sentry_url"] == false nil elsif repo_data["sentry_url"] repo_data["sentry_url"] else "https://sentry.io/govuk/app-#{repo_name}" end end def argo_cd_urls return [] unless production_hosted_on_eks? argo_cd_apps.each_with_object({}) do |app_name, hash| hash[app_name] = "https://argo.eks.production.govuk.digital/applications/cluster-services/#{app_name}" end end def dashboard_url if repo_data["dashboard_url"] repo_data["dashboard_url"] elsif production_hosted_on_eks? query_string = argo_cd_apps.map { |app| "var-app=#{app}" }.join("&") "https://grafana.eks.production.govuk.digital/d/app-requests/app3a-request-rates-errors-durations?#{query_string}" end end def kibana_url repo_data["kibana_url"] || kibana_url_for(app: app_name, hours: 3) end def kibana_worker_url repo_data["kibana_worker_url"] || kibana_url_for(app: "#{app_name}-worker", hours: 3, include: %w[level message]) end def api_docs_url repo_data["api_docs_url"] end def component_guide_url repo_data["component_guide_url"] end def metrics_dashboard_url repo_data["metrics_dashboard_url"] end def type repo_data.fetch("type") end def team repo_data["team"] || Repos::UNKNOWN end def alerts_team repo_data .fetch("alerts_team", team) end def description repo_data["description"] || description_from_github end def production_url return if repo_data["production_url"] == false repo_data["production_url"] || (type.in?(["Publishing apps", "Supporting apps"]) ? "https://#{repo_name}.publishing.service.gov.uk" : nil) end def readme github_readme end def skip_docs? repo_data.fetch("skip_docs", false) end private def kibana_url_for(app:, hours: 3, include: %w[level request status message]) if production_hosted_on_eks? "https://kibana.logit.io/s/13d1a0b1-f54f-407b-a4e5-f53ba653fac3/app/discover?security_tenant=global#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-#{hours}h,to:now))&_a=(columns:!(#{include.join(',')}),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'filebeat-*',key:kubernetes.labels.app_kubernetes_io%2Fname,negate:!f,params:(query:#{app}),type:phrase),query:(match_phrase:(kubernetes.labels.app_kubernetes_io%2Fname:#{app})))),index:'filebeat-*',interval:auto,query:(language:kuery,query:''),sort:!())" end end def argo_cd_apps repo_data["argo_cd_apps"] || [repo_name] end def shortname repo_data["shortname"] || app_name.underscore end def description_from_github github_repo_data["description"] end def github_repo_data return {} if private_repo? @github_repo_data ||= GitHubRepoFetcher.instance.repo(repo_name) end def github_readme return nil if private_repo? @github_readme ||= GitHubRepoFetcher.instance.readme(repo_name) end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/app/repo_sidebar.rb
app/repo_sidebar.rb
class RepoSidebar Item = Data.define(:path, :title, :children) def initialize(repo_name) @repo_name = repo_name end def items format_tree(tree) end private attr_reader :repo_name def format_tree(items) items.map do |_, value| Item.new( value[:path], value[:name], format_tree(value[:children]), ) end end def tree @tree ||= begin tree = {} docs_to_import.each do |item| path = item[:path].delete_prefix("/repos/#{repo_name}/") parts = path.split("/") current_level = tree parts.each_with_index do |part, index| current_level[part] ||= if index == parts.size - 1 # Assign title if available, otherwise use the file name { name: item[:title] || part, path: item[:path], children: {} } else { name: part, path: parts[0..index].join("/"), children: {} } end current_level = current_level[part][:children] end end tree end end def docs_to_import @docs_to_import ||= GitHubRepoFetcher.instance.docs(repo_name) || [] end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/helpers/analytics_helpers.rb
helpers/analytics_helpers.rb
module AnalyticsHelpers def urlize(string) string.downcase.gsub(" ", "_").gsub("-", "_") end def build_event(data, attributes = [], event_name = nil, output = {}) event_name ||= find_event_name(data) data.sort_by { |k, _v| k["name"] }.each do |item| name = item["name"] value = item["value"] variant = nil # look up name in the attributes, compare with this event's event_name, check if matching variant if attributes.any? && !variant attribute = attributes.find { |x| x["name"] == name } variant = find_variant(event_name, attribute) if attribute end if value case value when String output[name] = { "value" => value, "variant" => variant, } when Array output[name] = build_event(value, attributes, event_name) end else output[name] = { "value" => attribute ? attribute["type"] : value, "variant" => variant, } end end output end def find_variant(event_name, attribute) if attribute["variants"] attribute["variants"].each do |variant| return event_name if variant["event_name"] == event_name end end nil end def to_html(hash, html = "") html += "<ul class='govuk-list indented-list'>" hash.each do |key, value| if value.key?("value") link = "/analytics/attribute_#{urlize(key)}.html" link = "/analytics/attribute_#{urlize(key)}/variant_#{value['variant']}.html" if value["variant"] html += "<li><a href='#{link}' class='govuk-link'>#{key}</a>: #{value['value']}</li>" else html += "<li>#{key}: #{to_html(value)}</li>" end end html += "</ul>" html end def tag_colours { "high" => "govuk-tag--red", "medium" => "govuk-tag--yellow", "low" => "govuk-tag--green", } end def implementation_percentage(events) implemented = events.select { |x| x["implemented"] == true }.count percentage = ((implemented.to_f / events.count) * 100.00).round(2) percentage = 0 if implemented.zero? || events.count.zero? "#{implemented} of #{events.count} (#{percentage}%)" end def create_page_title(title) header = ["GOV.UK GA4 Implementation record"] header.prepend(title) if title header.join(" | ") end def events_by_type(events = nil) events ||= data.analytics.events.map { |e| JSON.parse(e.to_json) } by_type = {} events.each do |event| event["events"].each_with_index do |e, index| event_name = find_event_name(e["data"]) result = { name: event["name"], event_name: e["name"], index:, } if by_type[event_name.to_sym] by_type[event_name.to_sym][:events] << result else by_type[event_name.to_sym] = { name: event_name, events: [ result, ], } end end end by_type end def find_event_name(data) data.each do |item| next unless item["name"] == "event_data" item["value"].each do |i| return i["value"] if i["name"] == "event_name" end end "undefined" end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/helpers/properties_table_helpers.rb
helpers/properties_table_helpers.rb
module PropertiesTableHelpers def table_of_properties(properties) return unless properties rows = properties.map do |name, attrs| "<tr><td><strong>#{name}</strong><br/>#{possible_types(attrs)}</td> <td>#{display_attribute_value(attrs)}</td></tr>" end "<table class='schema-table'>#{rows.join("\n")}</table>" end private def display_attribute_value(attrs) return unless attrs if attrs["properties"] table_of_properties(attrs["properties"]) else [attrs["description"], enums(attrs)].join("<br/>") end end def enums(attrs) return unless attrs["enum"] values = attrs["enum"].map { |value| "<code>#{value}</code>" } "Allowed values: #{values.join(', ')}" end def possible_types(attrs) return unless attrs possible_types = attrs["type"] ? [attrs] : attrs["anyOf"] return unless possible_types possible_types.map { |a| "<code>#{a['type']}</code>" }.join(" or ") end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/helpers/navigation_helpers.rb
helpers/navigation_helpers.rb
module NavigationHelpers def active_page?(page_path) (current_page.path == "index.html" && page_path == "/") || "/#{current_page.path}" == page_path || current_page.data.parent == page_path end def sidebar_link(name, page_path) link_to(page_path, class: page_path == "/#{current_page.path}" ? "toc-link--in-view" : nil) do content_tag(:span, name) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/helpers/commit_helpers.rb
helpers/commit_helpers.rb
require "git" module CommitHelpers def commit_url(current_page) if current_page.data.latest_commit "https://github.com/alphagov/#{current_page.data.repo_name}/commit/#{current_page.data.latest_commit[:sha]}" elsif local_commit(current_page) "https://github.com/alphagov/govuk-developer-docs/commit/#{local_commit(current_page).sha}" else "#" end end def last_updated(current_page) # e.g. "2020-09-03 09:53:56 UTC" if current_page.data.latest_commit Time.parse(current_page.data.latest_commit[:timestamp].to_s) elsif local_commit(current_page) Time.parse(local_commit(current_page).author_date.to_s) else Time.now end end def format_timestamp(timestamp) timestamp.strftime("%e %b %Y").strip # e.g. "3 Sep 2020" end private def source_file(current_page) "source/#{current_page.file_descriptor.relative_path}" end def local_commit(current_page) Git.open(".").log.path(source_file(current_page)).first end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/helpers/url_helpers.rb
helpers/url_helpers.rb
module UrlHelpers def document_type_url(document_type_name) "/document-types/#{document_type_name}.html" end def slack_url(channel_name) "https://gds.slack.com/channels/#{channel_name.sub('#', '')}" end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/spec_helper.rb
spec/spec_helper.rb
require "simplecov" SimpleCov.start require "webmock/rspec" require "govuk_tech_docs" require_relative "./../app/requires" RSpec.configure do |config| config.before do WebMock.reset! end config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.shared_context_metadata_behavior = :apply_to_host_groups config.filter_run_when_matching :focus config.disable_monkey_patching! if config.files_to_run.one? config.default_formatter = "doc" end config.order = :random Kernel.srand config.seed end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/source_url_spec.rb
spec/app/source_url_spec.rb
Dir.glob(::File.expand_path("../helpers/**/*.rb", __dir__)).sort.each { |f| require_relative f } RSpec.describe SourceUrl do describe "#source_url" do it "returns the URL from the page local" do locals = { page: double(source_url: "https://example.org/via-page") } source_url = SourceUrl.new(locals, double).source_url expect(source_url).to eql("https://example.org/via-page") end it "returns the URL from the frontmatter" do current_page = double(data: double(source_url: "https://example.org/via-frontmatter")) source_url = SourceUrl.new({}, current_page).source_url expect(source_url).to eql("https://example.org/via-frontmatter") end it "returns the source from this repository" do current_page = double(data: double(source_url: nil), file_descriptor: { relative_path: "foo.html.md" }) source_url = SourceUrl.new({}, current_page).source_url expect(source_url).to eql("https://github.com/alphagov/govuk-developer-docs/blob/main/source/foo.html.md") end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/run_rake_task_spec.rb
spec/app/run_rake_task_spec.rb
require "capybara/rspec" RSpec.describe RunRakeTask do describe "#links" do subject(:html) do Capybara.string(described_class.links(application, rake_task)) end describe "given a Repo instance" do let(:application) do Repo.new( "repo_name" => "content-publisher", ) end let(:rake_task) { "publishing_api:republish" } it "contains the app name" do expect(html).to have_text("content-publisher") end it "contains the full name of the Rake task" do expect(html).to have_text(" publishing_api:republish") end end describe "given an application name" do let(:application) { "ckanext-datagovuk" } let(:rake_task) { "do:something" } it "contains the app name" do expect(html).to have_text("ckanext-datagovuk ") end it "contains the full name of the Rake task" do expect(html).to have_text(" do:something") end end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/document_types_spec.rb
spec/app/document_types_spec.rb
RSpec.describe DocumentTypes do describe ".pages" do it "returns document types" do stub_request(:get, "https://www.gov.uk/api/search.json?facet_content_store_document_type=500,examples:10,example_scope:global&count=0") .to_return( body: File.read("spec/fixtures/search-api-app-search-response.json"), headers: { content_type: "application/json", }, ) stub_request(:get, "https://raw.githubusercontent.com/alphagov/publishing-api/main/content_schemas/allowed_document_types.yml") .to_return(body: File.read("spec/fixtures/allowed-document-types-fixture.yml")) document_type = DocumentTypes.pages.first expect(document_type.examples.first.keys.sort).to eql(%w[link title]) end end describe "#schema_names_by_document_type" do it "returns schema names by document type" do schema_name = "aaib_report" allow(GovukSchemas::Schema).to receive(:schema_names).and_return([schema_name]) allow(GovukSchemas::Schema).to receive(:find).with(notification_schema: schema_name).and_return({ properties: { document_type: { enum: %w[ embassies_index field_of_operation ], }, }, }.as_json) expect(DocumentTypes.schema_names_by_document_type).to eq({ embassies_index: [schema_name], field_of_operation: [schema_name], }.as_json) end end describe "DocumentTypes::Page.schemas" do it "shifts low value schemas to the bottom of the list" do allow(DocumentTypes).to receive(:schema_names_by_document_type).and_return({ "aaib_report": %w[ generic generic_with_external_links placeholder x_something z_something ], }.as_json) page = DocumentTypes::Page.new(name: "aaib_report", total_count: nil, examples: nil) expect(page.schemas).to eq(%w[ x_something z_something generic generic_with_external_links placeholder ]) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/github_repo_fetcher_spec.rb
spec/app/github_repo_fetcher_spec.rb
require "ostruct" RSpec.describe GitHubRepoFetcher do before :each do stub_request(:get, "https://api.github.com/users/alphagov/repos?per_page=100") .to_return( body: "[ { \"name\": \"some-repo\", \"default_branch\": \"main\" } ]", headers: { content_type: "application/json" }, ) end let(:private_repo) { double("Private repo", private_repo?: true) } let(:public_repo) { double("Public repo", private_repo?: false, default_branch: "main") } def stub_cache cache = double("CACHE") allow(cache).to receive(:fetch).and_yield stub_const("CACHE", cache) cache end describe "#instance" do it "acts as a singleton" do expect(GitHubRepoFetcher.instance).to be_a_kind_of(GitHubRepoFetcher) expect(GitHubRepoFetcher.instance).to eq(GitHubRepoFetcher.instance) end end describe "#repo" do it "fetches a repo from cache if it exists" do allow(stub_cache).to receive(:fetch).with("all-repos", hash_including(:expires_in)) do some_repo = public_repo allow(some_repo).to receive(:name).and_return("some-repo") [some_repo] end repo = GitHubRepoFetcher.new.repo("some-repo") expect(repo).not_to be_nil end it "fetches a repo from GitHub if it doesn't exist in the cache" do stub_cache repo = GitHubRepoFetcher.new.repo("some-repo") expect(repo).not_to be_nil end it "raises error if no repo is found" do expect { GitHubRepoFetcher.new.repo("something-not-here") }.to raise_error(StandardError) end end describe "#readme" do let(:repo_name) { "some-repo" } before :each do stub_cache end def readme_url "https://raw.githubusercontent.com/alphagov/#{repo_name}/main/README.md" end it "caches the first response" do allow(GitHubRepoFetcher.new).to receive(:repo).and_return(public_repo) stubbed_request = stub_request(:get, readme_url) .to_return(status: 200, body: "Foo") outcome = "pending" allow(stub_cache).to receive(:fetch) do |&block| outcome = block.call end GitHubRepoFetcher.new.readme(repo_name) expect(outcome).to eq("Foo") expect(stubbed_request).to have_been_requested.once end it "retrieves the README content from the GitHub CDN" do readme_contents = "# temporary-test" stubbed_request = stub_request(:get, readme_url) .to_return(status: 200, body: readme_contents) expect(GitHubRepoFetcher.new.readme(repo_name)).to eq(readme_contents) remove_request_stub(stubbed_request) end it "retrieves the README content from the repo's default branch" do readme_contents = "# temporary-test from different branch" instance = GitHubRepoFetcher.new allow(instance).to receive(:repo).with(repo_name) do OpenStruct.new(default_branch: "latest") end stubbed_request = stub_request(:get, readme_url.sub("main", "latest")) .to_return(status: 200, body: readme_contents) expect(instance.readme(repo_name)).to eq(readme_contents) remove_request_stub(stubbed_request) end it "returns nil if no README exists" do stubbed_request = stub_request(:get, readme_url) .to_return(status: 404) expect(GitHubRepoFetcher.new.readme(repo_name)).to eq(nil) remove_request_stub(stubbed_request) end it "returns nil if the repo is private" do instance = GitHubRepoFetcher.new allow(instance).to receive(:repo).with(repo_name).and_return(private_repo) expect(instance.readme(repo_name)).to eq(nil) end end describe "#docs" do let(:repo_name) { SecureRandom.uuid } let(:commit) { { sha: SecureRandom.hex(40), timestamp: Time.now.utc.to_s } } def docs_url(repo_name) "https://api.github.com/repos/alphagov/#{repo_name}/contents/docs" end def github_repo_fetcher_returning(repo) instance = GitHubRepoFetcher.new allow(instance).to receive(:repo).with(repo_name).and_return(repo) allow(instance).to receive(:latest_commit).and_return(commit) instance end context "the repo contains a reachable docs/ folder" do let(:expected_hash_structure) { hash_including(:title, :markdown, :path, :relative_path, :source_url, :latest_commit) } def with_stubbed_client(temporary_client, instance) before_client = instance.instance_variable_get(:@client) instance.instance_variable_set(:@client, temporary_client) yield instance.instance_variable_set(:@client, before_client) end def stub_doc(contents: "arbitrary contents", path: "docs/foo.md") doc = double("doc", type: "file", download_url: "foo_url", path:, html_url: "foo_html_url") allow(HTTP).to receive(:get).with(doc.download_url).and_return(contents) doc end it "returns an array of hashes" do instance = github_repo_fetcher_returning(public_repo) with_stubbed_client(double("Octokit::Client", contents: [stub_doc]), instance) do expect(instance.docs(repo_name)).to match([expected_hash_structure]) end end it "derives each document title from its markdown" do instance = github_repo_fetcher_returning(public_repo) doc = stub_doc(contents: "# title \n Some document") with_stubbed_client(double("Octokit::Client", contents: [doc]), instance) do doc = instance.docs(repo_name).first expect(doc[:title]).to eq("title") end end it "derives document title from its filename if not present in markdown" do instance = github_repo_fetcher_returning(public_repo) doc = stub_doc(contents: "bar \n Some document") with_stubbed_client(double("Octokit::Client", contents: [doc]), instance) do doc = instance.docs(repo_name).first expect(doc[:title]).to eq("foo") end end it "maintains the original directory structure" do instance = github_repo_fetcher_returning(public_repo) doc = stub_doc(path: "docs/subdir/foo.md") with_stubbed_client(double("Octokit::Client", contents: [doc]), instance) do doc = instance.docs(repo_name).first expect(doc[:path]).to eq("/repos/#{repo_name}/subdir/foo.html") expect(doc[:relative_path]).to eq("docs/subdir/foo.md") end end it "retrieves documents recursively" do dir = double("dir", type: "dir", path: "docs/foo") nested_doc = stub_doc(path: "docs/foo/bar.md") instance = github_repo_fetcher_returning(public_repo) allow(HTTP).to receive(:get).with(nested_doc.download_url).and_return("some contents") stubbed_client = double("Octokit::Client") allow(stubbed_client).to receive(:contents).with("alphagov/#{repo_name}", path: "docs") .and_return([dir]) allow(stubbed_client).to receive(:contents).with("alphagov/#{repo_name}", path: "docs/foo") .and_return([nested_doc]) with_stubbed_client(stubbed_client, instance) do expect(instance.docs(repo_name)).to match([expected_hash_structure]) end end it "skips over any non-markdown files" do instance = github_repo_fetcher_returning(public_repo) non_markdown_file = double("non markdown file", type: "file", path: "docs/digests.png") with_stubbed_client(double("Octokit::Client", contents: [non_markdown_file]), instance) do expect(instance.docs(repo_name)).to eq([]) end end end it "returns nil if no docs folder exists" do instance = github_repo_fetcher_returning(public_repo) stub_request(:get, docs_url(repo_name)) .to_return(status: 404, body: "{}", headers: { content_type: "application/json" }) expect(instance.docs(repo_name)).to be_nil end it "returns nil if the repo is private" do instance = github_repo_fetcher_returning(private_repo) expect(instance.docs(repo_name)).to eq(nil) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/snippet_spec.rb
spec/app/snippet_spec.rb
RSpec.describe Snippet do describe ".generate" do it "generates a proper snippet without the opsmanual warning" do html = <<~HTML <blockquote> <p><strong>This page was imported from <a href="https://github.com/alphagov/govuk-legacy-opsmanual">the opsmanual on GitHub Enterprise</a></strong>. It hasn&rsquo;t been reviewed for accuracy yet. <a href="#">View history in old opsmanual</a></p> </blockquote> <h1 id='remove-an-asset'>Remove an asset</h1> <p>If you need to remove an asset manually from <code>assets.publishing.sevice.gov.uk</code>, follow these steps:</p> HTML snippet = Snippet.generate(html) expect(snippet).to eql("If you need to remove an asset manually from assets.publishing.sevice.gov.uk, follow these steps:") end it "removes headings" do html = <<~HTML <h1 id='deploy-an-application-to-govuk'>Deploy an application to GOV.UK</h1> <h2 id='introduction'>Introduction</h2> <p>We are responsible for:</p> <ul> <li>ensuring that software is released to GOV.UK responsibly</li> <li>providing access to deploy software for teams who can&rsquo;t deploy it themselves</li> </ul> <p>As far as possible, teams are responsible for deploying their own work. We believe that <a href="https://gds.blog.gov.uk/2012/11/02/regular-releases-reduce-risk/">regular releases minimise the risk of major problems</a> and improve recovery time.</p> HTML snippet = Snippet.generate(html) expect(snippet).to eql("We are responsible for: ensuring that software is released to GOV.UK responsibly providing access to deploy software for teams who can’t deploy it themselves As far as possible, teams are responsible for deploying their own work. We believe that regular releases minimise the risk of major problem...") end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/content_schema_spec.rb
spec/app/content_schema_spec.rb
RSpec.describe ContentSchema do describe "#frontend_schema" do it "it can link to GitHub" do schema = ContentSchema.new("generic").frontend_schema expect(schema.link_to_github).to eql("https://github.com/alphagov/publishing-api/blob/main/content_schemas/dist/formats/generic/frontend/schema.json") end it "it has a random example" do schema = ContentSchema.new("generic").frontend_schema expect(schema.random_example["content_id"]).not_to be_nil end it "it has properties with inlined definitions" do schema = ContentSchema.new("generic").frontend_schema expect(schema.properties["base_path"]["$ref"]).to eql(nil) expect(schema.properties["base_path"]["type"]).to eql("string") end end describe "#publisher_content_schema" do it "it can link to GitHub" do schema = ContentSchema.new("generic").publisher_content_schema expect(schema.link_to_github).to eql("https://github.com/alphagov/publishing-api/blob/main/content_schemas/dist/formats/generic/publisher_v2/schema.json") end it "it has a random example" do schema = ContentSchema.new("generic").publisher_content_schema expect(schema.random_example["base_path"]).not_to be_nil end it "it has properties with inlined definitions" do schema = ContentSchema.new("generic").publisher_content_schema expect(schema.properties["base_path"]["$ref"]).to eql(nil) expect(schema.properties["base_path"]["type"]).to eql("string") end end describe "#publisher_links_schema" do it "it can link to GitHub" do schema = ContentSchema.new("generic").publisher_links_schema expect(schema.link_to_github).to eql("https://github.com/alphagov/publishing-api/blob/main/content_schemas/dist/formats/generic/publisher_v2/links.json") end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/repo_spec.rb
spec/app/repo_spec.rb
RSpec.describe Repo do describe "is_app?" do it "returns false if 'production_hosted_on' is omitted" do expect(Repo.new({}).is_app?).to be(false) end it "returns true if 'production_hosted_on' is supplied" do expect(Repo.new({ "production_hosted_on" => "aws" }).is_app?).to be(true) end end describe "is_gem?" do it "returns true if assiged type is Gems" do expect(Repo.new({ "type" => "Gems" }).is_gem?).to be(true) end it "returns false if assigned type isn't Gems" do expect(Repo.new({ "type" => "Utilities" }).is_gem?).to be(false) end end describe "app_name" do it "returns repo_name if app_name not specified" do expect(Repo.new({ "repo_name" => "foo" }).app_name).to eq("foo") end it "returns app_name if both app_name and repo_name are specified" do expect(Repo.new({ "app_name" => "foo", "repo_name" => "bar" }).app_name).to eq("foo") end end describe "skip_docs?" do it "returns false if 'skip_docs' is omitted" do expect(Repo.new({}).skip_docs?).to be(false) end it "returns true if 'skip_docs' is true" do expect(Repo.new({ "skip_docs" => true }).skip_docs?).to be(true) end end describe "api_payload" do it "returns a hash of keys describing the app" do app_details = { "repo_name" => "foo", "team" => "bar", "alerts_team" => "baz", "production_hosted_on" => "aws", } payload = Repo.new(app_details).api_payload expect(payload[:app_name]).to eq(app_details["repo_name"]) expect(payload[:team]).to eq(app_details["team"]) expect(payload[:alerts_team]).to eq(app_details["alerts_team"]) expect(payload[:production_hosted_on]).to eq(app_details["production_hosted_on"]) expect(payload[:links]).to include(:self, :html_url, :repo_url, :sentry_url) end end describe "production_url" do it "has a good default" do app = Repo.new("type" => "Publishing apps", "repo_name" => "my-app") expect(app.production_url).to eql("https://my-app.publishing.service.gov.uk") end it "allows override" do app = Repo.new("type" => "Publishing apps", "production_url" => "something else") expect(app.production_url).to eql("something else") end end describe "dashboard_url" do let(:default_options) do { "type" => "Publishing app", "repo_name" => "my-app", } end let(:options) { default_options } subject(:dashboard_url) { described_class.new(options).dashboard_url } describe "configured dashboard_url set to false" do let(:options) { default_options.merge("dashboard_url" => false) } it { is_expected.to be_nil } end describe "configured dashboard_url" do let(:options) { default_options.merge("dashboard_url" => "https://example.com") } it { is_expected.to eql("https://example.com") } end describe "default dashboard_url for EKS hosted apps" do let(:production_hosted_on) { "eks" } let(:options) { default_options.merge("production_hosted_on" => "eks") } it { is_expected.to eql("https://grafana.eks.production.govuk.digital/d/app-requests/app3a-request-rates-errors-durations?var-app=my-app") } end describe "default dashboard_url" do it { is_expected.to eql(nil) } end end describe "kibana_url" do let(:default_options) { { "repo_name" => "content-publisher" } } let(:options) { default_options } subject(:kibana_url) { described_class.new(options).kibana_url } describe "default behaviour" do it { is_expected.to eql(nil) } end describe "hosted on EKS" do let(:options) { default_options.merge("production_hosted_on" => "eks") } it { is_expected.to eql("https://kibana.logit.io/s/13d1a0b1-f54f-407b-a4e5-f53ba653fac3/app/discover?security_tenant=global#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-3h,to:now))&_a=(columns:!(level,request,status,message),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'filebeat-*',key:kubernetes.labels.app_kubernetes_io%2Fname,negate:!f,params:(query:content-publisher),type:phrase),query:(match_phrase:(kubernetes.labels.app_kubernetes_io%2Fname:content-publisher)))),index:'filebeat-*',interval:auto,query:(language:kuery,query:''),sort:!())"), "Actual URL returned: #{kibana_url.inspect}" } end describe "hosted on EKS but custom URL provided" do let(:options) do default_options.merge( "production_hosted_on" => "eks", "kibana_url" => "https://kibana.logit.io/custom-url", ) end it { is_expected.to eql("https://kibana.logit.io/custom-url") } end end describe "kibana_worker_url" do let(:default_options) { { "repo_name" => "content-publisher" } } let(:options) { default_options } subject(:kibana_worker_url) { described_class.new(options).kibana_worker_url } describe "default behaviour" do it { is_expected.to eql(nil) } end describe "hosted on EKS" do let(:options) { default_options.merge("production_hosted_on" => "eks") } it { is_expected.to eql("https://kibana.logit.io/s/13d1a0b1-f54f-407b-a4e5-f53ba653fac3/app/discover?security_tenant=global#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-3h,to:now))&_a=(columns:!(level,message),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'filebeat-*',key:kubernetes.labels.app_kubernetes_io%2Fname,negate:!f,params:(query:content-publisher-worker),type:phrase),query:(match_phrase:(kubernetes.labels.app_kubernetes_io%2Fname:content-publisher-worker)))),index:'filebeat-*',interval:auto,query:(language:kuery,query:''),sort:!())"), "Actual URL returned: #{kibana_worker_url.inspect}" } end describe "hosted on EKS but custom URL provided" do let(:options) do default_options.merge( "production_hosted_on" => "eks", "kibana_worker_url" => "https://kibana.logit.io/custom-url", ) end it { is_expected.to eql("https://kibana.logit.io/custom-url") } end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/proxy_pages_spec.rb
spec/app/proxy_pages_spec.rb
RSpec.describe ProxyPages do before do allow(Repos).to receive(:all) .and_return([double("Repo", app_name: "", repo_name: "", page_title: "", description: "", skip_docs?: false, private_repo?: false, retired?: false)]) allow(DocumentTypes).to receive(:pages) .and_return([double("Page", name: "")]) allow(Supertypes).to receive(:all) .and_return([double("Supertype", name: "", description: "", id: "")]) allow(GitHubRepoFetcher.instance).to receive(:docs) .and_return([ { title: "A doc page", markdown: "# A doc page\n Foo", latest_commit: { sha: SecureRandom.hex(40), timestamp: Time.now.utc, }, }, ]) end describe ".repo_docs" do it "is indexed in search by its default contents" do expect(described_class.repo_docs).to all( include(frontmatter: hash_including(:title)) .and(include(frontmatter: hash_excluding(:content))), ) end it "sets the correct source_url for the doc" do expect(described_class.repo_docs).to all( include(frontmatter: hash_including(data: hash_including(:source_url))), ) end end describe ".repo_overviews" do it "is indexed in search by its default contents" do expect(described_class.repo_overviews).to all( include(frontmatter: hash_including(:title)) .and(include(frontmatter: hash_excluding(:content))), ) end end describe ".document_types" do it "is indexed in search by title only" do expect(described_class.document_types).to all(include(frontmatter: hash_including(:title, content: ""))) end end describe ".supertypes" do it "is indexed in search by title only" do expect(described_class.supertypes).to all(include(frontmatter: hash_including(:title, content: ""))) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/manual_spec.rb
spec/app/manual_spec.rb
RSpec.describe Manual do describe "#manual_pages_grouped_by_section" do it "returns the correct groups" do sitemap = double(resources: [ double(path: "foo.html", data: double(title: "Won't be included", important: true, review_by: Date.today, section: "Foo", type: nil)), double(path: "manual/foo.html", data: double(title: "Foo", important: true, review_by: Date.today, section: "Foo", type: nil)), double(path: "manual/bar.html", data: double(title: "Bar", important: true, review_by: Date.today, section: "Bar", type: nil)), ]) manual_pages_grouped_by_section = Manual.new(sitemap).manual_pages_grouped_by_section expect(manual_pages_grouped_by_section.map(&:first)).to eql(["Common tasks", "Bar", "Foo"]) end end describe "#other_pages_from_section" do it "returns the correct groups" do one = double(path: "manual/foo.html", data: double(title: "Foo", important: true, section: "A section", type: nil)) other = double(path: "manual/bar.html", data: double(title: "Bar", important: true, section: "A section", type: nil)) sitemap = double(resources: [ one, other, double(path: "manual/baz.html", data: double(title: "Baz", section: "B section", type: nil)), ]) other_pages_from_section = Manual.new(sitemap).other_pages_from_section(one) expect(other_pages_from_section).to eql([other]) end end describe "#other_alerts_from_subsection" do it "returns other Icinga Alert pages that have the same subsection" do def stub_page(data_args) double(path: "manual/#{SecureRandom.uuid}.html", data: double({ important: true, type: nil, subsection: nil }.merge(data_args))) end matching_subsection_and_alert = stub_page(title: "Foo", section: "Icinga alerts", subsection: "Emails") another_matching_subsection_and_alert = stub_page(title: "Bar", section: "Icinga alerts", subsection: "Emails") alert_but_not_matching_subsection = stub_page(title: "Alert about something else", section: "Icinga alerts", subsection: "Some other subject") matching_subsection_but_not_alert = stub_page(title: "NOT an alert", section: "Sausages", subsection: "Emails") sitemap = double(resources: [ matching_subsection_and_alert, another_matching_subsection_and_alert, alert_but_not_matching_subsection, matching_subsection_but_not_alert, ]) other_alerts_from_subsection = Manual.new(sitemap).other_alerts_from_subsection(matching_subsection_and_alert) expect(other_alerts_from_subsection).to eql([another_matching_subsection_and_alert]) end end describe "#pages_for_repo" do it "returns the pages that are relevant to a repo" do sitemap = double(resources: [ double(path: "foo.html", data: double(title: "Won't be included", important: true, review_by: Date.today, section: "Foo", type: nil)), double(path: "manual/foo.html", data: double(title: "Foo", related_repos: %w[publisher], section: "Foo", type: nil)), double(path: "manual/bar.html", data: double(title: "Bar", related_repos: %w[collections], section: "Bar", type: nil)), ]) pages_for_repo = Manual.new(sitemap).pages_for_repo("publisher") expect(pages_for_repo.map(&:path)).to eql(["manual/foo.html"]) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/string_to_id_spec.rb
spec/app/string_to_id_spec.rb
RSpec.describe StringToId do describe "convert" do subject(:c) { StringToId } it "removes HTML tags" do expect(c.convert("<marquee loop=\"-1\" scrolldelay='50'><b>lol</b></marquee>")).to eq("lol") end it "removes script elements and their content" do expect(c.convert("<script>foo</script>")).to eq("") end it "removes characters other than ASCII alphanumeric, dot, dash and underscore" do expect(c.convert("1!@#%^*()-+=[]{}|\\'\"`~?/,")).to eq("1-") expect(c.convert("💩")).to eq("") end it "removes ampersand, less-than and greater-than" do expect(c.convert("><<>&")).to eq("") end it "preserves entity names that are not part of actual entities" do expect(c.convert("ampere")).to eq("ampere") expect(c.convert("amp;ere")).to eq("ampere") expect(c.convert("felt;-tip-pen")).to eq("felt-tip-pen") end it "preserves empty string" do expect(c.convert("")).to eq("") end it "preserves lowercase alphanumeric ASCII, underscores and non-consecutive dashes" do expect(c.convert("xyz890-123abc_")).to eq("xyz890-123abc_") end it "converts space and . to -" do expect(c.convert("foo.bar baz")).to eq("foo-bar-baz") end it "converts to lowercase" do expect(c.convert("MICROPIGS")).to eq("micropigs") end it "elides runs of dashes" do expect(c.convert("o---o")).to eq("o-o") expect(c.convert("o----o")).to eq("o-o") end it "elides runs of dashes after converting characters to dashes" do expect(c.convert("o-... -o")).to eq("o-o") end it "does not elide runs of underscores" do expect(c.convert("__")).to eq("__") end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/document_types_csv_spec.rb
spec/app/document_types_csv_spec.rb
RSpec.describe DocumentTypesCsv do describe ".to_csv" do it "returns document types" do allow(DocumentTypes).to receive(:facet_query).and_return( JSON.parse(File.read("spec/fixtures/search-api-app-search-response.json")), ) allow(DocumentTypes).to receive(:all_document_types).and_return( YAML.load_file("spec/fixtures/allowed-document-types-fixture.yml", aliases: true), ) allow(Supertypes).to receive(:data).and_return( YAML.load_file("spec/fixtures/supertypes.yml", aliases: true), ) csv = DocumentTypes.to_csv expect(csv).to eql(File.read("spec/fixtures/document-types-export.csv")) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/repo_data_spec.rb
spec/app/repo_data_spec.rb
RSpec.describe RepoData do before do stub_request(:get, RepoData::SEARCH_URL) .to_return(body: "{}") end describe "result" do it "cannot be queried from outside the class" do expect { RepoData.result }.to raise_error(NoMethodError) end end describe "extract_examples_from_search_result" do it "cannot be queried from outside the class" do expect { RepoData.extract_examples_from_search_result }.to raise_error(NoMethodError) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/external_doc_spec.rb
spec/app/external_doc_spec.rb
require "capybara/rspec" RSpec.describe ExternalDoc do describe ".parse" do it "converts arbitrary markdown to HTML" do markdown = <<~MD # Title [link](#anchor) MD expected_html = "\n<p><a href=\"#anchor\">link</a></p>" expect(described_class.parse(markdown).to_s).to eq(expected_html) end it "forces encoding to UTF-8 " do markdown = String.new( "These curly quotes “make commonmarker throw an exception”", encoding: "ASCII-8BIT", ) expected_html = "<p>These curly quotes “make commonmarker throw an exception”</p>" expect(described_class.parse(markdown).to_s).to eq(expected_html) end context "when passed a repository and path" do before do lipsum = double( "Lipsum", repo_name: "Lipsum", ) allow(Repos).to receive(:all) { [lipsum] } end let(:path) { "markdown.md" } subject(:html) do Capybara.string(described_class.parse( File.read("spec/fixtures/markdown.md"), repository: "lipsum", path:, ).to_s) end it "removes the title of the page" do expect(html).not_to have_selector("h1", text: "Lorem ipsum") end it "does not rewrite links to markdown pages with a host" do expect(html).to have_link("Absolute link", href: "https://nam.com/eget/dui/absolute-link.md") end it "converts relative links to absolute GitHub URLs" do expect(html).to have_link("inline link", href: "https://github.com/alphagov/lipsum/blob/main/inline-link.md") end it "converts aliased links to absolute GitHub URLs" do expect(html).to have_link("aliased link", href: "https://github.com/alphagov/lipsum/blob/main/lib/aliased_link.rb") end it "converts relative GitHub links to Developer Docs HTML links if it is an imported document" do expect(html).to have_link("Relative docs link with period", href: "/repos/lipsum/prefixed.html") expect(html).to have_link("Relative docs link without period", href: "/repos/lipsum/no-prefix.html") end it "converts relative links to absolute GitHub URLs if link is outside of the `docs` folder" do expect(html).to have_link("inline link", href: "https://github.com/alphagov/lipsum/blob/main/inline-link.md") end it "converts relative links to absolute GitHub URLs if link is in a subfolder of the `docs` folder" do expect(html).to have_link("Subfolder", href: "https://github.com/alphagov/lipsum/blob/main/docs/some-subfolder/foo.md") end it "converts links relative to the 'root' to absolute GitHub URLs" do expect(html).to have_link("Link relative to root", href: "https://github.com/alphagov/lipsum/blob/main/public/json_examples/requests/foo.json") end context "the document we are parsing is in the `docs` folder" do let(:path) { "docs/some-document.md" } it "converts links relative to the `docs` folder and applies the same business logic as before" do expect(html).to have_link("inline link", href: "/repos/lipsum/inline-link.html") end it "converts links relative to the 'root' to absolute GitHub URLs" do expect(html).to have_link("Link relative to root", href: "https://github.com/alphagov/lipsum/blob/main/public/json_examples/requests/foo.json") end end it "rewrites relative images" do expect(html).to have_css('img[src="https://raw.githubusercontent.com/alphagov/lipsum/main/suspendisse_iaculis.png"]') end it "treats URLs containing non-default ports as absolute URLs" do expect(html).to have_link("localhost", href: "localhost:999") end it "skips over URLs with trailing unicode characters" do expect(html).not_to have_link("http://localhost:3108") expect(html).not_to have_link("http://localhost:3108”") expect(html).to have_content("Visit “http://localhost:3108”") end it "maintains anchor links" do expect(html).to have_link("Suspendisse iaculis", href: "#suspendisse-iaculis") end it "adds an id attribute to all headers so they can be accessed from a table of contents" do expect(html).to have_selector("h2#tldr") end it "converts heading IDs properly" do expect(html).to have_selector("h3#data-gov-uk") expect(html).to have_selector("h3#patterns-style-guides") end it "returns empty string if passed nil" do expect(described_class.parse(nil)).to eq("") end end end describe ".title" do it "returns the title from markdown" do markdown = <<~MD #Title [link](#anchor) MD expect(described_class.title(markdown)).to eq("Title") end it "strips extra spaces from the title markdown" do markdown = "# My Title" expect(described_class.title(markdown)).to eq("My Title") end it "returns nil if no title is found" do markdown = "" expect(described_class.title(markdown)).to be_nil end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/repo_sidebar_spec.rb
spec/app/repo_sidebar_spec.rb
RSpec.describe RepoSidebar do it "returns an ordered list of items" do docs_to_import = [ { path: "/repos/repo_name/base.html", title: "Base", }, { path: "/repos/repo_name/something/in_a_sub_dir.html", title: "Single level", }, { path: "/repos/repo_name/something/deeper/in_a_sub_dir.html", title: "Double level", }, ] allow(GitHubRepoFetcher.instance).to receive(:docs) .with("repo_name") .and_return(docs_to_import) result = RepoSidebar.new("repo_name").items expect(result.count).to eq(2) expect(result[0].title).to eq("Base") expect(result[0].path).to eq("/repos/repo_name/base.html") expect(result[0].children).to eq([]) expect(result[1].title).to eq("something") expect(result[1].path).to eq("something") expect(result[1].children.count).to eq(2) expect(result[1].children[0].title).to eq("Single level") expect(result[1].children[0].path).to eq("/repos/repo_name/something/in_a_sub_dir.html") expect(result[1].children[1].title).to eq("deeper") expect(result[1].children[1].path).to eq("something/deeper") expect(result[1].children[1].children.count).to eq(1) expect(result[1].children[1].children[0].title).to eq("Double level") expect(result[1].children[1].children[0].path).to eq("/repos/repo_name/something/deeper/in_a_sub_dir.html") expect(result[1].children[1].children[0].children).to eq([]) end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/supertypes_spec.rb
spec/app/supertypes_spec.rb
RSpec.describe Supertypes do describe ".all" do it "works" do stub_request(:get, "https://raw.githubusercontent.com/alphagov/govuk_document_types/master/data/supertypes.yml") .to_return(body: File.read("spec/fixtures/supertypes.yml")) supertypes = Supertypes.all expect(supertypes.first).to be_a(Supertypes::Supertype) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/app/repos_spec.rb
spec/app/repos_spec.rb
RSpec.describe Repos do before :each do allow(Repos).to receive(:all) do repos.map(&:stringify_keys).map { |repo_data| Repo.new(repo_data) } end end describe "public" do let(:repos) do [ { repo_name: "whitehall", private_repo: true }, { repo_name: "asset-manager", private_repo: false }, ] end it "should return only repos that are public" do expect(Repos.public.map(&:repo_name)).to eq(%w[asset-manager]) end end describe "active" do let(:repos) do [ { repo_name: "whitehall", retired: true }, { repo_name: "asset-manager", retired: false }, ] end it "should return only repos that are not retired" do expect(Repos.active.map(&:repo_name)).to eq(%w[asset-manager]) end context "repo contains multiple apps" do let(:repos) do [ { repo_name: "licensify", app_name: "licensify" }, { repo_name: "licensify", app_name: "licensify-feed" }, { repo_name: "licensify", app_name: "licensify-admin" }, ] end it "should return one repo name" do expect(Repos.active.map(&:repo_name)).to eq(%w[licensify]) end end end describe "active_public" do let(:repos) do [ { repo_name: "secret-squirrel", private_repo: true }, { repo_name: "olde-time-public-repo", retired: true }, { repo_name: "active-public-repo", retired: false }, { repo_name: "retired-secret-squirrel", private_repo: true, retired: true }, ] end it "should return only repos that are both public and not retired" do expect(Repos.active_public.map(&:repo_name)).to eq(%w[active-public-repo]) end end describe "active_apps" do let(:repos) do [ { repo_name: "whitehall", retired: true }, { repo_name: "asset-manager", retired: false, production_hosted_on: "aws" }, { repo_name: "some-non-hosted-thing", retired: false }, ] end it "should return only apps that are not retired and are hosted" do expect(Repos.active_apps.map(&:repo_name)).to eq(%w[asset-manager]) end end describe "active_gems" do let(:repos) do [ { repo_name: "cache-clearing-service", type: "Services" }, { repo_name: "gds-api-adapters", type: "Gems" }, ] end it "should return only apps that are classified as gems" do expect(Repos.active_gems.map(&:repo_name)).to eq(%w[gds-api-adapters]) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/helpers/commit_helpers_spec.rb
spec/helpers/commit_helpers_spec.rb
require "ostruct" require "spec_helper" require_relative "../../helpers/commit_helpers" RSpec.describe CommitHelpers do let(:helper) { Class.new { extend CommitHelpers } } let(:uncommitted_file) do path_to_file = "tmp/tmp.md" File.write(path_to_file, "new uncommitted file") path_to_file end describe "#commit_url" do it "returns the commit_url associated with the page data, if that exists" do repo_name = "some-repo" commit_sha = SecureRandom.hex(40) current_page = OpenStruct.new(data: OpenStruct.new( repo_name:, latest_commit: { sha: commit_sha, }, )) expect(helper.commit_url(current_page)).to eq("https://github.com/alphagov/#{repo_name}/commit/#{commit_sha}") end it "returns commit URL for the commit associated with the source file of current_page" do source_file = "index.html.erb" current_page = OpenStruct.new( data: OpenStruct.new, file_descriptor: OpenStruct.new(relative_path: source_file), ) expect(helper.commit_url(current_page)).to match( /https:\/\/github.com\/alphagov\/govuk-developer-docs\/commit\/[0-9a-f]{40}$/, ) end it "returns # if the file hasn't been committed yet" do current_page = OpenStruct.new( data: OpenStruct.new, file_descriptor: OpenStruct.new(relative_path: uncommitted_file), ) expect(helper.commit_url(current_page)).to eq("#") end end describe "#last_updated" do it "returns the commit timestamp associated with the (remote) page data, if that exists" do current_page = OpenStruct.new(data: OpenStruct.new( latest_commit: { timestamp: "2019-09-03 09:53:56 UTC" }, )) last_updated = helper.last_updated(current_page) expect(last_updated).to be_a_kind_of(Time) expect(last_updated.year).to eq(2019) end it "returns the commit date of the local file if no page data exists" do source_file = "index.html.erb" current_page = OpenStruct.new( data: OpenStruct.new, file_descriptor: OpenStruct.new(relative_path: source_file), ) expect(helper.last_updated(current_page)).to be_a_kind_of(Time) end it "returns the current time if the file hasn't been committed yet" do current_page = OpenStruct.new( data: OpenStruct.new, file_descriptor: OpenStruct.new(relative_path: uncommitted_file), ) expect(helper.last_updated(current_page).to_i).to eq(Time.now.to_i) end end describe "#format_timestamp" do it "formats a timestamp" do timestamp = Time.new(2020, 9, 3, 9, 53, 56, "UTC") expect(helper.format_timestamp(timestamp)).to eq("3 Sep 2020") end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/helpers/analytics_helpers_spec.rb
spec/helpers/analytics_helpers_spec.rb
require "spec_helper" require_relative "../../helpers/analytics_helpers" RSpec.describe AnalyticsHelpers do let(:helper) { Class.new { extend AnalyticsHelpers } } describe "#urlize" do it "returns a url safe version of the given string" do expect(helper.urlize("An event-name")).to eq("an_event_name") end end describe "#build_event" do it "returns an ordered hash given an array of un-ordered hashes" do input = [ { "name" => "type", "value" => "accordion" }, { "name" => "event_name", "value" => "select_content" }, ] expected = { "event_name" => { "value" => "select_content", "variant" => nil, }, "type" => { "value" => "accordion", "variant" => nil, }, } expect(helper.build_event(input)).to eq(expected) end it "returns a nested ordered hash given an array of hashes with one having a value that is an array" do input = [ { "name" => "event_data", "value" => [ { "name" => "event_name", "value" => "select_content" }, ], }, ] expected = { "event_data" => { "event_name" => { "value" => "select_content", "variant" => nil } }, } expect(helper.build_event(input)).to eq(expected) end it "returns a deeply nested ordered hash given an array of hashes with one having a value that is an array and another where the value is also an array and requires attribute lookup" do input = [ { "name" => "event_data", "value" => [ { "name" => "event_name", "value" => "select_content" }, { "name" => "index", "value" => [ { "name" => "index_section" }, ], }, ], }, ] attributes = [ { "name" => "index_section", "type" => "integer" }, ] expected = { "event_data" => { "event_name" => { "value" => "select_content", "variant" => nil, }, "index" => { "index_section" => { "value" => "integer", "variant" => nil, }, }, }, } expect(helper.build_event(input, attributes)).to eq(expected) end it "returns a deeply nested ordered hash given an array of hashes with one having a value that is an array and another where the value is also an array and requires attribute lookup and one with a matching variant" do input = [ { "name" => "event_data", "value" => [ { "name" => "event_name", "value" => "select_content" }, { "name" => "index", "value" => [ { "name" => "index_section" }, { "name" => "index_link" }, ], }, ], }, ] attributes = [ { "name" => "index_section", "type" => "integer", "variants" => [ { "event_name" => "select_content", }, ], }, { "name" => "index_link", "type" => "noun", }, ] expected = { "event_data" => { "event_name" => { "value" => "select_content", "variant" => nil, }, "index" => { "index_section" => { "value" => "integer", "variant" => "select_content", }, "index_link" => { "value" => "noun", "variant" => nil, }, }, }, } expect(helper.build_event(input, attributes)).to eq(expected) end it "returns a deeply nested ordered hash given an array of hashes with one having a value that is an array and another where the value is also an array and requires attribute lookup but without a matching value" do input = [ { "name" => "event_data", "value" => [ { "name" => "event_name", "value" => "select_content" }, { "name" => "index", "value" => [ { "name" => "index_section" }, ], }, ], }, ] expected = { "event_data" => { "event_name" => { "value" => "select_content", "variant" => nil, }, "index" => { "index_section" => { "value" => nil, "variant" => nil, }, }, }, } expect(helper.build_event(input)).to eq(expected) end end describe "#find_variant" do it "returns nothing if nothing is passed" do expect(helper.find_variant(nil, {})).to eq(nil) end it "does not error if the passed data is incomplete" do input = { "name" => "text", } expect(helper.find_variant("not_in_the_data", input)).to eq(nil) end it "finds a variant in passed data" do input = { "name" => "text", "variants" => [ { "event_name" => "search", }, { "event_name" => "navigation", }, { "event_name" => "file_download", }, ], } expect(helper.find_variant("search", input)).to eq("search") end it "returns nil if it cannot find a variant in passed data" do input = { "name" => "text", "variants" => [ { "event_name" => "search", }, { "event_name" => "navigation", }, { "event_name" => "file_download", }, ], } expect(helper.find_variant("not_in_the_data", input)).to eq(nil) end end describe "#to_html" do it "returns an HTML list item set given a hash" do input = { "event_name" => { "value" => "select_content", "variant" => nil, }, "type" => { "value" => "accordion", "variant" => nil, }, } expected = <<~HTML.gsub(/^\s+/, "").gsub("\n", "") <ul class='govuk-list indented-list'> <li> <a href='/analytics/attribute_event_name.html' class='govuk-link'>event_name</a>: select_content </li> <li> <a href='/analytics/attribute_type.html' class='govuk-link'>type</a>: accordion </li> </ul> HTML expect(helper.to_html(input)).to eq(expected) end it "returns an HTML list item set given a hash with variants" do input = { "event_name" => { "value" => "select_content", "variant" => "select_content", }, "type" => { "value" => "accordion", "variant" => nil, }, } expected = <<~HTML.gsub(/^\s+/, "").gsub("\n", "") <ul class='govuk-list indented-list'> <li> <a href='/analytics/attribute_event_name/variant_select_content.html' class='govuk-link'>event_name</a>: select_content </li> <li> <a href='/analytics/attribute_type.html' class='govuk-link'>type</a>: accordion </li> </ul> HTML expect(helper.to_html(input)).to eq(expected) end it "returns a nested HTML list item set given a nested hash" do input = { "event_data" => { "event_name" => { "value" => "select_content", "variant" => nil, }, }, } expected = <<~HTML.gsub(/^\s+/, "").gsub("\n", "") <ul class='govuk-list indented-list'> <li>event_data: <ul class='govuk-list indented-list'> <li> <a href='/analytics/attribute_event_name.html' class='govuk-link'>event_name</a>: select_content </li> </ul> </li> </ul> HTML expect(helper.to_html(input)).to eq(expected) end it "returns a deeply nested HTML list item set given a deeply nested hash" do input = { "event_data" => { "event_name" => { "value" => "select_content", "variant" => nil, }, "index" => { "index_section" => { "value" => "integer", "variant" => nil, }, }, }, } expected = <<~HTML.gsub(/^\s+/, "").gsub("\n", "") <ul class='govuk-list indented-list'> <li>event_data: <ul class='govuk-list indented-list'> <li> <a href='/analytics/attribute_event_name.html' class='govuk-link'>event_name</a>: select_content </li> <li>index: <ul class='govuk-list indented-list'> <li> <a href='/analytics/attribute_index_section.html' class='govuk-link'>index_section</a>: integer </li> </ul> </li> </ul> </li> </ul> HTML expect(helper.to_html(input)).to eq(expected) end end describe "#implementation_percentage" do it "should be 0% when there are no events" do expect(helper.implementation_percentage([])).to eq("0 of 0 (0%)") end it "should be 0% when none of the events are implemented" do events = [ { "implemented" => false }, ] expect(helper.implementation_percentage(events)).to eq("0 of 1 (0%)") end it "should be 100% when all the events are implemented" do events = [ { "implemented" => true }, ] expect(helper.implementation_percentage(events)).to eq("1 of 1 (100.0%)") end it "should be 50% when half of the events are implemented" do events = [ { "implemented" => true }, { "implemented" => false }, ] expect(helper.implementation_percentage(events)).to eq("1 of 2 (50.0%)") end end describe "#events_by_type" do it "converts YML into a usable object" do input = YAML.load_file("spec/fixtures/events-fixture.yml", aliases: true) expected = { navigation: { name: "navigation", events: [ { event_name: "Accordion links", index: 2, name: "accordion", }, { event_name: "link click", index: 0, name: "back link", }, ], }, select_content: { name: "select_content", events: [ { event_name: "Accordion section", index: 0, name: "accordion", }, { event_name: "Show all sections", index: 1, name: "accordion", }, ], }, } expect(helper.events_by_type(input)).to eq(expected) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/helpers/url_helpers_spec.rb
spec/helpers/url_helpers_spec.rb
require "spec_helper" require_relative "../../helpers/url_helpers" RSpec.describe UrlHelpers do let(:helper) { Class.new { extend UrlHelpers } } describe "#document_type_url" do it "returns the path to a document type page" do document_type = "html_publication" expect(helper.document_type_url(document_type)).to eq("/document-types/html_publication.html") end end describe "#slack_url" do it "returns the URL to open a channel in GDS Slack" do channel_name = "#general" expect(helper.slack_url(channel_name)).to eq("https://gds.slack.com/channels/general") end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/pages/manual_page_spec.rb
spec/pages/manual_page_spec.rb
Dir.glob("source/manual/**/*.md").each do |filename| RSpec.describe filename do raw = File.read(filename) frontmatter = YAML.load(raw.split("---")[1]) it "uses the correct spelling of GOV.UK" do expect(raw).not_to match "Gov.uk" end it "has an owner" do expect(frontmatter["owner_slack"]).to be_present, "Page doesn't have `owner_slack` set" expect(frontmatter["owner_slack"][0]).to be_in(%(# @)), "`owner_slack` should be a @username or #channel" end it "has a title" do expect(frontmatter["title"]).to be_present, "Page doesn't have `title` set" end unless frontmatter["section"] == "Icinga alerts" it "follows the styleguide" do expect(frontmatter["title"].split(" ").first).not_to end_with("ing"), "Page title `#{frontmatter['title']}`: don't use 'ing' at the end of verbs - https://docs.publishing.service.gov.uk/manual/docs-style-guide.html#title" end end it "has the correct suffix" do expect(filename).to match(/\.html\.md$/) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/spec/data/repos_spec.rb
spec/data/repos_spec.rb
RSpec.describe "repos.yml" do describe "repos.yml" do let!(:repos) { YAML.load_file("data/repos.yml", aliases: true) } it "lists each repository in alphabetical order" do expect(repos.pluck("repo_name")).to eq(repos.pluck("repo_name").sort) end end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
alphagov/govuk-developer-docs
https://github.com/alphagov/govuk-developer-docs/blob/9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b/mdl/rules.rb
mdl/rules.rb
rule "MY001", "No parentheses allowed after shortcut reference link (use collapsed reference link instead, e.g. `[foo]` => `[foo][]`)" do aliases "no-parentheses-after-shortcut-reference-link" check do |doc| # matches `[foo] (bar)`, doesn't match `[foo][baz] (bar)` doc.matching_lines(/ \[[^\]]+\] \(/) end end
ruby
MIT
9642e97c9bbb73e4827878ccfa3ac8e2ac282f6b
2026-01-04T17:48:06.150611Z
false
my-learn-project/nvim.comment-hide
https://github.com/my-learn-project/nvim.comment-hide/blob/33aa42530d1a0c41fd9f2e57d5fdb2d769e62c86/test/ruby.rb
test/ruby.rb
=begin MiniDynDNS v1.4.0 by Stephan Soller <stephan.soller@helionweb.de> # About the source code To keep the source code hackable and easier to understand it's organized in sections rather than classes. I've tried several class layouts but rejected them all because they added to much boiler plate and self organization code. But feel free to give it a try. Two global variables are used throughout the code: $config: The servers configuration, per default loaded from config.yml $db: The DNS database, per default loaded and automatically saved to db.yml Some functions don't take any parameters at all. They usually operate on the global variables. # Running tests Execute tests/gen_https_cert.sh and then tests/test.rb to put the DNS server through the paces. Run it as root (e.g. via sudo) to test privilege dropping. # Version history 1.0.0 2015-11-06 Initial release. 1.0.1 2015-11-08 Removed a left over debug output line. 1.0.2 2015-11-19 Trying to update records without a password now returns 403 forbidden. They're unchangable. Errors during HTTP or DNS requests are now logged to stderr. 1.0.3 2015-11-25 An empty answer is now returned if we can't find the requested record but the name has other records (RFC 4074 4.2. Return "Name Error"). 1.1.0 2017-01-06 Added HTTPS support. Fixed hanging HTTP connections of stupid routers breaking the DNS server (moved HTTP servers into extra thread and imposed timeout). 1.1.1 2017-02-12 The server can now resolve itself by using the name "@" (reported by Chris). 1.1.2 2017-03-31 Names are now matched case insensitive (reported by SebiTNT). HTTP server can now be disabled via configuration (requested by SebiTNT). 1.1.3 2017-04-01 Unknown DNS record types are now printed with their numerical value instead of an empty string (reported by SebiTNT). 1.1.4 2017-04-02 Server now answers NS queries about itself (reported by SebiTNT). 1.1.5 2017-11-28 Log messages and errors are now written immediatly (flushed) even when the output is redirected (reported by Catscrash). 1.2.0 2018-02-19 When the "myip" parameter is omitted in the HTTP interface the records IP is set to the peer IP of the connection (contributed by Chris). 1.2.1 2018-08-18 Fixed a server crash when receiving invalid packets that were just 1 or 2 bytes long (reported by acrolink). 1.3.0 2018-08-19 The database file is no longer saved after each HTTP request but only when a client actually reports a changed IP address (contributed by acrolink). 1.3.1 2019-07-11 Added an DNS hexdump option to track down incompatibilities. Fixed a bug that prevented HTTPS updates using the connections IP (reported by Rick). 2020-07-09 Updating the IP via an HTTP request now also works if the request was made through HTTP proxies. Added support for the X-Forwarded-For and Forwarded HTTP headers for this (requested by Mentor). Never released, only send to Mentor for feedback. 1.4.0 2023-05-09 Fixed corner cases of X-Forwarded-For and Forwarded headers. Updated the test suit to Ruby 3. =end require "optparse" require "yaml" require "etc" require "socket" require "cgi" require "base64" require "ipaddr" require "openssl" require "timeout" # # Logging functions to output messages with timestamps # # Returns true so it can be used with the "and" operator like this: # log("...") and return if something.broke? def log(message) $stdout.puts Time.now.strftime("%Y-%m-%d %H:%M:%S") + " " + message $stdout.flush return true end def error(message) $stderr.puts Time.now.strftime("%Y-%m-%d %H:%M:%S") + " " + message $stderr.flush return true end # Outputs to STDERR and exits. This way admins can redirect all errors # into a different file if they want. def die(message) abort Time.now.strftime("%Y-%m-%d %H:%M:%S") + " " + message end # # "Database" code # # If loading the DB fails an empty DB with a new serial is generated. def load_db raw_db = begin YAML.load_file $config[:db] rescue Errno::ENOENT false end raw_db = {} unless raw_db.kind_of? Hash # Convert all keys except "SERIAL" to lowercase since DNS names are case insensitive $db = Hash[ raw_db.map{|key, value| [key != "SERIAL" ? key.downcase : key, value]} ] $db["SERIAL"] = Time.now.strftime("%Y%m%d00").to_i unless $db.include? "SERIAL" end def save_db File.write $config[:db], YAML.dump($db) end # Updates the in-memory DB with new data from the DB file. # # - Adds users and IPs that don't exist yet # - Deletes users no longer in the DB file # - Loads passwords of all users from the DB file # - Bumps serial # - Doesn't overwrite IP addresses in memory (they're newer than the ones in the file) def merge_db raw_edited_db = YAML.load_file $config[:db] # Convert all keys except "SERIAL" to lowercase since DNS names are case insensitive edited_db = Hash[ raw_edited_db.map{|key, value| [key != "SERIAL" ? key.downcase : key, value]} ] new_users = edited_db.keys - $db.keys new_users.each do |name| $db[name] = edited_db[name] end deleted_users = $db.keys - edited_db.keys deleted_users.each do |name| $db.delete name end edited_db.each do |name, edited_data| next if name == "SERIAL" $db[name]["pass"] = edited_data["pass"] end $db["SERIAL"] += 1 log "SERVER: Updated DB from file, added #{new_users.join(", ")}, deleted #{deleted_users.join(", ")}, updated passwords and serial" rescue Errno::ENOENT nil end # # DNS server code # # Possible values for the RCODE field (response code) in the # DNS header, see RFC 1035, 4.1.1. Header section format RCODE_NO_ERROR = 0 RCODE_FORMAT_ERROR = 1 # The name server was unable to interpret the query. RCODE_SERVER_FAILURE = 2 # The name server was unable to process this query due to a problem with the name server. RCODE_NAME_ERROR = 3 # This code signifies that the domain name referenced in the query does not exist. RCODE_NOT_IMPLEMENTED = 4 # The name server does not support the requested kind of query. RCODE_REFUSED = 5 # The name server refuses to perform the specified operation for policy reasons. # Some handy record type values, see RFC 1035, 3.2.2. TYPE values. # Also a nice overview with numeric values: https://en.wikipedia.org/wiki/List_of_DNS_record_types TYPE_A = 1 # IPv4 host address TYPE_NS = 2 # an authoritative name server TYPE_CNAME = 5 # the canonical name for an alias TYPE_SOA = 6 # marks the start of a zone of authority TYPE_PTR = 12 # a domain name pointer TYPE_MX = 15 # a domain name pointer TYPE_TXT = 16 # text strings TYPE_AAAA = 28 # IPv6 host address (see RFC 3596, 2.1 AAAA record type) TYPE_ALL = 255 # A request for all records (only valid in question) # We try to ignore packets from possible attacks (queries for different domains) # # packet parse error → ignore # SOA for our domain → answer # not our domain → ignore # unknown subdomain → not found # known subdomain → answer def handle_dns_packet(packet) id, domain, type, recursion_desired = parse_dns_question(packet) type_as_string = { TYPE_A => "A", TYPE_AAAA => "AAAA", TYPE_SOA => "SOA", TYPE_NS => "NS", TYPE_ALL => "ANY" }[type] || "type(#{type})" # Don't respond if we failed to parse the packet log "DNS: Failed to parse DNS packet" and return nil unless id # Don't respond if the domain isn't a subdomain of our domain or our domain itself log "DNS: #{type_as_string} #{domain} -> wrong domain, ignoring" and return nil unless domain.end_with?($config["domain"]) # Extract the subdomain we're looking up (e.g. "foo" out of "foo.dyn.example.com"). Use "@" if someone asks about # the server itself (e.g. "@" for "dyn.example.com"). "@" is an alias for the zone origin in zone files so we use it # here for the same purpose (a name refering to the server itself). name = domain[0..-($config["domain"].bytesize + 2)] name = "@" if name == "" records, texts = [], [] # Add special start of authority (SOA) and/or nameserver (NS) records to the answer when someone asks about the # server itself. if name == "@" and (type == TYPE_SOA or type == TYPE_ALL) mail_name, mail_domain = $config["soa"]["mail"].split("@", 2) encoded_mail = mail_name.gsub(".", "\\.") + "." + mail_domain records << resource_record(TYPE_SOA, $config["soa"]["ttl"], soa_rdata($config["soa"]["nameserver"], encoded_mail, $db["SERIAL"], $config["soa"]["refresh_time"], $config["soa"]["retry_time"], $config["soa"]["expire_time"], $config["soa"]["negative_caching_ttl"]) ) texts << "SOA(#{$config["soa"]["nameserver"]}, #{$config["soa"]["mail"]}, ...)" end if name == "@" and (type == TYPE_NS or type == TYPE_ALL) records << resource_record(TYPE_NS, $config["soa"]["ttl"], domain_name($config["soa"]["nameserver"])) texts << "NS(#{$config["soa"]["nameserver"]})" end # Look for records in the database. There might also be records for the server itself ("@") in there. if $db[name] begin records << resource_record(TYPE_A, $config["ttl"], IPAddr.new($db[name]["A"]).hton) and texts << $db[name]["A"] if (type == TYPE_A or type == TYPE_ALL) and $db[name]["A"] records << resource_record(TYPE_AAAA, $config["ttl"], IPAddr.new($db[name]["AAAA"]).hton) and texts << $db[name]["AAAA"] if (type == TYPE_AAAA or type == TYPE_ALL) and $db[name]["AAAA"] rescue ArgumentError log "DNS: #{type_as_string} #{name} -> server fail, invalid IP in DB" return build_dns_answer id, recursion_desired, RCODE_SERVER_FAILURE, domain, type end end if records.empty? if $db[name] # No records found but we know the subdomain. Return an empty answer to indicate that there might be other records. log "DNS: #{type_as_string} #{name} -> no records returned" return build_dns_answer id, recursion_desired, RCODE_NO_ERROR, domain, type else # Unknown subdomain, return an error for an unkown domain. log "DNS: #{type_as_string} #{name} -> not found" return build_dns_answer id, recursion_desired, RCODE_NAME_ERROR, domain, type end else log "DNS: #{type_as_string} #{name} -> #{texts.join(", ")}" return build_dns_answer id, recursion_desired, RCODE_NO_ERROR, domain, type, *records end end # Parses a raw packet with one DNS question. Returns the query id, # lower case question name and type and if recursion is desired by # the client. If parsing fails nil is returned. def parse_dns_question(packet) if $config["dns"] and $config["dns"]["dump_packets"] packet.bytes.each_slice(16) do |slice| hex = slice.collect{ |byte| format("%02x", byte) }.join(" ") ascii = slice.collect{ |byte| if byte.ord >= 32 and byte.ord <= 126 then byte.chr else "." end }.join puts hex.ljust(16*3+1) + ascii end end # Abort if the packet is shorter than the header (we know it's invalid then). # This avoids a (harmless) exception thrown when processing the flags field. return if packet.bytesize < 12 # Taken from RFC 1035, 4.1.1. Header section format # # 1 1 1 1 1 1 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ID | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # |QR| Opcode |AA|TC|RD|RA| Z | RCODE | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QDCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ANCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | NSCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ARCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # # Z (bits 9, 10 and 11) are reserved and should be zero id, flags, question_count, answer_count, nameserver_count, additions_count = packet.unpack("n6") is_response = (flags & 0b1000000000000000) >> 15 opcode = (flags & 0b0111100000000000) >> 11 authoritative_anser = (flags & 0b0000010000000000) >> 10 truncated = (flags & 0b0000001000000000) >> 9 recursion_desired = (flags & 0b0000000100000000) >> 8 recursion_available = (flags & 0b0000000010000000) >> 7 response_code = (flags & 0b0000000000001111) >> 0 # Only continue when the packet is a standard query (QUERY, opcode == 0 and is_response = 0) with exactly one question. # This way we don't have to care about pointers in the question section (see RFC 1035, 4.1.4. Message compression). # Ignore answer, nameserver and additions counts since we don't care about the extra information. return unless opcode == 0 and is_response == 0 and question_count == 1 # Taken from RFC 1035, 4.1.2. Question section format # # 1 1 1 1 1 1 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | | # / QNAME / # / / # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QTYPE | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QCLASS | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ pos = 6*2 labels = [] while (length = packet.byteslice(pos).ord) > 0 labels << packet.byteslice(pos + 1, length) pos += 1 + length break if pos > packet.bytesize end pos += 1 # Skip the terminating null byte that kicked us out of the loop question_name = labels.join "." question_type, question_class = packet.unpack "@#{pos} n2" # Turn question name into lowercase. DNS names are case insensitive. # See https://tools.ietf.org/html/rfc4343 (Domain Name System (DNS) Case Insensitivity Clarification) question_name.downcase! return id, question_name, question_type, recursion_desired rescue StandardError => e error "DNS: Failed to parse request: #{e}" e.backtrace.each do |stackframe| $stderr.puts "\t#{stackframe}" end $stderr.flush return end def build_dns_answer(id, recursion_desired, response_code, domain, question_type, *answers) # Assemble flags for header is_response = 1 # We send a response, so QR bit is set to 1 opcode = 0 # Opcode 0 (a standard query) authoritative_anser = 1 # Authoritative answer, AA bit set to 1 truncated = 0 # Not truncated, TC set to 0 recursion_available = 0 # Recursion available, not implemented so set to 0 # Build header for the answer. # Taken from RFC 1035, 4.1.1. Header section format # # 1 1 1 1 1 1 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ID | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # |QR| Opcode |AA|TC|RD|RA| Z | RCODE | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QDCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ANCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | NSCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | ARCOUNT | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # # Z (bits 9, 10 and 11) are reserved and should be zero flags = 0 flags |= (is_response << 15) & 0b1000000000000000 flags |= (opcode << 11) & 0b0111100000000000 flags |= (authoritative_anser << 10) & 0b0000010000000000 flags |= (truncated << 9) & 0b0000001000000000 flags |= (recursion_desired << 8) & 0b0000000100000000 flags |= (recursion_available << 7) & 0b0000000010000000 flags |= (response_code << 0) & 0b0000000000001111 header = [ id, flags, 1, # question count answers.length, # answer count 0, # name server count 0 # additional records count ].pack "n6" # Build original question from query. # Taken from RFC 1035, 4.1.2. Question section format # # 1 1 1 1 1 1 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | | # / QNAME / # / / # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QTYPE | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | QCLASS | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ question_class = 1 # 1 = IN, the Internet question = domain.split(".").collect{|label| label.bytesize.chr + label}.join("") + "\x00" question += [question_type, question_class].pack "n2" return header + question + answers.join("") end # # DNS utility code to construct parts of DNS packets # # 3.1. Name space definitions # # Domain names in messages are expressed in terms of a sequence of labels. # Each label is represented as a one octet length field followed by that # number of octets. Since every domain name ends with the null label of # the root, a domain name is terminated by a length byte of zero. The # high order two bits of every length octet must be zero, and the # remaining six bits of the length field limit the label to 63 octets or # less. def domain_name(domain) domain.split(".").collect do |label| trimmed_label = label.byteslice(0, 63) trimmed_label.bytesize.chr + trimmed_label end.join("") + "\x00" end # Payload of an SOA record, see 3.3.13. SOA RDATA format def soa_rdata(source_host, mail, serial, refresh_interval, retry_interval, expire_interval, minimum_ttl) [ domain_name(source_host), domain_name(mail), serial, refresh_interval, retry_interval, expire_interval, minimum_ttl ].pack("a* a* N5") end # Generates a resource record fo the specified type, ttl in seconds # (0 = no caching) and payload. The record always references the name of # the first question in the packet and is always for the IN class # (the Internet). See 4.1.3. Resource record format. def resource_record(type, ttl, payload) header = [ # If the first 2 bits are set to 1 the length is interpreted as an offset into the packet where the name is # stored. We use this to reference the name in the first question that starts directly after the 12 byte header. # See RFC 1035, 4.1.4. Message compression. (0b1100000000000000 | 12), type, 1, # 1 = class IN (the Internet) ttl, # TTL, time in seconds that the answer may be cached, 0 = no caching payload.bytesize ].pack("n3 N n") return header + payload end # # HTTP server code # # Handles an entire HTTP connection from start to finish. Replies with # an HTTP/1.0 answer so the content automatically ends when we close # the connection. # # Only reacts to the basic authentication header and myip query parameter. # Everything else is ignored right now (path, other parameters or headers). def handle_http_connection(connection) log_prefix = if connection.is_a? OpenSSL::SSL::SSLSocket then "HTTPS" else "HTTP" end # Read the entire request from the connection and fill the local variables. # This must not take longer that the configured number of seconds or we'll kill the connection. # The idea is to handle all connections in a single thread (to avoid DOS attacks) but prevent # stupid routers from keeping connections open for ever. method, path_and_querystring, params, user, password, proxy_client_ip = nil, nil, nil, nil, nil, nil begin # I know timeout() is considered harmful but we rely on the global interpreter lock anyway to # synchronize access to $db. So the server only works correctly with interpreters that have a # global interpreter lock (e.g. MRI). Also this server isn't designed for high-load scenarios. # Given that timeout() won't hurt us to much... I hope. Timeout::timeout($config["http_timeout"]) do # Ignore empty TCP connections from chrome request_line = connection.gets("\n") return unless request_line and request_line.length > 0 # Extract path and URL parameters method, path_and_querystring, _ = request_line.chomp.split(" ", 3) path, query_string = path_and_querystring.split("?", 2) params = query_string ? CGI::parse(query_string) : {} # Extract user and password from HTTP headers. If we got the HTTP request via proxy server # extract the client ip from the X-Forwarded-For or Forwarded header. until (line = connection.gets("\n").chomp) == "" name, value = line.split(": ", 2) case name.downcase when "authorization" # Extract user and password from HTTP headers auth_method, rest = value.split(" ", 2) if auth_method.downcase == "basic" user, password = Base64.decode64(rest).split(":", 2) end when "x-forwarded-for" # e.g. X-Forwarded-For: 192.0.2.43, "[2001:db8:cafe::17]:1234" # See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For proxy_client_ip = value.split(",").first.strip.gsub(/^"|"$/, "") proxy_client_ip = $1 if proxy_client_ip =~ /^\[(.+)\](\:\d+)?$/ when "forwarded" # e.g. Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43, for="[2001:db8:cafe::17]" # See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded proxy_client_ip = value.split(",").first.strip.match(/for=(.*?)(?:;|\s|$)/i)[1].gsub(/^"|"$/, "") proxy_client_ip = $1 if proxy_client_ip =~ /^\[(.+)\](\:\d+)?$/ end end end rescue Timeout::Error log "#{log_prefix}: Client took to long to send data, ignoring" return end # Process request ip_as_string = nil status = catch :status do # Mare sure we got auth information throw :status, :not_authorized unless user and $db[user] # Tell the client if the name can't be changed throw :status, :unchangable if $db[user]["pass"].to_s.strip == "" # Make sure we're authenticated throw :status, :not_authorized unless password == $db[user]["pass"] if params.include? "myip" ip_as_string = CGI::unescape params["myip"].first elsif proxy_client_ip # If no myip parameter was provided but we got the client IP from an HTTP proxy use it ip_as_string = proxy_client_ip else # If all else fails directly use the public IP of the client connection ip_as_string = connection.peeraddr.last end if ip_as_string == '' $db[user]["A"] = nil $db[user]["AAAA"] = nil else begin ip = IPAddr.new ip_as_string rescue ArgumentError throw :status, :bad_request end record_type_to_update = if ip.ipv4? "A" elsif ip.ipv6? "AAAA" else throw :status, :bad_request end # Skip the DB update if the IP address hasn't changed (no point in writing the same data) throw :status, :same_as_before if $db[user][record_type_to_update] == ip_as_string $db[user][record_type_to_update] = ip_as_string end $db["SERIAL"] += 1 save_db :ok end case status when :ok log "#{log_prefix}: #{method} #{path_and_querystring} -> updated #{user} to #{ip_as_string}" connection.write [ "HTTP/1.0 200 OK", "Content-Type: text/plain", "", "Your IP has been updated" ].join("\r\n") when :same_as_before log "#{log_prefix}: #{method} #{path_and_querystring} -> skipped, #{user} reported same IP as before" connection.write [ "HTTP/1.0 200 OK", "Content-Type: text/plain", "", "Your IP has been updated" ].join("\r\n") when :bad_request log "#{log_prefix}: #{method} #{path_and_querystring} -> bad request for #{user}" connection.write [ "HTTP/1.0 400 Bad Request", "Content-Type: text/plain", "", "You need to specify a new IP in the myip URL parameter" ].join("\r\n") when :unchangable log "#{log_prefix}: #{method} #{path_and_querystring} -> denied, #{user} unchangable" connection.write [ "HTTP/1.0 403 Forbidden", "Content-Type: text/plain", "", "This IP address can't be changed, sorry." ].join("\r\n") else log "#{log_prefix}: #{method} #{path_and_querystring} -> not authorized" connection.write [ "HTTP/1.0 401 Not Authorized", 'WWW-Authenticate: Basic realm="Your friendly DynDNS server"', "Content-Type: text/plain", "", "Authentication required" ].join("\r\n") end rescue StandardError => e error "#{log_prefix}: Failed to process request: #{e}" e.backtrace.each do |stackframe| $stderr.puts "\t#{stackframe}" end $stderr.flush end # # Server startup # # Parse command line arguments options = { config: "config.yml", db: "db.yml" } OptionParser.new "Usage: dns.rb [options]", 20 do |opts| opts.on "-cFILE", "--config FILE", "YAML file containing the server configuration. Default: #{options[:config]}" do |value| options[:config] = value end opts.on "-dFILE", "--db FILE", "YAML file used to rembmer the IP addresses and passwords of DNS records. Default: #{options[:db]}" do |value| options[:db] = value end opts.on_tail "-h", "--help", "Show help" do puts opts exit end end.parse! # Load configuration $config = begin YAML.load_file options[:config] rescue Errno::ENOENT die "SERVER: Failed to load config file #{options[:config]}, sorry." end $config[:db] = options[:db] # Load the database load_db # Open sockets on privileged ports udp_socket = UDPSocket.new udp_socket.bind $config["dns"]["ip"], $config["dns"]["port"] # Open HTTP server if configured # Avoid lenghy name lookups when the connection IP is used as new IP by setting do_not_reverse_lookup to false. # peeraddr(:numeric) doesn't work for HTTPS servers, only for TCP servers (reported by Rick). http_server = if $config["http"] tcp_server = TCPServer.new $config["http"]["ip"], $config["http"]["port"] tcp_server.do_not_reverse_lookup = true tcp_server else nil end # Open HTTPS server if configured (again with do_not_reverse_lookup = false because of OpenSSLs peeraddr) https_server = if $config["https"] https_tcp_server = TCPServer.new $config["https"]["ip"], $config["https"]["port"] https_tcp_server.do_not_reverse_lookup = true ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.cert = OpenSSL::X509::Certificate.new File.open($config["https"]["cert"]) ssl_context.key = OpenSSL::PKey::RSA.new File.open($config["https"]["priv_key"]) OpenSSL::SSL::SSLServer.new https_tcp_server, ssl_context else nil end # Drop privileges, based on http://timetobleed.com/5-things-you-dont-know-about-user-ids-that-will-destroy-you/ running_as = nil if Process.uid == 0 Process::Sys.setgid Etc.getgrnam($config["group"]).gid Process.groups = [] Process::Sys.setuid Etc.getpwnam($config["user"]).uid die "SERVER: Failed to drop privileges!" if begin Process::Sys.setuid 0 rescue Errno::EPERM false else true end running_as = ", as user #{$config["user"]}:#{$config["group"]}" end # Merge the updated DB file with the data we have in memory if someone sends us the USR1 signal Signal.trap "USR1" do merge_db end log "SERVER: Running DNS on #{$config["dns"]["ip"]}:#{$config["dns"]["port"]}" + if http_server then ", HTTP on #{$config["http"]["ip"]}:#{$config["http"]["port"]}" else "" end + if https_server then ", HTTPS on #{$config["https"]["ip"]}:#{$config["https"]["port"]}" else "" end + "#{running_as}" # # Server mainloops (extra thread for HTTP and HTTPS servers, DNS in main thread) # # Handle HTTP/HTTPS connections in an extra thread so they don't block # handling of DNS requests. We rely on the global interpreter lock to synchronize # access to the $db variable. # All incoming connections are handled one after the other by that thread. This hopefully # makes us less susceptible to DOS attacks since attackers can only saturate that thread. # Anyway that server design usually is a bad idea but is adequat for low load and simple # (especially given OpenSSL integration). if http_server or https_server Thread.new do loop do # In case https_server is nil we need to remove it from the read array. # Otherwise select doesn't seem to work. ready_servers, _, _ = IO.select [http_server, https_server].compact ready_servers.each do |server| # HTTP/HTTPS connection ready, accept, handle and close it connection = server.accept handle_http_connection connection connection.close end end end end # Mainloop monitoring for incoming UDP packets. If the user presses ctrl+c we exit # the mainloop and shutdown the server. When the main thread exits this also kills the # HTTP thread above. loop do begin packet, (_, port, _, addr) = udp_socket.recvfrom 512 answer = handle_dns_packet packet udp_socket.send answer, 0, addr, port if answer rescue Interrupt break end end # Server cleanup and shutdown (we just kill of the HTTP thread by ending the main thread) log "SERVER: Saving DB and shutting down" https_server.close if https_server http_server.close if http_server udp_socket.close save_db
ruby
MIT
33aa42530d1a0c41fd9f2e57d5fdb2d769e62c86
2026-01-04T17:49:48.752453Z
false
manuelvanrijn/selectize-rails
https://github.com/manuelvanrijn/selectize-rails/blob/351e4b73054575707f406eae81d8d53eb64aac4e/lib/selectize-rails.rb
lib/selectize-rails.rb
require 'rails' require 'selectize-rails/version' module Selectize module Rails if ::Rails.version < '3.1' require 'selectize-rails/railtie' else require 'selectize-rails/engine' end end end
ruby
MIT
351e4b73054575707f406eae81d8d53eb64aac4e
2026-01-04T17:50:11.911481Z
false
manuelvanrijn/selectize-rails
https://github.com/manuelvanrijn/selectize-rails/blob/351e4b73054575707f406eae81d8d53eb64aac4e/lib/selectize-rails/version.rb
lib/selectize-rails/version.rb
module Selectize module Rails VERSION = '0.12.6'.freeze end end
ruby
MIT
351e4b73054575707f406eae81d8d53eb64aac4e
2026-01-04T17:50:11.911481Z
false
manuelvanrijn/selectize-rails
https://github.com/manuelvanrijn/selectize-rails/blob/351e4b73054575707f406eae81d8d53eb64aac4e/lib/selectize-rails/railtie.rb
lib/selectize-rails/railtie.rb
module Selectize module Rails class Railtie < ::Rails::Railtie; end end end
ruby
MIT
351e4b73054575707f406eae81d8d53eb64aac4e
2026-01-04T17:50:11.911481Z
false
manuelvanrijn/selectize-rails
https://github.com/manuelvanrijn/selectize-rails/blob/351e4b73054575707f406eae81d8d53eb64aac4e/lib/selectize-rails/engine.rb
lib/selectize-rails/engine.rb
module Selectize module Rails class Engine < ::Rails::Engine; end end end
ruby
MIT
351e4b73054575707f406eae81d8d53eb64aac4e
2026-01-04T17:50:11.911481Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/spec/backgrounded_spec.rb
spec/backgrounded_spec.rb
RSpec.describe Backgrounded do describe '.configure' do it 'saves configuration' do handler = double Backgrounded.configure do |config| config.handler = handler end expect(Backgrounded.handler).to eq handler end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false