Class: Textus::Handlers::Write::KeyMvPrefix

Inherits:
Object
  • Object
show all
Defined in:
lib/textus/handlers/write/key_mv_prefix.rb

Instance Method Summary collapse

Constructor Details

#initialize(orchestration:) ⇒ KeyMvPrefix

Returns a new instance of KeyMvPrefix.



5
6
7
# File 'lib/textus/handlers/write/key_mv_prefix.rb', line 5

def initialize(orchestration:)
  @orchestration = orchestration
end

Instance Method Details

#call(command, call) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/textus/handlers/write/key_mv_prefix.rb', line 9

def call(command, call)
  if command.from_prefix.nil? || command.to_prefix.nil?
    return Value::Result.failure(:usage_error,
                                 "from_prefix and to_prefix required")
  end

  list = @orchestration.list_keys(prefix: command.from_prefix, lane: nil, call: call)
  return list if list.failure?

  leaves = list.value.fetch("rows")

  if leaves.any? { |r| r["key"] == command.from_prefix }
    return Value::Result.failure(:usage_error,
                                 "from_prefix '#{command.from_prefix}' is itself a leaf — use `mv` to rename a single key")
  end

  warnings = leaves.empty? ? ["no keys under #{command.from_prefix}"] : []
  steps = leaves.map do |row|
    old_key = row["key"]
    tail = old_key.delete_prefix("#{command.from_prefix}.")
    new_key = "#{command.to_prefix}.#{tail}"
    { "op" => "mv", "from" => old_key, "to" => new_key }
  end

  plan = Textus::Store::Jobs::Plan.new(steps: steps, warnings: warnings)
  return Value::Result.success(plan) if command.dry_run

  steps.each do |step|
    move = @orchestration.move_key(old_key: step["from"], new_key: step["to"], call: call)
    return move if move.failure?
  end
  Value::Result.success(plan)
end