Module: SystemModule

Overview

Interaction with the operating system

Instance Method Summary collapse

Instance Method Details

#hash_to_yaml(hash) ⇒ Object

Print hash as yaml.



10
11
12
13
14
15
# File 'lib/takelage/lib/system.rb', line 10

def hash_to_yaml(hash)
  if hash == {}
    return nil.to_yaml
  end
  return hash.to_yaml(options = {:line_width => -1})
end

#read_yaml_file(file) ⇒ Hash

Returns content of yaml file.

Returns:

  • (Hash)

    content of yaml file



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
# File 'lib/takelage/lib/system.rb', line 18

def read_yaml_file(file)
  log.debug "Reading YAML file \"#{file}\""

  # Check file existenc
  unless File.exists? file
    log.debug "File \"#{file}\" doesn't exist"
    return nil
  end

  # Read file
  begin
    content_yaml =  File.read file
  rescue
    log.debug "Unable to read file \"#{file}\""
    return nil
  end

  # Parse YAML
  begin
    content = YAML.load content_yaml
  rescue
    log.debug "Invalid YAML file \"#{file}\""
    log.debug "Try: yamllint #{file}"
    return nil
  end

  content
end

#rm_fr(directory) ⇒ Object

Remove directory tree.



48
49
50
51
52
53
54
55
# File 'lib/takelage/lib/system.rb', line 48

def rm_fr(directory)
  unless File.directory? directory
    log.error "Cannot remove non-existing directory \"#{directory}\""
    return
  end
  log.debug "Removing directory \"#{directory}\" recursively"
  Pathname.new(directory).rmtree
end

#run(command, realtime = false) ⇒ String

Run a command and return the standard output.

Returns:

  • (String)

    stdout of command



59
60
61
62
63
64
# File 'lib/takelage/lib/system.rb', line 59

def run(command, realtime=false)
  log.debug "Running command \"#{command}\""
  stdout_str, stderr_str, status = Open3.capture3 command
  log.debug "Command \"#{command}\" has stdout:\n\"\"\"\n#{stdout_str}\"\"\""
  stdout_str
end

#run_and_exit(command) ⇒ Object

Use Kernel#exec to replace the ruby process with a command.



67
68
69
70
# File 'lib/takelage/lib/system.rb', line 67

def run_and_exit(command)
  log.debug "Running command \"#{command}\" and exiting afterwards"
  exec command
end

#run_and_fork(command) ⇒ Object

Use Kernel#fork and Kernel#exec to run a command as a background process.



73
74
75
76
77
78
79
# File 'lib/takelage/lib/system.rb', line 73

def run_and_fork(command)
  log.debug "Running command \"#{command}\" as a background process"
  job = fork do
    exec command
  end
  Process.detach(job)
end

#try(command) ⇒ Boolean

Run a command and return the result.

Returns:

  • (Boolean)

    success of command run



83
84
85
86
87
88
# File 'lib/takelage/lib/system.rb', line 83

def try(command)
  log.debug "Running command \"#{command}\""
  stdout_str, stderr_str, status = Open3.capture3 command
  log.debug "Command \"#{command}\" has exit status \"#{status.exitstatus}\""
  status
end