Top Level Namespace

Defined Under Namespace

Classes: State

Utilities: Methods for logging and small predicates collapse

Declarations: collapse

Utilities collapse

Instance Method Summary collapse

Instance Method Details

#aur(*names) ⇒ Object

aur command to install packages from aur on install step



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/declarations/pacman.rb', line 49

def aur(*names)
  names.flatten!
  @aurs ||= Set.new
  @aurs += names.map(&:to_s)

  on_install do
    names = @aurs || []
    log "Install AUR packages", packages: names
    cache = "./cache/aur"
    FileUtils.mkdir_p cache
    Dir.chdir cache do
      names.each do |package|
        system("git clone --depth 1 --shallow-submodules https://aur.archlinux.org/#{package}.git") unless Dir.exist?(package)
        Dir.chdir package do

          pkgbuild = File.readlines('PKGBUILD')
          pkgver = pkgbuild.find { |l| l.start_with?('pkgver=') }.split('=')[1].strip.chomp('"')
          package_info = `pacman -Qi #{package}`.strip.lines.map{|l| l.strip.split(/\s*:\s*/, 2) }.to_h
          installed = package_info["Version"].to_s.split("-")[0] == pkgver

          system("makepkg --syncdeps --install --noconfirm --needed") unless installed
        end
      end
    end
  end
end

#copy(src, dest) ⇒ Object

Copy src inside dest during configure step, if src/. will copy src content to dest



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/declarations/file.rb', line 6

def copy(src, dest)
  @copy ||= []
  @copy << { src: src, dest: dest }

  on_configure do
    next unless @copy
    next if @copy.empty?

    @copy.each do |item|
      log "Copying", item
      FileUtils.cp_r item[:src], item[:dest]
    end
  end
end

#file(path, content) ⇒ Object

Write a file during configure step



71
72
73
74
75
76
77
78
79
80
# File 'lib/declarations/file.rb', line 71

def file(path, content)
  @files ||= {}
  @files[path] = content

  on_configure do
    @files.each do |path, content|
      File.write(path, content)
    end
  end
end

#git_clone(from:, to: nil) ⇒ Object

on prepare make sure a git repository is cloned to directory



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/declarations/git.rb', line 6

def git_clone(from:, to: nil)
  @git_clone ||= Set.new
  @git_clone << {from: from, to: to}

  on_install do
    @git_clone.each do |item|
      from = item[:from]
      to = item[:to]
      system "git clone #{from} #{to}" unless File.exist?(File.expand_path(to))
    end
  end
end

#github_clone(from:, to: nil) ⇒ Object

git clone for github repositories



20
21
22
# File 'lib/declarations/git.rb', line 20

def github_clone(from:, to: nil)
  git_clone(from: "https://github.com/#{from}", to: to)
end

#hostname(name) ⇒ Object

Sets the machine hostname



91
92
93
94
95
96
97
98
99
100
# File 'lib/declarations/systemd.rb', line 91

def hostname(name)
  @hostname = name

  file '/etc/hostname', "#{@hostname}\n"

  on_configure do
    log "Setting hostname", hostname: @hostname
    sudo "hostnamectl set-hostname #{@hostname}"
  end
end

#keyboard(keymap: nil, layout: nil, model: nil, variant: nil, options: nil) ⇒ Object

set keyboard settings during prepare step



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/declarations/systemd.rb', line 60

def keyboard(keymap: nil, layout: nil, model: nil, variant: nil, options: nil)
  @keyboard ||= {}
  values = {
    keymap: keymap,
    layout: layout,
    model: model,
    variant: variant,
    options: options
  }.compact
  @keyboard.merge!(values)

  on_prepare do
    next unless @keyboard[:keymap]

    sudo "localectl set-keymap #{@keyboard[:keymap]}"

    m = @keyboard.to_h.slice(:layout, :model, :variant, :options)
    sudo "localectl set-x11-keymap \"#{m[:layout]}\" \"#{m[:model]}\" \"#{m[:variant]}\" \"#{m[:options]}\""
  end
end

#locale(value) ⇒ Object

Sets locale using localectl



82
83
84
85
86
87
88
# File 'lib/declarations/systemd.rb', line 82

def locale(value)
  @locale = value

  on_prepare do
    sudo "localectl set-locale #{@locale}"
  end
end

#log(msg, args = {}) ⇒ Object

Prints a message to the STDOUT

Parameters:

  • msg (String)

    a log message to print

  • args (Hash<String, Object>) (defaults to: {})

    prints each key and value in separate lines after message



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/utils.rb', line 8

def log(msg, args={})
  puts msg

  return unless args.any?

  max = args.keys.map(&:to_s).max_by(&:length).length
  args.each do |k, v|
    vs = case v
         when Array, Set
           "(#{v.length}) " + v.join(", ")
         else
           v
         end
    puts "\t#{k.to_s.rjust(max)}: #{vs}"
  end
end

#mkdir(*path) ⇒ Object

on prepare make sure the directory exists



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/declarations/file.rb', line 58

def mkdir(*path)
  path.flatten!
  @mkdir ||= Set.new
  @mkdir += path

  on_prepare do
    @mkdir.each do |path|
      FileUtils.mkdir_p File.expand_path(path)
    end
  end
end

#package(*names) ⇒ Object

Install a package on install step and remove packages not registered with this function



15
16
17
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
46
# File 'lib/declarations/pacman.rb', line 15

def package(*names)
  names.flatten!
  @packages ||= Set.new
  @packages += names.map(&:to_s)

  # install step to install packages required and remove not required
  on_install do
    # install missing packages
    need_install = @packages.reject { |p| package? p }
    need_install_args = need_install.join(" ")
    if need_install.any?
      log "Installing packages", packages: need_install
      sudo "pacman --noconfirm --needed -S #{need_install_args}"
    end

    # expand groups to packages
    packages_args = @packages.join(" ")
    group_packages = Set.new(`pacman --quiet -Sg #{packages_args}`.lines.map(&:strip))

    # full list of packages that should exist on the system
    all = @packages + group_packages

    # actual list on the system
    installed = Set.new(`pacman -Q --quiet --explicit --unrequired --native`.lines.map(&:strip))

    unneeded = installed - all
    next if unneeded.empty?

    log "Removing packages", packages: unneeded
    sudo("pacman -Rs #{unneeded.join(" ")}")
  end
end

#package?(name) ⇒ Boolean

Utility function, returns true of package is installed

Returns:

  • (Boolean)


7
8
9
# File 'lib/declarations/pacman.rb', line 7

def package?(name)
  system("pacman -Qi #{name} &> /dev/null")
end

#replace(file, pattern, replacement) ⇒ Object

Replace a regex pattern with replacement string in a file during configure step



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/declarations/file.rb', line 22

def replace(file, pattern, replacement)
  @replace ||= []
  @replace << {file: file, pattern: pattern, replacement: replacement}

  on_configure do
    @replace.each do |params|
      input = File.read(params[:file])
      output = input.gsub(params[:pattern], params[:replacement])
      File.write(params[:file], output)
    end
  end
end

#require_relative_dir(dir) ⇒ Object



1
2
3
# File 'lib/archlinux.rb', line 1

def require_relative_dir(dir)
  Dir["#{File.dirname(__FILE__)}/#{dir}/**/*.rb"].sort.each { |f| require f }
end

#root?Boolean

Checks if current user is the root

Returns:

  • (Boolean)

    true if current user is root and false otherwise



27
28
29
# File 'lib/utils.rb', line 27

def root?
  Process.uid == Etc.getpwnam('root').uid
end

#service(*names) ⇒ Object

enable system service if root or user service if not during finalize step



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/declarations/systemd.rb', line 17

def service(*names)
  names.flatten!
  @services ||= Set.new
  @services += names.map(&:to_s)

  on_finalize do
    log "Enable services", services: @services
    user_flags = root? ? "" : "--user"

    system "systemctl enable #{user_flags} #{@services.join(" ")}"

    # Disable services that were enabled manually and not in the list we have
    services = `systemctl list-unit-files #{user_flags} --state=enabled --type=service --no-legend --no-pager`
    enabled_manually = services.lines.map{|l| l.strip.split(/\s+/) }.select{|l| (l[1] == 'enabled') && (l[2] == 'disabled')}
    names_without_extension = enabled_manually.map{|l| l.first.delete_suffix(".service") }
    to_disable = names_without_extension - @services.to_a

    next if to_disable.empty?

    log "Services to disable", packages: to_disable
    # system "systemctl disable #{user_flags} #{to_disable.join(" ")}"
  end
end

#sudo(command) ⇒ Object

Runs the command with sudo if current user is not root



32
33
34
# File 'lib/utils.rb', line 32

def sudo(command)
  root? ? system(command) : system("sudo #{command}")
end

link file to destination



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/declarations/file.rb', line 36

def symlink(target, link_name)
  @symlink ||= Set.new
  @symlink << {target: target, link_name: link_name}

  on_configure do

    @symlink.each do |params|
      target = File.expand_path params[:target]
      link_name = File.expand_path params[:link_name]
      log "Linking", target: target, link_name: link_name

      # make the parent if it doesn't exist
      dest_dir = File.dirname(link_name)
      FileUtils.mkdir_p(dest_dir) unless File.exist?(dest_dir)

      # link with force
      FileUtils.ln_s(target, link_name, force: true)
    end
  end
end

#timedate(timezone: 'UTC', ntp: true) ⇒ Object

set timezone and NTP settings during prepare step



6
7
8
9
10
11
12
13
14
# File 'lib/declarations/systemd.rb', line 6

def timedate(timezone: 'UTC', ntp: true)
  @timedate = {timezone: timezone, ntp: ntp}

  on_configure do
    log "Set timedate", @timedate
    sudo "timedatectl set-timezone #{@timedate[:timezone]}"
    sudo "timedatectl set-ntp #{@timedate[:ntp]}"
  end
end

#timer(*names) ⇒ Object

enable system timer if root or user timer if not during finalize step



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/declarations/systemd.rb', line 42

def timer(*names)
  names.flatten!
  @timers ||= Set.new
  @timers += names.map(&:to_s)

  on_finalize do
    log "Enable timers", timers: @timers
    timers = @timers.map{ |t| "#{t}.timer" }.join(" ")
    if root?
      sudo "systemctl enable #{timers}"
    else
      system "systemctl enable --user #{timers}"
    end
    # disable all other timers
  end
end

#ufw(*allow) ⇒ Object

setup add ufw enable it and allow ports during configure step



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/applications/ufw.rb', line 6

def ufw(*allow)
  @ufw ||= Set.new
  @ufw += allow.map(&:to_s)

  package :ufw
  service :ufw

  on_configure do
    sudo "ufw allow #{@ufw.join(' ')}"
  end
end

#user(name, groups: [], &block) ⇒ Object

create a user and assign a set of group. if block is passes the block will run in as this user. block will run during the configure step



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/declarations/user.rb', line 8

def user(name, groups: [], &block)
  name = name.to_s

  @user ||= {}
  @user[name] ||= {}
  @user[name][:groups] ||= []
  @user[name][:groups] += groups.map(&:to_s)
  @user[name][:state] = State.new
  @user[name][:state].apply(block) if block_given?

  on_configure do
    @user.each do |name, conf|
      exists = Etc.getpwnam name rescue nil
      sudo "useradd #{name}" unless exists
      sudo "usermod --groups #{groups.join(",")} #{name}" if groups.any?

      fork do
        currentuser = Etc.getpwnam(name)
        Process::GID.change_privilege(currentuser.gid)
        Process::UID.change_privilege(currentuser.uid)
        ENV['XDG_RUNTIME_DIR'] = "/run/user/#{currentuser.uid}"
        ENV['HOME'] = currentuser.dir
        ENV['USER'] = currentuser.name
        ENV['LOGNAME'] = currentuser.name
        conf[:state].run_steps
      end

      Process.wait
    end
  end
end