Class: Dirfy::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/dirfy/cli.rb

Overview

Command-line interface

Class Method Summary collapse

Class Method Details

.start(argv = ARGV) ⇒ Object



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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/dirfy/cli.rb', line 10

def self.start(argv = ARGV)
  options = {
    dry_run: false,
    verbose: false,
    indent: 4,
    prefix: ""
  }

  parser = OptionParser.new do |opts|
    opts.banner = "Usage: dirfy [options] [treefile]"

    opts.on("-d", "--dry-run", "Preview only; no files/dirs created") do
      options[:dry_run] = true
    end

    opts.on("-v", "--verbose", "Log each action") do
      options[:verbose] = true
    end

    opts.on("-iN", "--indent=N", Integer, "Spaces per level (default 4)") do |n|
      options[:indent] = n
    end

    opts.on("-pDIR", "--prefix=DIR", "Prepend DIR/ to every path") do |dir|
      options[:prefix] = dir.chomp("/") + "/"
    end

    opts.on("-V", "--version", "Show version") do
      puts "dirfy #{Dirfy::VERSION}"
      exit
    end

    opts.on("-h", "--help", "Show this help") do
      puts opts
      exit
    end
  end

  parser.parse!(argv)

  lines =
    if argv[0] && File.file?(argv[0])
      File.readlines(argv[0]).map(&:chomp)
    elsif !STDIN.tty?
      STDIN.read.lines.map(&:chomp)
    else
      puts parser.to_s
      exit(0)
    end

  items = Parser.new(indent: options[:indent]).parse(lines)
  items.map! { |p| options[:prefix] + p }

  puts "🔍 Detected #{items.size} items to create."
  unless options[:dry_run]
    print "Proceed? (y/N) "
    answer = STDIN.gets.to_s.strip.downcase
    exit(1) unless %w[y yes].include?(answer)
  end

  IO.new(dry_run: options[:dry_run], verbose: options[:verbose]).create(items)
end