Class: Topicz::Commands::InitCommand

Inherits:
Object
  • Object
show all
Defined in:
lib/topicz/commands/init_command.rb

Instance Method Summary collapse

Constructor Details

#initialize(config_file = nil, arguments = []) ⇒ InitCommand

Returns a new instance of InitCommand.



10
11
12
13
14
15
16
# File 'lib/topicz/commands/init_command.rb', line 10

def initialize(config_file = nil, arguments = [])
  @config_file = Topicz::DEFAULT_CONFIG_LOCATION
  option_parser.order! arguments
  unless arguments.empty?
    @directory = arguments.shift
  end
end

Instance Method Details

#create_configurationObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/topicz/commands/init_command.rb', line 50

def create_configuration
  if File.exist? @config_file
    puts "Skipping creation of configuration file; one already exists at #{@config_file}."
  else
    File.open(@config_file, 'w') do |file|
      file.write(YAML.dump({'repository' => @directory}))
    end
    puts "Configuration file saved to: #{@config_file}."
  end
end

#create_repositoryObject



45
46
47
48
# File 'lib/topicz/commands/init_command.rb', line 45

def create_repository
  FileUtils.mkdir_p(@directory)
  puts "New topic repository created at: #{@directory}."
end

#executeObject



34
35
36
37
38
39
40
41
42
43
# File 'lib/topicz/commands/init_command.rb', line 34

def execute
  unless @directory
    raise 'Pass the location of the new repository as an argument.'
  end
  if File.exist? @directory
    raise "A file or directory already exists at this location: #{@directory}."
  end
  create_repository
  create_configuration
end

#option_parserObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/topicz/commands/init_command.rb', line 18

def option_parser
  OptionParser.new do |options|
    options.banner = 'Usage: init [options] <directory>'
    options.on('-c', '--config FILE') do |file|
      @config_file = file
    end
    options.separator ''
    options.separator 'Initializes a new topic repository. This creates a directory and writes its
location into a configuration file.'
    options.separator ''
    options.separator 'If the directory already exists, this command fails.'
    options.separator ''
    options.separator 'If a configuration file already exists, it will not be overwritten.'
  end
end