lib/cfn-flow/template.rb in cfn-flow-0.2.1 vs lib/cfn-flow/template.rb in cfn-flow-0.5.0

- old
+ new

@@ -1,64 +1,78 @@ -class CfnFlow::Template - attr_reader :from, :prefix, :bucket - def initialize(opts={}) - unless [:from, :prefix, :bucket].all? {|arg| opts.key?(arg) } - raise ArgumentError.new("Must pass :from, :prefix, and :bucket") +module CfnFlow + class Template + + # Tag for JSON/YAML loading errors + module Error; end + + attr_reader :local_path + def initialize(local_path) + @local_path = local_path end - @from, @prefix, @bucket = opts[:from], opts[:prefix], opts[:bucket] - end - def yaml? - from.end_with?('.yml') - end + def yaml? + local_path.end_with?('.yml') + end - def json? - ! yaml? - end + def json? + ! yaml? + end - # Determine if this file is a CFN template - def is_cfn_template? - from_data.is_a?(Hash) && from_data.key?('Resources') - end + # Determine if this file is a CFN template + def is_cfn_template? + local_data.is_a?(Hash) && local_data.key?('Resources') + end - # Returns a response object if valid, or raises an - # Aws::CloudFormation::Errors::ValidationError with an error message - def validate! - cfn.validate_template(template_body: to_json) - end + # Returns a response object if valid, or raises an + # Aws::CloudFormation::Errors::ValidationError with an error message + def validate! + cfn.validate_template(template_body: to_json) + end - def key - # Replace leading './' in from - File.join(prefix, from.sub(/\A\.\//, '')) - end + ## + # S3 methods + def key(release) + # Replace leading './' in local_path + clean_path = local_path.sub(/\A\.\//, '') + File.join(*[s3_prefix, release, clean_path].compact) + end - def upload! - s3_object.put(body: to_json) - end + def s3_object(release) + Aws::S3::Object.new(bucket, key(release)) + end - def url - s3_object.public_url - end + def url(release) + s3_object(release).public_url + end - def from_data - # We *could* load JSON as YAML, but that would generate confusing errors - # in the case of a JSON syntax error. - @from_data ||= yaml? ? YAML.load_file(from) : MultiJson.load(File.read(from)) - rescue - puts "Error loading #{from}" - raise $! - end + def upload(release) + s3_object(release).put(body: to_json) + end - def to_json - @to_json ||= MultiJson.dump(from_data, pretty: true) - end + def local_data + # We *could* load JSON as YAML, but that would generate confusing errors + # in the case of a JSON syntax error. + @local_data ||= yaml? ? YAML.load_file(local_path) : MultiJson.load(File.read(local_path)) + rescue Exception => error + # Tag & re-raise any error + error.extend(CfnFlow::Template::Error) + raise error + end - private - def cfn - Aws::CloudFormation::Client.new - end + def to_json + @to_json ||= MultiJson.dump(local_data, pretty: true) + end - def s3_object - Aws::S3::Object.new(bucket, key) - end + def bucket + CfnFlow.template_s3_bucket + end + def s3_prefix + CfnFlow.template_s3_prefix + end + + private + def cfn + CfnFlow.cfn_client + end + end end