|
1 | 1 | # frozen_string_literal: true
|
2 | 2 |
|
3 |
| -require 'fileutils' |
| 3 | +require "date" |
| 4 | +require "erb" |
| 5 | +require "net/http" |
| 6 | +require "open-uri" |
| 7 | +require "fileutils" |
4 | 8 |
|
5 | 9 | def next_advent_number
|
6 |
| - latest = Dir['./lib/advent*.rb'].map { |p| p.match(/\d{2}/)&.[](0)&.to_i }.compact.max || 0 |
| 10 | + latest = Dir["./lib/advent*.rb"].map { |p| p.match(/\d{2}/)&.[](0)&.to_i }.compact.max || 0 |
7 | 11 | latest + 1
|
8 | 12 | end
|
9 | 13 |
|
10 |
| -desc 'create class and spec file for DAY' |
| 14 | +desc "create class and spec file for DAY" |
11 | 15 | task :new do
|
12 |
| - day = ENV['DAY'].nil? ? next_advent_number : ENV['DAY'].to_i |
| 16 | + today = Date.today |
13 | 17 |
|
14 |
| - raise 'invalid DAY' unless day.between?(1, 31) |
| 18 | + day = ENV["DAY"].nil? ? next_advent_number : ENV["DAY"].to_i |
| 19 | + year = ENV["YEAR"].nil? ? today.year : ENV["YEAR"].to_i |
15 | 20 |
|
16 |
| - formatted_day = day.to_s.rjust(2, '0') |
| 21 | + raise "invalid DAY" unless day.between?(1, 31) |
| 22 | + raise "invalid YEAR" unless year.between?(2015, today.year) |
17 | 23 |
|
18 |
| - FileUtils.touch("./lib/advent_#{formatted_day}.rb") |
19 |
| - FileUtils.touch("./spec/advent_#{formatted_day}_spec.rb") |
20 |
| - FileUtils.touch("./spec/fixtures/advent-#{formatted_day}.txt") |
21 |
| - FileUtils.touch("./spec/fixtures/advent-#{formatted_day}-sample.txt") |
| 24 | + html = Net::HTTP.get(URI.parse("https://adventofcode.com/#{year}/day/#{day}")) |
| 25 | + |
| 26 | + title = html.match(%r{<h2>--- Day \d+: ([A-Za-z0-9\s-]+) ---</h2>}) { |m| m[1] }.to_s |
| 27 | + |
| 28 | + formatted_title = title.tr("-", "").tr(" ", "").gsub(/(.)([A-Z])/, '\1_\2').downcase |
| 29 | + formatted_day = day.to_s.rjust(2, "0") |
| 30 | + |
| 31 | + basename = "advent_#{formatted_day}_#{formatted_title}" |
| 32 | + |
| 33 | + templates = [ |
| 34 | + { template: "./templates/klass.rb.erb", path: "./lib/#{basename}.rb" }, |
| 35 | + { template: "./templates/spec.rb.erb", path: "./spec/#{basename}_spec.rb" } |
| 36 | + ] |
| 37 | + |
| 38 | + templates.each do |h| |
| 39 | + path = h[:path] |
| 40 | + next if File.exist?(path) |
| 41 | + |
| 42 | + erb = ERB.new(File.read(h[:template])) |
| 43 | + rendered = erb.result_with_hash(require_path: basename, day_number: formatted_day) |
| 44 | + |
| 45 | + puts "creating #{path}" |
| 46 | + puts rendered.inspect |
| 47 | + puts "----------------" |
| 48 | + |
| 49 | + File.write(path, rendered) |
| 50 | + end |
| 51 | + |
| 52 | + puzzle_inputs = [ |
| 53 | + "advent-#{formatted_day}-sample.txt", |
| 54 | + "advent-#{formatted_day}.txt" |
| 55 | + ] |
| 56 | + |
| 57 | + puzzle_inputs.each do |name| |
| 58 | + FileUtils.touch("./spec/fixtures/#{name}") |
| 59 | + end |
22 | 60 | end
|
0 commit comments