Class: Textus::Action::KeyMvPrefix

Inherits:
Base
  • Object
show all
Defined in:
lib/textus/action/key_mv_prefix.rb

Class Method Summary collapse

Methods inherited from Base

inherited, proposal_from

Methods included from Contract::DSL

#arg, #cli, #cli_stdin, #contract, #contract?, #summary, #surfaces, #verb, #view

Class Method Details

.call(container:, call:, from_prefix:, to_prefix:, dry_run: false) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/textus/action/key_mv_prefix.rb', line 19

def self.call(container:, call:, from_prefix:, to_prefix:, dry_run: false)
  return Failure(code: :usage_error, message: "from_prefix and to_prefix required") if from_prefix.nil? || to_prefix.nil?

  leaves = Textus::Action::List.leaf_keys(container: container, prefix: from_prefix)

  if leaves.include?(from_prefix)
    return Failure(code: :usage_error,
                   message: "from_prefix '#{from_prefix}' is itself a leaf — use `mv` to rename a single key")
  end

  warnings = []
  warnings << "no keys under #{from_prefix}" if leaves.empty?

  steps = leaves.map do |old_key|
    tail = old_key.delete_prefix("#{from_prefix}.")
    new_key = "#{to_prefix}.#{tail}"
    { "op" => "mv", "from" => old_key, "to" => new_key }
  end

  plan = Textus::Store::Jobs::Plan.new(steps: steps, warnings: warnings)
  return Success(plan) if dry_run

  steps.each do |step|
    Value::Result.unwrap(Textus::Action::KeyMv.call(container: container, call: call, old_key: step["from"], new_key: step["to"]))
  end
  Success(plan)
end