Class: Baker
- Inherits:
-
Object
- Object
- Baker
- Includes:
- BakerActions
- Defined in:
- lib/baker.rb,
lib/baker/version.rb
Constant Summary collapse
- VERSION =
"0.1.0"
Instance Attribute Summary collapse
-
#debug ⇒ Object
Returns the value of attribute debug.
-
#file_name ⇒ Object
Returns the value of attribute file_name.
-
#interactive ⇒ Object
Returns the value of attribute interactive.
-
#recipe ⇒ Object
Returns the value of attribute recipe.
Instance Method Summary collapse
- #expand_vars(input) ⇒ Object
- #inspect ⇒ Object
- #process_args ⇒ Object
- #run ⇒ Object
-
#run_diff ⇒ Object
Run diff will unmark all completed steps and perform a diff against the original template source.
- #save ⇒ Object
- #to_hash ⇒ Object
Methods included from BakerActions
#append_to_file, #format_command, #gsub_file, #inject_into_file, #unindent_common_whitespace
Instance Attribute Details
#debug ⇒ Object
Returns the value of attribute debug.
25 26 27 |
# File 'lib/baker.rb', line 25 def debug @debug end |
#file_name ⇒ Object
Returns the value of attribute file_name.
25 26 27 |
# File 'lib/baker.rb', line 25 def file_name @file_name end |
#interactive ⇒ Object
Returns the value of attribute interactive.
25 26 27 |
# File 'lib/baker.rb', line 25 def interactive @interactive end |
#recipe ⇒ Object
Returns the value of attribute recipe.
25 26 27 |
# File 'lib/baker.rb', line 25 def recipe @recipe end |
Instance Method Details
#expand_vars(input) ⇒ Object
79 80 81 82 83 84 85 86 87 |
# File 'lib/baker.rb', line 79 def (input) return "" if input.nil? || input.empty? o = OpenStruct.new(@context) o.singleton_class.define_singleton_method(:const_missing) { |name| o[name] } return o.instance_eval(input) end |
#inspect ⇒ Object
26 27 28 29 |
# File 'lib/baker.rb', line 26 def inspect # Nothing gained here from seeing instance variables return to_s end |
#process_args ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/baker.rb', line 35 def process_args begin OptionParser.new do |opts| opts. = 'Usage: baker [options] [file]' opts.on('-v', '--verbose', 'Enable verbose/debug output') do @debug = true puts "Verbose mode enabled".yellow end opts.on('-d', '--diff', 'Show diff of the bake file to its template') do @diff_mode = true puts "Diff mode enabled".yellow if $stdout.tty? end opts.on('-i', '--interactive', 'Enable interactive mode') do @interactive = true end opts.on('-h', '--help', 'Displays Help') do puts opts exit end end.parse! rescue OptionParser::InvalidOption => e puts e exit(1) end @file_name = ARGV.shift || 'template.md' @file_name = File.(@file_name) if !File.exist?(@file_name) puts "Error: File #{@file_name} does not exist.".red exit(1) end puts "Bake File: #{@file_name}".yellow if @debug return nil end |
#run ⇒ Object
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/baker.rb', line 124 def run status = process_args return if status == :close # @file_contents represents the file that baker believes is on disk. # It is used to check if there was any concurrent modification. @file_contents = File.read(@file_name) @recipe = Recipe.from_s(@file_contents) if @diff_mode run_diff() return end @context = { file_name: @file_name } @recipe.steps.each { |line| if @debug puts "#{line.type} : #{line}" else puts line end case line.type when :directive case line.directive_type when :var # STDERR.puts line.inspect if line.attributes == nil || line.attributes.strip.start_with?(/default\s*=/) puts "" initial_value = ((line.attributes || "").sub(/^\s*default\s*=\s*/, '')) puts initial_value use_tty = true if use_tty line.attributes = TTY::Prompt.new.ask(" → Please enter your value for variable '#{line.content}':\n".yellow, value: initial_value) else puts " → Please enter your value for variable '#{line.content}':".yellow line.attributes = STDIN.gets().strip end line.lines = ["::var[#{line.content}]{#{line.attributes}}\n"] @context[line.content] = line.attributes puts "" else @context[line.content] = line.attributes puts " → Variable '#{line.content}' set to '#{line.attributes}'.".yellow puts "" end next when :cd o = OpenStruct.new(@context) o.singleton_class.define_singleton_method(:const_missing) { |name| o[name] } dir = o.instance_eval(line.content) puts " → Changing directory to: #{dir}".yellow Dir.chdir(dir) when :template o = OpenStruct.new(@context) o.singleton_class.define_singleton_method(:const_missing) { |name| o[name] } template_name_suggestion = o.instance_eval(line.content) || File.filename(@file_name) puts (" → Executing template directive. Creating file: " + template_name_suggestion).yellow template_name_suggestion = File.(template_name_suggestion) if File.exist?(template_name_suggestion) puts "Error: The file #{template_name_suggestion} already exists.".red puts " ? Do you want to overwrite the file? Enter y/Y to overwrite. Any other key to cancel and exit baker.".yellow # Make a copy of the file contents before the user decides to overwrite @file_contents = File.read(template_name_suggestion) exit(1) if STDIN.gets().strip.downcase != 'y' end line.lines = ["::template_source[#{@file_name}]"] puts "" @file_name = template_name_suggestion save next when :template_source # Do nothing else raise "Unknown directive type: #{line.directive_type}" end next when :nop # Do nothing next when :ruby #eval line.content if line.completed? puts " → Already completed".green if @debug next end @context[:rails_gen_base] = Rails::Generators::Base.new @context[:myself] = self o = Struct.new(*@context.keys).new(*@context.values) # require 'ostruct' # o = OpenStruct.new(@context) o.singleton_class.define_singleton_method(:const_missing) { |name| o[name] } o.define_singleton_method (:inspect) { "<#{self.class}: #{self.instance_variables.map{|v| "#{v}=#{instance_variable_get(v).inspect.truncate(100)}"}.join(", ")}>" } o.extend Forwardable o.def_delegators :rails_gen_base, :create_file, :copy_file, :inside, :environment, :gem, :generate, :git, :initializer, :lib, :rails_command, :rake, :route o.def_delegators :myself, :inject_into_file, :append_file, :append_to_file, :insert_into_file, :gsub_file #o.singleton_class.include(Thor::Actions) #o.singleton_class.include(Rails::Generators::Actions) #o.destination_root = Dir.pwd command = line.command # Apply indentation and any additional formatting to_display = unindent_common_whitespace(format_command(command, max_line_length = 160)) line_will_break = to_display =~ /\n/ || to_display.length > 80 to_display = "\n#{to_display}\n" if line_will_break && to_display.scan(/\n/).length == 1 to_display = to_display.indent(1).gsub(/^/, '▐').indent(3) if line_will_break puts (" → Executing ruby code: #{"\n" if line_will_break}#{to_display}").yellow begin result = o.instance_eval(command) rescue Exception => e result = e end if result == false # We assume the ruby command outputted an error message puts " → Please fix the error or mark the todo as done.".red exit 1 end if result.is_a?(Exception) puts " → Failed with error:".red puts result puts result.backtrace puts " → Please fix the error or mark the todo as done.".red exit 1 end puts " → Successfully executed".green line.mark_complete when :shell # system line.content if line.completed? next end require 'ostruct' o = OpenStruct.new(@context) o.singleton_class.define_singleton_method(:const_missing) { |name| o[name] } command = o.instance_eval("%(" + line.command + ")") # Apply indentation and any additional formatting to_display = format_command(command, max_line_length = 160) line_will_break = to_display =~ /\n/ || to_display.length > 80 to_display = "\n#{to_display}\n" if line_will_break && to_display.scan(/\n/).length == 1 to_display = to_display.indent(1).gsub(/^/, '▐').indent(3) if line_will_break puts (" → Executing shell command: #{"\n" if line_will_break}#{to_display}").yellow mode = :ptyspawn_with_parser case mode when :system puts ">>>>>>".white # Bundler.with_clean_env { result = system(command, out: STDOUT) #} puts ">>>>>>".white when :open3 exit_status = nil require 'open3' Open3.popen2e(command) do |stdin, stdout_and_stderr, wait_thr| stdout_and_stderr.each_line do |line| # Remove trailing whitespace and apply formatting formatted_line = line.rstrip.indent(2).gsub(/^/, '▐').indent(3) puts formatted_line end exit_status = wait_thr.value end result = exit_status&.success? when :ptyspawn_with_parser require 'pty' begin line_indent = ' ▐ ' line_indent_width = line_indent.length line_indent = line_indent.yellow first_line_indent = true parser = VTParser.new do |action, ch, n, a| print line_indent if first_line_indent first_line_indent = false to_output = VTParser.to_ansi(action, ch, n, a) case action when :print, :execute, :put, :osc_put if ch == "\n" || ch == "\r" print ch print line_indent next end when :csi_dispatch if to_output == "\e[2K" print "\e[2K" print line_indent next else if ch == 'G' # puts "to_output: #{to_output.inspect} action: #{action} ch: #{ch.inspect}" # && parser.params.size == 1 print "\e[#{parser.params[0] + line_indent_width}G" next end end end print to_output end PTY.spawn(command) do |stdout_and_stderr, stdin, pid| Thread.new do while pid != nil stdin.write(STDIN.readpartial(1024)) end end begin stdout_and_stderr.winsize = [$stdout.winsize.first, $stderr.winsize.last - line_indent_width].max stdout_and_stderr.each_char do |char| parser.parse(char) end rescue Errno::EIO # End of output end Process.wait(pid) pid = nil exit_status = $?.exitstatus result = exit_status == 0 # Clear the line, reset the cursor to the start of the line print "\e[2K\e[1G" end rescue PTY::ChildExited # Child process has exited result = true end end puts "" if result puts " → Successfully executed".green line.mark_complete else puts " → Failed with error:".red puts $? puts " → Please fix the error or mark the todo as done.".red exit 1 end when :manual if line.completed? next end puts " → Perform the following steps manually:".yellow puts line.description puts puts " → Please enter: y/Y/x/./<space> to mark complete and continue or any other key to do nothing and exit".yellow input = STDIN.gets() case input.strip.downcase when 'y', 'x', '.', ' ' line.mark_complete else puts " → Please complete the task manually and run baker again".red exit 1 end end save } puts " → All steps completed.".green end |
#run_diff ⇒ Object
Run diff will unmark all completed steps and perform a diff against the original template source
The original template source is searched using the ::template_source directive.
The diff is shown using git diff.
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/baker.rb', line 94 def run_diff template_source_file = nil @recipe.steps.each { |line| case line.type when :directive case line.directive_type when :template_source template_source_file = line.content end when :ruby, :shell, :manual line.mark_todo if line.completed? end } if template_source_file.nil? puts "Error: No template source file found. Please add a ::template_source{path_to_template} directive to the bake file.".red exit(1) end to_write = @recipe.to_s Tempfile.open("#{File.basename(@file_name)}_unbaked") do |tempfile| tempfile.write(to_write) tempfile.flush # If attached to a tty, show color diff/word diff puts `git diff #{"--word-diff --color" if $stdout.tty?} #{template_source_file} #{tempfile.path}` end end |
#save ⇒ Object
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/baker.rb', line 448 def save to_write = @recipe.to_s if File.exist?(@file_name) && @file_contents != nil if File.read(@file_name) != @file_contents puts " → File has been modified by another program, while baker processed todos.".red while true puts " ? Do you want to overwrite the file? Enter y/Y to overwrite or d/D to show diff. Any other key to cancel and exit baker.".yellow input = STDIN.gets() case input.strip.downcase when 'y' puts " → Exiting without saving. Please manually mark the successfully executed steps as done.".red exit 1 when 'd' puts " → Diff:".red Tempfile.open('assumed_file_contents') do |tempfile| tempfile.write(@file_contents) tempfile.flush puts `git diff --color #{tempfile.path} #{@file_name}` end puts next # Repeat end break end end end if !File.exist?(@file_name) || File.read(@file_name) != to_write File.write(@file_name, to_write) @file_contents = to_write else puts " → No changes to save.".yellow end end |
#to_hash ⇒ Object
31 32 33 |
# File 'lib/baker.rb', line 31 def to_hash (self.instance_variables - [:@file_contents, :@recipe]).inject({}){ |cont, attr| cont[attr] = instance_variable_get(attr); cont } end |