Class: Ec2ssh::SshConfig

Inherits:
Object
  • Object
show all
Defined in:
lib/ec2ssh/ssh_config.rb

Defined Under Namespace

Classes: Section

Constant Summary collapse

HEADER =
"### EC2SSH BEGIN ###"
"### EC2SSH END ###"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = nil) ⇒ SshConfig

Returns a new instance of SshConfig.



11
12
13
14
# File 'lib/ec2ssh/ssh_config.rb', line 11

def initialize(path=nil)
  @path     = path || "#{ENV['HOME']}/.ssh/config"
  @sections = {}
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/ec2ssh/ssh_config.rb', line 9

def path
  @path
end

#sectionsObject (readonly)

Returns the value of attribute sections.



9
10
11
# File 'lib/ec2ssh/ssh_config.rb', line 9

def sections
  @sections
end

Instance Method Details

#append_mark!Object



35
36
37
38
39
40
# File 'lib/ec2ssh/ssh_config.rb', line 35

def append_mark!
  replace! ""
  File.open(@path, "a") do |f|
    f.puts wrap("")
  end
end

#config_srcObject



50
51
52
53
54
55
56
57
58
# File 'lib/ec2ssh/ssh_config.rb', line 50

def config_src
  unless File.exist?(@path)
    File.open(@path, "w", 0600).close()
  end

  @config_src ||= File.open(@path, "r") do |f|
    f.read
  end
end

#mark_exist?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/ec2ssh/ssh_config.rb', line 42

def mark_exist?
  config_src =~ /#{HEADER}\n.*#{FOOTER}\n/m
end

#parse!Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ec2ssh/ssh_config.rb', line 16

def parse!
  return unless mark_exist?
  ec2_config = config_src.match(/#{HEADER}\n(.*)#{FOOTER}/m).to_s

  current_section = 'default'
  @sections[current_section] = Section.new('default')

  ec2_config.split(/\n+/).each do |line|
    if line =~ /#{Section::HEADER} (.+)/
      current_section = $1
      @sections[current_section] ||= Section.new(current_section)
    elsif line =~ /^#/ # ignore
    elsif line =~ /^$/ # ignore
    else
      @sections[current_section].append("#{line}\n")
    end
  end
end

#replace!(str) ⇒ Object



46
47
48
# File 'lib/ec2ssh/ssh_config.rb', line 46

def replace!(str)
  save! config_src.gsub(/#{HEADER}\n.*#{FOOTER}\n/m, str)
end

#save!(str) ⇒ Object



60
61
62
63
64
# File 'lib/ec2ssh/ssh_config.rb', line 60

def save!(str)
  File.open(@path, "w") do |f|
    f.puts str
  end
end

#wrap(text) ⇒ Object



66
67
68
69
70
71
72
73
74
75
# File 'lib/ec2ssh/ssh_config.rb', line 66

def wrap(text)
  return <<-END
#{HEADER}
# Generated by ec2ssh http://github.com/mirakui/ec2ssh
# DO NOT edit this block!
# Updated #{Time.now.iso8601}
#{text}
#{FOOTER}
  END
end