Class: StackOperations::MkNest

Inherits:
MkTree
  • Object
show all
Defined in:
lib/mk_stack/mk_stack.rb

Instance Method Summary collapse

Methods inherited from MkTree

#mk_dir_tree, #print_tree

Constructor Details

#initialize(options, args) ⇒ MkNest

Returns a new instance of MkNest.



265
266
267
268
# File 'lib/mk_stack/mk_stack.rb', line 265

def initialize(options, args)
  @options = options
  @target_dir = args[0] || "."
end

Instance Method Details

#build_virtual_treeObject



276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/mk_stack/mk_stack.rb', line 276

def build_virtual_tree
  stacks = sorted_stacks
  tree = {}
  return tree if stacks.empty?
  
  current = tree
  stacks.each do |dir|
    name = File.basename(dir)
    current[name] = {}
    current = current[name]
  end
  tree
end

#nest_movesObject



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/mk_stack/mk_stack.rb', line 289

def nest_moves
  stacks = sorted_stacks
  moves = []
  return moves if stacks.size < 2
  
  # ENOENTエラーを防ぐため、一番奥(深い階層)に入るものから順に親へ移動する
  # 例: stacks = [7th, 6th, 5th] の場合
  # 1. 5th を 6th へ移動
  # 2. 6th を 7th へ移動
  (0...stacks.size - 1).to_a.reverse.each do |i|
    parent = stacks[i]
    child = stacks[i + 1]
    dest = File.join(parent, File.basename(child))
    moves << [child, dest]
  end
  moves
end

#runObject



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/mk_stack/mk_stack.rb', line 306

def run
  puts "Before nest:"
  puts @target_dir == "." ? "." : "#{File.basename(@target_dir)}/"
  print_tree(mk_dir_tree(@target_dir, 1, 999, dirs_only: true))

  moves = nest_moves

  puts "\nOperations:"
  prefix = @options[:dryrun] ? "[Dry Run] " : ""
  if moves.empty?
    puts "#{prefix}nothing to nest"
  else
    moves.each do |child, dest|
      puts "#{prefix}mv #{child} (to) #{dest}"
    end
  end

  puts "\nAfter nest:"
  puts "."
  print_tree(build_virtual_tree)

  unless @options[:dryrun]
    moves.each do |child, dest|
      FileUtils.mv(child, dest)
    end
    puts "\nExecution completed."
  end
end

#sorted_stacksObject



269
270
271
272
273
274
275
# File 'lib/mk_stack/mk_stack.rb', line 269

def sorted_stacks
  stacks = Dir.glob(File.join(@target_dir, "_stack_*_*")).select { |d| File.directory?(d) }
  stacks = stacks.sort_by { |d| d[/_stack_(\d+)(st|nd|rd|th)_/, 1].to_i }
  # デフォルトはFILO(新しいものがルート: 7th, 6th, 5th...)
  # -r オプションでFIFO(古いものがルート: 1st, 2nd, 3rd...)
  @options[:reverse] ? stacks : stacks.reverse
end