Class: Mxrb::Scaffold::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/mxrb/scaffold/registry.rb

Overview

Records generated files so scaffold removal never relies on guessing paths.

Constant Summary collapse

RELATIVE_PATH =
File.join('.mxrb', 'scaffolds.json')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Registry

Returns a new instance of Registry.



29
30
31
32
# File 'lib/mxrb/scaffold/registry.rb', line 29

def initialize(root)
  @root = File.expand_path(root)
  @path = File.join(@root, RELATIVE_PATH)
end

Class Method Details

.stage(transaction, root:, key:, files:) ⇒ Object

rubocop:disable Metrics/MethodLength



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mxrb/scaffold/registry.rb', line 14

def self.stage(transaction, root:, key:, files:) # rubocop:disable Metrics/MethodLength
  path = File.join(root, RELATIVE_PATH)
  payload = transaction.content(path) ? JSON.parse(transaction.content(path)) : { 'scaffolds' => {} }
  payload['scaffolds'][key] = {
    'files' => files.map do |file|
      { 'path' => file.delete_prefix("#{root}/"),
        'sha256' => Digest::SHA256.hexdigest(transaction.content(file)) }
    end
  }
  transaction.write(path, JSON.pretty_generate(payload) << "\n")
  path
rescue JSON::ParserError => e
  raise ArgumentError, "invalid scaffold registry: #{e.message}"
end

Instance Method Details

#entriesObject



34
35
36
37
38
39
40
# File 'lib/mxrb/scaffold/registry.rb', line 34

def entries
  return {} unless File.file?(@path)

  JSON.parse(File.read(@path)).fetch('scaffolds', {})
rescue JSON::ParserError => e
  raise ArgumentError, "invalid scaffold registry: #{e.message}"
end

#remove(key) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/mxrb/scaffold/registry.rb', line 42

def remove(key)
  registry = entries
  entry = registry.fetch(key) { raise ArgumentError, "scaffold not registered: #{key}" }
  paths = entry.fetch('files').map { safe_path(_1.fetch('path')) }
  verify_unchanged!(entry.fetch('files'), paths)
  paths.each { FileUtils.rm_f(_1) }
  registry.delete(key)
  write('scaffolds' => registry)
  Removal.new(key, paths.freeze)
end