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
burtlo/yard-cucumber
https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/cucumber/city_builder.rb
lib/cucumber/city_builder.rb
module Cucumber module Parser class CityBuilder < ::Gherkin::AstBuilder # # The Gherkin Parser is going to call the various methods within this # class as it finds items. This is similar to how Cucumber generates # it's Abstract Syntax Tree (AST). Here instead this generates the # various YARD::CodeObjects defined within this template. # # A namespace is specified and that is the place in the YARD namespacing # where all cucumber features generated will reside. The namespace specified # is the root namespaces. # # @param [String] file the name of the file which the content belongs # def initialize(file) super() @namespace = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE find_or_create_namespace(file) @file = file end # Return the feature that has been defined. This method is the final # method that is called when all the work is done. It is called by # the feature parser to return the complete Feature object that was created # # @return [YARD::CodeObject::Cucumber::Feature] the completed feature # # @see YARD::Parser::Cucumber::FeatureParser def ast feature(get_result) unless @feature @feature end # # Feature that are found in sub-directories are considered, in the way # that I chose to implement it, in another namespace. This is because # when you execute a cucumber test run on a directory any sub-directories # of features will be executed with that directory so the file is split # and then namespaces are generated if they have not already have been. # # The other duty that this does is look for a README.md file within the # specified directory of the file and loads it as the description for the # namespace. This is useful if you want to give a particular directory # some flavor or text to describe what is going on. # def find_or_create_namespace(file) @namespace = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE File.dirname(file).split('/').each do |directory| @namespace = @namespace.children.find {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) && child.name.to_s == directory } || @namespace = YARD::CodeObjects::Cucumber::FeatureDirectory.new(@namespace,directory) {|dir| dir.add_file(directory)} end if @namespace.description == "" && File.exists?("#{File.dirname(file)}/README.md") @namespace.description = File.read("#{File.dirname(file)}/README.md") end end # # Find the tag if it exists within the YARD Registry, if it doesn't then # create it. # # We note that the tag was used in this file at the current line. # # Then we add the tag to the current scenario or feature. We also add the # feature or scenario to the tag. # # @param [String] tag_name the name of the tag # @param [parent] parent the scenario or feature that is going to adopt # this tag. # def find_or_create_tag(tag_name,parent) #log.debug "Processing tag #{tag_name}" tag_code_object = YARD::Registry.all(:tag).find {|tag| tag.value == tag_name } || YARD::CodeObjects::Cucumber::Tag.new(YARD::CodeObjects::Cucumber::CUCUMBER_TAG_NAMESPACE,tag_name.gsub('@','')) {|t| t.owners = [] ; t.value = tag_name ; t.total_scenarios = 0} tag_code_object.add_file(@file,parent.line) parent.tags << tag_code_object unless parent.tags.find {|tag| tag == tag_code_object } tag_code_object.owners << parent unless tag_code_object.owners.find {|owner| owner == parent} end # # Each feature found will call this method, generating the feature object. # This is once, as the gherkin parser does not like multiple feature per # file. # def feature(document) #log.debug "FEATURE" feature = document[:feature] return unless document[:feature] return if has_exclude_tags?(feature[:tags].map { |t| t[:name].gsub(/^@/, '') }) @feature = YARD::CodeObjects::Cucumber::Feature.new(@namespace,File.basename(@file.gsub('.feature','').gsub('.','_'))) do |f| f.comments = feature[:comments] ? feature[:comments].map{|comment| comment[:text]}.join("\n") : '' f.description = feature[:description] || '' f.add_file(@file,feature[:location][:line]) f.keyword = feature[:keyword] f.value = feature[:name] f.tags = [] feature[:tags].each {|feature_tag| find_or_create_tag(feature_tag[:name],f) } end background(feature[:background]) if feature[:background] feature[:children].each do |child| case child[:type] when :Background background(child) when :ScenarioOutline outline = scenario_outline(child) @feature.total_scenarios += outline.scenarios.size when :Scenario scenario(child) end end @feature.tags.each do |feature_tag| tag_code_object = YARD::Registry.all(:tag).find {|tag| tag.name.to_s == feature_tag[:name].to_s } tag_code_object.total_scenarios += @feature.total_scenarios end end # # Called when a background has been found # # @see #feature def background(background) #log.debug "BACKGROUND" @background = YARD::CodeObjects::Cucumber::Scenario.new(@feature,"background") do |b| b.comments = background[:comments] ? background[:comments].map{|comment| comment.value}.join("\n") : '' b.description = background[:description] || '' b.keyword = background[:keyword] b.value = background[:name] b.add_file(@file,background[:location][:line]) end @feature.background = @background @background.feature = @feature @step_container = @background background[:steps].each { |s| step(s) } end # # Called when a scenario has been found # - create a scenario # - assign the scenario to the feature # - assign the feature to the scenario # - find or create tags associated with the scenario # # The scenario is set as the @step_container, which means that any steps # found before another scenario is defined belong to this scenario # # @param [Scenario] statement is a scenario object returned from Gherkin # @see #find_or_create_tag # def scenario(statement) #log.debug "SCENARIO" return if has_exclude_tags?(statement[:tags].map { |t| t[:name].gsub(/^@/, '') }) scenario = YARD::CodeObjects::Cucumber::Scenario.new(@feature,"scenario_#{@feature.scenarios.length + 1}") do |s| s.comments = statement[:comments] ? statement[:comments].map{|comment| comment.value}.join("\n") : '' s.description = statement[:description] || '' s.add_file(@file,statement[:location][:line]) s.keyword = statement[:keyword] s.value = statement[:name] statement[:tags].each {|scenario_tag| find_or_create_tag(scenario_tag[:name],s) } end scenario.feature = @feature @feature.scenarios << scenario @step_container = scenario statement[:steps].each { |s| step(s) } # count scenarios for scenario level tags scenario.tags.uniq.each { |scenario_tag| if !scenario.feature.tags.include?(scenario_tag) tag_code_object = YARD::Registry.all(:tag).find {|tag| tag.name.to_s == scenario_tag[:name].to_s } tag_code_object.total_scenarios += 1 end } end # # Called when a scenario outline is found. Very similar to a scenario, # the ScenarioOutline is still a distinct object as it can contain # multiple different example groups that can contain different values. # # @see #scenario # def scenario_outline(statement) #log.debug "SCENARIO OUTLINE" return if has_exclude_tags?(statement[:tags].map { |t| t[:name].gsub(/^@/, '') }) outline = YARD::CodeObjects::Cucumber::ScenarioOutline.new(@feature,"scenario_#{@feature.scenarios.length + 1}") do |s| s.comments = statement[:comments] ? statement[:comments].map{|comment| comment.value}.join("\n") : '' s.description = statement[:description] || '' s.add_file(@file,statement[:location][:line]) s.keyword = statement[:keyword] s.value = statement[:name] statement[:tags].each {|scenario_tag| find_or_create_tag(scenario_tag[:name],s) } end outline.feature = @feature @step_container = outline statement[:steps].each { |s| step(s) } statement[:examples].each { |e| example = examples(e, outline) } @feature.scenarios << outline # count scenarios for scenario outline level tags outline.tags.uniq.each { |outline_tag| if !outline.feature.tags.include?(outline_tag) tag_code_object = YARD::Registry.all(:tag).find {|tag| tag.name.to_s == outline_tag[:name].to_s } tag_code_object.total_scenarios += outline.scenarios.size end } # count scenarios for example table level tags outline.examples.each { |example| unless !example.tags.any? example.tags.uniq.each { |example_tag| if !outline.feature.tags.include?(example_tag) && !outline.tags.include?(example_tag) tag_code_object = YARD::Registry.all(:tag).find {|tag| tag.name.to_s == example_tag[:name].to_s } tag_code_object.total_scenarios += example.data.size end } end } return outline end # # Examples for a scenario outline are called here. This section differs # from the Cucumber parser because here each of the examples are exploded # out here as individual scenarios and step definitions. This is so that # later we can ensure that we have all the variations of the scenario # outline defined to be displayed. # def examples(examples, outline) #log.debug "EXAMPLES" return if has_exclude_tags?(examples[:tags].map { |t| t[:name].gsub(/^@/, '') }) example = YARD::CodeObjects::Cucumber::ScenarioOutline::Examples.new(:keyword => examples[:keyword], :name => examples[:name], :line => examples[:location][:line], :comments => examples[:comments] ? examples.comments.map{|comment| comment.value}.join("\n") : '', :rows => [], :tags => [], :scenario => outline ) unless !examples[:tags].any? examples[:tags].each {|example_tag| find_or_create_tag(example_tag[:name], example)} end example.rows = [examples[:tableHeader][:cells].map{ |c| c[:value] }] if examples[:tableHeader] example.rows += matrix(examples[:tableBody]) if examples[:tableBody] # add the example to the step containers list of examples @step_container.examples << example # For each example data row we want to generate a new scenario using our # current scenario as the template. example.data.length.times do |row_index| # Generate a copy of the scenario. scenario = YARD::CodeObjects::Cucumber::Scenario.new(@step_container,"example_#{@step_container.scenarios.length + 1}") do |s| s.comments = @step_container.comments s.description = @step_container.description s.add_file(@file,@step_container.line_number) s.keyword = @step_container.keyword s.value = "#{@step_container.value} (#{@step_container.scenarios.length + 1})" end # Generate a copy of the scenario steps. @step_container.steps.each do |step| step_instance = YARD::CodeObjects::Cucumber::Step.new(scenario,step.line_number) do |s| s.keyword = step.keyword.dup s.value = step.value.dup s.add_file(@file,step.line_number) s.text = step.text.dup if step.has_text? s.table = clone_table(step.table) if step.has_table? end # Look at the particular data for the example row and do a simple # find and replace of the <key> with the associated values. example.values_for_row(row_index).each do |key,text| text ||= "" #handle empty cells in the example table step_instance.value.gsub!("<#{key}>",text) step_instance.text.gsub!("<#{key}>",text) if step_instance.has_text? step_instance.table.each{|row| row.each{|col| col.gsub!("<#{key}>",text)}} if step_instance.has_table? end # Connect these steps that we created to the scenario we created # and then add the steps to the scenario created. step_instance.scenario = scenario scenario.steps << step_instance end # Add the scenario to the list of scenarios maintained by the feature # and add the feature to the scenario scenario.feature = @feature @step_container.scenarios << scenario end return example end # # Called when a step is found. The step is refered to a table owner, though # not all steps have a table or multliline arguments associated with them. # # If a multiline string is present with the step it is included as the text # of the step. If the step has a table it is added to the step using the # same method used by the Cucumber Gherkin model. # def step(step) #log.debug "STEP" @table_owner = YARD::CodeObjects::Cucumber::Step.new(@step_container,"#{step[:location][:line]}") do |s| s.keyword = step[:keyword] s.value = step[:text] s.add_file(@file,step[:location][:line]) end @table_owner.comments = step[:comments] ? step[:comments].map{|comment| comment.value}.join("\n") : '' multiline_arg = step[:argument] case(multiline_arg[:type]) when :DocString @table_owner.text = multiline_arg[:content] when :DataTable #log.info "Matrix: #{matrix(multiline_arg).collect{|row| row.collect{|cell| cell.class } }.flatten.join("\n")}" @table_owner.table = matrix(multiline_arg[:rows]) end if multiline_arg @table_owner.scenario = @step_container @step_container.steps << @table_owner end # Defined in the cucumber version so left here. No events for the end-of-file def eof end # When a syntax error were to occurr. This parser is not interested in errors def syntax_error(state, event, legal_events, line) # raise "SYNTAX ERROR" end private def matrix(gherkin_table) gherkin_table.map {|gherkin_row| gherkin_row[:cells].map{ |cell| cell[:value] } } end # # This helper method is used to deteremine what class is the current # Gherkin class. # # @return [Class] the class that is the current supported Gherkin Model # for multiline strings. Prior to Gherkin 2.4.0 this was the PyString # class. As of Gherkin 2.4.0 it is the DocString class. def gherkin_multiline_string_class if defined?(Gherkin::Formatter::Model::PyString) Gherkin::Formatter::Model::PyString elsif defined?(Gherkin::Formatter::Model::DocString) Gherkin::Formatter::Model::DocString else raise "Unable to find a suitable class in the Gherkin Library to parse the multiline step data." end end def clone_table(base) base.map {|row| row.map {|cell| cell.dup }} end def has_exclude_tags?(tags) if YARD::Config.options["yard-cucumber"] and YARD::Config.options["yard-cucumber"]["exclude_tags"] return true unless (YARD::Config.options["yard-cucumber"]["exclude_tags"] & tags).empty? end end end end end
ruby
MIT
177e5ad17aa4973660ce646b398118a6408d8913
2026-01-04T17:52:15.257300Z
false
burtlo/yard-cucumber
https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/docserver/doc_server/full_list/html/setup.rb
lib/docserver/doc_server/full_list/html/setup.rb
include T('default/fulldoc/html') def init # This is the css class type; here we just default to class @list_class = "class" case @list_type.to_sym when :features; @list_title = "Features" when :tags; @list_title = "Tags" when :class; @list_title = "Class List" when :methods; @list_title = "Method List" when :files; @list_title = "File List" end sections :full_list end def all_features_link linkify YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE, "All Features" end
ruby
MIT
177e5ad17aa4973660ce646b398118a6408d8913
2026-01-04T17:52:15.257300Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "serverkit" RSpec.configure do |config| 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.disable_monkey_patching! config.filter_run :focus config.run_all_when_everything_filtered = true end # Dirty configuration to silent useless warnings from specinfra. require "specinfra" Specinfra.configuration.backend = :exec
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/spec/serverkit/recipe_spec.rb
spec/serverkit/recipe_spec.rb
# frozen_string_literal: true RSpec.describe Serverkit::Recipe do let(:recipe) do described_class.new(recipe_data) end let(:recipe_data) do { "resources" => resources } end let(:resources) do [] end describe "#errors" do subject do recipe.errors end context "with invalid typed recipe data" do let(:recipe_data) do nil end it "returns InvalidRecipeTypeError" do is_expected.to match( [ an_instance_of(Serverkit::Errors::InvalidRecipeTypeError) ] ) end end context "with unknown type resource" do let(:resources) do [ { "type" => "test", }, ] end it "returns UnknownTypeResourceError" do is_expected.to match( [ an_instance_of(Serverkit::Errors::UnknownResourceTypeError) ] ) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/spec/serverkit/command_spec.rb
spec/serverkit/command_spec.rb
# frozen_string_literal: true RSpec.describe Serverkit::Command do let(:command) do described_class.new(argv) end describe "#call" do subject do command.call end context "with validate as 1st argument" do let(:argv) do ["validate", "recipe.yml"] end it "calls Serverkit::Actions::Validate action" do expect(Serverkit::Actions::Validate).to receive(:new).with( hash_including( log_level: Logger::INFO, recipe_path: "recipe.yml", ) ).and_call_original expect_any_instance_of(Serverkit::Actions::Validate).to receive(:call) subject end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/spec/serverkit/resource_builder_spec.rb
spec/serverkit/resource_builder_spec.rb
# frozen_string_literal: true RSpec.describe Serverkit::ResourceBuilder do let(:recipe) do Serverkit::Recipe.new(recipe_data) end let(:recipe_data) do { "resources" => resources } end let(:resources) do [resource_attributes] end let(:resource_attributes) do { "destination" => "b", "source" => "a", "type" => "symlink", } end let(:resource_builder) do described_class.new(recipe, resource_attributes) end describe "#build" do subject do resource_builder.build end context "with normal case" do it { is_expected.to be_a Serverkit::Resources::Symlink } end context "with unknown type attribute" do let(:resource_attributes) do super().merge("type" => "unknown") end it { is_expected.to be_a Serverkit::Resources::Unknown } end context "without type attribute" do let(:resource_attributes) do super().except("type") end it { is_expected.to be_a Serverkit::Resources::Missing } end context "with abstract type attribute" do let(:resource_attributes) do super().merge("type" => "entry") end it { is_expected.to be_a Serverkit::Resources::Unknown } end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/spec/serverkit/resources/user_spec.rb
spec/serverkit/resources/user_spec.rb
# frozen_string_literal: true RSpec.describe Serverkit::Resources::User do let(:recipe) { Serverkit::Recipe.new(resources: [attributes]) } subject { described_class.new(recipe, attributes) } describe "attributes" do let(:attributes) do { "type" => "user" } end it { expect(subject.type).to eq "user" } it { is_expected.to respond_to :gid } it { is_expected.to respond_to :home } it { is_expected.to respond_to :name } it { is_expected.to respond_to :password } it { is_expected.to respond_to :shell } it { is_expected.to respond_to :system } it { is_expected.to respond_to :uid } end describe "system" do context "system is true" do let(:attributes) do { "type" => "user", "system" => true, } end it { expect(subject.system).to be true } end context "system is false" do let(:attributes) do { "type" => "user", "system" => false, } end it { expect(subject.system).to be false } end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/type_validator.rb
lib/type_validator.rb
# frozen_string_literal: true require "active_model" class TypeValidator < ActiveModel::EachValidator def options super.merge(allow_nil: true) end def validate_each(record, attribute, value) classes = options[:in] || [options[:with]] if classes.all? { |klass| !value.is_a?(klass) } record.errors.add(attribute, "must be a #{classes.join(' or ')}, not a #{value.class}") end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/readable_validator.rb
lib/readable_validator.rb
# frozen_string_literal: true require "active_model" class ReadableValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if !value.nil? && !File.readable?(value) record.errors.add(attribute, "can't be unreadable path") end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/required_validator.rb
lib/required_validator.rb
# frozen_string_literal: true require "active_model" class RequiredValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if value.nil? record.errors.add(attribute, "is required") end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/regexp_validator.rb
lib/regexp_validator.rb
# frozen_string_literal: true require "active_model" class RegexpValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless value.nil? Regexp.new(value) end rescue RegexpError record.errors.add(attribute, "is invalid regexp expression #{value.inspect}") end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/at_least_one_of_validator.rb
lib/at_least_one_of_validator.rb
# frozen_string_literal: true require "active_model" require "active_support/core_ext/array/conversions" require "active_support/core_ext/object/try" class AtLeastOneOfValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) attributes = options[:in] + [attribute] if attributes.all? { |name| record.try(name).nil? } record.errors.add(attribute, "is required because at least one of #{attributes.to_sentence} are required") end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit.rb
lib/serverkit.rb
# frozen_string_literal: true require_relative "serverkit/command" require_relative "serverkit/version"
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/recipe.rb
lib/serverkit/recipe.rb
# frozen_string_literal: true require "active_support/core_ext/hash/deep_merge" require "serverkit/errors/invalid_recipe_type_error" require "serverkit/errors/invalid_resources_type_error" require "serverkit/resource_builder" module Serverkit class Recipe attr_reader :recipe_data, :variables_path # @param [Hash] recipe_data # @param [String, nil] variables_path Used for recipe resource to render ERB template def initialize(recipe_data, variables_path = nil) @recipe_data = recipe_data @variables_path = variables_path end # @return [Array<Serverkit::Errors::Base>] def errors @errors ||= if !has_valid_typed_recipe_data? errors_for_invalid_typed_recipe_data elsif !has_valid_typed_resources_property? errors_for_invalid_typed_resources_property else errors_in_resources end end # @return [Array<Serverkit::Resource>] def handlers @handlers ||= Array(handlers_property).flat_map do |attributes| ResourceBuilder.new(self, attributes).build.to_a end end # @param [Serverkit::Recipe] recipe # @return [Serverkit::Recipe] def merge(recipe) self.class.new( recipe_data.deep_merge(recipe.recipe_data) do |key, a, b| if a.is_a?(Array) a | b else b end end ) end # @note recipe resource will be expanded into resources defined in its recipe # @return [Array<Serverkit::Resources::Base>] def resources @resources ||= resources_property.flat_map do |attributes| ResourceBuilder.new(self, attributes).build.to_a end end # @return [Hash] Fully-expanded recipe data def to_hash @recipe_data.merge("resources" => resources.map(&:attributes)) end def valid? errors.empty? end private # @return [Array<Serverkit::Errors::Base>] def errors_for_invalid_typed_recipe_data [Errors::InvalidRecipeTypeError.new(@recipe_data.class)] end # @return [Array<Serverkit::Errors::Base>] def errors_for_invalid_typed_resources_property [Errors::InvalidResourcesTypeError.new(resources_property.class)] end # @return [Array<Serverkit::Errors::AttributeValidationError>] def errors_in_resources resources.flat_map(&:all_errors) end # @return [Array<String>, nil] def handlers_property @recipe_data["handlers"] end def has_valid_typed_resources_property? resources_property.is_a?(Array) end def has_valid_typed_recipe_data? @recipe_data.is_a?(Hash) end # @return [Array<String>, nil] def resources_property @recipe_data["resources"] end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/command.rb
lib/serverkit/command.rb
# frozen_string_literal: true require "rainbow" require "serverkit/actions/apply" require "serverkit/actions/check" require "serverkit/actions/inspect" require "serverkit/actions/validate" require "serverkit/errors/missing_action_name_argument_error" require "serverkit/errors/missing_recipe_path_argument_error" require "serverkit/errors/unknown_action_name_error" module Serverkit # This class is responsible for command line interface. # An instance of this class builds an instance of Actions::Base class, # then calls its `#call` method, and it exits with exit status 0 unless any error found. # This class should be used only from bin/serverkit executable. # If you need to use serverkit's any feature from Ruby code, # use a child of Actions::Base class instead because # this class only focuses on command line interface. class Command LOG_LEVELS_TABLE = { "" => Logger::INFO, "0" => Logger::DEBUG, "1" => Logger::INFO, "2" => Logger::WARN, "3" => Logger::ERROR, "4" => Logger::FATAL, "DEBUG" => Logger::DEBUG, "ERROR" => Logger::ERROR, "FATAL" => Logger::FATAL, "INFO" => Logger::INFO, "WARN" => Logger::WARN, }.freeze # @param [Array<String>] argv def initialize(argv) @argv = argv end def call setup case action_name when nil raise Errors::MissingActionNameArgumentError when "apply" apply when "check" check when "inspect" _inspect when "validate" validate else raise Errors::UnknownActionNameError, action_name end rescue Errors::Base, Psych::SyntaxError, Slop::MissingArgumentError, Slop::MissingOptionError => e abort "Error: #{e}" end private # @note #inspect is reserved ;( def _inspect Actions::Inspect.new(**action_options).call end # @return [String, nil] def action_name @argv.first end # @return [Hash<Symbol => String>] def action_options { hosts: hosts, log_level: log_level, recipe_path: recipe_path, variables_path: variables_path, ssh_options: ssh_options, }.compact end def apply Actions::Apply.new(**action_options).call end def check Actions::Check.new(**action_options).call end # @note This options are commonly used from all actions for now, however, # someday a new action that requires options might appear. # @return [Slop] def command_line_options @command_line_options ||= Slop.parse!(@argv, help: true) do banner "Usage: serverkit ACTION [options]" on "--hosts=", "Hostname to execute command over SSH" on "--log-level=", "Log level (DEBUG, INFO, WARN, ERROR, FATAL)" on "--no-color", "Disable coloring" on "--variables=", "Path to variables file for ERB recipe" on "--ssh-user=", "SSH user name" on "--ssh-identity=", "SSH identity (private key) file path" end end # @return [String, nil] def hosts command_line_options["hosts"] end # @return [Fixnum] def log_level LOG_LEVELS_TABLE[command_line_options["log-level"].to_s.upcase] || ::Logger::UNKNOWN end # @return [String] def recipe_path @argv[1] or raise Errors::MissingRecipePathArgumentError end def setup ::Rainbow.enabled = !command_line_options["no-color"] end def validate Actions::Validate.new(**action_options).call end def variables_path command_line_options["variables"] end def ssh_options identity = command_line_options["ssh-identity"] keys = identity ? [identity] : nil { user: command_line_options["ssh-user"], keys: keys, }.compact end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/version.rb
lib/serverkit/version.rb
# frozen_string_literal: true module Serverkit VERSION = "1.0.0" end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/logger.rb
lib/serverkit/logger.rb
# frozen_string_literal: true require "logger" require "rainbow" module Serverkit # A logger class that has a simple formatter by default. class Logger < ::Logger def initialize(*) super self.formatter = Formatter.new end # @param [Serverkit::Resources::Base] def report_apply_result_of(resource) message = ResourceApplyStateView.new(resource).to_s fatal(message) end # @param [Serverkit::Resources::Base] def report_check_result_of(resource) message = ResourceCheckStateView.new(resource).to_s fatal(message) end class Formatter def call(severity, time, program_name, message) message = "#{message.to_s.gsub(/\n\z/, '').gsub(/\e\[(\d+)(;\d+)*m/, '')}\n" message = Rainbow(message).black.bright if severity == "DEBUG" message end end class ResourceStateView def initialize(resource) @resource = resource end def to_s "[#{result_tag}] #{@resource.type} #{@resource.id} on #{backend_host}" end private def backend_host @resource.backend.host end end class ResourceApplyStateView < ResourceStateView private # @return [String] def result_tag case @resource.recheck_result when nil "SKIP" when false "FAIL" else "DONE" end end end class ResourceCheckStateView < ResourceStateView private # @return [String] def result_tag if @resource.check_result " OK " else " NG " end end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resource_builder.rb
lib/serverkit/resource_builder.rb
# frozen_string_literal: true require "active_support/core_ext/string/inflections" require "serverkit/resources/command" require "serverkit/resources/directory" require "serverkit/resources/file" require "serverkit/resources/git" require "serverkit/resources/group" require "serverkit/resources/line" require "serverkit/resources/missing" require "serverkit/resources/nothing" require "serverkit/resources/package" require "serverkit/resources/recipe" require "serverkit/resources/remote_file" require "serverkit/resources/service" require "serverkit/resources/symlink" require "serverkit/resources/template" require "serverkit/resources/unknown" require "serverkit/resources/user" module Serverkit class ResourceBuilder # @param [Serverkit::Recipe] recipe # @param [Hash] attributes def initialize(recipe, attributes) @attributes = attributes @recipe = recipe end # @return [Serverkit::Resources::Base] def build resource_class.new(@recipe, @attributes) end private # @return [Array<Class>] def available_resource_classes Resources.constants.select do |constant_name| constant = Resources.const_get(constant_name) constant < Resources::Base && !constant.abstract_class? end end def has_known_type? available_resource_classes.map(&:to_s).include?(resource_class_name) end # @return [Class] def resource_class if type.nil? Resources::Missing elsif has_known_type? Resources.const_get(resource_class_name, false) else Resources::Unknown end end # @return [String] (e.g. "File", "Symlink") def resource_class_name type.to_s.camelize end # @note Expected to return String in normal case # @return [Object] (e.g. "file", "symlink") def type @attributes["type"] end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/variables.rb
lib/serverkit/variables.rb
# frozen_string_literal: true require "active_support/core_ext/hash/deep_merge" require "hashie/mash" module Serverkit class Variables attr_reader :variables_data # @param [Hash] variables_data def initialize(variables_data) @variables_data = variables_data end # @param [Serverkit::Variables] variables # @return [Serverkit::Variables] def merge(variables) self.class.new(variables_data.deep_merge(variables.variables_data)) end # @return [Hashie::Mash] def to_mash BindableMash.new(@variables_data.dup) end class BindableMash < Hashie::Mash DEFAULT_PROC = ->(hash, key) do raise KeyError, "key not found: #{key.inspect} (perhaps variables are wrong?)" end # @note Override to raise KeyError on missing key def initialize(*, &block) super self.default_proc = DEFAULT_PROC end # @note Override visibility from private to public def binding # rubocop:disable Lint/UselessMethodDefinition super end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/unknown_resource_type_error.rb
lib/serverkit/errors/unknown_resource_type_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class UnknownResourceTypeError < Base # @param [String] type def initialize(type) @type = type end # @return [String] def to_s "Unknown `#{@type}` resource type" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/missing_resource_type_error.rb
lib/serverkit/errors/missing_resource_type_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class MissingResourceTypeError < Base # @return [String] def to_s "Missing resource type" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/invalid_resources_type_error.rb
lib/serverkit/errors/invalid_resources_type_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class InvalidResourcesTypeError < Base # @param [Class] type def initialize(type) @type = type end def to_s "resources property must be an Array, not #{@type}" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/missing_action_name_argument_error.rb
lib/serverkit/errors/missing_action_name_argument_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class MissingActionNameArgumentError < Base # @return [String] def to_s "Missing action name argument" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/base.rb
lib/serverkit/errors/base.rb
# frozen_string_literal: true module Serverkit module Errors class Base < StandardError end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/unknown_action_name_error.rb
lib/serverkit/errors/unknown_action_name_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class UnknownActionNameError < Base # @param [String] action_name def initialize(action_name) @action_name = action_name end # @return [String] def to_s abort "Unknown action name `#{@action_name}`" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/non_existent_path_error.rb
lib/serverkit/errors/non_existent_path_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class NonExistentPathError < Base # @param [#to_s] path def initialize(path) @path = path end # @return [String] def to_s abort "No such file or directory `#{@path}`" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/invalid_recipe_type_error.rb
lib/serverkit/errors/invalid_recipe_type_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class InvalidRecipeTypeError < Base # @param [Class] type def initialize(type) @type = type end def to_s "Recipe data must be a Hash, not #{@type}" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/missing_recipe_path_argument_error.rb
lib/serverkit/errors/missing_recipe_path_argument_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class MissingRecipePathArgumentError < Base # @return [String] def to_s "Missing recipe path argument" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/errors/attribute_validation_error.rb
lib/serverkit/errors/attribute_validation_error.rb
# frozen_string_literal: true require "serverkit/errors/base" module Serverkit module Errors class AttributeValidationError < Base # @param [Serverkit::Resources::Base] resource # @param [String] validation_error_message def initialize(resource, attribute_name, validation_error_message) @attribute_name = attribute_name @resource = resource @validation_error_message = validation_error_message end # @return [String] def to_s "#{@attribute_name} attribute #{@validation_error_message} in #{@resource.type} resource" end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/actions/inspect.rb
lib/serverkit/actions/inspect.rb
# frozen_string_literal: true require "serverkit/actions/base" module Serverkit module Actions class Inspect < Base def run puts JSON.pretty_generate(recipe.to_hash) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/actions/base.rb
lib/serverkit/actions/base.rb
# frozen_string_literal: true require "bundler" require "logger" require "serverkit/backends/local_backend" require "serverkit/backends/ssh_backend" require "serverkit/loaders/recipe_loader" require "serverkit/recipe" require "slop" require "specinfra" module Serverkit module Actions class Base DEFAULT_LOG_LEVEL = ::Logger::INFO # @param [String, nil] hosts # @param [Fixnum] log_level # @param [String] recipe_path # @param [Hash, nil] ssh_options For override default ssh options # @param [Stirng, nil] variables_path def initialize(hosts: nil, log_level: nil, recipe_path: nil, ssh_options: nil, variables_path: nil) @hosts = hosts @log_level = log_level @recipe_path = recipe_path @ssh_options = ssh_options @variables_path = variables_path end def call setup run end private def abort_with_errors abort recipe.errors.map { |error| "Error: #{error}" }.join("\n") end # @return [Array<Serverkit::Backends::Base>] def backends if has_hosts? hosts.map do |host| Backends::SshBackend.new( host: host, log_level: @log_level, ssh_options: @ssh_options, ) end else [Backends::LocalBackend.new(log_level: @log_level)] end end def bundle Bundler.require(:default) rescue Bundler::GemfileNotFound end def has_hosts? !@hosts.nil? end # @return [Array<String>, nil] def hosts if has_hosts? @hosts.split(",") end end def setup bundle abort_with_errors unless recipe.valid? end # @return [Serverkit::Recipe] def recipe @recipe ||= Loaders::RecipeLoader.new(@recipe_path, variables_path: @variables_path).load end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/actions/validate.rb
lib/serverkit/actions/validate.rb
# frozen_string_literal: true require "serverkit/actions/base" module Serverkit module Actions class Validate < Base def run end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/actions/apply.rb
lib/serverkit/actions/apply.rb
# frozen_string_literal: true require "serverkit/actions/base" module Serverkit module Actions class Apply < Base # Apply recipe so that all backends have ideal states, then exit with 0 or 1 def run if apply_resources exit else exit(1) end end private # @return [true, false] True if all backends have ideal states def apply_resources backends.map do |backend| Thread.new do resources = recipe.resources.map(&:clone).map do |resource| resource.backend = backend resource.run_apply backend.logger.report_apply_result_of(resource) resource end handlers = resources.select(&:notifiable?).flat_map(&:handlers).uniq.map(&:clone).each do |handler| handler.backend = backend handler.run_apply backend.logger.report_apply_result_of(handler) end resources + handlers end end.map(&:value).flatten.all?(&:successful?) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/actions/check.rb
lib/serverkit/actions/check.rb
# frozen_string_literal: true require "serverkit/actions/base" module Serverkit module Actions class Check < Base # Check if all backends have ideal states, then exit with exit-code 0 or 1 def run if check_resources exit else exit(1) end end private # @return [true, false] True if all backends have ideal states def check_resources backends.map do |backend| Thread.new do recipe.resources.map(&:clone).map do |resource| resource.backend = backend resource.run_check backend.logger.report_check_result_of(resource) resource end end end.map(&:value).flatten.all?(&:successful?) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/backends/ssh_backend.rb
lib/serverkit/backends/ssh_backend.rb
# frozen_string_literal: true require "etc" require "net/ssh" require "serverkit/backends/base_backend" require "specinfra" module Serverkit module Backends class SshBackend < BaseBackend DEFAULT_SSH_OPTIONS = {}.freeze attr_reader :host # @param [String] host # @param [Hash] ssh_options def initialize(host: nil, ssh_options: nil, **args) super(**args) @host = host @ssh_options = ssh_options end private # @return [Specinfra::Backend::Ssh] def specinfra_backend @specinfra_backend ||= ::Specinfra::Backend::Ssh.new( host: host, ssh_options: ssh_options, request_pty: true, ) end # @return [Hash] def ssh_options { user: user }.merge(@ssh_options || DEFAULT_SSH_OPTIONS) end # @return [String] def user ::Net::SSH::Config.for(@host)[:user] || ::Etc.getlogin end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/backends/local_backend.rb
lib/serverkit/backends/local_backend.rb
# frozen_string_literal: true require "serverkit/backends/base_backend" require "specinfra" module Serverkit module Backends class LocalBackend < BaseBackend HOST = "localhost" # @note Override def host HOST end private # @return [Specinfra::Backend::Exec] def specinfra_backend @specinfra_backend ||= Specinfra::Backend::Exec.new end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/backends/base_backend.rb
lib/serverkit/backends/base_backend.rb
# frozen_string_literal: true require "active_support/core_ext/module/delegation" require "serverkit/logger" module Serverkit module Backends class BaseBackend delegate( :command, :send_file, to: :specinfra_backend, ) def initialize(log_level: nil) @log_level = log_level end # @note Override me # @return [String] # @example "localhost" def host raise NotImplementedError end # @return [Serverkit::Logger] def logger @logger ||= Serverkit::Logger.new($stdout).tap do |_logger| _logger.level = @log_level end end # @param [String] command one-line shell script to be executed on remote machine # @return [Specinfra::CommandResult] def run_command(command) logger.debug("Running #{command} on #{host}") specinfra_backend.run_command(command).tap do |result| logger.debug(result.stdout) unless result.stdout.empty? logger.debug(result.stderr) unless result.stderr.empty? logger.debug("Finished with #{result.exit_status} on #{host}") end end def send_file(from, to) logger.debug("Sending file #{from} to #{to}") specinfra_backend.send_file(from, to) end private # @note Override me # @return [Specinfra::Backend::Base] def specinfra_backend raise NotImplementedError end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/loaders/recipe_loader.rb
lib/serverkit/loaders/recipe_loader.rb
# frozen_string_literal: true require "serverkit/loaders/base_loader" require "serverkit/loaders/variables_loader" require "serverkit/recipe" module Serverkit module Loaders class RecipeLoader < BaseLoader DEFAULT_VARIABLES_DATA = {}.freeze # @param [String] path # @param [String, nil] variables_path def initialize(path, variables_path: nil) super(path) @variables_path = variables_path end private # @note Override # @return [Binding] def binding_for_erb variables.to_mash.binding end # @note Override to pass @variables_path def create_empty_loadable loaded_class.new({}, @variables_path) end def has_variables_path? !@variables_path.nil? end # @note Override to pass @variables_path def load_from_data loaded_class.new(load_data, @variables_path) end # @return [Serverkit::Variables] def load_variables Loaders::VariablesLoader.new(@variables_path).load end # @note Implementation def loaded_class Serverkit::Recipe end # @return [Serverkit::Variables] def variables @variables ||= if has_variables_path? load_variables else Variables.new(DEFAULT_VARIABLES_DATA.dup) end end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/loaders/base_loader.rb
lib/serverkit/loaders/base_loader.rb
# frozen_string_literal: true require "erb" require "json" require "pathname" require "serverkit/errors/non_existent_path_error" require "tempfile" require "yaml" module Serverkit module Loaders class BaseLoader YAML_EXTNAMES = [".yaml", ".yml"].freeze # @param [String] path def initialize(path) @path = path end def load if !pathname.exist? raise Errors::NonExistentPathError, pathname elsif has_directory_path? load_from_directory elsif has_erb_path? load_from_erb else load_from_data end end private # @return [Binding] def binding_for_erb TOPLEVEL_BINDING end # @note For override def create_empty_loadable loaded_class.new({}) end # @return [ERB] def erb _erb = ERB.new(pathname.read, trim_mode: "-") _erb.filename = pathname.to_s _erb end # @return [String] def execute `#{pathname}` end # @return [String] def expand_erb erb.result(binding_for_erb) end # @return [String] def expanded_erb_path_suffix ".#{pathname.basename('.erb').to_s.split('.', 2).last}" end # @note Memoizing to prevent GC # @return [Tempfile] def expanded_erb_tempfile @expanded_erb_tempfile ||= Tempfile.new(["", expanded_erb_path_suffix]).tap do |tempfile| tempfile << expand_erb tempfile.close end end def has_directory_path? pathname.directory? end def has_erb_path? pathname.extname == ".erb" end def has_executable_path? pathname.executable? end def has_yaml_path? YAML_EXTNAMES.include?(pathname.extname) end # @return [Hash] def load_data if has_executable_path? load_data_from_executable elsif has_yaml_path? load_data_from_yaml else load_data_from_json end end def load_from_data loaded_class.new(load_data) end def load_from_directory loads_from_directory.inject(create_empty_loadable, :merge) end def load_from_erb self.class.new(expanded_erb_tempfile.path).load end # @return [Array] def loads_from_directory Dir.glob(pathname.join("*")).sort.flat_map do |path| self.class.new(path).load end end # @return [Hash] def load_data_from_executable JSON.parse(execute) end # @return [Hash] def load_data_from_json JSON.parse(pathname.read) end # @return [Hash] def load_data_from_yaml YAML.load_file(pathname) end # @return [Pathname] def pathname @pathname ||= Pathname.new(@path) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/loaders/variables_loader.rb
lib/serverkit/loaders/variables_loader.rb
# frozen_string_literal: true require "serverkit/loaders/base_loader" require "serverkit/variables" module Serverkit module Loaders class VariablesLoader < BaseLoader private # @note Implementation def loaded_class Serverkit::Variables end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/recipe.rb
lib/serverkit/resources/recipe.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Recipe < Base attribute :path, readable: true, required: true, type: String # @note Override def to_a if valid? loaded_recipe.resources else self end end private # @return [Serverkit::Recipe] Recipe loaded from given path def loaded_recipe @loaded_recipe ||= Loaders::RecipeLoader.new(path, variables_path: recipe.variables_path).load end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/command.rb
lib/serverkit/resources/command.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Command < Base attribute :script, required: true, type: String # @note Override def apply run_command(script) end # @note Override def check false end private # @note Override def recheck if check_script check_command(check_script) else true end end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/entry.rb
lib/serverkit/resources/entry.rb
# frozen_string_literal: true require "digest" require "serverkit/resources/base" require "tempfile" module Serverkit module Resources # Abstract class for file and directory class Entry < Base attribute :group, type: String attribute :mode, type: [Integer, String] attribute :owner, type: String self.abstract_class = true # @note Override def apply update_entry unless has_correct_entry? update_group unless has_correct_group? update_mode unless has_correct_mode? update_owner unless has_correct_owner? end # @note Override def check has_correct_entry? && has_correct_group? && has_correct_mode? && has_correct_owner? end private # @note Override me # @return [String] Path to the entry on remote side def destination raise NotImplementedError end def has_correct_content? content.nil? || remote_file_sha256sum == local_content_sha256sum end # @note Override me def has_correct_entry? raise NotImplementedError end def has_correct_group? group.nil? || check_command_from_identifier(:check_file_is_grouped, destination, group) end def has_correct_mode? mode.nil? || check_command_from_identifier(:check_file_has_mode, destination, mode_in_octal_notation) end def has_correct_owner? owner.nil? || check_command_from_identifier(:check_file_is_owned_by, destination, owner) end def has_remote_file? check_command_from_identifier(:check_file_is_file, destination) end # @return [String] def local_content_sha256sum ::Digest::SHA256.hexdigest(content) end # @return [String] # @example "755" # for 0755 def mode_in_octal_notation if mode.is_a?(Integer) mode.to_s(8) else mode end end # @return [String] def remote_file_sha256sum run_command_from_identifier(:get_file_sha256sum, destination).stdout.rstrip end def send_content_to_destination ::Tempfile.open("") do |file| file.write(content || "") file.close backend.send_file(file.path, destination) end end # @note Override me def update_entry raise NotImplementedError end def update_group run_command_from_identifier(:change_file_group, destination, group) end def update_mode run_command_from_identifier(:change_file_mode, destination, mode_in_octal_notation) end def update_owner run_command_from_identifier(:change_file_owner, destination, owner) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/directory.rb
lib/serverkit/resources/directory.rb
# frozen_string_literal: true require "serverkit/resources/entry" module Serverkit module Resources class Directory < Entry attribute :path, required: true, type: String private # @note Override def destination path end # @note Override def has_correct_entry? check_command_from_identifier(:check_file_is_directory, destination) end # @note Override def update_entry run_command_from_identifier(:create_file_as_directory, destination) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/group.rb
lib/serverkit/resources/group.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Group < Base attribute :gid, type: Integer attribute :name, required: true, type: String # @note Override def apply if has_correct_group? run_command_from_identifier(:update_group_gid, name, gid) else run_command_from_identifier(:add_group, name, gid: gid) end end # @note Override def check has_correct_group? && has_correct_gid? end private def has_correct_gid? gid.nil? || gid == remote_gid end def has_correct_group? check_command_from_identifier(:check_group_exists, name) end # @return [Integer] def remote_gid run_command_from_identifier(:get_group_gid, name).stdout.strip.to_i end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/symlink.rb
lib/serverkit/resources/symlink.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Symlink < Base attribute :destination, required: true, type: String attribute :source, required: true, type: String # @note Override def apply run_command_from_identifier(:link_file_to, source, destination, force: true) end # @note Override def check check_command_from_identifier(:check_file_is_linked_to, source, destination) end private # @note Override def default_id source end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/unknown.rb
lib/serverkit/resources/unknown.rb
# frozen_string_literal: true require "serverkit/errors/unknown_resource_type_error" require "serverkit/resources/base" module Serverkit module Resources class Unknown < Base # @return [Array<Serverkit::Errors::UnknownResourceTypeError>] def all_errors [Errors::UnknownResourceTypeError.new(type)] end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/package.rb
lib/serverkit/resources/package.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Package < Base attribute :name, required: true, type: String attribute :options, type: String attribute :version, type: String # @note Override def apply run_command_from_identifier(:install_package, name, version, options) end # @note Override def check check_command_from_identifier(:check_package_is_installed, name, version) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/line.rb
lib/serverkit/resources/line.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources # Ensure a particular line is in a file, or replace an existing line using regexp. # @example Example line resource that ensures a line is in /etc/sudoers # - type: line # path: /etc/sudoers # line: "#includedir /etc/sudoers.d" class Line < Base DEFAULT_STATE = "present" attribute :path, required: true, type: String attribute :insert_after, type: String attribute :insert_before, type: String attribute :line, required: true, type: String attribute :pattern, regexp: true, type: String attribute :state, default: DEFAULT_STATE, inclusion: %w[absent present], type: String attribute :validation_script, type: String # @note Override def apply if has_correct_file? if validation_script update_remote_file_content_with_validation else update_remote_file_content_without_validation end end end # @note Override def check has_correct_file? && has_correct_line? end private def absent? state == "absent" end # @return [String] def applied_remote_file_content if absent? content.delete(line) elsif insert_after content.insert_after(Regexp.new(insert_after), line) elsif insert_before content.insert_before(Regexp.new(insert_before), line) else content.append(line) end.to_s end # @return [Serverkit::Resources::Line::Content] def content Content.new(get_remote_file_content) end # @return [String] def get_remote_file_content run_command_from_identifier(:get_file_content, path).stdout end def has_correct_file? check_command_from_identifier(:check_file_is_file, path) end def has_correct_line? if present? && !has_matched_line? false elsif !present? && has_matched_line? false else true end end def has_matched_line? if pattern content.match(Regexp.new(pattern)) else content.match(line) end end def present? state == "present" end # Create a new temp file on remote side, then validate it with given script, # and move it to right file path if it succeeded. Note that `%{path}` in validation # script will be replaced with the path to temp file. def update_remote_file_content_with_validation temp_path = create_remote_temp_file(applied_remote_file_content) if check_command(format(validation_script, path: temp_path)) move_remote_file_keeping_destination_metadata(temp_path, path) end run_command_from_identifier(:remove_file, temp_path) end # Create or update remote file def update_remote_file_content_without_validation update_remote_file_content(content: applied_remote_file_content, path: path) end # Wrapper class to easily manage lines in remote file content. class Content # @param [String] raw def initialize(raw) @raw = raw end # @param [String] line # @return [Serverkit::Resources::Line::Content] def append(line) self.class.new([*lines, line, ""].join("\n")) end # @param [String] line # @return [Serverkit::Resources::Line::Content] def delete(line) self.class.new(@raw.gsub(/^#{Regexp.escape(line)}[\n$]/, "")) end # Insert the line after the last matched line or EOF # @param [Regexp] regexp # @param [String] line # @return [Serverkit::Resources::Line::Content] def insert_after(regexp, line) if index = lines.rindex { |line| line =~ regexp } insert(index + 1, line) else append(line) end end # Insert the line before the last matched line or BOF # @param [Regexp] regexp # @param [String] line # @return [Serverkit::Resources::Line::Content] def insert_before(regexp, line) if index = lines.rindex { |line| line =~ regexp } insert(index, line) else prepend(line) end end # @param [Regexp, String] pattern # @return [false, true] True if any line matches given pattern def match(pattern) lines.lazy.grep(pattern).any? end # @note Override def to_s @raw.dup end private # @param [Integer] index # @param [String] line # @return [Serverkit::Resources::Line::Content] def insert(index, line) self.class.new([*lines.dup.insert(index, line), ""].join("\n")) end # @return [Array<String>] def lines @lines ||= @raw.each_line.map do |line| line.gsub(/\n$/, "") end end # @param [String] line # @return [Serverkit::Resources::Line::Content] def prepend(line) self.class.new("#{line}\n#{@raw}") end end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/file.rb
lib/serverkit/resources/file.rb
# frozen_string_literal: true require "serverkit/resources/entry" module Serverkit module Resources class File < Entry attribute :content, type: String attribute :path, required: true, type: String private # @note Override def destination path end # @note Override def has_correct_entry? has_remote_file? && has_correct_content? end # @note Override def update_entry send_content_to_destination end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/missing.rb
lib/serverkit/resources/missing.rb
# frozen_string_literal: true require "serverkit/errors/missing_resource_type_error" require "serverkit/resources/base" module Serverkit module Resources class Missing < Base # @return [Array<Serverkit::Errors::MissingResourceTypeError>] def all_errors [Errors::MissingResourceTypeError.new] end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/base.rb
lib/serverkit/resources/base.rb
# frozen_string_literal: true require "active_model" require "active_model/errors" require "active_support/core_ext/module/delegation" require "at_least_one_of_validator" require "readable_validator" require "regexp_validator" require "required_validator" require "serverkit/errors/attribute_validation_error" require "type_validator" module Serverkit module Resources class Base class << self attr_writer :abstract_class def abstract_class? !!@abstract_class end # @note DSL method to define attribute with its validations def attribute(name, options = {}) default = options.delete(:default) define_method(name) do @attributes.fetch(name.to_s, default) end validates name, options unless options.empty? end end include ActiveModel::Validations attr_accessor :backend attr_reader :attributes, :check_result, :recheck_result, :recipe attribute :check_script, type: String attribute :cwd, type: String attribute :id, type: String attribute :notify, type: Array attribute :recheck_script, type: String attribute :type, type: String attribute :user, type: String delegate( :send_file, to: :backend, ) self.abstract_class = true # @param [Serverkit::Recipe] recipe # @param [Hash] attributes def initialize(recipe, attributes) @attributes = attributes @recipe = recipe end # @note For override # @return [Array<Serverkit::Errors::Base>] def all_errors attribute_validation_errors end # @return [true, false] def check_command(*args) run_command(*args).success? end # @return [true, false] def check_command_from_identifier(*args) run_command_from_identifier(*args).success? end # @return [String] def get_command_from_identifier(*args) backend.command.get(*args) end # @return [Array<Serverkit::Resource>] def handlers @handlers ||= Array(notify).map do |id| recipe.handlers.find do |handler| handler.id == id end end.compact end # @note For logging and notifying # @return [String] def id @attributes["id"] || default_id end # @return [true, false] True if this resource should call any handler def notifiable? @recheck_result == true && !handlers.nil? end # @note #check and #apply wrapper def run_apply unless run_check apply @recheck_result = !!recheck_with_script end end # @note #check wrapper # @return [true, false] def run_check @check_result = !!check_with_script end def successful? successful_on_check? || successful_on_recheck? end def successful_on_check? @check_result == true end def successful_on_recheck? @recheck_result == true end # @note recipe resource will override to replace itself with multiple resources # @return [Array<Serverkit::Resources::Base>] def to_a [self] end private # @return [Array<Serverkit::Errors::AttributeValidationError>] def attribute_validation_errors valid? errors.map do |attribute_name, message| Serverkit::Errors::AttributeValidationError.new(self, attribute_name, message) end end # @note Prior check_script attribute to resource's #check implementation def check_with_script if check_script check_command(check_script) else check end end # Create a file on remote side # @param [String] content # @param [String] path def create_remote_file(content: nil, path: nil) ::Tempfile.open("") do |file| file.write(content) file.close backend.send_file(file.path, path) end end # Create temp file on remote side with given content # @param [String] content # @return [String] Path to remote temp file def create_remote_temp_file(content) make_remote_temp_path.tap do |path| update_remote_file_content(content: content, path: path) end end # @note For override # @return [String] def default_id required_values.join(" ") end # @note GNU mktemp doesn't require -t option, but BSD mktemp does # @return [String] def make_remote_temp_path run_command("mktemp -u 2>/dev/null || mktemp -u -t tmp").stdout.rstrip end # @note "metadata" means a set of group, mode, and owner # @param [String] destination # @param [String] source def move_remote_file_keeping_destination_metadata(source, destination) group = run_command_from_identifier(:get_file_owner_group, destination).stdout.rstrip mode = run_command_from_identifier(:get_file_mode, destination).stdout.rstrip owner = run_command_from_identifier(:get_file_owner_user, destination).stdout.rstrip run_command_from_identifier(:change_file_group, source, group) unless group.empty? run_command_from_identifier(:change_file_mode, source, mode) unless mode.empty? run_command_from_identifier(:change_file_owner, source, owner) unless owner.empty? run_command_from_identifier(:move_file, source, destination) end # @note For override # @return [true, false] def recheck check end # @note Prior recheck_script attribute to resource's #recheck implementation def recheck_with_script if recheck_script check_command(recheck_script) else recheck end end # @return [Array<Symbol>] def required_attribute_names _validators.select do |key, validators| validators.grep(::RequiredValidator).any? end.keys end # @return [Array] def required_values required_attribute_names.map do |required_attribute_name| send(required_attribute_name) end end # @note Wraps backend.run_command for `cwd` and `user` attributes # @param [String] command one-line shell script to be executed on remote machine # @return [Specinfra::CommandResult] def run_command(command) if cwd command = "cd #{Shellwords.escape(cwd)} && #{command}" elsif user command = "cd && #{command}" end unless user.nil? command = "sudo -H -u #{user} -i -- /bin/bash -i -c #{Shellwords.escape(command)}" end backend.run_command(command) end # @return [Specinfra::CommandResult] def run_command_from_identifier(*args) run_command(get_command_from_identifier(*args)) end # Update remote file content on given path with given content # @param [String] content # @param [String] path def update_remote_file_content(content: nil, path: nil) group = run_command_from_identifier(:get_file_owner_group, path).stdout.rstrip mode = run_command_from_identifier(:get_file_mode, path).stdout.rstrip owner = run_command_from_identifier(:get_file_owner_user, path).stdout.rstrip create_remote_file(content: content, path: path) run_command_from_identifier(:change_file_group, path, group) unless group.empty? run_command_from_identifier(:change_file_mode, path, mode) unless mode.empty? run_command_from_identifier(:change_file_owner, path, owner) unless owner.empty? end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/template.rb
lib/serverkit/resources/template.rb
# frozen_string_literal: true require "erb" require "serverkit/loaders/variables_loader" require "serverkit/resources/remote_file" module Serverkit module Resources class Template < RemoteFile DEFAULT_VARIABLES_DATA = {}.freeze private # @note Override def content @content ||= erb.result(variables.to_mash.binding) end # @return [ERB] def erb _erb = ::ERB.new(template_content, trim_mode: "-") _erb.filename = source _erb end # @return [String] ERB content def template_content @template_content ||= ::File.read(source) end # @note Override def update_entry send_content_to_destination end # @return [Serverkit::Variables] def variables @variables ||= if recipe.variables_path Loaders::VariablesLoader.new(recipe.variables_path).load else Variables.new(DEFAULT_VARIABLES_DATA.dup) end end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/nothing.rb
lib/serverkit/resources/nothing.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources # A class to do nothing for debugging. class Nothing < Base # @note Override def apply end # @note Override for #apply to be always called def check false end private # @note Override to always pass rechecking def recheck true end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/service.rb
lib/serverkit/resources/service.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Service < Base attribute :name, required: true, type: String # @note Override def apply run_command_from_identifier(:start_service, name) end # @note Override def check check_command_from_identifier(:check_service_is_running, name) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/remote_file.rb
lib/serverkit/resources/remote_file.rb
# frozen_string_literal: true require "serverkit/resources/entry" module Serverkit module Resources class RemoteFile < Entry attribute :destination, required: true, type: String attribute :source, readable: true, required: true, type: String private def content @content ||= ::File.read(source) end # @note Override def has_correct_entry? has_remote_file? && has_correct_content? end # @note Override def update_entry send_file(source, destination) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/git.rb
lib/serverkit/resources/git.rb
# frozen_string_literal: true require "serverkit/resources/base" module Serverkit module Resources class Git < Base DEFAULT_STATE = "cloned" attribute :path, required: true, type: String attribute :repository, required: true, type: String attribute :state, default: DEFAULT_STATE, inclusion: %w[cloned updated], type: String attribute :branch, type: String # @note Override def apply _clone if clonable? checkout if checkoutable? update if updatable? end # @note Override def check has_git? && cloned? && !checkoutable? && !updatable? end private def clonable? !cloned? end # @note #clone is reserved ;( def _clone run_command("git clone #{repository} #{path}") end def cloned? check_command_from_identifier(:check_file_is_directory, git_path) end def checkoutable? branch && !checkouted? end def checkout run_command("git -C #{path} checkout #{branch}") end def checkouted? check_command("cd #{path} && test `git rev-parse HEAD` = `git rev-parse #{branch}`") end # @return [String] Path to .git directory in the cloned repository def git_path ::File.join(path, ".git") end def has_git? check_command("which git") end # @return [String] def local_head_revision run_command("cd #{path} && git rev-parse HEAD").stdout.rstrip end # @return [String] def origin_head_revision run_command("cd #{path} && git ls-remote origin HEAD").stdout.split.first end def updatable? state == "updated" && !updated? end def update run_command("cd #{path} && git fetch origin && git reset --hard FETCH_HEAD") end def updated? local_head_revision == origin_head_revision end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
serverkit/serverkit
https://github.com/serverkit/serverkit/blob/48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf/lib/serverkit/resources/user.rb
lib/serverkit/resources/user.rb
# frozen_string_literal: true require "serverkit/resources/base" require "unix_crypt" module Serverkit module Resources class User < Base attribute :gid, type: [Integer, String] attribute :home, type: String attribute :name, type: String, required: true attribute :password, type: String attribute :shell, type: String attribute :system, type: [FalseClass, TrueClass] attribute :uid, type: Integer # @note Override def apply if has_correct_user? update_user_encrypted_password unless has_correct_password? update_user_gid unless has_correct_gid? update_user_home_directory unless has_correct_home_directory? update_user_login_shell unless has_correct_login_shell? update_user_uid unless has_correct_uid? else add_user end end # @note Override def check if !has_correct_user? false elsif !has_correct_gid? false elsif !has_correct_home_directory? false elsif !has_correct_password? false elsif !has_correct_login_shell? false elsif !has_correct_uid? false else true end end private def add_user run_command_from_identifier( :add_user, name, gid: gid, home_directory: home, password: encrypted_password, shell: shell, system_user: system, uid: uid, ) end # @return [String, nil] def encrypted_password unless password.nil? @encrypted_password ||= UnixCrypt::SHA512.build(password) end end def get_remote_encrypted_password run_command_from_identifier(:get_user_encrypted_password, name).stdout end def has_correct_gid? gid.nil? || check_command_from_identifier(:check_user_belongs_to_group, name, gid) end def has_correct_home_directory? home.nil? || check_command_from_identifier(:check_user_has_home_directory, name, home) end def has_correct_login_shell? shell.nil? || check_command_from_identifier(:check_user_has_login_shell, name, shell) end def has_correct_password? password.nil? || ::UnixCrypt.valid?(password, get_remote_encrypted_password) end def has_correct_uid? uid.nil? || check_command_from_identifier(:check_user_has_uid, name, uid) end def has_correct_user? check_command_from_identifier(:check_user_exists, name) end def update_user_encrypted_password run_command_from_identifier(:update_user_encrypted_password, name, encrypted_password) end def update_user_gid run_command_from_identifier(:update_user_gid, name, gid) end def update_user_home_directory run_command_from_identifier(:update_user_home_directory, name, home) end def update_user_login_shell run_command_from_identifier(:update_user_login_shell, name, shell) end def update_user_uid run_command_from_identifier(:update_user_uid, name, uid) end end end end
ruby
MIT
48e2bf1de089c6e3ab14e2ea0dd24da5461f9faf
2026-01-04T17:52:19.132705Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/password.rb
test/password.rb
require_relative "helper" scope do test "encrypt" do encrypted = Shield::Password.encrypt("password") assert Shield::Password.check("password", encrypted) end test "with custom 64 character salt" do encrypted = Shield::Password.encrypt("password", "A" * 64) assert Shield::Password.check("password", encrypted) end test "DOS fix" do too_long = '*' * (Shield::Password::MAX_LEN + 1) assert_raise Shield::Password::Error do Shield::Password.encrypt(too_long) end end end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/nested.rb
test/nested.rb
require_relative "helper" require_relative "user" require "cuba" Cuba.use Rack::Session::Cookie, secret: "R6zSBQWz0VGVSwvT8THurhJwaVqzpnsH27J5FoI58pxoIciDQYvE4opVvDTLMyfjj7c5inIc6PDNaQWvArMvK3" Cuba.plugin Shield::Helpers class Admin < Cuba use Shield::Middleware, "/admin/login" define do on "login" do res.write "Login" end on default do res.status = 401 end end end Cuba.define do on "admin" do run Admin end end scope do def app Cuba end setup do clear_cookies end test "return + return flow" do get "/admin" assert_equal "/admin/login?return=%2Fadmin", redirection_url end end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/model_integration.rb
test/model_integration.rb
require_relative "helper" class User include Shield::Model attr_accessor :email, :crypted_password def self.fetch(email) $users[email] end def initialize(email, password) @email = email self.password = password end end setup do $users = {} $users["foo@bar.com"] = User.new("foo@bar.com", "pass1234") end test "fetch" do |user| assert_equal user, User.fetch("foo@bar.com") end test "authenticate" do |user| assert_equal user, User.authenticate("foo@bar.com", "pass1234") end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/shield.rb
test/shield.rb
require_relative "helper" class User < Struct.new(:id) extend Shield::Model def self.[](id) User.new(1) unless id.to_s.empty? end def self.authenticate(username, password) User.new(1001) if username == "quentin" && password == "password" end end class Context def initialize(path) @path = path end def env { "SCRIPT_NAME" => "", "PATH_INFO" => @path } end def session @session ||= {} end class Request < Struct.new(:fullpath) end def req Request.new(@path) end def redirect(redirect = nil) @redirect = redirect if redirect @redirect end include Shield::Helpers end setup do Context.new("/events/1") end class Admin < Struct.new(:id) def self.[](id) new(id) unless id.to_s.empty? end end test "authenticated" do |context| context.session["User"] = 1 assert User.new(1) == context.authenticated(User) assert nil == context.authenticated(Admin) end test "caches authenticated in @_shield" do |context| context.session["User"] = 1 context.authenticated(User) assert User.new(1) == context.instance_variable_get(:@_shield)[User] end test "login success" do |context| assert context.login(User, "quentin", "password") assert 1001 == context.session["User"] end test "login failure" do |context| assert ! context.login(User, "wrong", "creds") assert nil == context.session["User"] end test "logout" do |context| context.session["User"] = 1001 # Now let's make it memoize the User context.authenticated(User) context.logout(User) assert nil == context.session["User"] assert nil == context.authenticated(User) end test "authenticate" do |context| context.session["no_fixation"] = 1 context.authenticate(User[1001]) assert User[1] == context.authenticated(User) assert nil == context.session["no_fixation"] end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/middleware.rb
test/middleware.rb
require_relative "helper" require_relative "user" require "cuba" Cuba.use Rack::Session::Cookie, secret: "R6zSBQWz0VGVSwvT8THurhJwaVqzpnsH27J5FoI58pxoIciDQYvE4opVvDTLMyfjj7c5inIc6PDNaQWvArMvK3" Cuba.use Shield::Middleware Cuba.plugin Shield::Helpers Cuba.define do on "secured" do if not authenticated(User) halt [401, { "Content-Type" => "text/html" }, []] end res.write "You're in" end on "foo" do puts env.inspect end end test do env = { "PATH_INFO" => "/secured", "SCRIPT_NAME" => "" } status, headers, body = Cuba.call(env) assert_equal 302, status assert_equal "/login?return=%2Fsecured", headers["Location"] end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/cuba.rb
test/cuba.rb
require_relative "helper" require_relative "user" require "cuba" Cuba.use Rack::Session::Cookie, secret: "R6zSBQWz0VGVSwvT8THurhJwaVqzpnsH27J5FoI58pxoIciDQYvE4opVvDTLMyfjj7c5inIc6PDNaQWvArMvK3" Cuba.use Shield::Middleware Cuba.plugin Shield::Helpers Cuba.define do on get, "public" do res.write "Public" end on get, "private" do if authenticated(User) res.write "Private" else res.status = 401 end end on get, "login" do res.write "Login" end on post, "login", param("login"), param("password") do |u, p| if login(User, u, p) remember if req.params["remember_me"] res.redirect(req.params["return"] || "/") else res.redirect "/login" end end on "logout" do logout(User) res.redirect "/" end end scope do def app Cuba end setup do clear_cookies end test "public" do get "/public" assert "Public" == last_response.body end test "successful logging in" do get "/private" assert_equal "/login?return=%2Fprivate", redirection_url post "/login", login: "quentin", password: "password", return: "/private" assert_redirected_to "/private" assert 1001 == session["User"] end test "failed login" do post "/login", :login => "q", :password => "p" assert_redirected_to "/login" assert nil == session["User"] end test "logging out" do post "/login", :login => "quentin", :password => "password" get "/logout" assert nil == session["User"] end test "remember functionality" do post "/login", :login => "quentin", :password => "password", :remember_me => "1" assert_equal session["remember_for"], 86400 * 14 get "/logout" assert_equal nil, session["remember_for"] end end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/helper.rb
test/helper.rb
require "cutest" require "rack/test" require_relative "../lib/shield" class Cutest::Scope include Rack::Test::Methods def assert_redirected_to(path) unless last_response.status == 302 flunk end assert_equal path, URI(redirection_url).path end def redirection_url last_response.headers["Location"] end def session last_request.env["rack.session"] end end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/model.rb
test/model.rb
require_relative "helper" class User < Struct.new(:crypted_password) include Shield::Model end test "fetch" do ex = nil begin User.fetch("quentin") rescue Exception => ex end assert ex.kind_of?(Shield::Model::FetchMissing) assert "User.fetch not implemented" == ex.message end test "is_valid_password?" do user = User.new(Shield::Password.encrypt("password")) assert User.is_valid_password?(user, "password") assert ! User.is_valid_password?(user, "password1") end class User class << self attr_accessor :fetched end def self.fetch(username) return fetched if username == "quentin" end end test "authenticate" do user = User.new(Shield::Password.encrypt("pass")) User.fetched = user assert user == User.authenticate("quentin", "pass") assert nil == User.authenticate("unknown", "pass") assert nil == User.authenticate("quentin", "wrongpass") end test "#password=" do u = User.new u.password = "pass1234" assert Shield::Password.check("pass1234", u.crypted_password) end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/test/user.rb
test/user.rb
class User include Shield::Model def self.[](id) User.new(1001) unless id.to_s.empty? end def self.fetch(username) User.new(1001) if username == "quentin" end attr :id def initialize(id) @id = id end def crypted_password @crypted_password ||= Shield::Password.encrypt("password") end end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
cyx/shield
https://github.com/cyx/shield/blob/effcb6316b723e63ff5792b36d16facf336f0625/lib/shield.rb
lib/shield.rb
require "armor" require "uri" module Shield class Middleware attr :url def initialize(app, url = "/login") @app = app @url = url end def call(env) tuple = @app.call(env) if tuple[0] == 401 [302, headers(env["SCRIPT_NAME"] + env["PATH_INFO"]), []] else tuple end end private def headers(path) { "Location" => "%s?return=%s" % [url, encode(path)], "Content-Type" => "text/html", "Content-Length" => "0" } end def encode(str) URI.encode_www_form_component(str) end end module Helpers def persist_session! if session[:remember_for] env["rack.session.options"][:expire_after] = session[:remember_for] end end def authenticated(model) @_shield ||= {} @_shield[model] ||= session[model.to_s] && model[session[model.to_s]] end def authenticate(user) session.clear session[user.class.to_s] = user.id end def login(model, username, password) user = model.authenticate(username, password) authenticate(user) if user end def remember(expire = 1209600) session[:remember_for] = expire end def logout(model) session.delete(model.to_s) session.delete(:remember_for) @_shield.delete(model) if defined?(@_shield) end end module Model def self.included(model) model.extend(ClassMethods) end class FetchMissing < StandardError; end module ClassMethods def authenticate(username, password) user = fetch(username) if user and is_valid_password?(user, password) return user end end def fetch(login) raise FetchMissing, "#{self}.fetch not implemented" end def is_valid_password?(user, password) Shield::Password.check(password, user.crypted_password) end end def password=(password) self.crypted_password = Shield::Password.encrypt(password.to_s) end end module Password Error = Class.new(StandardError) # == DOS attack fix # # Excessively long passwords (e.g. 1MB strings) would hang # a server. # # @see: https://www.djangoproject.com/weblog/2013/sep/15/security/ MAX_LEN = 4096 def self.encrypt(password, salt = generate_salt) digest(password, salt) + salt end def self.check(password, encrypted) sha512, salt = encrypted.to_s[0...128], encrypted.to_s[128..-1] Armor.compare(digest(password, salt), sha512) end protected def self.digest(password, salt) raise Error if password.length > MAX_LEN Armor.digest(password, salt) end def self.generate_salt Armor.hex(OpenSSL::Random.random_bytes(32)) end end end
ruby
MIT
effcb6316b723e63ff5792b36d16facf336f0625
2026-01-04T17:52:17.585471Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/integration/default/serverspec/default_spec.rb
test/integration/default/serverspec/default_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'rbconfig' require 'serverspec' if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ set :backend, :cmd set :os, :family => 'windows' else set :backend, :exec end # Set up the shared example for python_runtime_test. RSpec.shared_examples 'a python_runtime_test' do |python_name, version=nil| let(:python_name) { python_name } let(:python_path) { File.join('', "python_test_#{python_name}") } # Helper for all the file checks. def self.assert_file(rel_path, should_exist=true, &block) describe rel_path do subject { file(File.join(python_path, rel_path)) } # Do nothing for nil. if should_exist == true it { is_expected.to be_a_file } elsif should_exist == false it { is_expected.to_not exist } end instance_eval(&block) if block end end describe 'python_runtime' do assert_file('version') do its(:content) { is_expected.to start_with version } if version end end describe 'python_package' do describe 'sqlparse' do assert_file('import_sqlparse_before', false) assert_file('import_sqlparse_mid') assert_file('import_sqlparse_after', false) assert_file('sentinel_sqlparse') assert_file('sentinel_sqlparse2', false) end describe 'setuptools' do assert_file('sentinel_setuptools', false) end describe 'pep8' do assert_file('import_pep8') end describe 'pytz' do assert_file('import_pytz') end end describe 'python_virtualenv' do assert_file('venv', nil) do it { is_expected.to be_a_directory } end assert_file('import_pytest', false) assert_file('import_pytest_venv') end describe 'pip_requirements' do assert_file('import_requests') do its(:content) { is_expected.to match /^2\.7\.0\s*$/ } end assert_file('import_six') do its(:content) { is_expected.to match /^1\.8\.0\s*$/ } end end describe 'non default version' do assert_file('import_requests_version') do its(:content) { is_expected.to match /^2\.8\.0\s*$/ } end end unless os[:family] == 'windows' describe 'user install' do assert_file('import_docopt') end end end describe 'python 2', unless: File.exist?('/no_py2') do it_should_behave_like 'a python_runtime_test', '2', '2' end describe 'python 3', unless: File.exist?('/no_py3') do it_should_behave_like 'a python_runtime_test', '3', '3' end describe 'pypy', unless: File.exist?('/no_pypy') do it_should_behave_like 'a python_runtime_test', 'pypy' end describe 'system provider', unless: File.exist?('/no_system') do it_should_behave_like 'a python_runtime_test', 'system' end describe 'scl provider', unless: File.exist?('/no_scl') do it_should_behave_like 'a python_runtime_test', 'scl' end describe 'pip reversion test', unless: File.exist?('/no_pip') do path_suffix = if os[:family] == 'windows' '/Scripts/python.exe' else '/bin/pypy' end # Confirm pip verisons. describe command("/test_pip1#{path_suffix} -m pip --version") do its(:exit_status) { is_expected.to eq 0 } its(:stdout) { is_expected.to include ' 18.' } end describe command("/test_pip2#{path_suffix} -m pip --version") do its(:exit_status) { is_expected.to eq 0 } its(:stdout) { is_expected.to include '8.1.2' } end describe command("/test_pip3#{path_suffix} -m pip --version") do its(:exit_status) { is_expected.to eq 0 } its(:stdout) { is_expected.to include '7.1.2' } end describe command("/test_pip4#{path_suffix} -m pip --version") do its(:exit_status) { is_expected.to eq 0 } its(:stdout) { is_expected.to include '9.0.3' } end # Check that structlog installed. describe command("/test_pip1#{path_suffix} -c 'import structlog'") do its(:exit_status) { is_expected.to eq 0 } end describe command("/test_pip2#{path_suffix} -c 'import structlog'") do its(:exit_status) { is_expected.to eq 0 } end describe command("/test_pip3#{path_suffix} -c 'import structlog'") do its(:exit_status) { is_expected.to eq 0 } end describe command("/test_pip4#{path_suffix} -c 'import structlog'") do its(:exit_status) { is_expected.to eq 0 } end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/cookbook/metadata.rb
test/cookbook/metadata.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name 'poise-python_test' depends 'poise-python'
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/cookbook/recipes/default.rb
test/cookbook/recipes/default.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_python/resources/python_runtime_test' # Install lsb-release because Debian 6 doesn't by default and serverspec requires it package 'lsb-release' if platform?('debian') && node['platform_version'].start_with?('6') # Which tests to run on each platform. tests_to_run = value_for_platform( default: %w{py2 py3 system pypy pip}, centos: {default: %w{py2 py3 system scl pypy pip}}, redhat: {default: %w{py2 py3 system scl pypy pip}}, ubuntu: { '12.04' => %w{py2 pypy pip}, 'default' => %w{py2 py3 system pypy pip}, }, windows: {default: %w{py2 py3}}, ) %w{py2 py3 system pypy scl pip msi}.each do |test| unless tests_to_run.include?(test) file "/no_#{test}" next end case test when 'py2' python_runtime_test '2' when 'py3' python_runtime_test '3' when 'system' python_runtime_test 'system' do version '' runtime_provider :system end when 'scl' python_runtime_test 'scl' do version '' runtime_provider :scl end when 'pypy' python_runtime_test 'pypy' when 'pip' # Some pip-related tests that I don't need to run on every Python version. # Pip does plenty of testing on different Python versions and I already touch # the basics. pip_provider = value_for_platform_family(default: :portable_pypy, windows: :msi) # Check the baseline state, should pull the latest pip. python_runtime 'pip1' do provider pip_provider options path: '/test_pip1' version '' end # Check installing a requested version. python_runtime 'pip2' do pip_version '8.1.2' provider pip_provider options path: '/test_pip2' version '' end # Check installing the latest and reverting to an old version. python_runtime 'pip3' do provider pip_provider options path: '/test_pip3' version '' end python_runtime 'pip3b' do pip_version '7.1.2' provider pip_provider options path: '/test_pip3' version '' end # Test pip9 specifically just to be safe. python_runtime 'pip4' do pip_version '9.0.3' provider pip_provider options path: '/test_pip4' version '' end # Run a simple package install on each just to test things. (1..4).each do |n| python_package 'structlog' do python "pip#{n}" end end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/utils_spec.rb
test/spec/utils_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::Utils do describe '.to_python' do subject { described_class.to_python(1) } it { is_expected.to eq '1' } # More detailed encoder specs in python_encoder_spec.rb end # /describe .to_python describe '.path_to_module' do let(:path) { '' } let(:base) { nil } subject { described_class.path_to_module(path, base) } context 'with a relative path' do let(:path) { 'foo.py' } it { is_expected.to eq 'foo' } end # /context with a relative path context 'with a nested relative path' do let(:path) { File.join('foo', 'bar', 'baz.py') } it { is_expected.to eq 'foo.bar.baz' } end # /context with a nested relative path context 'with a non-.py file' do let(:path) { File.join('foo', 'bar', 'baz') } it { is_expected.to eq 'foo.bar.baz' } end # /context with a non-.py file context 'with a base path' do let(:path) { File.join('', 'foo', 'bar', 'baz.py') } let(:base) { File.join('', 'foo') } it { is_expected.to eq 'bar.baz' } end # /context with a base path context 'with a base path that does not match the path' do let(:path) { File.join('', 'foo', 'bar', 'baz.py') } let(:base) { File.join('', 'bar') } it { expect { subject }.to raise_error PoisePython::Error } end # /context with a base path that does not match the path context 'with a base and relative path' do let(:path) { File.join('bar', 'baz.py') } let(:base) { File.join('', 'foo') } it { is_expected.to eq 'bar.baz' } end # /context with a base and relative path end # /describe .path_to_module describe '.module_to_path' do let(:mod) { '' } let(:base) { nil } subject { described_class.module_to_path(mod, base) } context 'with a module' do let(:mod) { 'foo' } it { is_expected.to eq 'foo.py' } end # /context with a module context 'with a nested module' do let(:mod) { 'foo.bar.baz' } it { is_expected.to eq File.join('foo', 'bar', 'baz.py') } end # /context with a nested module context 'with a base path' do let(:mod) { 'bar.baz' } let(:base) { File.join('', 'foo') } it { is_expected.to eq File.join('', 'foo', 'bar', 'baz.py') } end # /context with a base path end # /describe .module_to_path end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/python_command_mixin_spec.rb
test/spec/python_command_mixin_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::PythonCommandMixin do describe PoisePython::PythonCommandMixin::Resource do resource(:poise_test) do include described_class end provider(:poise_test) describe '#python' do let(:python) { chef_run.python_runtime('test') } context 'with an implicit parent' do recipe do python_runtime 'test' do provider :dummy end poise_test 'test' end it { is_expected.to run_poise_test('test').with(parent_python: python, python: '/python') } end # /context with an implicit parent context 'with a parent resource' do recipe do r = python_runtime 'test' do provider :dummy end poise_test 'test' do python r end end it { is_expected.to run_poise_test('test').with(parent_python: python, python: '/python') } end # /context with a parent resource context 'with a parent resource name' do recipe do python_runtime 'test' do provider :dummy end poise_test 'test' do python 'test' end end it { is_expected.to run_poise_test('test').with(parent_python: python, python: '/python') } end # /context with a parent resource name context 'with a parent resource name that looks like a path' do let(:python) { chef_run.python_runtime('/usr/bin/other') } recipe do python_runtime '/usr/bin/other' do provider :dummy end poise_test 'test' do python '/usr/bin/other' end end it { is_expected.to run_poise_test('test').with(parent_python: python, python: '/python') } end # /context with a parent resource name that looks like a path context 'with a path' do recipe do poise_test 'test' do python '/usr/bin/other' end end it { is_expected.to run_poise_test('test').with(parent_python: nil, python: '/usr/bin/other') } end # /context with a path context 'with a path and an implicit parent' do recipe do python_runtime 'test' do provider :dummy end poise_test 'test' do python '/usr/bin/other' end end it { is_expected.to run_poise_test('test').with(parent_python: python, python: '/usr/bin/other') } end # /context with a path and an implicit parent context 'with an invalid parent' do recipe do poise_test 'test' do python 'test' end end it { expect { subject }.to raise_error Chef::Exceptions::ResourceNotFound } end # /context with an invalid parent end # /describe #python end # /describe PoisePython::PythonCommandMixin::Resource end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/spec_helper.rb
test/spec/spec_helper.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_boiler/spec_helper' require 'poise_python' require 'poise_python/cheftie'
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/python_providers/dummy_spec.rb
test/spec/python_providers/dummy_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::PythonProviders::Dummy do let(:python_runtime) { chef_run.python_runtime('test') } step_into(:python_runtime) recipe do python_runtime 'test' do provider :dummy end end describe '#python_binary' do subject { python_runtime.python_binary } it { is_expected.to eq '/python' } end # /describe #python_binary describe '#python_environment' do subject { python_runtime.python_environment } it { is_expected.to eq({}) } end # /describe #python_environment describe 'action :install' do # Just make sure it doesn't error. it { run_chef } end # /describe action :install describe 'action :uninstall' do recipe do python_runtime 'test' do action :uninstall provider :dummy end end # Just make sure it doesn't error. it { run_chef } end # /describe action :uninstall end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/python_providers/portable_pypy_spec.rb
test/spec/python_providers/portable_pypy_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::PythonProviders::PortablePyPy do let(:python_version) { nil } let(:chefspec_options) { {platform: 'ubuntu', version: '14.04'} } let(:default_attributes) { {poise_python_version: python_version} } let(:python_runtime) { chef_run.python_runtime('test') } step_into(:python_runtime) recipe do python_runtime 'test' do provider_no_auto 'dummy' version node['poise_python_version'] virtualenv_version false end end shared_examples_for 'portablepypy provider' do |base| it { expect(python_runtime.provider_for_action(:install)).to be_a described_class } it { is_expected.to install_poise_languages_static(File.join('', 'opt', base)).with(source: "https://bitbucket.org/squeaky/portable-pypy/downloads/#{base}-linux_x86_64-portable.tar.bz2") } it { expect(python_runtime.python_binary).to eq File.join('', 'opt', base, 'bin', 'pypy') } end context 'with version pypy' do let(:python_version) { 'pypy' } it_behaves_like 'portablepypy provider', 'pypy-5.7.1' end # /context with version pypy context 'with version pypy-2.4' do let(:python_version) { 'pypy-2.4' } it_behaves_like 'portablepypy provider', 'pypy-2.4' end # /context with version pypy-2.4 context 'action :uninstall' do recipe do python_runtime 'test' do version 'pypy' action :uninstall end end it { is_expected.to uninstall_poise_languages_static('/opt/pypy-5.7.1') } end # /context action :uninstall end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/python_providers/scl_spec.rb
test/spec/python_providers/scl_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::PythonProviders::Scl do let(:python_version) { '' } let(:chefspec_options) { {platform: 'centos', version: '7.4.1708'} } let(:default_attributes) { {poise_python_version: python_version} } let(:python_runtime) { chef_run.python_runtime('test') } step_into(:python_runtime) recipe do python_runtime 'test' do provider_no_auto 'dummy' version node['poise_python_version'] virtualenv_version false end end shared_examples_for 'scl provider' do |pkg| it { expect(python_runtime.provider_for_action(:install)).to be_a described_class } it { is_expected.to install_poise_languages_scl(pkg) } it do expect_any_instance_of(described_class).to receive(:install_scl_package) run_chef end end context 'with version ""' do let(:python_version) { '' } it_behaves_like 'scl provider', 'rh-python36' end # /context with version "" context 'with version "2"' do let(:python_version) { '2' } it_behaves_like 'scl provider', 'python27' end # /context with version "2" context 'with version "3"' do let(:python_version) { '3' } it_behaves_like 'scl provider', 'rh-python36' end # /context with version "3" context 'with version "3.3"' do let(:python_version) { '3.3' } it_behaves_like 'scl provider', 'python33' end # /context with version "3.3" context 'with version "" on CentOS 6' do let(:chefspec_options) { {platform: 'centos', version: '6.9'} } let(:python_version) { '' } it_behaves_like 'scl provider', 'rh-python36' end # /context with version "" on CentOS 6 context 'action :uninstall' do recipe do python_runtime 'test' do action :uninstall version node['poise_python_version'] end end it do expect_any_instance_of(described_class).to receive(:uninstall_scl_package) run_chef end it { expect(python_runtime.provider_for_action(:uninstall)).to be_a described_class } end # /context action :uninstall end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/python_providers/portable_pypy3_spec.rb
test/spec/python_providers/portable_pypy3_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::PythonProviders::PortablePyPy3 do let(:python_version) { nil } let(:chefspec_options) { {platform: 'ubuntu', version: '14.04'} } let(:default_attributes) { {poise_python_version: python_version} } let(:python_runtime) { chef_run.python_runtime('test') } step_into(:python_runtime) recipe do python_runtime 'test' do provider_no_auto 'dummy' version node['poise_python_version'] virtualenv_version false end end shared_examples_for 'portablepypy3 provider' do |base, url=nil| it { expect(python_runtime.provider_for_action(:install)).to be_a described_class } it { is_expected.to install_poise_languages_static(File.join('', 'opt', base)).with(source: url || "https://bitbucket.org/squeaky/portable-pypy/downloads/#{base}-linux_x86_64-portable.tar.bz2") } it { expect(python_runtime.python_binary).to eq File.join('', 'opt', base, 'bin', 'pypy') } end context 'with version pypy3' do let(:python_version) { 'pypy3' } it_behaves_like 'portablepypy3 provider', 'pypy3-2.4' end # /context with version pypy3 context 'with version pypy3-2.3.1' do let(:python_version) { 'pypy3-2.3.1' } it_behaves_like 'portablepypy3 provider', 'pypy3-2.3.1' end # /context with version pypy3-2.3.1 context 'with version pypy3-5.5' do let(:python_version) { 'pypy3-5.5' } it_behaves_like 'portablepypy3 provider', 'pypy3-5.5-alpha-20161014', 'https://bitbucket.org/squeaky/portable-pypy/downloads/pypy3.3-5.5-alpha-20161014-linux_x86_64-portable.tar.bz2' end # /context with version pypy3-5.5 context 'with version pypy3-5.7' do let(:python_version) { 'pypy3-5.7' } it_behaves_like 'portablepypy3 provider', 'pypy3-5.7.1-beta', 'https://bitbucket.org/squeaky/portable-pypy/downloads/pypy3.5-5.7.1-beta-linux_x86_64-portable.tar.bz2' end # /context with version pypy3-5.5 context 'action :uninstall' do recipe do python_runtime 'test' do version 'pypy3' action :uninstall end end it { is_expected.to uninstall_poise_languages_static('/opt/pypy3-2.4') } end # /context action :uninstall end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/python_providers/system_spec.rb
test/spec/python_providers/system_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::PythonProviders::System do let(:python_version) { '' } let(:chefspec_options) { {platform: 'ubuntu', version: '14.04'} } let(:default_attributes) { {poise_python_version: python_version} } let(:python_runtime) { chef_run.python_runtime('test') } let(:system_package_candidates) { python_runtime.provider_for_action(:install).send(:system_package_candidates, python_version) } step_into(:python_runtime) recipe do python_runtime 'test' do provider_no_auto 'dummy' version node['poise_python_version'] virtualenv_version false end end shared_examples_for 'system provider' do |candidates=nil, pkg| it { expect(python_runtime.provider_for_action(:install)).to be_a described_class } it { expect(system_package_candidates).to eq candidates } if candidates it { is_expected.to install_poise_languages_system(pkg) } it do expect_any_instance_of(described_class).to receive(:install_system_packages) run_chef end end context 'with version ""' do let(:python_version) { '' } it_behaves_like 'system provider', %w{python3.7 python37 python3.6 python36 python3.5 python35 python3.4 python34 python3.3 python33 python3.2 python32 python3.1 python31 python3.0 python30 python3 python2.7 python27 python2.6 python26 python2.5 python25 python}, 'python3.4' end # /context with version "" context 'with version 2' do let(:python_version) { '2' } it_behaves_like 'system provider', %w{python2.7 python27 python2.6 python26 python2.5 python25 python}, 'python2.7' end # /context with version 2 context 'with version 3' do let(:python_version) { '3' } it_behaves_like 'system provider', %w{python3.7 python37 python3.6 python36 python3.5 python35 python3.4 python34 python3.3 python33 python3.2 python32 python3.1 python31 python3.0 python30 python3 python}, 'python3.4' end # /context with version 3 context 'with version 2.3' do let(:python_version) { '2.3' } before do default_attributes['poise-python'] ||= {} default_attributes['poise-python']['test'] = {'package_name' => 'python2.3'} end it_behaves_like 'system provider', %w{python2.3 python23 python}, 'python2.3' end # /context with version 2.3 context 'on Ubuntu 18.04' do let(:chefspec_options) { {platform: 'ubuntu', version: '18.04'} } let(:python_version) { '3.6' } it { is_expected.to install_package(%w{python3.6-venv python3.6-distutils}) } end # /context on Ubuntu 18.04 context 'on Debian 8' do before { chefspec_options.update(platform: 'debian', version: '8.9') } it_behaves_like 'system provider', 'python3.4' end # /context on Debian 8 context 'on CentOS 7' do before { chefspec_options.update(platform: 'centos', version: '7.4.1708') } recipe do python_runtime 'test' do provider :system version node['poise_python_version'] virtualenv_version false end end it_behaves_like 'system provider', 'python' end # /context on CentOS 7 context 'action :uninstall' do recipe do python_runtime 'test' do action :uninstall version node['poise_python_version'] end end it do expect_any_instance_of(described_class).to receive(:uninstall_system_packages) run_chef end it { expect(python_runtime.provider_for_action(:uninstall)).to be_a described_class } end # /context action :uninstall end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/utils/python_encoder_spec.rb
test/spec/utils/python_encoder_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::Utils::PythonEncoder do let(:obj) { nil } subject { described_class.new(obj).encode } context 'with a string' do let(:obj) { 'foobar' } it { is_expected.to eq '"foobar"' } end # /context with a string context 'with a complicated string' do let(:obj) { "im\nalittle\"teapot'" } it { is_expected.to eq '"im\\nalittle\\"teapot\'"' } end # /context with a complicated string context 'with an integer' do let(:obj) { 123 } it { is_expected.to eq '123' } end # /context with an integer context 'with a float' do let(:obj) { 1.3 } it { is_expected.to eq '1.3' } end # /context with a float context 'with a hash' do let(:obj) { {foo: 'bar'} } it { is_expected.to eq '{"foo":"bar"}' } end # /context with a hash context 'with an array' do let(:obj) { ['foo', 1, 'bar'] } it { is_expected.to eq '["foo",1,"bar"]' } end # /context with an array context 'with true' do let(:obj) { true } it { is_expected.to eq 'True' } end # /context with true context 'with false' do let(:obj) { false } it { is_expected.to eq 'False' } end # /context with false context 'with nil' do let(:obj) { nil } it { is_expected.to eq 'None' } end # /context with nil context 'with a broken object' do let(:obj) do {}.tap {|obj| obj[:x] = obj } end it { expect { subject }.to raise_error ArgumentError } end # /context with a broken object context 'with a complex object' do let(:obj) { {a: [1, "2", true], b: false, c: {d: nil}} } it { is_expected.to eq '{"a":[1,"2",True],"b":False,"c":{"d":None}}' } end # /context with a complex object end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/resources/python_runtime_spec.rb
test/spec/resources/python_runtime_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' class PythonRuntimeTestProvider < PoisePython::PythonProviders::Base provides(:test) def self.provides_auto?(*args) true end def python_binary '/python' end def install_python end def uninstall_python end end describe PoisePython::Resources::PythonRuntime do step_into(:python_runtime) let(:venv_installed) { false } before do allow_any_instance_of(PythonRuntimeTestProvider).to receive(:poise_shell_out).with(%w{/python -m venv -h}, environment: {}).and_return(double(error?: !venv_installed)) end context 'with defaults' do recipe do python_runtime 'test' do provider :test end end it { is_expected.to install_python_runtime_pip('test').with(version: nil, get_pip_url: 'https://bootstrap.pypa.io/get-pip.py') } end # /context with defaults context 'with a pip_version' do recipe do python_runtime 'test' do provider :test pip_version '1.2.3' end end it { is_expected.to install_python_runtime_pip('test').with(version: '1.2.3', get_pip_url: 'https://bootstrap.pypa.io/get-pip.py') } end # /context with a pip_version context 'with a pip_version URL' do recipe do python_runtime 'test' do provider :test pip_version 'http://example.com/get-pip.py' end end it { is_expected.to install_python_runtime_pip('test').with(version: nil, get_pip_url: 'http://example.com/get-pip.py') } end # /context with a pip_version URL context 'with a pip_version and a get_pip_url' do recipe do python_runtime 'test' do provider :test pip_version '1.2.3' get_pip_url 'http://example.com/get-pip.py' end end it { is_expected.to install_python_runtime_pip('test').with(version: '1.2.3', get_pip_url: 'http://example.com/get-pip.py') } end # /context with a pip_version and a get_pip_url end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/resources/python_runtime_pip_spec.rb
test/spec/resources/python_runtime_pip_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::Resources::PythonRuntimePip do step_into(:python_runtime_pip) recipe do python_runtime 'test' python_runtime_pip 'test' do get_pip_url 'http://example.com/' end end before do provider = PoisePython::Resources::PythonRuntimePip::Provider allow_any_instance_of(provider).to receive(:pip_version).and_return(nil) allow_any_instance_of(provider).to receive(:bootstrap_pip) end # Make sure it can at least vaguely run. it { chef_run } end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/resources/python_package_spec.rb
test/spec/resources/python_package_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::Resources::PythonPackage do describe PoisePython::Resources::PythonPackage::Resource do describe '#response_file' do recipe do python_package 'foo' do response_file 'bar' end end it { expect { subject }.to raise_error NoMethodError } end # /describe #response_file describe '#response_file_variables' do recipe do python_package 'foo' do response_file_variables 'bar' end end it { expect { subject }.to raise_error NoMethodError } end # /describe #response_file_variables describe '#source' do recipe do python_package 'foo' do source 'bar' end end it { expect { subject }.to raise_error NoMethodError } end # /describe #source end # /describe PoisePython::Resources::PythonPackage::Resource describe PoisePython::Resources::PythonPackage::Provider do let(:test_resource) { PoisePython::Resources::PythonPackage::Resource.new('package', chef_run.run_context) } let(:test_provider) { described_class.new(test_resource, chef_run.run_context) } def stub_cmd(cmd, **options) options = options.dup array_13 = options.delete(:array_13) if array_13 && Gem::Requirement.create('>= 13').satisfied_by?(Gem::Version.create(Chef::VERSION)) cmd = Shellwords.split(cmd) end output_options = {error?: options.delete(:error?) || false, stdout: options.delete(:stdout) || '', stderr: options.delete(:stderr) || ''} expect(test_provider).to receive(:python_shell_out!).with(cmd, options).and_return(double("python #{cmd} return", **output_options)) end describe '#load_current_resource' do let(:package_name) { nil } let(:package_version) { nil } let(:test_resource) { PoisePython::Resources::PythonPackage::Resource.new(package_name, chef_run.run_context).tap {|r| r.version(package_version) if package_version } } let(:candidate_version) { subject; test_provider.candidate_version } subject { test_provider.load_current_resource } context 'with package_name foo' do let(:package_name) { 'foo' } before do stub_cmd(%w{-m pip.__main__ list}, environment: {'PIP_FORMAT' => 'json'}, stdout: '') stub_cmd(%w{- foo}, input: kind_of(String), stdout: '{"foo":"1.0.0"}') end its(:version) { is_expected.to be nil } it { expect(candidate_version).to eq '1.0.0' } end # /context with package_name foo context 'with package_name ["foo", "bar"]' do let(:package_name) { %w{foo bar} } before do stub_cmd(%w{-m pip.__main__ list}, environment: {'PIP_FORMAT' => 'json'}, stdout: '') stub_cmd(%w{- foo bar}, input: kind_of(String), stdout: '{"foo":"1.0.0","bar":"2.0.0"}') end its(:version) { is_expected.to eq [nil, nil] } it { expect(candidate_version).to eq %w{1.0.0 2.0.0} } end # /context with package_name ["foo", "bar"] context 'with a package with extras' do let(:package_name) { 'foo[bar]' } before do stub_cmd(%w{-m pip.__main__ list}, environment: {'PIP_FORMAT' => 'json'}, stdout: '') stub_cmd(%w{- foo}, input: kind_of(String), stdout: '{"foo":"1.0.0"}') end its(:version) { is_expected.to be nil } it { expect(candidate_version).to eq '1.0.0' } end # /context with a package with extras context 'with a package with underscores' do let(:package_name) { 'cx_foo' } before do stub_cmd(%w{-m pip.__main__ list}, environment: {'PIP_FORMAT' => 'json'}, stdout: '') stub_cmd(%w{- cx-foo}, input: kind_of(String), stdout: '{"cx-foo":"1.0.0"}') end its(:version) { is_expected.to be nil } it { expect(candidate_version).to eq '1.0.0' } end # /context with a package with underscores context 'with options' do let(:package_name) { 'foo' } before do test_resource.options('--index-url=http://example') stub_cmd("-m pip.__main__ list --index-url=http://example ", environment: {'PIP_FORMAT' => 'json'}, stdout: '', array_13: true) stub_cmd("- --index-url=http://example foo", input: kind_of(String), stdout: '{"foo":"1.0.0"}', array_13: true) end its(:version) { is_expected.to be nil } it { expect(candidate_version).to eq '1.0.0' } end # /context with options context 'with list options' do let(:package_name) { 'foo' } before do test_resource.list_options('--index-url=http://example') stub_cmd("-m pip.__main__ list --index-url=http://example ", environment: {'PIP_FORMAT' => 'json'}, stdout: '') stub_cmd("- --index-url=http://example foo", input: kind_of(String), stdout: '{"foo":"1.0.0"}') end its(:version) { is_expected.to be nil } it { expect(candidate_version).to eq '1.0.0' } end # /context with list options context 'with array list options' do let(:package_name) { 'foo' } before do test_resource.list_options(%w{--index-url=http://example}) stub_cmd(%w{-m pip.__main__ list --index-url=http://example}, environment: {'PIP_FORMAT' => 'json'}, stdout: '') stub_cmd(%w{- --index-url=http://example foo}, input: kind_of(String), stdout: '{"foo":"1.0.0"}') end its(:version) { is_expected.to be nil } it { expect(candidate_version).to eq '1.0.0' } end # /context with array list options end # /describe #load_current_resource describe 'actions' do let(:package_name) { nil } let(:current_version) { nil } let(:candidate_version) { nil } let(:test_resource) { PoisePython::Resources::PythonPackage::Resource.new(package_name, chef_run.run_context) } subject { test_provider.run_action } before do current_version = self.current_version candidate_version = self.candidate_version allow(test_provider).to receive(:load_current_resource) do current_resource = double('current_resource', package_name: package_name, version: current_version) test_provider.instance_eval do @current_resource = current_resource @candidate_version = candidate_version end end end describe 'action :install' do before { test_provider.action = :install } context 'with package_name foo' do let(:package_name) { 'foo' } let(:candidate_version) { '1.0.0' } it do stub_cmd(%w{-m pip.__main__ install foo==1.0.0}) subject end end # /context with package_name foo context 'with package_name ["foo", "bar"]' do let(:package_name) { %w{foo bar} } let(:candidate_version) { %w{1.0.0 2.0.0} } it do stub_cmd(%w{-m pip.__main__ install foo==1.0.0 bar==2.0.0}) subject end end # /context with package_name ["foo", "bar"] context 'with options' do let(:package_name) { 'foo' } let(:candidate_version) { '1.0.0' } before { test_resource.options('--editable') } it do stub_cmd('-m pip.__main__ install --editable foo\\=\\=1.0.0', array_13: true) subject end end # /context with options context 'with install options' do let(:package_name) { 'foo' } let(:candidate_version) { '1.0.0' } before { test_resource.install_options('--editable') } it do stub_cmd('-m pip.__main__ install --editable foo\\=\\=1.0.0') subject end end # /context with install options context 'with array install options' do let(:package_name) { 'foo' } let(:candidate_version) { '1.0.0' } before { test_resource.install_options(%w{--editable}) } it do stub_cmd(%w{-m pip.__main__ install --editable foo==1.0.0}) subject end end # /context with array install options context 'with a package with extras' do let(:package_name) { 'foo[bar]' } let(:candidate_version) { '1.0.0' } it do stub_cmd(%w{-m pip.__main__ install foo[bar]==1.0.0}) subject end end # /context with a package with extras context 'with a package with underscores' do let(:package_name) { 'cx_foo' } let(:candidate_version) { '1.0.0' } it do stub_cmd(%w{-m pip.__main__ install cx_foo==1.0.0}) subject end end # /context with a package with underscores end # /describe action :install describe 'action :upgrade' do before { test_provider.action = :upgrade } context 'with package_name foo' do let(:package_name) { 'foo' } let(:candidate_version) { '1.0.0' } it do stub_cmd(%w{-m pip.__main__ install --upgrade foo==1.0.0}) subject end end # /context with package_name foo context 'with package_name ["foo", "bar"]' do let(:package_name) { %w{foo bar} } let(:candidate_version) { %w{1.0.0 2.0.0} } it do stub_cmd(%w{-m pip.__main__ install --upgrade foo==1.0.0 bar==2.0.0}) subject end end # /context with package_name ["foo", "bar"] end # /describe action :upgrade describe 'action :remove' do before { test_provider.action = :remove } context 'with package_name foo' do let(:package_name) { 'foo' } let(:current_version) { '1.0.0' } it do stub_cmd(%w{-m pip.__main__ uninstall --yes foo}) subject end end # /context with package_name foo context 'with package_name ["foo", "bar"]' do let(:package_name) { %w{foo bar} } let(:current_version) { %w{1.0.0 2.0.0} } it do stub_cmd(%w{-m pip.__main__ uninstall --yes foo bar}) subject end end # /context with package_name ["foo", "bar"] end # /describe action :remove end # /describe actions describe '#parse_pip_list' do let(:text) { '' } subject { test_provider.send(:parse_pip_list, text) } context 'with no content' do it { is_expected.to eq({}) } end # /context with no content context 'with standard content' do let(:text) { <<-EOH } eventlet (0.12.1) Fabric (1.9.1) fabric-rundeck (1.2, /Users/coderanger/src/bal/fabric-rundeck) flake8 (2.1.0.dev0) cx-Freeze (4.3.4) EOH it { is_expected.to eq({'eventlet' => '0.12.1', 'fabric' => '1.9.1', 'fabric-rundeck' => '1.2', 'flake8' => '2.1.0.dev0', 'cx-freeze' => '4.3.4'}) } end # /context with standard content context 'with JSON content' do let(:text) { <<-EOH.strip } [{"name":"eventlet","version":"0.12.1"}, {"name":"Fabric","version":"1.9.1"}, {"name":"fabric-rundeck","version":"1.2"}, {"name":"flake8","version":"2.1.0.dev0"}, {"name":"cx-Freeze","version":"4.3.4"}] EOH it { is_expected.to eq({'eventlet' => '0.12.1', 'fabric' => '1.9.1', 'fabric-rundeck' => '1.2', 'flake8' => '2.1.0.dev0', 'cx-freeze' => '4.3.4'}) } end # /context with JSON content context 'with malformed content' do let(:text) { <<-EOH } eventlet (0.12.1) Fabric (1.9.1) fabric-rundeck (1.2, /Users/coderanger/src/bal/fabric-rundeck) flake 8 (2.1.0.dev0) cx_Freeze (4.3.4) EOH it { is_expected.to eq({'eventlet' => '0.12.1', 'fabric' => '1.9.1', 'fabric-rundeck' => '1.2', 'cx-freeze' => '4.3.4'}) } end # /context with malformed content end # /describe #parse_pip_list end # /describe PoisePython::Resources::PythonPackage::Provider end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/resources/pip_requirements_spec.rb
test/spec/resources/pip_requirements_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::Resources::PipRequirements do let(:pip_cmd) { %w{-m pip.__main__ install --requirement /test/requirements.txt} } let(:pip_output) { '' } let(:pip_user) { nil } let(:pip_group) { nil } let(:pip_cwd) { '/test' } step_into(:pip_requirements) before do allow(File).to receive(:directory?).and_call_original allow(File).to receive(:directory?).with('/test').and_return(true) end before do expect_any_instance_of(PoisePython::Resources::PipRequirements::Provider).to receive(:python_shell_out!).with(pip_cmd, {user: pip_user, group: pip_group, cwd: pip_cwd}).and_return(double(stdout: pip_output)) end context 'with a directory' do recipe do pip_requirements '/test' end it { is_expected.to install_pip_requirements('/test') } end # /context with a directory context 'with a file' do let(:pip_cmd) { %w{-m pip.__main__ install --requirement /test/reqs.txt} } recipe do pip_requirements '/test/reqs.txt' end it { is_expected.to install_pip_requirements('/test/reqs.txt') } end # /context with a file context 'with a user' do let(:pip_user) { 'testuser' } recipe do pip_requirements '/test' do user 'testuser' end end it { is_expected.to install_pip_requirements('/test') } end # /context with a user context 'with a group' do let(:pip_group) { 'testgroup' } recipe do pip_requirements '/test' do group 'testgroup' end end it { is_expected.to install_pip_requirements('/test') } end # /context with a group context 'action :upgrade' do let(:pip_cmd) { %w{-m pip.__main__ install --upgrade --requirement /test/requirements.txt} } recipe do pip_requirements '/test' do action :upgrade end end it { is_expected.to upgrade_pip_requirements('/test') } end # /context action :upgrade context 'with output' do let(:pip_output) { 'Successfully installed' } recipe do pip_requirements '/test' end it { is_expected.to install_pip_requirements('/test').with(updated?: true) } end # /context with output context 'with a cwd' do let(:pip_cwd) { '/other' } recipe do pip_requirements '/test' do cwd '/other' end end it { is_expected.to install_pip_requirements('/test') } end # /context with a cwd context 'with options' do let(:pip_cmd) { '-m pip.__main__ install --index-url=http://example --requirement /test/requirements.txt' } recipe do pip_requirements '/test' do options '--index-url=http://example' end end it { is_expected.to install_pip_requirements('/test') } end # /context with options end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/test/spec/resources/python_virtualenv_spec.rb
test/spec/resources/python_virtualenv_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoisePython::Resources::PythonVirtualenv do step_into(:python_virtualenv) let(:expect_cmd) { nil } let(:has_venv) { false } let(:venv_help_output) { ' --without-pip Skips installing or upgrading pip in the virtual' } let(:expect_user) { nil } before do if expect_cmd expect_any_instance_of(PoisePython::Resources::PythonVirtualenv::Provider).to receive(:python_shell_out).with(%w{-m venv -h}).and_return(double(error?: !has_venv, stdout: venv_help_output)) expect_any_instance_of(PoisePython::Resources::PythonVirtualenv::Provider).to receive(:python_shell_out!).with(expect_cmd, environment: be_a(Hash), user: expect_user, group: expect_user) end end context 'without venv' do let(:expect_cmd) { %w{-m virtualenv /test} } recipe do python_virtualenv '/test' end it { is_expected.to create_python_virtualenv('/test') } it { expect(chef_run.python_virtualenv('/test').python_binary).to eq '/test/bin/python' } it { expect(chef_run.python_virtualenv('/test').python_environment).to eq({}) } it { is_expected.to install_python_package('wheel').with(parent_python: chef_run.python_virtualenv('/test')) } it { is_expected.to install_python_package('setuptools').with(parent_python: chef_run.python_virtualenv('/test')) } it { is_expected.to_not install_python_package('virtualenv') } it { is_expected.to install_python_runtime_pip('/test').with(parent: chef_run.python_virtualenv('/test')) } end # /context without venv context 'with venv' do let(:has_venv) { true } let(:expect_cmd) { %w{-m venv --without-pip /test} } recipe do python_virtualenv '/test' end it { is_expected.to create_python_virtualenv('/test') } end # /context with venv context 'with venv on python 3.3' do let(:has_venv) { true } let(:venv_help_output) { '' } let(:expect_cmd) { %w{-m venv /test} } recipe do python_virtualenv '/test' end it { is_expected.to create_python_virtualenv('/test') } end # /context with venv on python 3.3 context 'with system_site_packages' do let(:expect_cmd) { %w{-m virtualenv --system-site-packages /test} } recipe do python_virtualenv '/test' do system_site_packages true end end it { is_expected.to create_python_virtualenv('/test') } end # /context with system_site_packages context 'with a user and group' do let(:expect_cmd) { %w{-m virtualenv /test} } let(:expect_user) { 'me' } recipe do python_virtualenv '/test' do user 'me' group 'me' end end it { is_expected.to create_python_virtualenv('/test') } it { is_expected.to install_python_package('wheel').with(group: 'me', user: 'me') } it { is_expected.to install_python_package('setuptools').with(group: 'me', user: 'me') } end # /context with a user and group context 'with action :delete' do recipe do python_virtualenv '/test' do action :delete end end it { is_expected.to delete_python_virtualenv('/test') } it { is_expected.to delete_directory('/test') } end # /context with action :delete context 'with a parent Python' do let(:expect_cmd) { %w{-m virtualenv /test} } recipe do python_runtime '2' do def self.python_environment {'KEY' => 'VALUE'} end end python_virtualenv '/test' end it { is_expected.to create_python_virtualenv('/test') } it { expect(chef_run.python_virtualenv('/test').python_binary).to eq '/test/bin/python' } it { expect(chef_run.python_virtualenv('/test').python_environment).to eq({'KEY' => 'VALUE'}) } end # /context with a parent Python end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/chef/recipes/default.rb
chef/recipes/default.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Default runtimes, last one will be the default. python_runtime 'pypy' if node['poise-python']['install_pypy'] python_runtime '3' if node['poise-python']['install_python3'] python_runtime '2' if node['poise-python']['install_python2']
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/chef/attributes/default.rb
chef/attributes/default.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Default inversion options. default['poise-python']['provider'] = 'auto' default['poise-python']['options'] = {} # Used for the default recipe. default['poise-python']['install_python2'] = true default['poise-python']['install_python3'] = false default['poise-python']['install_pypy'] = false
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python.rb
lib/poise_python.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module PoisePython autoload :Error, 'poise_python/error' autoload :Resources, 'poise_python/resources' autoload :PythonCommandMixin, 'poise_python/python_command_mixin' autoload :PythonProviders, 'poise_python/python_providers' autoload :Utils, 'poise_python/utils' autoload :VERSION, 'poise_python/version' end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_command_mixin.rb
lib/poise_python/python_command_mixin.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise/utils' require 'poise_languages' module PoisePython # Mixin for resources and providers which run Python commands. # # @since 1.0.0 module PythonCommandMixin include Poise::Utils::ResourceProviderMixin # Mixin for resources which run Python commands. module Resource include PoiseLanguages::Command::Mixin::Resource(:python) # Wrapper for setting the parent to be a virtualenv. # # @param name [String] Name of the virtualenv resource. # @return [void] def virtualenv(name) if name.is_a?(PoisePython::Resources::PythonVirtualenv::Resource) parent_python(name) else parent_python("python_virtualenv[#{name}]") end end end module Provider include PoiseLanguages::Command::Mixin::Provider(:python) end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/version.rb
lib/poise_python/version.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module PoisePython VERSION = '1.7.1.pre' end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/resources.rb
lib/poise_python/resources.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_python/resources/pip_requirements' require 'poise_python/resources/python_package' require 'poise_python/resources/python_runtime' require 'poise_python/resources/python_runtime_pip' require 'poise_python/resources/python_execute' require 'poise_python/resources/python_virtualenv' module PoisePython # Chef resources and providers for poise-python. # # @since 1.0.0 module Resources end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/utils.rb
lib/poise_python/utils.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_python/error' module PoisePython # Helper methods for Python-related things. # # @since 1.0.0 module Utils autoload :PythonEncoder, 'poise_python/utils/python_encoder' extend self # Convert an object to a Python literal. # # @param obj [Object] Ovject to convert. # @return [String] def to_python(obj) PythonEncoder.new(obj).encode end # Convert path to a Python dotted module name. # # @param path [String] Path to the file. If base is not given, this must be # a relative path. # @param base [String] Optional base path to treat the file as relative to. # @return [String] def path_to_module(path, base=nil) if base path = ::File.expand_path(path, base) raise PoisePython::Error.new("Path #{path} is not inside base path #{base}") unless path.start_with?(base) path = path[base.length+1..-1] end path = path[0..-4] if path.end_with?('.py') path.gsub(/#{::File::SEPARATOR}/, '.') end # Convert a Python dotted module name to a path. # # @param mod [String] Dotted module name. # @param base [String] Optional base path to treat the file as relative to. # @return [String] def module_to_path(mod, base=nil) path = mod.gsub(/\./, ::File::SEPARATOR) + '.py' path = ::File.join(base, path) if base path end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers.rb
lib/poise_python/python_providers.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/platform/provider_priority_map' require 'poise_python/python_providers/dummy' require 'poise_python/python_providers/msi' require 'poise_python/python_providers/portable_pypy' require 'poise_python/python_providers/portable_pypy3' require 'poise_python/python_providers/scl' require 'poise_python/python_providers/system' module PoisePython # Inversion providers for the python_runtime resource. # # @since 1.0.0 module PythonProviders autoload :Base, 'poise_python/python_providers/base' Chef::Platform::ProviderPriorityMap.instance.priority(:python_runtime, [ PoisePython::PythonProviders::Dummy, PoisePython::PythonProviders::Msi, PoisePython::PythonProviders::PortablePyPy3, PoisePython::PythonProviders::PortablePyPy, PoisePython::PythonProviders::Scl, PoisePython::PythonProviders::System, ]) end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/cheftie.rb
lib/poise_python/cheftie.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_python/resources' require 'poise_python/python_providers'
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/error.rb
lib/poise_python/error.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_languages' module PoisePython class Error < PoiseLanguages::Error end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/scl.rb
lib/poise_python/python_providers/scl.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/resource' require 'poise_languages' require 'poise_python/error' require 'poise_python/python_providers/base' module PoisePython module PythonProviders class Scl < Base include PoiseLanguages::Scl::Mixin provides(:scl) scl_package('3.6.3', 'rh-python36', 'rh-python36-python-devel') scl_package('3.5.1', 'rh-python35', 'rh-python35-python-devel') scl_package('3.4.2', 'rh-python34', 'rh-python34-python-devel') scl_package('3.3.2', 'python33', 'python33-python-devel') scl_package('2.7.8', 'python27', 'python27-python-devel') def python_binary ::File.join(scl_folder, 'root', 'usr', 'bin', 'python') end def python_environment scl_environment end private def install_python install_scl_package end def uninstall_python uninstall_scl_package end end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/dummy.rb
lib/poise_python/python_providers/dummy.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_python/python_providers/base' module PoisePython module PythonProviders # Inversion provider for the `python_runtime` resource to use a fake Python, # for use in unit tests. # # @since 1.1.0 # @provides dummy class Dummy < Base provides(:dummy) # Enable by default on ChefSpec. # # @api private def self.provides_auto?(node, _resource) node.platform?('chefspec') end # Manual overrides for dummy data. # # @api private def self.default_inversion_options(node, resource) super.merge({ python_binary: ::File.join('', 'python'), python_environment: nil, }) end # The `install` action for the `python_runtime` resource. # # @return [void] def action_install # This space left intentionally blank. end # The `uninstall` action for the `python_runtime` resource. # # @return [void] def action_uninstall # This space left intentionally blank. end # Path to the non-existent python. # # @return [String] def python_binary options['python_binary'] end # Environment for the non-existent python. # # @return [String] def python_environment options['python_environment'] || super end end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/portable_pypy.rb
lib/poise_python/python_providers/portable_pypy.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_languages/static' require 'poise_python/error' require 'poise_python/python_providers/base' module PoisePython module PythonProviders class PortablePyPy < Base provides(:portable_pypy) include PoiseLanguages::Static( name: 'pypy', versions: %w{5.7.1 5.6 5.4.1 5.4 5.3.1 5.1.1 5.1 5.0.1 5.0 4.0.1 2.6.1 2.5.1 2.5 2.4 2.3.1 2.3 2.2.1 2.2 2.1 2.0.2}, machines: %w{linux-i686 linux-x86_64}, url: 'https://bitbucket.org/squeaky/portable-pypy/downloads/pypy-%{version}-%{kernel}_%{machine}-portable.tar.bz2' ) def python_binary ::File.join(static_folder, 'bin', 'pypy') end private def install_python install_static end def uninstall_python uninstall_static end end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/base.rb
lib/poise_python/python_providers/base.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider' require 'poise' module PoisePython module PythonProviders class Base < Chef::Provider include Poise(inversion: :python_runtime) # Set default inversion options. # # @api private def self.default_inversion_options(node, new_resource) super.merge({ get_pip_url: new_resource.get_pip_url, pip_version: new_resource.pip_version, setuptools_version: new_resource.setuptools_version, version: new_resource.version, virtualenv_version: new_resource.virtualenv_version, wheel_version: new_resource.wheel_version, }) end # The `install` action for the `python_runtime` resource. # # @return [void] def action_install # First inner converge for the Python install. notifying_block do install_python end # Second inner converge for the support tools. This is needed because # we run a python command to check if venv is available. notifying_block do install_pip install_setuptools install_wheel install_virtualenv end end # The `uninstall` action for the `python_runtime` resource. # # @abstract # @return [void] def action_uninstall notifying_block do uninstall_python end end # The path to the `python` binary. This is an output property. # # @abstract # @return [String] def python_binary raise NotImplementedError end # The environment variables for this Python. This is an output property. # # @return [Hash<String, String>] def python_environment {} end private # Install the Python runtime. Must be implemented by subclass. # # @abstract # @return [void] def install_python raise NotImplementedError end # Uninstall the Python runtime. Must be implemented by subclass. # # @abstract # @return [void] def uninstall_python raise NotImplementedError end # Install pip in to the Python runtime. # # @return [void] def install_pip pip_version_or_url = options[:pip_version] return unless pip_version_or_url # If there is a : in the version, use it as a URL and ignore the actual # URL option. if pip_version_or_url.is_a?(String) && pip_version_or_url.include?(':') pip_version = nil pip_url = pip_version_or_url else pip_version = pip_version_or_url pip_url = options[:get_pip_url] end Chef::Log.debug("[#{new_resource}] Installing pip #{pip_version || 'latest'}") # Install or bootstrap pip. python_runtime_pip new_resource.name do parent new_resource # If the version is `true`, don't pass it at all. version pip_version if pip_version.is_a?(String) get_pip_url pip_url end end # Install setuptools in to the Python runtime. This is very similar to the # {#install_wheel} and {#install_virtualenv} methods but they are kept # separate for the benefit of subclasses being able to override them # individually. # # @return [void] def install_setuptools # Captured because #options conflicts with Chef::Resource::Package#options. setuptools_version = options[:setuptools_version] return unless setuptools_version Chef::Log.debug("[#{new_resource}] Installing setuptools #{setuptools_version == true ? 'latest' : setuptools_version}") # Install setuptools via pip. python_package 'setuptools' do parent_python new_resource version setuptools_version if setuptools_version.is_a?(String) end end # Install wheel in to the Python runtime. # # @return [void] def install_wheel # Captured because #options conflicts with Chef::Resource::Package#options. wheel_version = options[:wheel_version] return unless wheel_version Chef::Log.debug("[#{new_resource}] Installing wheel #{wheel_version == true ? 'latest' : wheel_version}") # Install wheel via pip. python_package 'wheel' do parent_python new_resource version wheel_version if wheel_version.is_a?(String) end end # Install virtualenv in to the Python runtime. # # @return [void] def install_virtualenv # Captured because #options conflicts with Chef::Resource::Package#options. virtualenv_version = options[:virtualenv_version] return unless virtualenv_version # Check if the venv module exists. cmd = poise_shell_out([python_binary, '-m', 'venv', '-h'], environment: python_environment) return unless cmd.error? Chef::Log.debug("[#{new_resource}] Installing virtualenv #{virtualenv_version == true ? 'latest' : virtualenv_version}") # Install virtualenv via pip. python_package 'virtualenv' do parent_python new_resource version virtualenv_version if virtualenv_version.is_a?(String) end end end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false
poise/poise-python
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/python_providers/system.rb
lib/poise_python/python_providers/system.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/resource' require 'poise_languages' require 'poise_python/error' require 'poise_python/python_providers/base' module PoisePython module PythonProviders class System < Base include PoiseLanguages::System::Mixin provides(:system) packages('python', { debian: { '~> 10.0' => %w{python3.6 python2.7}, '~> 9.0' => %w{python3.5 python2.7}, '~> 8.0' => %w{python3.4 python2.7}, '~> 7.0' => %w{python3.2 python2.7 python2.6}, '~> 6.0' => %w{python3.1 python2.6 python2.5}, }, ubuntu: { '18.04' => %w{python3.6 python2.7}, '16.04' => %w{python3.5 python2.7}, '14.04' => %w{python3.4 python2.7}, '12.04' => %w{python3.2 python2.7}, '10.04' => %w{python3.1 python2.6}, }, redhat: {default: %w{python}}, centos: {default: %w{python}}, fedora: {default: %w{python3 python}}, amazon: {default: %w{python34 python27 python26 python}}, }) # Output value for the Python binary we are installing. Seems to match # package name on all platforms I've checked. def python_binary ::File.join('', 'usr', 'bin', system_package_name) end private def install_python install_system_packages if node.platform_family?('debian') && system_package_name == 'python3.6' # Ubuntu 18.04 and Debian 10 have some weird dependency fuckery going on. _options = options package %w{python3.6-venv python3.6-distutils} do action(:upgrade) if _options['package_upgrade'] end end end def uninstall_python if node.platform_family?('debian') && system_package_name == 'python3.6' # Other side of the depdency nonsense. package %w{python3.6-venv python3.6-distutils} do action(:purge) end end uninstall_system_packages end def system_package_candidates(version) [].tap do |names| # For two (or more) digit versions. if match = version.match(/^(\d+\.\d+)/) # Debian style pythonx.y names << "python#{match[1]}" # Amazon style pythonxy names << "python#{match[1].gsub(/\./, '')}" end # Aliases for 2 and 3. if version == '3' || version == '' names.concat(%w{python3.7 python37 python3.6 python36 python3.5 python35 python3.4 python34 python3.3 python33 python3.2 python32 python3.1 python31 python3.0 python30 python3}) end if version == '2' || version == '' names.concat(%w{python2.7 python27 python2.6 python26 python2.5 python25}) end # For RHEL and friends. names << 'python' names.uniq! end end end end end
ruby
Apache-2.0
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
2026-01-04T17:52:09.242542Z
false