├── .travis.yml ├── spec ├── spec_helper.rb └── cfoo │ ├── module_spec.rb │ ├── project_spec.rb │ ├── renderer_spec.rb │ ├── factory_spec.rb │ ├── array_spec.rb │ ├── yaml_spec.rb │ ├── cfoo_spec.rb │ ├── el_parser_spec.rb │ ├── file_system_spec.rb │ ├── yaml_parser_spec.rb │ ├── processor_spec.rb │ └── parser_spec.rb ├── lib ├── cfoo │ ├── version.rb │ ├── constants.rb │ ├── renderer.rb │ ├── project.rb │ ├── array.rb │ ├── module.rb │ ├── yaml_parser.rb │ ├── cfoo.rb │ ├── factory.rb │ ├── yaml.rb │ ├── processor.rb │ ├── file_system.rb │ ├── parser.rb │ └── el_parser.rb └── cfoo.rb ├── .simplecov ├── Gemfile ├── features ├── support │ └── env.rb ├── el_escaping.feature ├── error_reporting.feature ├── attribute_expansion.feature ├── reference_expansion.feature ├── parse_files.feature ├── convert_yaml_to_json.feature ├── map_reference_expansion.feature ├── step_definitions │ └── cfoo_steps.rb ├── modules.feature ├── function_expansion.feature └── yamly_shortcuts.feature ├── Guardfile ├── .gitignore ├── Rakefile ├── bin └── cfoo ├── TODO ├── cfoo.gemspec ├── README.md └── LICENSE.txt /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - "2.2" 4 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'simplecov' 2 | require 'cfoo' 3 | -------------------------------------------------------------------------------- /lib/cfoo/version.rb: -------------------------------------------------------------------------------- 1 | module Cfoo 2 | VERSION = "0.0.6" 3 | end 4 | -------------------------------------------------------------------------------- /.simplecov: -------------------------------------------------------------------------------- 1 | SimpleCov.start do 2 | add_filter "/spec/" 3 | add_filter "/features/" 4 | end 5 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in cfoo.gemspec 4 | gemspec 5 | -------------------------------------------------------------------------------- /lib/cfoo/constants.rb: -------------------------------------------------------------------------------- 1 | module Cfoo 2 | CLOUDFORMATION_FUNCTIONS = %w[Base64 FindInMap GetAtt GetAZs ImportValue Join Split Select And Equals If Not Or] 3 | end 4 | -------------------------------------------------------------------------------- /features/support/env.rb: -------------------------------------------------------------------------------- 1 | lib_path = File.expand_path('../../../lib', __FILE__) 2 | $LOAD_PATH.unshift lib_path unless $LOAD_PATH.include? lib_path 3 | 4 | require 'simplecov' 5 | require 'cfoo' 6 | -------------------------------------------------------------------------------- /lib/cfoo/renderer.rb: -------------------------------------------------------------------------------- 1 | require 'json' 2 | 3 | module Cfoo 4 | class Renderer 5 | def render(hash) 6 | JSON.pretty_unparse hash 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /Guardfile: -------------------------------------------------------------------------------- 1 | notification :terminal_notifier 2 | 3 | guard :rspec do 4 | watch(%r{^spec/.+_spec\.rb$}) 5 | watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" } 6 | watch('spec/spec_helper.rb') { "spec" } 7 | end 8 | 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | *.rbc 3 | *.swp 4 | *.un~ 5 | .bundle 6 | .config 7 | .yardoc 8 | Gemfile.lock 9 | InstalledFiles 10 | _yardoc 11 | coverage 12 | doc/ 13 | lib/bundler/man 14 | pkg 15 | rdoc 16 | spec/reports 17 | test/tmp 18 | test/version_tmp 19 | tmp 20 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/gem_tasks' 2 | require 'rspec/core/rake_task' 3 | require 'cucumber/rake/task' 4 | require 'coveralls/rake/task' 5 | 6 | Coveralls::RakeTask.new 7 | RSpec::Core::RakeTask.new(:spec) 8 | Cucumber::Rake::Task.new(:features) 9 | 10 | task :default => [:spec, :features, 'coveralls:push'] 11 | -------------------------------------------------------------------------------- /lib/cfoo.rb: -------------------------------------------------------------------------------- 1 | require "cfoo/array" 2 | require "cfoo/cfoo" 3 | require "cfoo/constants" 4 | require "cfoo/el_parser" 5 | require "cfoo/factory" 6 | require "cfoo/file_system" 7 | require "cfoo/module" 8 | require "cfoo/parser" 9 | require "cfoo/processor" 10 | require "cfoo/project" 11 | require "cfoo/renderer" 12 | require "cfoo/version" 13 | require "cfoo/yaml" 14 | require "cfoo/yaml_parser" 15 | 16 | -------------------------------------------------------------------------------- /lib/cfoo/project.rb: -------------------------------------------------------------------------------- 1 | require 'cfoo/module' 2 | 3 | module Cfoo 4 | class Project 5 | def initialize(file_system) 6 | @file_system = file_system 7 | end 8 | 9 | def modules 10 | module_dirs = @file_system.glob_relative("modules/*") 11 | module_dirs.map do |dir| 12 | Module.new(dir, @file_system) 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /lib/cfoo/array.rb: -------------------------------------------------------------------------------- 1 | class Array 2 | def join_adjacent_strings 3 | return clone if empty? 4 | self[1..-1].inject([first]) do |combined_parts, part| 5 | previous = combined_parts.pop 6 | if previous.class == String && part.class == String 7 | combined_parts << previous + part 8 | else 9 | combined_parts << previous << part 10 | end 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /lib/cfoo/module.rb: -------------------------------------------------------------------------------- 1 | module Cfoo 2 | class Module 3 | attr_reader :dir 4 | 5 | def initialize(dir, file_system) 6 | @dir, @file_system = dir, file_system 7 | end 8 | 9 | def files 10 | @file_system.glob_relative("#{dir}/*.yml") 11 | end 12 | 13 | def ==(other) 14 | eql? other 15 | end 16 | 17 | def eql?(other) 18 | dir = other.dir 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /bin/cfoo: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | lib_path = File.expand_path('../../lib', __FILE__) 4 | $LOAD_PATH.unshift lib_path unless $LOAD_PATH.include? lib_path 5 | require 'cfoo' 6 | 7 | if ARGV.include? "--help" 8 | STDERR.puts "Usage: #{File.basename $0} [filename...]" 9 | exit 1 10 | end 11 | 12 | filenames = ARGV 13 | 14 | factory = Cfoo::Factory.new(STDOUT, STDERR) 15 | cfoo = factory.cfoo 16 | 17 | if filenames.empty? 18 | cfoo.build_project 19 | else 20 | cfoo.process *filenames 21 | end 22 | -------------------------------------------------------------------------------- /lib/cfoo/yaml_parser.rb: -------------------------------------------------------------------------------- 1 | require 'cfoo/constants' 2 | require 'cfoo/yaml' 3 | 4 | module Cfoo 5 | class YamlParser 6 | 7 | CFN_DOMAIN_TYPES = ::Cfoo::CLOUDFORMATION_FUNCTIONS + %w[Ref Concat] 8 | 9 | def load_file(file_name) 10 | #TODO: raise errors if "value" isn't the right type 11 | CFN_DOMAIN_TYPES.each do |domain_type| 12 | YAML.add_domain_type_that_gets_loaded_like_in_ruby_1_8(domain_type) 13 | end 14 | YAML.load_file(file_name) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/cfoo/module_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Module do 5 | let(:file_system) { double('file_system') } 6 | let(:mod) { Module.new("/modulepath", file_system) } 7 | 8 | describe "#files" do 9 | it "lists all files in the module directory" do 10 | files = ["file1.yml", "file2.yml", "file3.yml"] 11 | file_system.should_receive(:glob_relative).with("/modulepath/*.yml").and_return files 12 | mod.files.should == files 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /spec/cfoo/project_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Project do 5 | 6 | let(:file_system) { double('file_system') } 7 | let(:project) { Project.new(file_system) } 8 | describe '#modules' do 9 | it 'lists the directories in the "modules" folder of the project' do 10 | file_system.should_receive(:glob_relative).with("modules/*").and_return ["a", "b", "c"] 11 | project.modules.should == ["a", "b", "c"].map {|e| Module.new("modules/#{e}", file_system) } 12 | end 13 | end 14 | end 15 | end 16 | 17 | -------------------------------------------------------------------------------- /lib/cfoo/cfoo.rb: -------------------------------------------------------------------------------- 1 | module Cfoo 2 | class Cfoo 3 | def initialize(processor, renderer, stdout, stderr) 4 | @processor, @renderer, @stdout, @stderr = processor, renderer, stdout, stderr 5 | end 6 | 7 | def process(*filenames) 8 | @stdout.puts(@renderer.render @processor.process(*filenames)) 9 | rescue Exception => error 10 | @stderr.puts error 11 | end 12 | 13 | def build_project 14 | @stdout.puts(@renderer.render @processor.process_all) 15 | rescue Exception => error 16 | @stderr.puts error 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/cfoo/renderer_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Renderer do 5 | describe "#render" do 6 | let(:renderer) { Renderer.new } 7 | it "renders a Hash as a CloudFormation JSON template" do 8 | hash = { 9 | "Resources" => { 10 | "Server" => { "Type" => "EC2Instance" }, 11 | "DNS Entry" => { "Type" => "ARecord" } 12 | } 13 | } 14 | renderer.render(hash).should == JSON.pretty_unparse(hash) 15 | end 16 | end 17 | end 18 | end 19 | 20 | -------------------------------------------------------------------------------- /features/el_escaping.feature: -------------------------------------------------------------------------------- 1 | Feature: EL escaping 2 | As a CloudFormation user 3 | I want to to be able to escape the EL 4 | So that I can type whatever text I want 5 | 6 | Scenario: Escape EL 7 | Given I have a file "outputs.yml" containing 8 | """ 9 | EntryPoint: 10 | Value: \$(BastionHost.PublicIp) 11 | """ 12 | When I process "outputs.yml" 13 | Then the output should match JSON 14 | """ 15 | { 16 | "AWSTemplateFormatVersion" : "2010-09-09", 17 | "EntryPoint" : { 18 | "Value" : "$(BastionHost.PublicIp)" 19 | } 20 | } 21 | """ 22 | -------------------------------------------------------------------------------- /spec/cfoo/factory_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Factory do 5 | let(:stdout) { double('stderr') } 6 | let(:stderr) { double('stderr') } 7 | let(:factory) { Factory.new(stdout, stderr) } 8 | 9 | describe "#cfoo" do 10 | it "builds a Cfoo instance with its dependencies" do 11 | cfoo = factory.cfoo 12 | cfoo.class.should be Cfoo 13 | 14 | cfoo.instance_eval{ @stdout }.should be stdout 15 | cfoo.instance_eval{ @stderr }.should be stderr 16 | cfoo.instance_eval{ @processor }.class.should be Processor 17 | cfoo.instance_eval{ @renderer }.class.should be Renderer 18 | end 19 | end 20 | 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /lib/cfoo/factory.rb: -------------------------------------------------------------------------------- 1 | require "cfoo/cfoo" 2 | require "cfoo/file_system" 3 | require "cfoo/parser" 4 | require "cfoo/processor" 5 | require "cfoo/project" 6 | require "cfoo/renderer" 7 | require "cfoo/yaml_parser" 8 | 9 | module Cfoo 10 | class Factory 11 | def initialize(stdout, stderr) 12 | @stdout, @stderr = stdout, stderr 13 | end 14 | 15 | def cfoo 16 | yaml_parser = YamlParser.new 17 | file_system = FileSystem.new(".", yaml_parser) 18 | project = Project.new(file_system) 19 | parser = Parser.new(file_system) 20 | processor = Processor.new(parser, project) 21 | renderer = Renderer.new 22 | cfoo = Cfoo.new(processor, renderer, @stdout, @stderr) 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /features/error_reporting.feature: -------------------------------------------------------------------------------- 1 | Feature: Error reporting 2 | As a Cfoo user 3 | I want to get useful parse errors 4 | So that I can debug my templates 5 | 6 | Scenario: YAML Parse error 7 | Given I have a file "bad_yaml.yml" containing 8 | """ 9 | EntryPoint: Key: Value: 10 | """ 11 | When I process "bad_yaml.yml" 12 | Then I should see an error containing "bad_yaml.yml" 13 | And I should see an error containing "line" 14 | And I should see an error containing "col" 15 | 16 | Scenario: EL Parse error 17 | Given I have a file "bad_el.yml" containing 18 | """ 19 | EntryPoint: $( 20 | """ 21 | When I process "bad_el.yml" 22 | Then I should see an error containing "Source: $(" 23 | And I should see an error containing "Location: bad_el.yml line 1, column 13" 24 | -------------------------------------------------------------------------------- /spec/cfoo/array_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Array do 4 | describe "#join_adjacent_strings" do 5 | context "when the array is empty" do 6 | it "returns an array with an empty string in it" do 7 | [].join_adjacent_strings.should == [] 8 | end 9 | end 10 | 11 | context "when array has only strings" do 12 | it "returns an array with them all joined together" do 13 | ["j", "oi", "nme"].join_adjacent_strings.should == ["joinme"] 14 | end 15 | end 16 | 17 | context "when array has some strings and other things" do 18 | it "returns an array with all the adjacent strings joined together" do 19 | [["1"], "a", "bc", ["2", "3"], "d", " ", { "e" => "f"}, ""].join_adjacent_strings.should == [["1"], "abc", ["2", "3"], "d ", { "e"=> "f" }, ""] 20 | end 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /lib/cfoo/yaml.rb: -------------------------------------------------------------------------------- 1 | require 'yaml' 2 | 3 | module YAML 4 | 5 | def self.add_domain_type_that_gets_loaded_like_in_ruby_1_8(domain_type) 6 | add_domain_type "", domain_type do |tag, value| 7 | DomainType.create(domain_type, value) 8 | end 9 | end 10 | 11 | class DomainType 12 | attr_accessor :domain, :type_id, :value 13 | 14 | def self.create(type_id, value) 15 | type = self.allocate 16 | type.domain = "yaml.org,2002" 17 | type.type_id = type_id 18 | type.value = value 19 | type 20 | end 21 | 22 | def ==(other) 23 | eq? other 24 | end 25 | 26 | def eq?(other) 27 | if other.respond_to?(:domain) && other.respond_to?(:type_id) && other.respond_to?(:value) 28 | domain == other.domain && type_id == other.type_id && value == other.value 29 | else 30 | false 31 | end 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Features 2 | ---------- 3 | More tests for EL parsing 4 | Spaces in EL? 5 | Allow lone dollar signs in strings? (escaping is only necessary if the dollar is in front of a bracket) 6 | Shorthand for AWS variables (e.g. { "Ref" : "AWS::StackId" } ) 7 | Allow arrays as function args (e.g. $(Join("", [1,2,3]))) 8 | Split into resources/mappings/parameters/etc by putting templates into directories with those names 9 | Allow traditional JSON CloudFormation templates (including modules, splitting, etc) 10 | Expose parser, for use with Fog (github fog/fog) 11 | Vim highlighting 12 | Use multi-json instead of json gem (spec.add_dependency 'multi_json', '~> 1.0') 13 | Disablable warnings about naming conventions 14 | Allow module references to remote templates (inc. Git repositories) (auto-included) 15 | Allow rendering only part of the project (in case part of the infrastructure already exists) 16 | Render templates with ERB to allow extra flexibility/substitution 17 | Resolve EL and complain/fail if targets don't exist 18 | Unit testing for templates 19 | 20 | Tests 21 | ---------- 22 | 23 | Tasks 24 | ---------- 25 | 26 | Bugs 27 | ---------- 28 | -------------------------------------------------------------------------------- /lib/cfoo/processor.rb: -------------------------------------------------------------------------------- 1 | 2 | class Hash 3 | def deep_merge(other) 4 | merge(other) do |key, our_item, their_item| 5 | if [our_item, their_item].all? {|item| item.respond_to? :deep_merge } 6 | our_item.deep_merge(their_item) 7 | elsif [our_item, their_item].all? {|item| item.respond_to?(:+) && item.respond_to?(:uniq) } 8 | our_item.concat(their_item).uniq 9 | else 10 | their_item 11 | end 12 | end 13 | end 14 | end 15 | 16 | module Cfoo 17 | class Processor 18 | def initialize(parser, project) 19 | @parser, @project = parser, project 20 | end 21 | 22 | def process(*filenames) 23 | project_map = { "AWSTemplateFormatVersion" => "2010-09-09" } 24 | filenames.each do |filename| 25 | module_map = @parser.parse_file filename 26 | project_map = project_map.deep_merge module_map 27 | end 28 | project_map 29 | end 30 | 31 | def process_all 32 | project_files = @project.modules.inject([]) do |all_files, mod| 33 | all_files += mod.files 34 | end 35 | process *project_files 36 | end 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /spec/cfoo/yaml_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module YAML 4 | describe DomainType do 5 | describe "#eq?" do 6 | it "returns true when all properties are equal" do 7 | left = DomainType.create("type", "value") 8 | right = DomainType.create("type", "value") 9 | left.should == right 10 | end 11 | it "returns false when type IDs are different" do 12 | left = DomainType.create("type_a", "value") 13 | right = DomainType.create("type_b", "value") 14 | left.should_not == right 15 | end 16 | it "returns false when values are different" do 17 | left = DomainType.create("type", "value_1") 18 | right = DomainType.create("type", "value_2") 19 | left.should_not == right 20 | end 21 | it "returns false when domains are different" do 22 | left = DomainType.create("type", "value") 23 | right = DomainType.create("type", "value") 24 | left.domain = "some domain" 25 | right.domain = "some other domain" 26 | left.should_not == right 27 | end 28 | it "returns false when other type is not a domain type" do 29 | left = DomainType.create("type", "value") 30 | right = "not a domain type" 31 | left.should_not == right 32 | end 33 | end 34 | end 35 | end 36 | 37 | -------------------------------------------------------------------------------- /cfoo.gemspec: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'cfoo/version' 5 | 6 | Gem::Specification.new do |gem| 7 | gem.name = "cfoo" 8 | gem.version = Cfoo::VERSION 9 | gem.authors = ["drrb"] 10 | gem.email = ["drrrrrrrrrrrb@gmail.com"] 11 | gem.license = "GPL-3" 12 | gem.description = "Cfoo: CloudFormation master" 13 | gem.summary = <<-EOF 14 | Cfoo (pronounced 'sifu') allows you to write your CloudFormation templates in a 15 | YAML-based markup language, and organise it into modules to make it easier to 16 | maintain. 17 | EOF 18 | gem.homepage = "https://github.com/drrb/cfoo" 19 | 20 | gem.files = `git ls-files`.split($/) 21 | gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } 22 | gem.test_files = gem.files.grep(%r{^(spec|features)/}) 23 | gem.require_paths = ["lib"] 24 | 25 | gem.add_dependency "json" 26 | gem.add_dependency "parslet", "~> 1.5.0" 27 | 28 | gem.add_development_dependency "bundler", "~> 1.3" 29 | gem.add_development_dependency "rake" 30 | gem.add_development_dependency "rspec" 31 | gem.add_development_dependency "cucumber" 32 | gem.add_development_dependency "simplecov" 33 | gem.add_development_dependency "coveralls", ">= 0.6.3" 34 | gem.add_development_dependency "rest-client", "< 1.7.0" 35 | gem.add_development_dependency "mime-types", "< 2" # Needed to support Ruby 1.8 36 | 37 | unless ["1.8.7", "1.9.2"].include? RUBY_VERSION 38 | gem.add_development_dependency "guard" 39 | gem.add_development_dependency "guard-rspec" 40 | gem.add_development_dependency "terminal-notifier-guard" 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /features/attribute_expansion.feature: -------------------------------------------------------------------------------- 1 | Feature: Expand EL Attribute References 2 | As a CloudFormation user 3 | I want to use an expression language as a shorthand for references 4 | So that I my templates are easier to read 5 | 6 | Scenario: Attribute expansion 7 | Given I have a file "outputs.yml" containing 8 | """ 9 | EntryPoint: 10 | Description: IP address of the Bastion Host 11 | Value: $(BastionHost[PublicIp]) 12 | """ 13 | When I process "outputs.yml" 14 | Then the output should match JSON 15 | """ 16 | { 17 | "AWSTemplateFormatVersion" : "2010-09-09", 18 | "EntryPoint" : { 19 | "Description" : "IP address of the Bastion Host", 20 | "Value" : { "Fn::GetAtt" : [ "BastionHost", "PublicIp" ]} 21 | } 22 | } 23 | """ 24 | 25 | Scenario: Embedded attribute expansion 26 | Given I have a file "outputs.yml" containing 27 | """ 28 | WebSite: 29 | Description: URL of the website 30 | Value: http://$(PublicElasticLoadBalancer[DNSName])/index.html 31 | """ 32 | When I process "outputs.yml" 33 | Then the output should match JSON 34 | """ 35 | { 36 | "AWSTemplateFormatVersion" : "2010-09-09", 37 | "WebSite" : { 38 | "Description" : "URL of the website", 39 | "Value" : { "Fn::Join" : [ "", [ "http://", { "Fn::GetAtt" : [ "PublicElasticLoadBalancer", "DNSName" ]}, "/index.html"]]} 40 | } 41 | } 42 | """ 43 | 44 | -------------------------------------------------------------------------------- /features/reference_expansion.feature: -------------------------------------------------------------------------------- 1 | Feature: Expand EL References 2 | As a CloudFormation user 3 | I want to use an expression language as a shorthand for references 4 | So that I my templates are easier to read 5 | 6 | Scenario: Simple reference 7 | Given I have a file "reference.yml" containing 8 | """ 9 | Server: 10 | InstanceType: $(InstanceType) 11 | SecurityGroups: 12 | - sg-123456 13 | - $(SshSecurityGroup) 14 | - sg-987654 15 | """ 16 | When I process "reference.yml" 17 | Then the output should match JSON 18 | """ 19 | { 20 | "AWSTemplateFormatVersion" : "2010-09-09", 21 | "Server" : { 22 | "InstanceType" : { "Ref" : "InstanceType" }, 23 | "SecurityGroups" : [ 24 | "sg-123456", 25 | { "Ref": "SshSecurityGroup" }, 26 | "sg-987654" 27 | ] 28 | } 29 | } 30 | """ 31 | 32 | Scenario: Embedded reference 33 | Given I have a file "reference.yml" containing 34 | """ 35 | content: 36 | /var/www/html: http://$(DownloadHost)/website.tar.gz 37 | /etc/puppet: https://github.com/$(GithubAccount)/$(RepoName).git 38 | """ 39 | When I process "reference.yml" 40 | Then the output should match JSON 41 | """ 42 | { 43 | "AWSTemplateFormatVersion" : "2010-09-09", 44 | "content": { 45 | "/var/www/html" : { "Fn::Join" : [ "", [ "http://", {"Ref" : "DownloadHost"}, "/website.tar.gz" ] ] }, 46 | "/etc/puppet" : { "Fn::Join" : [ "", [ "https://github.com/", {"Ref" : "GithubAccount"}, "/", {"Ref" : "RepoName"}, ".git" ] ] } 47 | } 48 | } 49 | """ 50 | -------------------------------------------------------------------------------- /features/parse_files.feature: -------------------------------------------------------------------------------- 1 | Feature: Modules 2 | As a casual Cfoo user 3 | I want to combine arbitrary Cfoo templates 4 | So that I can quickly generate a CloudFormation template without a project structure 5 | 6 | Scenario: Parse files 7 | Given I have a file "webapp.yml" containing 8 | """ 9 | Resources: 10 | FrontendFleet: 11 | Type: AWS::AutoScaling::AutoScalingGroup 12 | Properties: 13 | MinSize: 1 14 | MaxSize: 10 15 | """ 16 | And I have a file "vpc.yml" containing 17 | """ 18 | Resources: 19 | VPC: 20 | Type: AWS::EC2::VPC 21 | Properties: 22 | CidrBlock: "10.0.0.0/16" 23 | """ 24 | When I process files "webapp.yml" and "vpc.yml" 25 | Then the output should match JSON 26 | """ 27 | { 28 | "AWSTemplateFormatVersion" : "2010-09-09", 29 | "Resources" : { 30 | "FrontendFleet" : { 31 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 32 | "Properties" : { 33 | "MinSize" : 1, 34 | "MaxSize" : 10 35 | } 36 | }, 37 | "VPC" : { 38 | "Type" : "AWS::EC2::VPC", 39 | "Properties" : { 40 | "CidrBlock" : "10.0.0.0/16" 41 | } 42 | } 43 | } 44 | } 45 | """ 46 | 47 | -------------------------------------------------------------------------------- /features/convert_yaml_to_json.feature: -------------------------------------------------------------------------------- 1 | Feature: Convert YAML to JSON 2 | As a JSON provider 3 | I want to generate my JSON from YAML 4 | So that it's easier to read 5 | 6 | Scenario: Basic array conversion 7 | Given I have a file "list.yml" containing 8 | """ 9 | list: 10 | - One 11 | - 2 12 | - "3" 13 | """ 14 | When I process "list.yml" 15 | Then the output should match JSON 16 | """ 17 | { 18 | "AWSTemplateFormatVersion" : "2010-09-09", 19 | "list" : ["One", 2, "3"] 20 | } 21 | """ 22 | 23 | Scenario: Basic map conversion 24 | Given I have a file "map.yml" containing 25 | """ 26 | 1: One 27 | 2: Two 28 | 3: Three 29 | """ 30 | When I process "map.yml" 31 | Then the output should match JSON 32 | """ 33 | { 34 | "AWSTemplateFormatVersion" : "2010-09-09", 35 | "1" : "One", 36 | "2" : "Two", 37 | "3" : "Three" 38 | } 39 | """ 40 | 41 | Scenario: Embedded map structure 42 | Given I have a file "embeddedmap.yml" containing 43 | """ 44 | Fruit: 45 | - Apples: [ red, green ] 46 | - Bananas 47 | - Grapes: [ seeded, seedless ] 48 | Vegetables: 49 | - Beans: [ red, black ] 50 | - Sweet Corn 51 | - Mirleton 52 | """ 53 | When I process "embeddedmap.yml" 54 | Then the output should match JSON 55 | """ 56 | { 57 | "AWSTemplateFormatVersion" : "2010-09-09", 58 | "Fruit": [ 59 | { "Apples": [ "red", "green" ] }, 60 | "Bananas", 61 | { "Grapes": [ "seeded", "seedless" ] } 62 | ], 63 | "Vegetables": [ 64 | { "Beans": [ "red", "black" ] }, 65 | "Sweet Corn", 66 | "Mirleton" 67 | ] 68 | } 69 | """ 70 | -------------------------------------------------------------------------------- /lib/cfoo/file_system.rb: -------------------------------------------------------------------------------- 1 | require 'cfoo/yaml_parser' 2 | 3 | class String 4 | def coordinates_of_index(index) 5 | lines = split("\n") 6 | line_number = 1 7 | column_number = index + 1 8 | lines.each do |line| 9 | if line.length < column_number 10 | line_number += 1 11 | column_number -= line.length 12 | else 13 | return [ line_number, column_number ] 14 | end 15 | end 16 | [ -1, -1 ] 17 | end 18 | end 19 | 20 | module Cfoo 21 | class FileSystem 22 | def initialize(project_root, yaml_parser) 23 | @project_root, @yaml_parser = project_root, yaml_parser 24 | end 25 | 26 | def resolve_file(file_name) 27 | "#{@project_root}/#{file_name}" 28 | end 29 | 30 | def parse_file(file_name) 31 | @yaml_parser.load_file(resolve_file file_name) 32 | end 33 | 34 | def open(file_name, &block) 35 | File.open(resolve_file(file_name), &block) 36 | end 37 | 38 | def find_coordinates(string, file_name) 39 | open(file_name) do |file| 40 | content = file.read 41 | lines = string.split "\n" 42 | patterns = lines.map { |line| Regexp.escape(line) } 43 | pattern = patterns.join '\n\s*' 44 | regex = %r[#{pattern}] 45 | index = regex =~ content 46 | if index.nil? 47 | raise CoordinatesNotFound, "Couldn't find '#{string.inspect}' in '#{file_name}'" 48 | else 49 | content.coordinates_of_index(index) 50 | end 51 | end 52 | end 53 | 54 | def glob_relative(path) 55 | absolute_files = Dir.glob(resolve_file path) 56 | absolute_files.map do |file| 57 | file.gsub(@project_root + '/', '') 58 | end 59 | end 60 | 61 | def list(path) 62 | Dir.glob("#{resolve_file path}/*") 63 | end 64 | end 65 | 66 | class CoordinatesNotFound < StandardError 67 | end 68 | end 69 | -------------------------------------------------------------------------------- /spec/cfoo/cfoo_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Cfoo do 5 | let(:processor) { double('processor') } 6 | let(:renderer) { double('renderer') } 7 | let(:stdout) { double('stdout') } 8 | let(:stderr) { double('stderr') } 9 | let(:cfoo) { Cfoo.new(processor, renderer, stdout, stderr) } 10 | 11 | describe "#process" do 12 | it "processes the specified files" do 13 | output_map = double("output_map") 14 | processor.should_receive(:process).with("1.yml", "2.yml").and_return output_map 15 | renderer.should_receive(:render).with(output_map).and_return "cfn_template" 16 | stdout.should_receive(:puts).with "cfn_template" 17 | cfoo.process("1.yml", "2.yml") 18 | end 19 | 20 | context "when an error is raised" do 21 | it "prints it to stderr" do 22 | error = RuntimeError.new("parse fail") 23 | processor.should_receive(:process).with("1.yml").and_raise error 24 | stderr.should_receive(:puts).with error 25 | cfoo.process("1.yml") 26 | end 27 | end 28 | end 29 | 30 | describe "#build_project" do 31 | # TODO: but it doesn't know about the project! 32 | it "processes all files in the project" do 33 | output_map = double("output_map") 34 | processor.should_receive(:process_all).and_return output_map 35 | renderer.should_receive(:render).with(output_map).and_return "cfn_template" 36 | stdout.should_receive(:puts).with "cfn_template" 37 | cfoo.build_project 38 | end 39 | 40 | context "when an error is raised" do 41 | it "prints it to stderr" do 42 | error = RuntimeError.new("parse fail") 43 | processor.should_receive(:process_all).and_raise error 44 | stderr.should_receive(:puts).with error 45 | cfoo.build_project 46 | end 47 | end 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /features/map_reference_expansion.feature: -------------------------------------------------------------------------------- 1 | Feature: Expand EL Mapping References 2 | As a CloudFormation user 3 | I want to use an expression language as a shorthand for mapping references 4 | So that I my templates are easier to read 5 | 6 | Scenario: Map reference expansion 7 | Given I have a file "outputs.yml" containing 8 | """ 9 | EntryPoint: 10 | Description: IP address of the Bastion Host 11 | Value: $(SubnetConfig[VPC][CIDR]) 12 | """ 13 | When I process "outputs.yml" 14 | Then the output should match JSON 15 | """ 16 | { 17 | "AWSTemplateFormatVersion" : "2010-09-09", 18 | "EntryPoint" : { 19 | "Description" : "IP address of the Bastion Host", 20 | "Value" : { "Fn::FindInMap" : [ "SubnetConfig", "VPC", "CIDR" ]} 21 | } 22 | } 23 | """ 24 | 25 | Scenario: Embedded map reference expansion 26 | Given I have a file "outputs.yml" containing 27 | """ 28 | WebSite: 29 | Description: URL of the website 30 | Value: http://$(Network[Dns][LoadBalancerDnsName])/index.html 31 | """ 32 | When I process "outputs.yml" 33 | Then the output should match JSON 34 | """ 35 | { 36 | "AWSTemplateFormatVersion" : "2010-09-09", 37 | "WebSite" : { 38 | "Description" : "URL of the website", 39 | "Value" : { "Fn::Join" : [ "", [ "http://", { "Fn::FindInMap" : [ "Network", "Dns", "LoadBalancerDnsName" ]}, "/index.html"]]} 40 | } 41 | } 42 | """ 43 | 44 | Scenario: Map key is reference 45 | Given I have a file "nat.yml" containing 46 | """ 47 | Resources: 48 | NATDevice: 49 | Type: AWS::EC2::Instance 50 | Properties: 51 | ImageId: $(AWSNATAMI[$(AWS::Region)][AMI]) 52 | """ 53 | When I process "nat.yml" 54 | Then the output should match JSON 55 | """ 56 | { 57 | "AWSTemplateFormatVersion" : "2010-09-09", 58 | "Resources" : { 59 | "NATDevice" : { 60 | "Type" : "AWS::EC2::Instance", 61 | "Properties" : { 62 | "ImageId" : { "Fn::FindInMap" : [ "AWSNATAMI" , { "Ref" : "AWS::Region" } , "AMI" ] } 63 | } 64 | } 65 | } 66 | } 67 | """ 68 | 69 | -------------------------------------------------------------------------------- /features/step_definitions/cfoo_steps.rb: -------------------------------------------------------------------------------- 1 | require 'fileutils' 2 | require 'json' 3 | include FileUtils 4 | 5 | Given /^I have a project$/ do 6 | end 7 | 8 | Given /^I have a module named "(.*?)"$/ do |module_name| 9 | create_dir "modules/#{module_name}" 10 | end 11 | 12 | Given /^I have a file "(.*?)" containing$/ do |filename, content| 13 | write_file(filename, content) 14 | end 15 | 16 | When /^I process "(.*?)"$/ do |filename| 17 | cfoo.process(filename) 18 | end 19 | 20 | #TODO: can we use varargs? 21 | When /^I process files "(.*?)"(?:(?:,| and) "(.*?)")$/ do |filename_1, filename_2| 22 | cfoo.process(filename_1, filename_2) 23 | end 24 | 25 | When /^I build the project$/ do 26 | cfoo.build_project 27 | end 28 | 29 | Then /^the output should match JSON$/ do |expected_json| 30 | begin 31 | expected = JSON.parse(expected_json) 32 | rescue StandardError => e 33 | puts "Couldn't parse expected ouput as JSON" 34 | raise e 35 | end 36 | begin 37 | actual = JSON.parse(stdout.messages.join "") 38 | rescue StandardError => e 39 | puts "Couldn't parse actual ouput as JSON" 40 | raise e 41 | end 42 | actual.should == expected 43 | end 44 | 45 | Then /^I should see "(.*?)"$/ do |expected_output| 46 | stdout.messages.join("\n").should include expected_output 47 | end 48 | 49 | Then /^I should see an error containing "(.*?)"$/ do |expected_output| 50 | stderr.messages.join("\n").should include expected_output 51 | end 52 | 53 | def write_file(filename, content) 54 | file_fqn = resolve_file(filename) 55 | mkdir_p(File.dirname file_fqn) 56 | File.open(file_fqn, "w") do |file| 57 | file.puts content 58 | end 59 | end 60 | 61 | def create_dir(directory) 62 | mkdir_p(resolve_file(directory)) 63 | end 64 | 65 | def resolve_file(filename) 66 | "#{project_root}/#{filename}" 67 | end 68 | 69 | def cfoo 70 | @cfoo ||= Cfoo::Cfoo.new(processor, renderer, stdout, stderr) 71 | end 72 | 73 | def processor 74 | @processor ||= Cfoo::Processor.new(parser, project) 75 | end 76 | 77 | def parser 78 | @parser ||= Cfoo::Parser.new(file_system) 79 | end 80 | 81 | def renderer 82 | @renderer ||= Cfoo::Renderer.new 83 | end 84 | 85 | def project 86 | @project ||= Cfoo::Project.new(file_system) 87 | end 88 | 89 | def file_system 90 | @file_system ||= Cfoo::FileSystem.new(project_root, Cfoo::YamlParser.new) 91 | end 92 | 93 | def project_root 94 | @project_root ||= "/tmp/cfoo-cucumber-#{$$}" 95 | mkdir_p(@project_root) 96 | @project_root 97 | end 98 | 99 | def stdout 100 | @output ||= Output.new 101 | end 102 | 103 | def stderr 104 | @output ||= Output.new 105 | end 106 | 107 | After do 108 | rm_rf project_root if File.directory? project_root 109 | end 110 | 111 | class Output 112 | def messages 113 | @messages ||= [] 114 | end 115 | 116 | def puts(message) 117 | messages << message 118 | end 119 | end 120 | -------------------------------------------------------------------------------- /lib/cfoo/parser.rb: -------------------------------------------------------------------------------- 1 | require 'cfoo/constants' 2 | require 'cfoo/el_parser' 3 | require 'cfoo/yaml' 4 | require 'rubygems' 5 | require 'parslet' 6 | 7 | module Parslet 8 | class Source 9 | def str 10 | @str 11 | end 12 | end 13 | end 14 | 15 | class Object 16 | def expand_el 17 | raise Cfoo::Parser::ElExpansionError, "Couldn't parse object '#{self}'. I don't know how to parse an instance of '#{self.class}'" 18 | end 19 | end 20 | 21 | class Fixnum 22 | def expand_el 23 | self 24 | end 25 | end 26 | 27 | class FalseClass 28 | def expand_el 29 | to_s 30 | end 31 | end 32 | 33 | class TrueClass 34 | def expand_el 35 | to_s 36 | end 37 | end 38 | 39 | class String 40 | def expand_el 41 | Cfoo::ElParser.parse(self) 42 | end 43 | end 44 | 45 | class Array 46 | def expand_el 47 | map {|element| element.expand_el } 48 | end 49 | end 50 | 51 | class Hash 52 | def expand_el 53 | Hash[map do |key, value| 54 | [ key, value.expand_el ] 55 | end] 56 | end 57 | end 58 | 59 | module YAML 60 | class DomainType 61 | 62 | CLOUDFORMATION_FUNCTION_REGEX = %r[^(#{::Cfoo::CLOUDFORMATION_FUNCTIONS.join '|'})$] 63 | 64 | def expand_el 65 | case type_id 66 | when "Ref" 67 | { "Ref" => value.expand_el } 68 | when "GetAZs" 69 | if value.nil? 70 | { "Fn::GetAZs" => "" } 71 | else 72 | { "Fn::GetAZs" => value.expand_el } 73 | end 74 | when CLOUDFORMATION_FUNCTION_REGEX 75 | { "Fn::#{type_id}" => value.expand_el } 76 | when "Concat" 77 | { "Fn::Join" => ['', value.expand_el] } 78 | else 79 | super 80 | end 81 | end 82 | end 83 | end 84 | 85 | module Cfoo 86 | class Parser 87 | class ParseError < RuntimeError 88 | end 89 | 90 | class CfooParseError < ParseError 91 | attr_reader :file_name, :cause 92 | 93 | def initialize(file_name, failure) 94 | super("Failed to parse '#{file_name}':\n#{failure}") 95 | @file_name = file_name 96 | @cause = cause 97 | end 98 | end 99 | 100 | class ElExpansionError < ParseError 101 | end 102 | 103 | class ElParseError < ParseError 104 | attr_accessor :file_name, :cause, :source, :line, :column 105 | 106 | def initialize(file_name, cause, source, line, column) 107 | super("Failed to parse '#{file_name}':\nLocation: #{file_name} line #{line}, column #{column} \nSource: #{source}\nCause: #{cause.ascii_tree}") 108 | 109 | @file_name = file_name 110 | @cause = cause 111 | @source = source 112 | @line = line 113 | @column = column 114 | end 115 | end 116 | 117 | def initialize(file_system) 118 | @file_system = file_system 119 | end 120 | 121 | def parse_file(file_name) 122 | @file_system.parse_file(file_name).expand_el 123 | rescue Parslet::ParseFailed => failure 124 | #TODO: spec this somehow 125 | cause = failure.cause 126 | source = cause.source.str 127 | row, column = @file_system.find_coordinates(source, file_name) 128 | raise ElParseError.new(file_name, cause, source, row, column) 129 | rescue ElExpansionError => failure 130 | raise failure 131 | rescue Exception => failure 132 | raise CfooParseError.new(file_name, failure) 133 | end 134 | end 135 | end 136 | -------------------------------------------------------------------------------- /spec/cfoo/el_parser_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe ElParser do 5 | let(:parser) { ElParser } 6 | it 'turns simple EL references into CloudFormation "Ref" maps' do 7 | parser.parse("$(orange)").should == {"Ref" => "orange"} 8 | end 9 | 10 | it 'turns simple EL references with dots into CloudFormation "Ref" maps' do 11 | parser.parse("$(orange.color)").should == {"Ref" => "orange.color"} 12 | end 13 | 14 | it 'turns EL references embedded in strings into appended arrays' do 15 | parser.parse("large $(MelonType) melon").should == {"Fn::Join" => [ "" , [ "large ", { "Ref" => "MelonType" }, " melon" ]]} 16 | end 17 | 18 | it 'turns multiple EL references embedded in strings into single appended arrays' do 19 | parser.parse("I have $(number) apples and $(otherNumber) oranges").should == {"Fn::Join" => [ "" , ["I have ", { "Ref" => "number" }, " apples and ", { "Ref" => "otherNumber" }, " oranges" ]]} 20 | end 21 | 22 | it 'turns EL attribute map references into CloudFormation "GetAtt" maps' do 23 | parser.parse("$(apple[color])").should == {"Fn::GetAtt" => ["apple", "color"]} 24 | end 25 | 26 | it 'turns EL attribute map references with dots into CloudFormation "GetAtt" maps' do 27 | parser.parse("$(apple[color.primary])").should == {"Fn::GetAtt" => ["apple", "color.primary"]} 28 | end 29 | 30 | it 'turns EL map references into CloudFormation "FindInMap" maps' do 31 | parser.parse("$(fruit[apple][color])").should == {"Fn::FindInMap" => ["fruit", "apple", "color"]} 32 | end 33 | 34 | context "parsing function calls" do 35 | it 'turns no-arg function calls into "Fn" maps with an empty string as the value' do 36 | parser.parse("$(Fruit())").should == {"Fn::Fruit" => ""} 37 | end 38 | 39 | it 'turns single-arg function calls into "Fn" maps with the string as the value' do 40 | parser.parse("$(Fruit(Favorite))").should == {"Fn::Fruit" => "Favorite"} 41 | end 42 | 43 | it 'turns multi-arg function calls into "Fn" maps with the an array of the arg strings as the value' do 44 | parser.parse("$(Fruit(One, Two, Three))").should == {"Fn::Fruit" => [ "One", "Two", "Three" ]} 45 | end 46 | 47 | it 'copes with no spaces between function arguments' do 48 | parser.parse("$(Fruit(One,Two,Three))").should == {"Fn::Fruit" => [ "One", "Two", "Three" ]} 49 | end 50 | 51 | it 'copes with spaces between around function arguments' do 52 | parser.parse("$(Fruit( One , Two ,Three ))").should == {"Fn::Fruit" => [ "One", "Two", "Three" ]} 53 | end 54 | 55 | it 'copes with EL as arguments' do 56 | parser.parse("$(FindInMap(AWSRegionArch2AMI, $(AWS::Region), $(AWSInstanceType2Arch[FrontendInstanceType][Arch])))"). 57 | should == {"Fn::FindInMap" => ["AWSRegionArch2AMI", {"Ref" => "AWS::Region"}, { "Fn::FindInMap" => ["AWSInstanceType2Arch", "FrontendInstanceType", "Arch"] }]} 58 | end 59 | end 60 | 61 | it "doesn't expand escaped EL" do 62 | parser.parse("\\$(apple.color) apple").should == "$(apple.color) apple" 63 | end 64 | 65 | it "copes with lone backslashes" do 66 | parser.parse("\\ apple").should == "\\ apple" 67 | end 68 | 69 | it "copes with EL in maps" do 70 | parser.parse("$(Fruit[$(AWS::FruitType)][$(FruitProperty)])").should == {"Fn::FindInMap" => ["Fruit", {"Ref" => "AWS::FruitType"}, {"Ref" => "FruitProperty"}]} 71 | end 72 | 73 | it "copes with EL in references" do 74 | parser.parse("$($(appleProperty))").should == {"Ref" => {"Ref" => "appleProperty"}} 75 | end 76 | 77 | it "handles letters, numbers, underscores, and colons in identifiers" do 78 | parser.parse("$(AWS::Hip_2_the_groove_identifier)").should == {"Ref" => "AWS::Hip_2_the_groove_identifier"} 79 | end 80 | end 81 | end 82 | 83 | -------------------------------------------------------------------------------- /lib/cfoo/el_parser.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | require 'parslet' 3 | require 'cfoo/array' 4 | 5 | module Cfoo 6 | class ElParser < Parslet::Parser 7 | 8 | def self.parse(string) 9 | return string if string.empty? 10 | 11 | parser = ElParser.new 12 | transform = ElTransform.new 13 | 14 | tree = parser.parse(string) 15 | transform.apply(tree) 16 | #rescue Parslet::ParseFailed => failure 17 | # #TODO: handle this properly 18 | end 19 | 20 | rule(:space) { match('\s').repeat(1) } 21 | rule(:space?) { space.maybe } 22 | rule(:escaped_dollar) { str('\$').as(:escaped_dollar) } 23 | rule(:lone_backslash) { str('\\').as(:lone_backslash) } 24 | rule(:lparen) { str('(') >> space? } 25 | rule(:rparen) { str(')') } 26 | rule(:lbracket) { str('[') } 27 | rule(:rbracket) { str(']') } 28 | rule(:dot) { str('.') } 29 | rule(:comma) { str(",") >> space? } 30 | rule(:text_character) { match['^\\\\$'] } 31 | rule(:identifier) { match['a-zA-Z0-9._\-:'].repeat(1).as(:identifier) >> space? } 32 | rule(:text) { text_character.repeat(1).as(:text) } 33 | 34 | rule(:attribute_reference) do 35 | ( 36 | expression.as(:reference) >> ( 37 | str("[") >> expression.as(:attribute) >> str("]") 38 | ) 39 | ).as(:attribute_reference) 40 | end 41 | rule(:mapping) do 42 | ( 43 | expression.as(:map) >> 44 | str("[") >> expression.as(:key) >> str("]") >> 45 | str("[") >> expression.as(:value) >> str("]") 46 | ).as(:mapping) 47 | end 48 | rule(:function_call) do 49 | ( 50 | identifier.as(:function) >> 51 | lparen >> 52 | (expression >> (comma >> expression).repeat).as(:arguments).maybe >> 53 | rparen 54 | ).as(:function_call) 55 | end 56 | rule(:reference) do 57 | expression.as(:reference) 58 | end 59 | 60 | rule(:expression) { el | identifier } 61 | rule(:el) do 62 | str("$(") >> ( mapping | attribute_reference | function_call | reference ) >> str(")") 63 | end 64 | rule(:string) do 65 | ( escaped_dollar | lone_backslash | el | text ).repeat.as(:string) 66 | end 67 | 68 | root(:string) 69 | end 70 | 71 | class ElTransform < Parslet::Transform 72 | 73 | rule(:escaped_dollar => simple(:dollar)) { "$" } 74 | rule(:lone_backslash => simple(:backslash)) { "\\" } 75 | 76 | rule(:identifier => simple(:identifier)) do 77 | identifier.str 78 | end 79 | 80 | rule(:text => simple(:text)) do 81 | text.str 82 | end 83 | 84 | rule(:reference => subtree(:reference)) do 85 | { "Ref" => reference } 86 | end 87 | 88 | rule(:attribute_reference => { :reference => subtree(:reference), :attribute => subtree(:attribute)}) do 89 | { "Fn::GetAtt" => [ reference, attribute ] } 90 | end 91 | 92 | rule(:function_call => { :function => simple(:function) }) do 93 | { "Fn::#{function}" => "" } 94 | end 95 | 96 | rule(:function_call => { :function => simple(:function), :arguments => simple(:argument) }) do 97 | { "Fn::#{function}" => argument } 98 | end 99 | 100 | rule(:function_call => { :function => simple(:function), :arguments => subtree(:arguments) }) do 101 | { "Fn::#{function}" => arguments } 102 | end 103 | 104 | rule(:mapping => { :map => subtree(:map), :key => subtree(:key), :value => subtree(:value)}) do 105 | { "Fn::FindInMap" => [map, key, value] } 106 | end 107 | 108 | rule(:string => subtree(:string_parts)) do 109 | # EL is parsed separately from other strings 110 | parts = string_parts.join_adjacent_strings 111 | 112 | if parts.size == 1 113 | parts.first 114 | else 115 | { "Fn::Join" => [ "", parts ] } 116 | end 117 | end 118 | end 119 | end 120 | -------------------------------------------------------------------------------- /features/modules.feature: -------------------------------------------------------------------------------- 1 | Feature: Modules 2 | As a CloudFormation user 3 | I want to split my templates into logical modules 4 | So that I can organise them and share them 5 | 6 | Scenario: Module with a template 7 | Given I have a project 8 | And I have a module named "webapp" 9 | And I have a file "modules/webapp/webapp.yml" containing 10 | """ 11 | Parameters: 12 | FrontendSize: 13 | Type: Integer 14 | Default: 5 15 | Resources: 16 | FrontendFleet: 17 | Type: AWS::AutoScaling::AutoScalingGroup 18 | Properties: 19 | MinSize: 1 20 | MaxSize: 10 21 | """ 22 | When I build the project 23 | Then the output should match JSON 24 | """ 25 | { 26 | "AWSTemplateFormatVersion" : "2010-09-09", 27 | "Parameters" : { 28 | "FrontendSize" : { "Type" : "Integer", "Default" : 5 } 29 | }, 30 | "Resources" : { 31 | "FrontendFleet" : { 32 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 33 | "Properties" : { 34 | "MinSize" : 1, 35 | "MaxSize" : 10 36 | } 37 | } 38 | } 39 | } 40 | """ 41 | 42 | Scenario: Multiple modules get merged 43 | Given I have a project 44 | And I have a module named "webapp" 45 | And I have a file "modules/webapp/webapp.yml" containing 46 | """ 47 | Parameters: 48 | FrontendSize: 49 | Type: Integer 50 | Default: 5 51 | Resources: 52 | FrontendFleet: 53 | Type: AWS::AutoScaling::AutoScalingGroup 54 | Properties: 55 | MinSize: 1 56 | MaxSize: $(FrontendSize) 57 | """ 58 | And I have a module named "database" 59 | And I have a file "modules/database/database.yml" containing 60 | """ 61 | Parameters: 62 | DbName: 63 | Type: String 64 | Default: My Precious 65 | Resources: 66 | MySQLDatabase: 67 | Type: AWS::RDS::DBInstance 68 | Properties: 69 | Engine: MySQL 70 | DBName: $(DbName) 71 | MultiAZ: true 72 | """ 73 | When I build the project 74 | Then the output should match JSON 75 | """ 76 | { 77 | "AWSTemplateFormatVersion" : "2010-09-09", 78 | "Parameters" : { 79 | "FrontendSize" : { "Type" : "Integer", "Default" : 5 }, 80 | "DbName" : { "Type" : "String", "Default" : "My Precious" } 81 | }, 82 | "Resources" : { 83 | "FrontendFleet" : { 84 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 85 | "Properties" : { 86 | "MinSize" : 1, 87 | "MaxSize" : { "Ref" : "FrontendSize" } 88 | } 89 | }, 90 | "MySQLDatabase": { 91 | "Type": "AWS::RDS::DBInstance", 92 | "Properties": { 93 | "Engine" : "MySQL", 94 | "DBName" : { "Ref": "DbName" }, 95 | "MultiAZ" : "true" 96 | } 97 | } 98 | } 99 | } 100 | """ 101 | 102 | -------------------------------------------------------------------------------- /spec/cfoo/file_system_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | module Cfoo 6 | describe FileSystem do 7 | let(:project_root) { "/tmp/#{File.basename(__FILE__)}#{$$}" } 8 | let(:yaml_parser) { double("yaml_parser") } 9 | let(:file_system) { FileSystem.new(project_root, yaml_parser) } 10 | before do 11 | rm_rf project_root 12 | mkdir project_root 13 | end 14 | 15 | after do 16 | rm_rf project_root 17 | end 18 | 19 | describe "#list" do 20 | it "returns full path of files, resolved relative to project root" do 21 | files = %w[a b c].map {|file| File.join(project_root, "modules", file) } 22 | mkdir File.join(project_root, "modules") 23 | touch files 24 | 25 | file_system.list("modules").sort.should == files 26 | end 27 | end 28 | 29 | describe "#open" do 30 | it "opens a file on disk for reading and passes it to the provided block" do 31 | write_project_file "file.txt", "test content" 32 | 33 | actual_content = "block not called" 34 | file_system.open("file.txt") do |file| 35 | actual_content = file.read 36 | end 37 | 38 | actual_content.should include "test content" 39 | end 40 | end 41 | 42 | describe "#find_coordinates" do 43 | it "returns the coordinates of the first match of the specified string in the specified file" do 44 | write_project_file "test.txt", <<-EOF 45 | the quick brown fox 46 | jumps over the lazy 47 | dog 48 | the quick brown fox 49 | jumps over the lazy 50 | dog 51 | EOF 52 | 53 | coordinates = file_system.find_coordinates("lazy", "test.txt") 54 | expect(coordinates).to eq [2,37] 55 | end 56 | it "returns the coordinates of multiline strings" do 57 | write_project_file "test.txt", <<-EOF 58 | the quick brown fox 59 | jumps over the lazy 60 | dog 61 | EOF 62 | 63 | file_system.find_coordinates("lazy\ndog", "test.txt") 64 | end 65 | it "raises an error if it can't find the text" do 66 | write_project_file "test.txt", <<-EOF 67 | the quick brown fox 68 | jumps over the lazy 69 | dog 70 | EOF 71 | 72 | expect { 73 | file_system.find_coordinates("xxxxxx", "test.txt") 74 | }.to raise_error CoordinatesNotFound 75 | end 76 | end 77 | 78 | describe "#glob_relative" do 79 | it "returns relative path of files, resolved relative to project root" do 80 | files = %w[a b c].map {|file| File.join(project_root, "modules", file) } 81 | mkdir File.join(project_root, "modules") 82 | touch files 83 | 84 | relative_files = files.map {|f| f.gsub(project_root + "/", "")} 85 | 86 | file_system.glob_relative("modules/*").sort.should == relative_files 87 | end 88 | it "expands globs" do 89 | files = %w[a.txt b.json c.yml].map {|file| File.join(project_root, "modules", file) } 90 | mkdir File.join(project_root, "modules") 91 | touch files 92 | 93 | file_system.glob_relative("modules/*.yml").should == ["modules/c.yml"] 94 | end 95 | end 96 | 97 | describe "#parse_file" do 98 | it "loads the file with the YAML parser" do 99 | yaml_parser.should_receive(:load_file).with("#{project_root}/yamlfile.yml") 100 | file_system.parse_file("yamlfile.yml") 101 | end 102 | end 103 | 104 | def relative(file) 105 | File.join(project_root, file) 106 | end 107 | 108 | def write(file, content) 109 | File.open(file, "w+") do |f| 110 | f.puts content 111 | end 112 | end 113 | 114 | def write_project_file(file, content) 115 | write(relative(file), content) 116 | end 117 | end 118 | end 119 | -------------------------------------------------------------------------------- /features/function_expansion.feature: -------------------------------------------------------------------------------- 1 | Feature: Expand Function Calls 2 | As a CloudFormation user 3 | I want to use an expression language as a shorthand for function calls 4 | So that I my templates are easier to read 5 | 6 | Scenario: Function with no parameters 7 | Given I have a file "autoscaling_group.yml" containing 8 | """ 9 | WebServerGroup: 10 | Type: AWS::AutoScaling::AutoScalingGroup 11 | Properties: 12 | AvailabilityZones: $(GetAZs()) 13 | """ 14 | When I process "autoscaling_group.yml" 15 | Then the output should match JSON 16 | """ 17 | { 18 | "AWSTemplateFormatVersion" : "2010-09-09", 19 | "WebServerGroup" : { 20 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 21 | "Properties" : { 22 | "AvailabilityZones" : { "Fn::GetAZs" : "" } 23 | } 24 | } 25 | } 26 | """ 27 | 28 | Scenario: Function with one parameter 29 | Given I have a file "autoscaling_group.yml" containing 30 | """ 31 | WebServerGroup: 32 | Type: AWS::AutoScaling::AutoScalingGroup 33 | Properties: 34 | AvailabilityZones: $(GetAZs(us-east-1)) 35 | """ 36 | When I process "autoscaling_group.yml" 37 | Then the output should match JSON 38 | """ 39 | { 40 | "AWSTemplateFormatVersion" : "2010-09-09", 41 | "WebServerGroup" : { 42 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 43 | "Properties" : { 44 | "AvailabilityZones" : { "Fn::GetAZs" : "us-east-1" } 45 | } 46 | } 47 | } 48 | """ 49 | 50 | Scenario: Function with multiple parameters 51 | Given I have a file "autoscaling_group.yml" containing 52 | """ 53 | FrontendFleet: 54 | Type: AWS::AutoScaling::AutoScalingGroup 55 | Properties: 56 | AvailabilityZones: 57 | - $(GetAtt(PrivateSubnet, AvailabilityZone)) 58 | """ 59 | When I process "autoscaling_group.yml" 60 | Then the output should match JSON 61 | """ 62 | { 63 | "AWSTemplateFormatVersion" : "2010-09-09", 64 | "FrontendFleet" : { 65 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 66 | "Properties" : { 67 | "AvailabilityZones" : [{ "Fn::GetAtt" : [ "PrivateSubnet", "AvailabilityZone" ] }] 68 | } 69 | } 70 | } 71 | """ 72 | 73 | Scenario: Function with no spaces between arguments 74 | Given I have a file "autoscaling_group.yml" containing 75 | """ 76 | FrontendFleet: 77 | Type: AWS::AutoScaling::AutoScalingGroup 78 | Properties: 79 | AvailabilityZones: 80 | - $(GetAtt(PrivateSubnet,AvailabilityZone)) 81 | """ 82 | When I process "autoscaling_group.yml" 83 | Then the output should match JSON 84 | """ 85 | { 86 | "AWSTemplateFormatVersion" : "2010-09-09", 87 | "FrontendFleet" : { 88 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 89 | "Properties" : { 90 | "AvailabilityZones" : [{ "Fn::GetAtt" : [ "PrivateSubnet", "AvailabilityZone" ] }] 91 | } 92 | } 93 | } 94 | """ 95 | 96 | Scenario: Function with lots of spaces between and around arguments 97 | Given I have a file "autoscaling_group.yml" containing 98 | """ 99 | FrontendFleet: 100 | Type: AWS::AutoScaling::AutoScalingGroup 101 | Properties: 102 | AvailabilityZones: 103 | - $(GetAtt( PrivateSubnet , AvailabilityZone )) 104 | """ 105 | When I process "autoscaling_group.yml" 106 | Then the output should match JSON 107 | """ 108 | { 109 | "AWSTemplateFormatVersion" : "2010-09-09", 110 | "FrontendFleet" : { 111 | "Type" : "AWS::AutoScaling::AutoScalingGroup", 112 | "Properties" : { 113 | "AvailabilityZones" : [{ "Fn::GetAtt" : [ "PrivateSubnet", "AvailabilityZone" ] }] 114 | } 115 | } 116 | } 117 | """ 118 | 119 | Scenario: Function with embedded EL 120 | Given I have a file "app_servers.yml" containing 121 | """ 122 | AppServerLaunchConfig: 123 | Type: AWS::AutoScaling::LaunchConfiguration 124 | Properties: 125 | ImageId: $(FindInMap(AWSRegionArch2AMI, $(AWS::Region), $(AWSInstanceType2Arch[$(FrontendInstanceType)][Arch]))) 126 | """ 127 | When I process "app_servers.yml" 128 | Then the output should match JSON 129 | """ 130 | { 131 | "AWSTemplateFormatVersion" : "2010-09-09", 132 | "AppServerLaunchConfig" : { 133 | "Type": "AWS::AutoScaling::LaunchConfiguration", 134 | "Properties" : { 135 | "ImageId": { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "FrontendInstanceType" }, "Arch" ] } ] } 136 | } 137 | } 138 | } 139 | """ 140 | -------------------------------------------------------------------------------- /spec/cfoo/yaml_parser_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe YamlParser do 5 | 6 | let(:parser) { YamlParser.new } 7 | let(:working_dir) { "/tmp/#{File.basename(__FILE__)}#{$$}" } 8 | 9 | before do 10 | rm_rf working_dir 11 | mkdir working_dir 12 | end 13 | 14 | after do 15 | rm_rf working_dir 16 | end 17 | 18 | describe "#load_file" do 19 | it "parses a file as YAML" do 20 | write "#{working_dir}/file.yml", "key: value" 21 | 22 | parser.load_file("#{working_dir}/file.yml").should == {"key" => "value"} 23 | end 24 | context "when the YAML contains EL" do 25 | it "parses it with the EL intact" do 26 | write "#{working_dir}/el.yml", "key: [$(value)]" 27 | 28 | parser.load_file("#{working_dir}/el.yml").should == {"key" => ["$(value)"]} 29 | end 30 | end 31 | context "when the YAML is invalid" do 32 | it "raises an error" do 33 | write "#{working_dir}/bad.yml", "key: : value" 34 | 35 | expect {parser.load_file("#{working_dir}/bad.yml")}.to raise_error 36 | end 37 | end 38 | context "when the YAML contains a custom AWS datatype" do 39 | it "wraps references in AWS Ref maps" do 40 | write "#{working_dir}/ref.yml", "!Ref AWS::Region" 41 | 42 | parser.load_file("#{working_dir}/ref.yml").should == YAML::DomainType.create("Ref", "AWS::Region") 43 | end 44 | it "wraps attribute references in AWS GetAtt maps" do 45 | write "#{working_dir}/getatt.yml", "!GetAtt [Object, Property]" 46 | 47 | parser.load_file("#{working_dir}/getatt.yml").should == YAML::DomainType.create("GetAtt", ["Object", "Property"]) 48 | end 49 | it "wraps joins in AWS Join function-calls" do 50 | write "#{working_dir}/join.yml", "!Join ['', [a, b, c]]" 51 | 52 | parser.load_file("#{working_dir}/join.yml").should == YAML::DomainType.create("Join", ["", ["a","b","c"]]) 53 | end 54 | it "wraps splits in AWS Split function-calls" do 55 | write "#{working_dir}/split.yml", "!Split ['|', 'a|b|c']" 56 | 57 | parser.load_file("#{working_dir}/split.yml").should == YAML::DomainType.create("Split", ["|", "a|b|c"]) 58 | end 59 | it "wraps imported value strings in AWS ImportValue function-calls" do 60 | write "#{working_dir}/importvalue.yml", "!ImportValue exportedvaluename" 61 | 62 | parser.load_file("#{working_dir}/importvalue.yml").should == YAML::DomainType.create("ImportValue", "exportedvaluename") 63 | end 64 | it "wraps selects in AWS Select function-calls" do 65 | write "#{working_dir}/select.yml", "!Select [1, [a, b, c]]" 66 | 67 | parser.load_file("#{working_dir}/select.yml").should == YAML::DomainType.create("Select", [1, ["a","b","c"]]) 68 | end 69 | it "wraps concatenations in AWS Join function-calls with empty strings" do 70 | write "#{working_dir}/concat.yml", "!Concat [a, b, c]" 71 | 72 | parser.load_file("#{working_dir}/concat.yml").should == YAML::DomainType.create("Concat", ["a","b","c"]) 73 | end 74 | it "wraps map lookups in AWS FindInMap function-calls" do 75 | write "#{working_dir}/findinmap.yml", "!FindInMap [Map, Key, Value]" 76 | 77 | parser.load_file("#{working_dir}/findinmap.yml").should == YAML::DomainType.create("FindInMap", ["Map", "Key", "Value"]) 78 | end 79 | it "wraps conditions in AWS condition function-calls" do 80 | write "#{working_dir}/findinmap.yml", "!Equals [a, b]" 81 | 82 | parser.load_file("#{working_dir}/findinmap.yml").should == YAML::DomainType.create("Equals", ["a", "b"]) 83 | end 84 | it "wraps base64 strings in AWS Base64 function-calls" do 85 | write "#{working_dir}/base64.yml", "!Base64 myencodedstring" 86 | 87 | parser.load_file("#{working_dir}/base64.yml").should == YAML::DomainType.create("Base64", "myencodedstring") 88 | end 89 | it "converts AZ lookups to GetAZs function-calls" do 90 | write "#{working_dir}/get_azs.yml", "!GetAZs myregion" 91 | 92 | parser.load_file("#{working_dir}/get_azs.yml").should == YAML::DomainType.create("GetAZs", "myregion") 93 | end 94 | it "converts empty AZ lookups to GetAZs function-calls" do 95 | write "#{working_dir}/get_azs_empty.yml", "!GetAZs ''" 96 | 97 | value = YAML.name == "Psych" ? nil : "" 98 | parser.load_file("#{working_dir}/get_azs_empty.yml").should == YAML::DomainType.create("GetAZs", value) 99 | end 100 | end 101 | end 102 | 103 | def write(file, content) 104 | File.open(file, "w+") do |f| 105 | f.puts content 106 | end 107 | end 108 | end 109 | end 110 | 111 | -------------------------------------------------------------------------------- /features/yamly_shortcuts.feature: -------------------------------------------------------------------------------- 1 | Feature: YAMLy shortcuts 2 | I should be able to write standalone (non-embedded) CloudFormation bits using custom YAML datatypes 3 | So that I can have a quick YAMLy way to write them 4 | 5 | Scenario: Reference 6 | Given I have a file "ref.yml" containing 7 | """ 8 | Reference: !Ref AWS::Region 9 | """ 10 | When I process "ref.yml" 11 | Then the output should match JSON 12 | """ 13 | { 14 | "AWSTemplateFormatVersion" : "2010-09-09", 15 | "Reference" : { "Ref" : "AWS::Region" } 16 | } 17 | """ 18 | 19 | Scenario: Attribute 20 | Given I have a file "getatt.yml" containing 21 | """ 22 | Attribute: !GetAtt [ BastionHost, PublicIp ] 23 | """ 24 | When I process "getatt.yml" 25 | Then the output should match JSON 26 | """ 27 | { 28 | "AWSTemplateFormatVersion" : "2010-09-09", 29 | "Attribute" : { "Fn::GetAtt" : [ "BastionHost", "PublicIp" ]} 30 | } 31 | """ 32 | 33 | Scenario: Condition 34 | Given I have a file "cond.yml" containing 35 | """ 36 | Condition: !Equals [ "string a", "string b" ] 37 | """ 38 | When I process "cond.yml" 39 | Then the output should match JSON 40 | """ 41 | { 42 | "AWSTemplateFormatVersion" : "2010-09-09", 43 | "Condition": { "Fn::Equals" : [ "string a", "string b" ]} 44 | } 45 | """ 46 | 47 | Scenario: Join function call 48 | Given I have a file "join.yml" containing 49 | """ 50 | Join: !Join 51 | - "" 52 | - [ "string a", "string b" ] 53 | """ 54 | When I process "join.yml" 55 | Then the output should match JSON 56 | """ 57 | { 58 | "AWSTemplateFormatVersion" : "2010-09-09", 59 | "Join" : { "Fn::Join" : [ "", [ "string a", "string b" ] ]} 60 | } 61 | """ 62 | 63 | Scenario: Split function call 64 | Given I have a file "split.yml" containing 65 | """ 66 | Split: !Split 67 | - "|" 68 | - "a|b|c" 69 | """ 70 | When I process "split.yml" 71 | Then the output should match JSON 72 | """ 73 | { 74 | "AWSTemplateFormatVersion" : "2010-09-09", 75 | "Split" : { "Fn::Split" : [ "|", "a|b|c" ] } 76 | } 77 | """ 78 | 79 | Scenario: Join function call with empty strings 80 | Given I have a file "join.yml" containing 81 | """ 82 | Join: !Concat [ "string a", "string b" ] 83 | """ 84 | When I process "join.yml" 85 | Then the output should match JSON 86 | """ 87 | { 88 | "AWSTemplateFormatVersion" : "2010-09-09", 89 | "Join" : { "Fn::Join" : ["", [ "string a", "string b" ]]} 90 | } 91 | """ 92 | 93 | Scenario: FindInMap lookup 94 | Given I have a file "map.yml" containing 95 | """ 96 | MapLookup: !FindInMap [Map, Key, Value] 97 | """ 98 | When I process "map.yml" 99 | Then the output should match JSON 100 | """ 101 | { 102 | "AWSTemplateFormatVersion" : "2010-09-09", 103 | "MapLookup" : { "Fn::FindInMap" : ["Map", "Key", "Value"] } 104 | } 105 | """ 106 | 107 | Scenario: AZ listing 108 | Given I have a file "map.yml" containing 109 | """ 110 | AvailabilityZones: !GetAZs us-east-1 111 | """ 112 | When I process "map.yml" 113 | Then the output should match JSON 114 | """ 115 | { 116 | "AWSTemplateFormatVersion" : "2010-09-09", 117 | "AvailabilityZones" : { "Fn::GetAZs" : "us-east-1" } 118 | } 119 | """ 120 | 121 | Scenario: AZ listing with empty string 122 | Given I have a file "map.yml" containing 123 | """ 124 | AvailabilityZones: !GetAZs 125 | """ 126 | When I process "map.yml" 127 | Then the output should match JSON 128 | """ 129 | { 130 | "AWSTemplateFormatVersion" : "2010-09-09", 131 | "AvailabilityZones" : { "Fn::GetAZs" : "" } 132 | } 133 | """ 134 | 135 | Scenario: Base64 string 136 | Given I have a file "multistring.yml" containing 137 | """ 138 | mystring: !Base64 | 139 | Some string 140 | across multiple 141 | lines 142 | """ 143 | When I process "multistring.yml" 144 | Then the output should match JSON 145 | """ 146 | { 147 | "AWSTemplateFormatVersion" : "2010-09-09", 148 | "mystring" : { "Fn::Base64" : "Some string\nacross multiple\nlines\n" } 149 | } 150 | """ 151 | 152 | Scenario: Base64 string with embedded EL 153 | Given I have a file "embeddedel.yml" containing 154 | """ 155 | mystring: !Base64 | 156 | Some string 157 | across $(Number) 158 | lines 159 | """ 160 | When I process "embeddedel.yml" 161 | Then the output should match JSON 162 | """ 163 | { 164 | "AWSTemplateFormatVersion" : "2010-09-09", 165 | "mystring" : 166 | { "Fn::Base64" : 167 | { "Fn::Join": [ "", [ 168 | "Some string\nacross ", 169 | { "Ref" : "Number" }, 170 | "\nlines\n" 171 | ] 172 | ] 173 | } 174 | } 175 | } 176 | """ 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cfoo 2 | 3 | [![Build Status](https://travis-ci.org/drrb/cfoo.svg)](https://travis-ci.org/drrb/cfoo) 4 | [![Coverage Status](https://img.shields.io/coveralls/drrb/cfoo.svg)](https://coveralls.io/r/drrb/cfoo) 5 | [![Code Climate](https://img.shields.io/codeclimate/github/drrb/cfoo.svg)](https://codeclimate.com/github/drrb/cfoo) 6 | 7 | [![Gem Version](https://badge.fury.io/rb/cfoo.svg)](https://badge.fury.io/rb/cfoo) 8 | [![Dependency Status](https://gemnasium.com/drrb/cfoo.svg)](https://gemnasium.com/drrb/cfoo) 9 | 10 | Cfoo (pronounced "sifu") lets you write your [CloudFormation](https://aws.amazon.com/cloudformation) 11 | templates [in YAML](#templates), and makes it easier with some [helpers](#shortcuts). 12 | 13 | ## Installation 14 | 15 | Cfoo can be installed as a Ruby Gem 16 | 17 | $ gem install cfoo 18 | 19 | ## Usage 20 | 21 | 1. Write your CloudFormation templates using Cfoo YAML 22 | 23 | 2. Turn your Cfoo templates into normal CloudFormation templates 24 | ```terminal 25 | $ cfoo web-server.template.yml database.template.yml > web-stack.template.json 26 | ``` 27 | 28 | 3. Create your stack with CloudFormation 29 | ```terminal 30 | $ cfn-create-stack --stack-name WebStack -f web-stack.template.json 31 | ``` 32 | 33 | ## Templates 34 | 35 | ### Comparison with standard CloudFormation templates 36 | 37 | Snippet from a CloudFormation template (based on [this example](https://s3.amazonaws.com/cloudformation-templates-us-east-1/Rails_Single_Instance.template)): 38 | 39 | ```json 40 | "Properties": { 41 | "ImageId" : { "Fn::FindInMap" : [ "AWSRegion2AMI", { "Ref" : "AWS::Region" }, "AMI" ] }, 42 | "InstanceType" : { "Ref" : "InstanceType" }, 43 | "SecurityGroups" : [ {"Ref" : "FrontendGroup"} ], 44 | "KeyName" : { "Ref" : "KeyName" }, 45 | "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ 46 | "#!/bin/bash -v\n", 47 | "yum update -y aws-cfn-bootstrap\n", 48 | 49 | "function error_exit\n", 50 | "{\n", 51 | " /opt/aws/bin/cfn-signal -e 1 -r \"$1\" '", { "Ref" : "WaitHandle" }, "'\n", 52 | " exit 1\n", 53 | "}\n", 54 | 55 | "/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackId" }, " -r WebServer ", 56 | " --region ", { "Ref" : "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n", 57 | 58 | "/opt/aws/bin/cfn-signal -e 0 -r \"cfn-init complete\" '", { "Ref" : "WaitHandle" }, "'\n" 59 | ]]}} 60 | } 61 | ``` 62 | 63 | Equivalent Cfoo template snippet: 64 | 65 | ```yaml 66 | Properties: 67 | ImageId : AWSRegion2AMI[$(AWS::Region)][AMI] 68 | InstanceType: $(InstanceType) 69 | SecurityGroups: 70 | - $(FrontendGroup) 71 | KeyName: $(KeyName) 72 | UserData: !Base64 | 73 | #!/bin/bash -v 74 | yum update -y aws-cfn-bootstrap 75 | 76 | function error_exit 77 | { 78 | /opt/aws/bin/cfn-signal -e 1 -r "\$1" '$(WaitHandle)' 79 | exit 1 80 | } 81 | 82 | /opt/aws/bin/cfn-init -s $(AWS::StackId) -r WebServer --region $(AWS::Region) || error_exit 'Failed to run cfn-init' 83 | 84 | /opt/aws/bin/cfn-signal -e 0 -r "cfn-init completed" '$(WaitHandle)' 85 | ``` 86 | 87 | ## Projects 88 | 89 | Using Cfoo, it is possible to split your templates up into logical components that will 90 | combined to form your CloudFormation template. 91 | 92 | First, create a directory in your project directory called `modules`. For each module, 93 | create some Cfoo templates defining the different parts of your app. Your project 94 | structure will look like this: 95 | 96 | ``` 97 | my-web-app 98 | └── modules 99 |    ├── application 100 |    │   ├── app_servers.yml 101 |    │   ├── database.yml 102 |    │   └── public_load_balancer.yml 103 |    ├── instances 104 |    │   └── instance_mappings.yml 105 |    └── network 106 |    ├── bastion.yml 107 |    ├── cfn_user.yml 108 |    ├── dns.yml 109 |    ├── nat.yml 110 |    ├── private_subnet.yml 111 |    ├── public_subnet.yml 112 |    └── vpc.yml 113 | ``` 114 | 115 | Use Cfoo to generate your project's CloudFormation template 116 | 117 | ```terminal 118 | $ cfoo > web-app.template.json 119 | ``` 120 | 121 | ## Shortcuts 122 | 123 | Cfoo allows you to simplify CloudFormation [intrinsic function](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html) 124 | references using its own shorthand 125 | 126 | ##### Reference 127 | 128 | CloudFormation: `{ "Ref" : "InstanceType" }` 129 | 130 | Cfoo Shortcut: `$(InstanceType)` 131 | 132 | ##### Mapping Reference 133 | 134 | CloudFormation: `{ "FindInMap" : [ "SubnetConfig", "VPC", "CIDR" ] }` 135 | 136 | Cfoo Shortcut: `$(SubnetConfig[VPC][CIDR])` 137 | 138 | ##### Attribute Reference 139 | 140 | CloudFormation: `{ "Fn::GetAtt" : [ "Ec2Instance", "PublicIp" ] }` 141 | 142 | Cfoo Shortcut: `$(Ec2Instance[PublicIp])` 143 | 144 | ##### Embedded Reference 145 | 146 | CloudFormation: `{ "Fn::Join" : [ "", [{"Ref" : "HostedZone"}, "." ]]}` 147 | 148 | Cfoo Shortcut: `$(HostedZone).` 149 | 150 | ### YAML Types 151 | 152 | Cfoo gives you the option of using YAML custom data-types where it helps to make your templates easier to read. 153 | 154 | ##### Reference 155 | 156 | CloudFormation: 157 | ```json 158 | { "Ref" : "InstanceType" } 159 | ``` 160 | 161 | YAML Type: 162 | ```yaml 163 | !Ref InstanceType 164 | ``` 165 | 166 | ##### Mapping Reference 167 | 168 | CloudFormation: 169 | ```json 170 | { "FindInMap" : [ "SubnetConfig", "VPC", "CIDR" ] } 171 | ``` 172 | 173 | YAML Type: 174 | ```yaml 175 | !FindInMap [ SubnetConfig, VPC, CIDR ] 176 | ``` 177 | 178 | ##### Attribute Reference 179 | 180 | CloudFormation: 181 | ```json 182 | { "Fn::GetAtt" : [ "Ec2Instance", "PublicIp" ] } 183 | ``` 184 | 185 | YAML Type: 186 | ```yaml 187 | !GetAtt [ Ec2Instance, PublicIp ] 188 | ``` 189 | 190 | ##### Base64 String 191 | 192 | CloudFormation: 193 | ```json 194 | { "Fn::Base64" : "#!/bin/bash\necho 'Running script...'" } 195 | ``` 196 | 197 | YAML Type: 198 | ```yaml 199 | !Base64 "#!/bin/bash\necho 'running script...'" 200 | ``` 201 | 202 | Alternative YAML Type: 203 | ```yaml 204 | !Base64 | 205 | #!/bin/bash 206 | echo 'running script...' 207 | ``` 208 | 209 | ##### Condition Function 210 | 211 | CloudFormation: 212 | ```json 213 | { "Fn::Equals": [ "sg-mysggroup", {"Ref": "ASecurityGroup"} ] }, 214 | ``` 215 | 216 | YAML Type: 217 | ```yaml 218 | !Equals [ "sg-mysggroup", $(ASecurityGroup) ] 219 | ``` 220 | 221 | ## Goals 222 | 223 | ### Primary Goals 224 | 225 | Cfoo aims to let developers simplify CloudFormation templates by: 226 | 227 | - allowing them to write templates in YAML 228 | - providing an expression language to simplify CF Ref/Attr/etc expressions 229 | - allowing templates to be split up into logical components (to simplify and share) 230 | 231 | ### Secondary Goals 232 | 233 | Cfoo also aims (subject to Primary Goals) to: 234 | 235 | - allow inclusion existing JSON templates (so you don't have to switch all at once) 236 | 237 | ### Non-goals 238 | 239 | Cfoo does not (yet) aim to: 240 | 241 | - provide commandline utilities for interacting directly with CloudFormation (it just generates the templates for now) 242 | - resolve/validate references (the CloudFormation API already does this) 243 | 244 | ## Contributing 245 | 246 | 1. Fork it 247 | 2. Create your feature branch (`git checkout -b my-new-feature`) 248 | 3. Make your changes (with tests please) 249 | 4. Commit your changes (`git commit -am 'Add some feature'`) 250 | 5. Push to the branch (`git push origin my-new-feature`) 251 | 6. Create new Pull Request 252 | -------------------------------------------------------------------------------- /spec/cfoo/processor_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Processor do 5 | 6 | let(:parser) { double('parser') } 7 | let(:project) { double('project') } 8 | let(:processor) { Processor.new(parser, project) } 9 | 10 | describe "#process" do 11 | it "parses and merges the specified files" do 12 | parser.should_receive(:parse_file).with("app.yml").and_return({"Resources" => { "AppServer" => { "Type" => "LaunchConfiguration"} } }) 13 | parser.should_receive(:parse_file).with("db.yml").and_return({"Resources" => { "DbServer" => { "Type" => "EC2Instance" } } }) 14 | parser.should_receive(:parse_file).with("network.yml").and_return({"Parameters" => { "LoadBalancerIpAddress" => "10.0.0.51" } }) 15 | processor.process("app.yml", "db.yml", "network.yml").should == { 16 | "AWSTemplateFormatVersion" => "2010-09-09", 17 | "Parameters" => { 18 | "LoadBalancerIpAddress" => "10.0.0.51" 19 | }, 20 | "Resources" => { 21 | "AppServer" => { "Type" => "LaunchConfiguration" }, 22 | "DbServer" => { "Type" => "EC2Instance" } 23 | } 24 | } 25 | end 26 | context "when there's a duplicate resource definition" do 27 | it "merges them" do 28 | parser.should_receive(:parse_file).with("app.yml").and_return( 29 | "Resources" => { 30 | "FrontendFleet" => { 31 | "Type" => "AutoScalingGroup" 32 | } 33 | } 34 | ) 35 | parser.should_receive(:parse_file).with("app_extra.yml").and_return( 36 | "Resources" => { 37 | "FrontendFleet" => { 38 | "LoadBalancerNames" => [ "load balancer" ] 39 | } 40 | } 41 | ) 42 | processor.process("app.yml", "app_extra.yml").should == { 43 | "AWSTemplateFormatVersion" => "2010-09-09", 44 | "Resources" => { 45 | "FrontendFleet" => { 46 | "Type" => "AutoScalingGroup", 47 | "LoadBalancerNames" => [ "load balancer" ] 48 | } 49 | } 50 | } 51 | end 52 | context "when the resources both define the same property" do 53 | it "replaces strings" do 54 | parser.should_receive(:parse_file).with("app.yml").and_return( 55 | "Resources" => { 56 | "WebApp" => { 57 | "Type" => "Ec2Instance" 58 | } 59 | } 60 | ) 61 | parser.should_receive(:parse_file).with("app_extra.yml").and_return( 62 | "Resources" => { 63 | "WebApp" => { 64 | "Type" => "LaunchConfiguration" 65 | } 66 | } 67 | ) 68 | processor.process("app.yml", "app_extra.yml").should == { 69 | "AWSTemplateFormatVersion" => "2010-09-09", 70 | "Resources" => { 71 | "WebApp" => { 72 | "Type" => "LaunchConfiguration" 73 | } 74 | } 75 | } 76 | end 77 | it "merges arrays" do 78 | parser.should_receive(:parse_file).with("app.yml").and_return( 79 | "Resources" => { 80 | "FrontendFleet" => { 81 | "LoadBalancerNames" => [ "load balancer A" ] 82 | } 83 | } 84 | ) 85 | parser.should_receive(:parse_file).with("app_extra.yml").and_return( 86 | "Resources" => { 87 | "FrontendFleet" => { 88 | "LoadBalancerNames" => [ "load balancer B" ] 89 | } 90 | } 91 | ) 92 | processor.process("app.yml", "app_extra.yml").should == { 93 | "AWSTemplateFormatVersion" => "2010-09-09", 94 | "Resources" => { 95 | "FrontendFleet" => { 96 | "LoadBalancerNames" => [ "load balancer A", "load balancer B" ] 97 | } 98 | } 99 | } 100 | end 101 | it "merges maps" do 102 | parser.should_receive(:parse_file).with("app.yml").and_return( 103 | "Resources" => { 104 | "FrontendFleet" => { 105 | "Properties" => { 106 | "LoadBalancerNames" => [ "load balancer A" ] 107 | } 108 | } 109 | } 110 | ) 111 | parser.should_receive(:parse_file).with("app_extra.yml").and_return( 112 | "Resources" => { 113 | "FrontendFleet" => { 114 | "Properties" => { 115 | "MinSize" => "1" 116 | } 117 | } 118 | } 119 | ) 120 | processor.process("app.yml", "app_extra.yml").should == { 121 | "AWSTemplateFormatVersion" => "2010-09-09", 122 | "Resources" => { 123 | "FrontendFleet" => { 124 | "Properties" => { 125 | "LoadBalancerNames" => [ "load balancer A" ], 126 | "MinSize" => "1" 127 | } 128 | } 129 | } 130 | } 131 | end 132 | end 133 | end 134 | end 135 | 136 | describe "#process_all" do 137 | it "processes all modules" do 138 | modules = [ double("module0"), double("module1") ] 139 | project.should_receive(:modules).and_return(modules) 140 | modules[0].should_receive(:files).and_return ["app.yml", "db.yml"] 141 | modules[1].should_receive(:files).and_return ["network.yml"] 142 | parser.should_receive(:parse_file).with("app.yml").and_return({"Resources" => { "AppServer" => { "Type" => "EC2Instance" } } }) 143 | parser.should_receive(:parse_file).with("db.yml").and_return({"Resources" => { "DbServer" => { "Type" => "EC2Instance" } } }) 144 | parser.should_receive(:parse_file).with("network.yml").and_return({"Parameters" => { "LoadBalancerIpAddress" => "10.0.0.51" } }) 145 | 146 | processor.process_all.should == { 147 | "AWSTemplateFormatVersion" => "2010-09-09", 148 | "Parameters" => { 149 | "LoadBalancerIpAddress" => "10.0.0.51" 150 | }, 151 | "Resources" => { 152 | "AppServer" => { "Type" => "EC2Instance" }, 153 | "DbServer" => { "Type" => "EC2Instance" } 154 | } 155 | } 156 | end 157 | end 158 | end 159 | end 160 | 161 | -------------------------------------------------------------------------------- /spec/cfoo/parser_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | module Cfoo 4 | describe Parser do 5 | let(:file_system) { double('file_system') } 6 | let(:parser) { Parser.new(file_system) } 7 | 8 | describe "#parse_file" do 9 | context "when parsing fails" do 10 | it "raises an error" do 11 | file_system.should_receive(:parse_file).and_raise "parsing failed" 12 | expect { parser.parse_file("myfile.yml") }.to raise_error Parser::CfooParseError, "Failed to parse 'myfile.yml':\nparsing failed" 13 | end 14 | end 15 | 16 | context "when processing a normal array" do 17 | it "returns it" do 18 | file_system.should_receive(:parse_file).with("myfile.yml").and_return([1, 2, 3]) 19 | parser.parse_file("myfile.yml").should == [1, 2, 3] 20 | end 21 | end 22 | 23 | context "when processing a normal map" do 24 | it "returns it" do 25 | file_system.should_receive(:parse_file).with("myfile.yml").and_return({"a" => "b"}) 26 | parser.parse_file("myfile.yml").should == { "a" => "b" } 27 | end 28 | end 29 | 30 | context "when parsing integer literals" do 31 | it "returns them" do 32 | file_system.should_receive(:parse_file).with("myfile.yml").and_return(1) 33 | parser.parse_file("myfile.yml").should == 1 34 | end 35 | end 36 | 37 | context "when parsing boolean literals" do 38 | it "turns false into a string" do 39 | file_system.should_receive(:parse_file).with("myfile.yml").and_return(false) 40 | parser.parse_file("myfile.yml").should == "false" 41 | end 42 | it "turns true into a string" do 43 | file_system.should_receive(:parse_file).with("myfile.yml").and_return(true) 44 | parser.parse_file("myfile.yml").should == "true" 45 | end 46 | end 47 | 48 | context "when parsing a string" do 49 | it 'turns simple EL references into CloudFormation "Ref" maps' do 50 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("$(orange)") 51 | parser.parse_file("myfile.yml").should == {"Ref" => "orange"} 52 | end 53 | 54 | it 'turns simple EL references with dots into CloudFormation "Ref" maps' do 55 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("$(orange.color)") 56 | parser.parse_file("myfile.yml").should == {"Ref" => "orange.color"} 57 | end 58 | 59 | it 'turns EL references embedded in strings into appended arrays' do 60 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("large $(MelonType) melon") 61 | parser.parse_file("myfile.yml").should == {"Fn::Join" => [ "", [ "large ", { "Ref" => "MelonType" }, " melon" ] ] } 62 | end 63 | 64 | it 'turns multiple EL references embedded in strings into single appended arrays' do 65 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("$(apples) and $(oranges)") 66 | expected = {"Fn::Join" => [ "", [ { "Ref" => "apples" }, " and ", { "Ref" => "oranges" } ] ] } 67 | parser.parse_file("myfile.yml").should == expected 68 | end 69 | 70 | it 'turns EL attribute references into CloudFormation "GetAtt" maps' do 71 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("$(apple[color])") 72 | parser.parse_file("myfile.yml").should == {"Fn::GetAtt" => ["apple", "color"]} 73 | end 74 | 75 | it 'turns EL attribute references with dots into CloudFormation "GetAtt" maps' do 76 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("$(apple[color.primary])") 77 | parser.parse_file("myfile.yml").should == {"Fn::GetAtt" => ["apple", "color.primary"]} 78 | end 79 | 80 | it 'turns EL map references into CloudFormation "FindInMap" maps' do 81 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("$(fruit[apple][color])") 82 | parser.parse_file("myfile.yml").should == {"Fn::FindInMap" => ["fruit", "apple", "color"]} 83 | end 84 | 85 | it 'leaves escaped EL alone' do 86 | file_system.should_receive(:parse_file).with("myfile.yml").and_return("\\$(apple.color) apple") 87 | parser.parse_file("myfile.yml").should == "$(apple.color) apple" 88 | end 89 | end 90 | 91 | context "when parsing a YAML::PrivateType" do 92 | it "wraps references in AWS Ref maps" do 93 | file_system.should_receive(:parse_file).with("ref.yml").and_return(YAML::DomainType.create("Ref", "AWS::Region")) 94 | parser.parse_file("ref.yml").should == {"Ref" => "AWS::Region" } 95 | end 96 | it "wraps attribute references in AWS GetAtt maps" do 97 | file_system.should_receive(:parse_file).with("getattr.yml").and_return(YAML::DomainType.create("GetAtt", ["Object", "Property"])) 98 | 99 | parser.parse_file("getattr.yml").should == {"Fn::GetAtt" => [ "Object", "Property" ] } 100 | end 101 | it "wraps joins in AWS Join function-calls" do 102 | file_system.should_receive(:parse_file).with("join.yml").and_return(YAML::DomainType.create("Join", ['', ["a","b","c"]])) 103 | 104 | parser.parse_file("join.yml").should == {"Fn::Join" => [ "" , [ "a", "b", "c" ] ] } 105 | end 106 | it "wraps concatenations in AWS Join function-calls with empty strings" do 107 | file_system.should_receive(:parse_file).with("join.yml").and_return(YAML::DomainType.create("Concat", ["a","b","c"])) 108 | 109 | parser.parse_file("join.yml").should == {"Fn::Join" => [ "" , [ "a", "b", "c" ] ] } 110 | end 111 | it "wraps splits in AWS Split function-calls" do 112 | file_system.should_receive(:parse_file).with("split.yml").and_return(YAML::DomainType.create("Split", ["|", "a|b|c"])) 113 | 114 | parser.parse_file("split.yml").should == {"Fn::Split" => [ "|" , "a|b|c" ] } 115 | end 116 | it "wraps map lookups in AWS FindInMap function-calls" do 117 | file_system.should_receive(:parse_file).with("findinmap.yml").and_return(YAML::DomainType.create("FindInMap", ["Map", "Key", "Value"])) 118 | 119 | parser.parse_file("findinmap.yml").should == {"Fn::FindInMap" => [ "Map", "Key", "Value" ] } 120 | end 121 | it "wraps AZ lookups in AWS GetAZs function-calls" do 122 | file_system.should_receive(:parse_file).with("az.yml").and_return(YAML::DomainType.create("GetAZs", "us-east-1")) 123 | 124 | parser.parse_file("az.yml").should == {"Fn::GetAZs" => "us-east-1"} 125 | end 126 | it "wraps base64 strings in AWS Base64 function-calls" do 127 | file_system.should_receive(:parse_file).with("b64.yml").and_return(YAML::DomainType.create("Base64", "myencodedstring")) 128 | 129 | parser.parse_file("b64.yml").should == {"Fn::Base64" => "myencodedstring"} 130 | end 131 | it "raises an error when finding other (unknown) domain types" do 132 | file_system.should_receive(:parse_file).with("domaintype.yml").and_return(YAML::DomainType.create("Unknown type", "unknowntypecontent")) 133 | 134 | expect {parser.parse_file("domaintype.yml")}.to raise_error /Couldn't parse object/ 135 | end 136 | end 137 | 138 | context "in an array" do 139 | it "expands elements' EL" do 140 | file_system.should_receive(:parse_file).with("myfile.yml").and_return [ "$(orange)" ] 141 | parser.parse_file("myfile.yml").should == [{"Ref" => "orange"}] 142 | end 143 | end 144 | 145 | context "in a map" do 146 | it "expands values' EL" do 147 | file_system.should_receive(:parse_file).with("myfile.yml").and_return({ "IpAddress" => "$(IpAddress)" }) 148 | parser.parse_file("myfile.yml").should == {"IpAddress" => { "Ref" => "IpAddress"}} 149 | end 150 | end 151 | 152 | context "in a complex data structure" do 153 | it "expands EL deeply" do 154 | input_map = { 155 | "AvailabilityZones" => ["$(PublicSubnetAz)"], 156 | "URLs" => ["http://$(Hostname)/index.html"] 157 | } 158 | expected_output = { 159 | "AvailabilityZones" => [ {"Ref" => "PublicSubnetAz"}], 160 | "URLs" => [{"Fn::Join" => [ "", [ "http://", { "Ref" => "Hostname" }, "/index.html" ] ] }] 161 | } 162 | file_system.should_receive(:parse_file).with("myfile.yml").and_return(input_map) 163 | parser.parse_file("myfile.yml").should == expected_output 164 | end 165 | end 166 | 167 | context "when presented with an unknown object" do 168 | it "raises an error" do 169 | file_system.should_receive(:parse_file).with("myfile.yml").and_return(/a regex/) 170 | expect {parser.parse_file("myfile.yml")}.to raise_error Parser::ElExpansionError 171 | end 172 | end 173 | end 174 | end 175 | end 176 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 drrb 2 | 3 | GNU GENERAL PUBLIC LICENSE 4 | Version 3, 29 June 2007 5 | 6 | Copyright (C) 2007 Free Software Foundation, Inc. 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for 13 | software and other kinds of works. 14 | 15 | The licenses for most software and other practical works are designed 16 | to take away your freedom to share and change the works. By contrast, 17 | the GNU General Public License is intended to guarantee your freedom to 18 | share and change all versions of a program--to make sure it remains free 19 | software for all its users. We, the Free Software Foundation, use the 20 | GNU General Public License for most of our software; it applies also to 21 | any other work released this way by its authors. You can apply it to 22 | your programs, too. 23 | 24 | When we speak of free software, we are referring to freedom, not 25 | price. Our General Public Licenses are designed to make sure that you 26 | have the freedom to distribute copies of free software (and charge for 27 | them if you wish), that you receive source code or can get it if you 28 | want it, that you can change the software or use pieces of it in new 29 | free programs, and that you know you can do these things. 30 | 31 | To protect your rights, we need to prevent others from denying you 32 | these rights or asking you to surrender the rights. Therefore, you have 33 | certain responsibilities if you distribute copies of the software, or if 34 | you modify it: responsibilities to respect the freedom of others. 35 | 36 | For example, if you distribute copies of such a program, whether 37 | gratis or for a fee, you must pass on to the recipients the same 38 | freedoms that you received. You must make sure that they, too, receive 39 | or can get the source code. And you must show them these terms so they 40 | know their rights. 41 | 42 | Developers that use the GNU GPL protect your rights with two steps: 43 | (1) assert copyright on the software, and (2) offer you this License 44 | giving you legal permission to copy, distribute and/or modify it. 45 | 46 | For the developers' and authors' protection, the GPL clearly explains 47 | that there is no warranty for this free software. For both users' and 48 | authors' sake, the GPL requires that modified versions be marked as 49 | changed, so that their problems will not be attributed erroneously to 50 | authors of previous versions. 51 | 52 | Some devices are designed to deny users access to install or run 53 | modified versions of the software inside them, although the manufacturer 54 | can do so. This is fundamentally incompatible with the aim of 55 | protecting users' freedom to change the software. The systematic 56 | pattern of such abuse occurs in the area of products for individuals to 57 | use, which is precisely where it is most unacceptable. Therefore, we 58 | have designed this version of the GPL to prohibit the practice for those 59 | products. If such problems arise substantially in other domains, we 60 | stand ready to extend this provision to those domains in future versions 61 | of the GPL, as needed to protect the freedom of users. 62 | 63 | Finally, every program is threatened constantly by software patents. 64 | States should not allow patents to restrict development and use of 65 | software on general-purpose computers, but in those that do, we wish to 66 | avoid the special danger that patents applied to a free program could 67 | make it effectively proprietary. To prevent this, the GPL assures that 68 | patents cannot be used to render the program non-free. 69 | 70 | The precise terms and conditions for copying, distribution and 71 | modification follow. 72 | 73 | TERMS AND CONDITIONS 74 | 75 | 0. Definitions. 76 | 77 | "This License" refers to version 3 of the GNU General Public License. 78 | 79 | "Copyright" also means copyright-like laws that apply to other kinds of 80 | works, such as semiconductor masks. 81 | 82 | "The Program" refers to any copyrightable work licensed under this 83 | License. Each licensee is addressed as "you". "Licensees" and 84 | "recipients" may be individuals or organizations. 85 | 86 | To "modify" a work means to copy from or adapt all or part of the work 87 | in a fashion requiring copyright permission, other than the making of an 88 | exact copy. The resulting work is called a "modified version" of the 89 | earlier work or a work "based on" the earlier work. 90 | 91 | A "covered work" means either the unmodified Program or a work based 92 | on the Program. 93 | 94 | To "propagate" a work means to do anything with it that, without 95 | permission, would make you directly or secondarily liable for 96 | infringement under applicable copyright law, except executing it on a 97 | computer or modifying a private copy. Propagation includes copying, 98 | distribution (with or without modification), making available to the 99 | public, and in some countries other activities as well. 100 | 101 | To "convey" a work means any kind of propagation that enables other 102 | parties to make or receive copies. Mere interaction with a user through 103 | a computer network, with no transfer of a copy, is not conveying. 104 | 105 | An interactive user interface displays "Appropriate Legal Notices" 106 | to the extent that it includes a convenient and prominently visible 107 | feature that (1) displays an appropriate copyright notice, and (2) 108 | tells the user that there is no warranty for the work (except to the 109 | extent that warranties are provided), that licensees may convey the 110 | work under this License, and how to view a copy of this License. If 111 | the interface presents a list of user commands or options, such as a 112 | menu, a prominent item in the list meets this criterion. 113 | 114 | 1. Source Code. 115 | 116 | The "source code" for a work means the preferred form of the work 117 | for making modifications to it. "Object code" means any non-source 118 | form of a work. 119 | 120 | A "Standard Interface" means an interface that either is an official 121 | standard defined by a recognized standards body, or, in the case of 122 | interfaces specified for a particular programming language, one that 123 | is widely used among developers working in that language. 124 | 125 | The "System Libraries" of an executable work include anything, other 126 | than the work as a whole, that (a) is included in the normal form of 127 | packaging a Major Component, but which is not part of that Major 128 | Component, and (b) serves only to enable use of the work with that 129 | Major Component, or to implement a Standard Interface for which an 130 | implementation is available to the public in source code form. A 131 | "Major Component", in this context, means a major essential component 132 | (kernel, window system, and so on) of the specific operating system 133 | (if any) on which the executable work runs, or a compiler used to 134 | produce the work, or an object code interpreter used to run it. 135 | 136 | The "Corresponding Source" for a work in object code form means all 137 | the source code needed to generate, install, and (for an executable 138 | work) run the object code and to modify the work, including scripts to 139 | control those activities. However, it does not include the work's 140 | System Libraries, or general-purpose tools or generally available free 141 | programs which are used unmodified in performing those activities but 142 | which are not part of the work. For example, Corresponding Source 143 | includes interface definition files associated with source files for 144 | the work, and the source code for shared libraries and dynamically 145 | linked subprograms that the work is specifically designed to require, 146 | such as by intimate data communication or control flow between those 147 | subprograms and other parts of the work. 148 | 149 | The Corresponding Source need not include anything that users 150 | can regenerate automatically from other parts of the Corresponding 151 | Source. 152 | 153 | The Corresponding Source for a work in source code form is that 154 | same work. 155 | 156 | 2. Basic Permissions. 157 | 158 | All rights granted under this License are granted for the term of 159 | copyright on the Program, and are irrevocable provided the stated 160 | conditions are met. This License explicitly affirms your unlimited 161 | permission to run the unmodified Program. The output from running a 162 | covered work is covered by this License only if the output, given its 163 | content, constitutes a covered work. This License acknowledges your 164 | rights of fair use or other equivalent, as provided by copyright law. 165 | 166 | You may make, run and propagate covered works that you do not 167 | convey, without conditions so long as your license otherwise remains 168 | in force. You may convey covered works to others for the sole purpose 169 | of having them make modifications exclusively for you, or provide you 170 | with facilities for running those works, provided that you comply with 171 | the terms of this License in conveying all material for which you do 172 | not control copyright. Those thus making or running the covered works 173 | for you must do so exclusively on your behalf, under your direction 174 | and control, on terms that prohibit them from making any copies of 175 | your copyrighted material outside their relationship with you. 176 | 177 | Conveying under any other circumstances is permitted solely under 178 | the conditions stated below. Sublicensing is not allowed; section 10 179 | makes it unnecessary. 180 | 181 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 182 | 183 | No covered work shall be deemed part of an effective technological 184 | measure under any applicable law fulfilling obligations under article 185 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 186 | similar laws prohibiting or restricting circumvention of such 187 | measures. 188 | 189 | When you convey a covered work, you waive any legal power to forbid 190 | circumvention of technological measures to the extent such circumvention 191 | is effected by exercising rights under this License with respect to 192 | the covered work, and you disclaim any intention to limit operation or 193 | modification of the work as a means of enforcing, against the work's 194 | users, your or third parties' legal rights to forbid circumvention of 195 | technological measures. 196 | 197 | 4. Conveying Verbatim Copies. 198 | 199 | You may convey verbatim copies of the Program's source code as you 200 | receive it, in any medium, provided that you conspicuously and 201 | appropriately publish on each copy an appropriate copyright notice; 202 | keep intact all notices stating that this License and any 203 | non-permissive terms added in accord with section 7 apply to the code; 204 | keep intact all notices of the absence of any warranty; and give all 205 | recipients a copy of this License along with the Program. 206 | 207 | You may charge any price or no price for each copy that you convey, 208 | and you may offer support or warranty protection for a fee. 209 | 210 | 5. Conveying Modified Source Versions. 211 | 212 | You may convey a work based on the Program, or the modifications to 213 | produce it from the Program, in the form of source code under the 214 | terms of section 4, provided that you also meet all of these conditions: 215 | 216 | a) The work must carry prominent notices stating that you modified 217 | it, and giving a relevant date. 218 | 219 | b) The work must carry prominent notices stating that it is 220 | released under this License and any conditions added under section 221 | 7. This requirement modifies the requirement in section 4 to 222 | "keep intact all notices". 223 | 224 | c) You must license the entire work, as a whole, under this 225 | License to anyone who comes into possession of a copy. This 226 | License will therefore apply, along with any applicable section 7 227 | additional terms, to the whole of the work, and all its parts, 228 | regardless of how they are packaged. This License gives no 229 | permission to license the work in any other way, but it does not 230 | invalidate such permission if you have separately received it. 231 | 232 | d) If the work has interactive user interfaces, each must display 233 | Appropriate Legal Notices; however, if the Program has interactive 234 | interfaces that do not display Appropriate Legal Notices, your 235 | work need not make them do so. 236 | 237 | A compilation of a covered work with other separate and independent 238 | works, which are not by their nature extensions of the covered work, 239 | and which are not combined with it such as to form a larger program, 240 | in or on a volume of a storage or distribution medium, is called an 241 | "aggregate" if the compilation and its resulting copyright are not 242 | used to limit the access or legal rights of the compilation's users 243 | beyond what the individual works permit. Inclusion of a covered work 244 | in an aggregate does not cause this License to apply to the other 245 | parts of the aggregate. 246 | 247 | 6. Conveying Non-Source Forms. 248 | 249 | You may convey a covered work in object code form under the terms 250 | of sections 4 and 5, provided that you also convey the 251 | machine-readable Corresponding Source under the terms of this License, 252 | in one of these ways: 253 | 254 | a) Convey the object code in, or embodied in, a physical product 255 | (including a physical distribution medium), accompanied by the 256 | Corresponding Source fixed on a durable physical medium 257 | customarily used for software interchange. 258 | 259 | b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the 269 | Corresponding Source from a network server at no charge. 270 | 271 | c) Convey individual copies of the object code with a copy of the 272 | written offer to provide the Corresponding Source. This 273 | alternative is allowed only occasionally and noncommercially, and 274 | only if you received the object code with such an offer, in accord 275 | with subsection 6b. 276 | 277 | d) Convey the object code by offering access from a designated 278 | place (gratis or for a charge), and offer equivalent access to the 279 | Corresponding Source in the same way through the same place at no 280 | further charge. You need not require recipients to copy the 281 | Corresponding Source along with the object code. If the place to 282 | copy the object code is a network server, the Corresponding Source 283 | may be on a different server (operated by you or a third party) 284 | that supports equivalent copying facilities, provided you maintain 285 | clear directions next to the object code saying where to find the 286 | Corresponding Source. Regardless of what server hosts the 287 | Corresponding Source, you remain obligated to ensure that it is 288 | available for as long as needed to satisfy these requirements. 289 | 290 | e) Convey the object code using peer-to-peer transmission, provided 291 | you inform other peers where the object code and Corresponding 292 | Source of the work are being offered to the general public at no 293 | charge under subsection 6d. 294 | 295 | A separable portion of the object code, whose source code is excluded 296 | from the Corresponding Source as a System Library, need not be 297 | included in conveying the object code work. 298 | 299 | A "User Product" is either (1) a "consumer product", which means any 300 | tangible personal property which is normally used for personal, family, 301 | or household purposes, or (2) anything designed or sold for incorporation 302 | into a dwelling. In determining whether a product is a consumer product, 303 | doubtful cases shall be resolved in favor of coverage. For a particular 304 | product received by a particular user, "normally used" refers to a 305 | typical or common use of that class of product, regardless of the status 306 | of the particular user or of the way in which the particular user 307 | actually uses, or expects or is expected to use, the product. A product 308 | is a consumer product regardless of whether the product has substantial 309 | commercial, industrial or non-consumer uses, unless such uses represent 310 | the only significant mode of use of the product. 311 | 312 | "Installation Information" for a User Product means any methods, 313 | procedures, authorization keys, or other information required to install 314 | and execute modified versions of a covered work in that User Product from 315 | a modified version of its Corresponding Source. The information must 316 | suffice to ensure that the continued functioning of the modified object 317 | code is in no case prevented or interfered with solely because 318 | modification has been made. 319 | 320 | If you convey an object code work under this section in, or with, or 321 | specifically for use in, a User Product, and the conveying occurs as 322 | part of a transaction in which the right of possession and use of the 323 | User Product is transferred to the recipient in perpetuity or for a 324 | fixed term (regardless of how the transaction is characterized), the 325 | Corresponding Source conveyed under this section must be accompanied 326 | by the Installation Information. But this requirement does not apply 327 | if neither you nor any third party retains the ability to install 328 | modified object code on the User Product (for example, the work has 329 | been installed in ROM). 330 | 331 | The requirement to provide Installation Information does not include a 332 | requirement to continue to provide support service, warranty, or updates 333 | for a work that has been modified or installed by the recipient, or for 334 | the User Product in which it has been modified or installed. Access to a 335 | network may be denied when the modification itself materially and 336 | adversely affects the operation of the network or violates the rules and 337 | protocols for communication across the network. 338 | 339 | Corresponding Source conveyed, and Installation Information provided, 340 | in accord with this section must be in a format that is publicly 341 | documented (and with an implementation available to the public in 342 | source code form), and must require no special password or key for 343 | unpacking, reading or copying. 344 | 345 | 7. Additional Terms. 346 | 347 | "Additional permissions" are terms that supplement the terms of this 348 | License by making exceptions from one or more of its conditions. 349 | Additional permissions that are applicable to the entire Program shall 350 | be treated as though they were included in this License, to the extent 351 | that they are valid under applicable law. If additional permissions 352 | apply only to part of the Program, that part may be used separately 353 | under those permissions, but the entire Program remains governed by 354 | this License without regard to the additional permissions. 355 | 356 | When you convey a copy of a covered work, you may at your option 357 | remove any additional permissions from that copy, or from any part of 358 | it. (Additional permissions may be written to require their own 359 | removal in certain cases when you modify the work.) You may place 360 | additional permissions on material, added by you to a covered work, 361 | for which you have or can give appropriate copyright permission. 362 | 363 | Notwithstanding any other provision of this License, for material you 364 | add to a covered work, you may (if authorized by the copyright holders of 365 | that material) supplement the terms of this License with terms: 366 | 367 | a) Disclaiming warranty or limiting liability differently from the 368 | terms of sections 15 and 16 of this License; or 369 | 370 | b) Requiring preservation of specified reasonable legal notices or 371 | author attributions in that material or in the Appropriate Legal 372 | Notices displayed by works containing it; or 373 | 374 | c) Prohibiting misrepresentation of the origin of that material, or 375 | requiring that modified versions of such material be marked in 376 | reasonable ways as different from the original version; or 377 | 378 | d) Limiting the use for publicity purposes of names of licensors or 379 | authors of the material; or 380 | 381 | e) Declining to grant rights under trademark law for use of some 382 | trade names, trademarks, or service marks; or 383 | 384 | f) Requiring indemnification of licensors and authors of that 385 | material by anyone who conveys the material (or modified versions of 386 | it) with contractual assumptions of liability to the recipient, for 387 | any liability that these contractual assumptions directly impose on 388 | those licensors and authors. 389 | 390 | All other non-permissive additional terms are considered "further 391 | restrictions" within the meaning of section 10. If the Program as you 392 | received it, or any part of it, contains a notice stating that it is 393 | governed by this License along with a term that is a further 394 | restriction, you may remove that term. If a license document contains 395 | a further restriction but permits relicensing or conveying under this 396 | License, you may add to a covered work material governed by the terms 397 | of that license document, provided that the further restriction does 398 | not survive such relicensing or conveying. 399 | 400 | If you add terms to a covered work in accord with this section, you 401 | must place, in the relevant source files, a statement of the 402 | additional terms that apply to those files, or a notice indicating 403 | where to find the applicable terms. 404 | 405 | Additional terms, permissive or non-permissive, may be stated in the 406 | form of a separately written license, or stated as exceptions; 407 | the above requirements apply either way. 408 | 409 | 8. Termination. 410 | 411 | You may not propagate or modify a covered work except as expressly 412 | provided under this License. Any attempt otherwise to propagate or 413 | modify it is void, and will automatically terminate your rights under 414 | this License (including any patent licenses granted under the third 415 | paragraph of section 11). 416 | 417 | However, if you cease all violation of this License, then your 418 | license from a particular copyright holder is reinstated (a) 419 | provisionally, unless and until the copyright holder explicitly and 420 | finally terminates your license, and (b) permanently, if the copyright 421 | holder fails to notify you of the violation by some reasonable means 422 | prior to 60 days after the cessation. 423 | 424 | Moreover, your license from a particular copyright holder is 425 | reinstated permanently if the copyright holder notifies you of the 426 | violation by some reasonable means, this is the first time you have 427 | received notice of violation of this License (for any work) from that 428 | copyright holder, and you cure the violation prior to 30 days after 429 | your receipt of the notice. 430 | 431 | Termination of your rights under this section does not terminate the 432 | licenses of parties who have received copies or rights from you under 433 | this License. If your rights have been terminated and not permanently 434 | reinstated, you do not qualify to receive new licenses for the same 435 | material under section 10. 436 | 437 | 9. Acceptance Not Required for Having Copies. 438 | 439 | You are not required to accept this License in order to receive or 440 | run a copy of the Program. Ancillary propagation of a covered work 441 | occurring solely as a consequence of using peer-to-peer transmission 442 | to receive a copy likewise does not require acceptance. However, 443 | nothing other than this License grants you permission to propagate or 444 | modify any covered work. These actions infringe copyright if you do 445 | not accept this License. Therefore, by modifying or propagating a 446 | covered work, you indicate your acceptance of this License to do so. 447 | 448 | 10. Automatic Licensing of Downstream Recipients. 449 | 450 | Each time you convey a covered work, the recipient automatically 451 | receives a license from the original licensors, to run, modify and 452 | propagate that work, subject to this License. You are not responsible 453 | for enforcing compliance by third parties with this License. 454 | 455 | An "entity transaction" is a transaction transferring control of an 456 | organization, or substantially all assets of one, or subdividing an 457 | organization, or merging organizations. If propagation of a covered 458 | work results from an entity transaction, each party to that 459 | transaction who receives a copy of the work also receives whatever 460 | licenses to the work the party's predecessor in interest had or could 461 | give under the previous paragraph, plus a right to possession of the 462 | Corresponding Source of the work from the predecessor in interest, if 463 | the predecessor has it or can get it with reasonable efforts. 464 | 465 | You may not impose any further restrictions on the exercise of the 466 | rights granted or affirmed under this License. For example, you may 467 | not impose a license fee, royalty, or other charge for exercise of 468 | rights granted under this License, and you may not initiate litigation 469 | (including a cross-claim or counterclaim in a lawsuit) alleging that 470 | any patent claim is infringed by making, using, selling, offering for 471 | sale, or importing the Program or any portion of it. 472 | 473 | 11. Patents. 474 | 475 | A "contributor" is a copyright holder who authorizes use under this 476 | License of the Program or a work on which the Program is based. The 477 | work thus licensed is called the contributor's "contributor version". 478 | 479 | A contributor's "essential patent claims" are all patent claims 480 | owned or controlled by the contributor, whether already acquired or 481 | hereafter acquired, that would be infringed by some manner, permitted 482 | by this License, of making, using, or selling its contributor version, 483 | but do not include claims that would be infringed only as a 484 | consequence of further modification of the contributor version. For 485 | purposes of this definition, "control" includes the right to grant 486 | patent sublicenses in a manner consistent with the requirements of 487 | this License. 488 | 489 | Each contributor grants you a non-exclusive, worldwide, royalty-free 490 | patent license under the contributor's essential patent claims, to 491 | make, use, sell, offer for sale, import and otherwise run, modify and 492 | propagate the contents of its contributor version. 493 | 494 | In the following three paragraphs, a "patent license" is any express 495 | agreement or commitment, however denominated, not to enforce a patent 496 | (such as an express permission to practice a patent or covenant not to 497 | sue for patent infringement). To "grant" such a patent license to a 498 | party means to make such an agreement or commitment not to enforce a 499 | patent against the party. 500 | 501 | If you convey a covered work, knowingly relying on a patent license, 502 | and the Corresponding Source of the work is not available for anyone 503 | to copy, free of charge and under the terms of this License, through a 504 | publicly available network server or other readily accessible means, 505 | then you must either (1) cause the Corresponding Source to be so 506 | available, or (2) arrange to deprive yourself of the benefit of the 507 | patent license for this particular work, or (3) arrange, in a manner 508 | consistent with the requirements of this License, to extend the patent 509 | license to downstream recipients. "Knowingly relying" means you have 510 | actual knowledge that, but for the patent license, your conveying the 511 | covered work in a country, or your recipient's use of the covered work 512 | in a country, would infringe one or more identifiable patents in that 513 | country that you have reason to believe are valid. 514 | 515 | If, pursuant to or in connection with a single transaction or 516 | arrangement, you convey, or propagate by procuring conveyance of, a 517 | covered work, and grant a patent license to some of the parties 518 | receiving the covered work authorizing them to use, propagate, modify 519 | or convey a specific copy of the covered work, then the patent license 520 | you grant is automatically extended to all recipients of the covered 521 | work and works based on it. 522 | 523 | A patent license is "discriminatory" if it does not include within 524 | the scope of its coverage, prohibits the exercise of, or is 525 | conditioned on the non-exercise of one or more of the rights that are 526 | specifically granted under this License. You may not convey a covered 527 | work if you are a party to an arrangement with a third party that is 528 | in the business of distributing software, under which you make payment 529 | to the third party based on the extent of your activity of conveying 530 | the work, and under which the third party grants, to any of the 531 | parties who would receive the covered work from you, a discriminatory 532 | patent license (a) in connection with copies of the covered work 533 | conveyed by you (or copies made from those copies), or (b) primarily 534 | for and in connection with specific products or compilations that 535 | contain the covered work, unless you entered into that arrangement, 536 | or that patent license was granted, prior to 28 March 2007. 537 | 538 | Nothing in this License shall be construed as excluding or limiting 539 | any implied license or other defenses to infringement that may 540 | otherwise be available to you under applicable patent law. 541 | 542 | 12. No Surrender of Others' Freedom. 543 | 544 | If conditions are imposed on you (whether by court order, agreement or 545 | otherwise) that contradict the conditions of this License, they do not 546 | excuse you from the conditions of this License. If you cannot convey a 547 | covered work so as to satisfy simultaneously your obligations under this 548 | License and any other pertinent obligations, then as a consequence you may 549 | not convey it at all. For example, if you agree to terms that obligate you 550 | to collect a royalty for further conveying from those to whom you convey 551 | the Program, the only way you could satisfy both those terms and this 552 | License would be to refrain entirely from conveying the Program. 553 | 554 | 13. Use with the GNU Affero General Public License. 555 | 556 | Notwithstanding any other provision of this License, you have 557 | permission to link or combine any covered work with a work licensed 558 | under version 3 of the GNU Affero General Public License into a single 559 | combined work, and to convey the resulting work. The terms of this 560 | License will continue to apply to the part which is the covered work, 561 | but the special requirements of the GNU Affero General Public License, 562 | section 13, concerning interaction through a network will apply to the 563 | combination as such. 564 | 565 | 14. Revised Versions of this License. 566 | 567 | The Free Software Foundation may publish revised and/or new versions of 568 | the GNU General Public License from time to time. Such new versions will 569 | be similar in spirit to the present version, but may differ in detail to 570 | address new problems or concerns. 571 | 572 | Each version is given a distinguishing version number. If the 573 | Program specifies that a certain numbered version of the GNU General 574 | Public License "or any later version" applies to it, you have the 575 | option of following the terms and conditions either of that numbered 576 | version or of any later version published by the Free Software 577 | Foundation. If the Program does not specify a version number of the 578 | GNU General Public License, you may choose any version ever published 579 | by the Free Software Foundation. 580 | 581 | If the Program specifies that a proxy can decide which future 582 | versions of the GNU General Public License can be used, that proxy's 583 | public statement of acceptance of a version permanently authorizes you 584 | to choose that version for the Program. 585 | 586 | Later license versions may give you additional or different 587 | permissions. However, no additional obligations are imposed on any 588 | author or copyright holder as a result of your choosing to follow a 589 | later version. 590 | 591 | 15. Disclaimer of Warranty. 592 | 593 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 594 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 595 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 596 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 597 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 598 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 599 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 600 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 601 | 602 | 16. Limitation of Liability. 603 | 604 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 605 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 606 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 607 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 608 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 609 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 610 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 611 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 612 | SUCH DAMAGES. 613 | 614 | 17. Interpretation of Sections 15 and 16. 615 | 616 | If the disclaimer of warranty and limitation of liability provided 617 | above cannot be given local legal effect according to their terms, 618 | reviewing courts shall apply local law that most closely approximates 619 | an absolute waiver of all civil liability in connection with the 620 | Program, unless a warranty or assumption of liability accompanies a 621 | copy of the Program in return for a fee. 622 | 623 | END OF TERMS AND CONDITIONS 624 | 625 | How to Apply These Terms to Your New Programs 626 | 627 | If you develop a new program, and you want it to be of the greatest 628 | possible use to the public, the best way to achieve this is to make it 629 | free software which everyone can redistribute and change under these terms. 630 | 631 | To do so, attach the following notices to the program. It is safest 632 | to attach them to the start of each source file to most effectively 633 | state the exclusion of warranty; and each file should have at least 634 | the "copyright" line and a pointer to where the full notice is found. 635 | 636 | 637 | Copyright (C) 638 | 639 | This program is free software: you can redistribute it and/or modify 640 | it under the terms of the GNU General Public License as published by 641 | the Free Software Foundation, either version 3 of the License, or 642 | (at your option) any later version. 643 | 644 | This program is distributed in the hope that it will be useful, 645 | but WITHOUT ANY WARRANTY; without even the implied warranty of 646 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 647 | GNU General Public License for more details. 648 | 649 | You should have received a copy of the GNU General Public License 650 | along with this program. If not, see . 651 | 652 | Also add information on how to contact you by electronic and paper mail. 653 | 654 | If the program does terminal interaction, make it output a short 655 | notice like this when it starts in an interactive mode: 656 | 657 | Copyright (C) 658 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 659 | This is free software, and you are welcome to redistribute it 660 | under certain conditions; type `show c' for details. 661 | 662 | The hypothetical commands `show w' and `show c' should show the appropriate 663 | parts of the General Public License. Of course, your program's commands 664 | might be different; for a GUI interface, you would use an "about box". 665 | 666 | You should also get your employer (if you work as a programmer) or school, 667 | if any, to sign a "copyright disclaimer" for the program, if necessary. 668 | For more information on this, and how to apply and follow the GNU GPL, see 669 | . 670 | 671 | The GNU General Public License does not permit incorporating your program 672 | into proprietary programs. If your program is a subroutine library, you 673 | may consider it more useful to permit linking proprietary applications with 674 | the library. If this is what you want to do, use the GNU Lesser General 675 | Public License instead of this License. But first, please read 676 | . 677 | --------------------------------------------------------------------------------