|
| 1 | +# typed: strict |
| 2 | + |
| 3 | +require_relative "concept" |
| 4 | + |
| 5 | +class Forge |
| 6 | + # Allows defining a template for the file and path of the output of a |
| 7 | + # synthesizer. |
| 8 | + class PathTemplate |
| 9 | + extend T::Sig |
| 10 | + |
| 11 | + class BadSignatureError < StandardError |
| 12 | + end |
| 13 | + |
| 14 | + class MultipleFilesForConceptError < StandardError |
| 15 | + end |
| 16 | + |
| 17 | + sig { params(path: String, basename: String, extension: String).void } |
| 18 | + def initialize(path:, basename:, extension:) |
| 19 | + @path = path |
| 20 | + @basename = basename |
| 21 | + @extension = extension |
| 22 | + @filename_regex = T.let(nil, T.nilable(Regexp)) |
| 23 | + @existing_file = T.let(nil, T.nilable(String)) |
| 24 | + end |
| 25 | + |
| 26 | + sig { params(signature: String).returns(String) } |
| 27 | + def filename(signature) |
| 28 | + "#{basename}.#{signature}.#{extension}" |
| 29 | + end |
| 30 | + |
| 31 | + sig { params(signature: String).returns(String) } |
| 32 | + def full_path(signature) |
| 33 | + File.join(path, filename(signature)) |
| 34 | + end |
| 35 | + |
| 36 | + sig { params(path: String).returns(String) } |
| 37 | + def parse_signature_from_file(path) |
| 38 | + match = path.match(filename_regex) |
| 39 | + unless match |
| 40 | + raise BadSignatureError, "Cannot parse signature from #{path}" |
| 41 | + end |
| 42 | + T.must(match[1]) |
| 43 | + end |
| 44 | + |
| 45 | + sig { returns(T.nilable(String)) } |
| 46 | + def existing_file |
| 47 | + @existing_file ||= find_existing_file |
| 48 | + end |
| 49 | + |
| 50 | + private |
| 51 | + |
| 52 | + sig { returns(T.nilable(String)) } |
| 53 | + def find_existing_file |
| 54 | + signatures = |
| 55 | + Dir |
| 56 | + .glob(glob) |
| 57 | + .filter_map do |path| |
| 58 | + match = path.match(filename_regex) |
| 59 | + raise BadSignatureError, "Bad signature found: #{path}" unless match |
| 60 | + match[1] |
| 61 | + end |
| 62 | + |
| 63 | + if signatures.size > 1 |
| 64 | + raise MultipleFilesForConceptError, "Multiple files found for #{glob}" |
| 65 | + end |
| 66 | + signatures.first |
| 67 | + end |
| 68 | + |
| 69 | + sig { returns(String) } |
| 70 | + def glob |
| 71 | + full_path("*").gsub(".", "\.") |
| 72 | + end |
| 73 | + |
| 74 | + sig { returns(Regexp) } |
| 75 | + def filename_regex |
| 76 | + @filename_regex ||= Regexp.new("#{basename}\.(\H+)\.#{extension}", "i") |
| 77 | + end |
| 78 | + |
| 79 | + sig { returns(String) } |
| 80 | + attr_reader :path |
| 81 | + |
| 82 | + sig { returns(String) } |
| 83 | + attr_reader :basename |
| 84 | + |
| 85 | + sig { returns(String) } |
| 86 | + attr_reader :extension |
| 87 | + end |
| 88 | +end |
0 commit comments