Module: ContentParser

Included in:
EtcGroup, FreeBSDUser, LinuxUser, Passwd, SimpleConfig
Defined in:
lib/utils/parser.rb

Overview

author: Christoph Hartmann author: Dominik Richter

Instance Method Summary collapse

Instance Method Details

#parse_comment_line(raw, opts) ⇒ Array

Parse a line with a command. For example: ‘a = b # comment`. Retrieves the actual content.

Parameters:

  • raw (String)

    the content lines you want to be parsed

  • opts (Hash)

    optional configuration

Returns:

  • (Array)

    contains the actual line and the position of the line end



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/utils/parser.rb', line 39

def parse_comment_line(raw, opts)
  idx_nl = raw.index("\n")
  idx_comment = raw.index(opts[:comment_char])
  idx_nl = raw.length if idx_nl.nil?
  idx_comment = idx_nl + 1 if idx_comment.nil?
  line = ''

  # is a comment inside this line
  if idx_comment < idx_nl && idx_comment != 0
    line = raw[0..(idx_comment - 1)]
    # in case we don't allow comments at the end
    # of an assignment/statement, ignore it and fall
    # back to treating this as a regular line
    if opts[:standalone_comments] && !is_empty_line(line)
      line = raw[0..(idx_nl - 1)]
    end
  # if there is no comment in this line
  elsif idx_comment > idx_nl && idx_nl != 0
    line = raw[0..(idx_nl - 1)]
  end
  [line, idx_nl]
end

#parse_passwd(content) ⇒ Array

Parse /etc/passwd files.

Parameters:

  • content (String)

    the raw content of /etc/passwd

Returns:

  • (Array)

    Collection of passwd entries



10
11
12
13
14
# File 'lib/utils/parser.rb', line 10

def parse_passwd(content)
  content.to_s.split("\n").map do |line|
    parse_passwd_line(line)
  end
end

#parse_passwd_line(line) ⇒ Hash

Parse a line of /etc/passwd

Parameters:

  • line (String)

    a line of /etc/passwd

Returns:

  • (Hash)

    Map of entries in this line



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/utils/parser.rb', line 20

def parse_passwd_line(line)
  x = line.split(':')
  {
    'name' => x.at(0),
    'password' => x.at(1),
    'uid' => x.at(2),
    'gid' => x.at(3),
    'desc' => x.at(4),
    'home' => x.at(5),
    'shell' => x.at(6),
  }
end