Class: Confinicky::ShellFile

Inherits:
Object
  • Object
show all
Defined in:
lib/confinicky/shell_file.rb

Overview

A model that loads and represents a shell file.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path: "") ⇒ ShellFile

Parses the configuration file if it exists.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/confinicky/shell_file.rb', line 28

def initialize(file_path: "")
  raise "Config file not found. Please set" if !File.exists?(@file_path = file_path)
  @exports = []
  @aliases = []
  @lines = []

  file = File.new(@file_path, "r")
  command = nil

  while (line = file.gets)
    if !command.nil? && command.open?
      command.append line
    else
      command = Confinicky::Parsers::Command.new(line: line)
    end

    @lines << line if command.line?
    @exports << command.values_array if command.export? and command.closed?
    @aliases << command.values_array if command.alias? and command.closed?
  end

  file.close()
end

Instance Attribute Details

#aliasesObject

The alias commands stored in the shell file.



11
12
13
# File 'lib/confinicky/shell_file.rb', line 11

def aliases
  @aliases
end

#exportsObject

Returns a list of all exports in alphanumeric order.



15
16
17
# File 'lib/confinicky/shell_file.rb', line 15

def exports
  @exports
end

#file_pathObject (readonly)

Returns the file path for the current instance of the shell file class.



24
25
26
# File 'lib/confinicky/shell_file.rb', line 24

def file_path
  @file_path
end

#linesObject (readonly)

The preserved lines of code from the shell file which confinicky will write back to the new shell file in the order they were received.



20
21
22
# File 'lib/confinicky/shell_file.rb', line 20

def lines
  @lines
end

Instance Method Details

#backup!Object

Copies the current shell file to a temporary location.



60
61
62
63
64
# File 'lib/confinicky/shell_file.rb', line 60

def backup!
  backup_name = @file_path+Time.now.getutc.to_i.to_s+".bak.tmp"
  FileUtils.cp(@file_path, backup_name)
  backup_name
end

#write!Object

Writes a new version of the configuration file.



68
69
70
71
72
73
74
75
76
77
# File 'lib/confinicky/shell_file.rb', line 68

def write!
  File.open(@file_path, "w") do |f|
    for line in @lines
      f.write line
    end
    f.puts @exports.map{|e| "export #{e.join("=")}"}.join("\n") if !@exports.nil? and @exports.length > 0
    f.puts @aliases.map{|a| "alias #{a.join("=")}"}.join("\n") if !@aliases.nil? and @aliases.length > 0
  end
  true
end