aboutsummaryrefslogtreecommitdiff
path: root/src/utils.nim
blob: 1d7c6bde41f01567edfc1029de33296501d85b27 (plain) (blame)
1
2
3
4
5
6
7
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
39
40
41
42
43
44
45
46
47
48
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import
  future, hashes, options, os, osproc, posix, strutils, tables

type
  HaltError* = object of Exception
    code*: int

  CommandError* = object of Exception
    color*: Option[bool]
    error*: bool

const
  pkgLibDir* = getenv("PROG_PKGLIBDIR")
  localStateDir* = getenv("PROG_LOCALSTATEDIR")
  sysConfDir* = getenv("PROG_SYSCONFDIR")

  bashCmd* = "/bin/bash"
  suCmd* = "/usr/bin/su"
  sudoCmd* = "/usr/bin/sudo"
  gitCmd* = "/usr/bin/git"
  pacmanCmd* = "/usr/bin/pacman"
  makepkgCmd* = "/usr/bin/makepkg"

template haltError*(code: int): untyped =
  var e: ref HaltError
  new(e)
  e.code = code
  e

template commandError*(message: string, colorNeeded: Option[bool] = none(bool),
  showError: bool = true): untyped =
  var e: ref CommandError
  new(e)
  e.msg = message
  e.color = colorNeeded
  e.error = showError
  e

iterator items*[T](self: Option[T]): T {.raises: [].} =
  if self.isSome:
    yield self.unsafeGet

template len*[T](self: Option[T]): int =
  if self.isSome: 1 else: 0

template orElse*[T, R](opt1: Option[T], opt2: Option[R]): Option[R] =
  if opt1.isSome: opt1 else: opt2

template hash*[T](opt: Option[T]): int =
  opt.map(hash).get(0)

proc opt*[K, V](table: Table[K, V], key: K): Option[V] =
  if table.hasKey(key): some(table[key]) else: none(V)

proc opt*[K, V](table: OrderedTable[K, V], key: K): Option[V] =
  if table.hasKey(key): some(table[key]) else: none(V)

proc optFirst*[T](s: openArray[T]): Option[T] =
  if s.len > 0: some(s[s.low]) else: none(T)

proc optLast*[T](s: openArray[T]): Option[T] =
  if s.len > 0: some(s[s.high]) else: none(T)

iterator enumerate*[T: enum]: T =
  let elow = T.low.ord
  let ehigh = T.high.ord
  for i in elow .. ehigh:
    yield T(i)

iterator namedPairs*[K, V](table: Table[K, V]): tuple[key: K, value: V] =
  for key, value in table.pairs:
    yield (key, value)

iterator reversed*[T](s: openArray[T]): T =
    for i in countdown(s.len - 1, 0):
      yield s[i]

proc groupBy*[T, X](s: seq[T], callback: T -> X): seq[tuple[key: X, values: seq[T]]] =
  var table = initOrderedTable[X, ref seq[T]]()
  for value in s:
    let key = callback(value)
    var work: ref seq[T]
    if table.hasKey(key):
      work = table[key]
    else:
      new(work)
      work[] = newSeq[T]()
      table[key] = work
    work[] &= value

  result = newSeq[tuple[key: X, values: seq[T]]]()
  for key, values in table.pairs:
    result &= (key, values[])

proc perror*(s: cstring): void {.importc, header: "<stdio.h>".}
template perror*: void = perror(getAppFilename())

proc execResult*(args: varargs[string]): int =
  let cexec = allocCStringArray(args)
  let code = execvp(cexec[0], cexec)
  perror()
  deallocCStringArray(cexec)
  code

const
  interruptSignals* = [SIGINT, SIGTERM]

template blockSignals*(signals: openArray[cint],
  unblock: untyped, body: untyped): untyped =
  block:
    var sigset: Sigset
    var sigoldset: Sigset

    discard sigemptyset(sigset)
    for s in signals:
      discard sigaddset(sigset, s)
    discard sigprocmask(SIG_BLOCK, sigset, sigoldset)

    var unblocked = false
    let unblock = () => (block:
      if not unblocked:
        discard sigprocmask(SIG_SETMASK, sigoldset, sigset)
      unblocked = true)

    try:
      body
    finally:
      unblock()

proc forkWait*(call: () -> int): int =
  blockSignals(interruptSignals, unblock):
    let pid = fork()
    if pid == 0:
      unblock()
      quit(call())
    else:
      var status: cint = 1
      discard waitpid(pid, status, 0)
      if WIFEXITED(status):
        return WEXITSTATUS(status)
      else:
        discard kill(getpid(), status)
        return 1

proc runProgram*(args: varargs[string]): seq[string] =
  let output = execProcess(args[0], @args[1 .. ^1], options = {})
  if output.len == 0:
    @[]
  elif output.len > 0 and $output[^1] == "\n":
    output[0 .. ^2].split("\n")
  else:
    output.split("\n")

proc setenv*(name: cstring, value: cstring, override: cint): cint
  {.importc, header: "<stdlib.h>".}

proc getUser*: (int, string) =
  let uid = getuid()
  while true:
    var pw = getpwent()
    if pw == nil:
      raise newException(SystemError, "")
    if pw.pw_uid == uid:
      return (uid.int, $pw.pw_name)

proc toString*[T](arr: array[T, char], length: Option[int]): string =
  var workLength = length.get(T.high + 1)
  var str = newStringOfCap(workLength)
  for i in 0 .. workLength - 1:
    let c = arr[i]
    if length.isNone and c == '\0':
      break
    str.add(arr[i])
  str

proc removeDirQuiet*(s: string) =
  try:
    removeDir(s)
  except:
    discard

proc dgettext(domain: cstring, s: cstring): cstring
  {.cdecl, importc: "dgettext".}

proc gettext(domain: string, s: string): string =
  let translated = dgettext(domain, s)
  if translated != nil: $translated else: s

proc gettextHandle(domain: string, s: string): string =
  let res = gettext(domain, s).replace("%s", "$#").replace("%c", "$#")
  if res.len > 0 and res[^1 .. ^1] == "\n": res[0 .. ^2] else: res

template tr*(s: string): string =
  gettext("pakku", s)

template trp*(s: string): string =
  gettextHandle("pacman", s)

template tra*(s: string): string =
  gettextHandle("libalpm", s)

template trc*(s: string): string =
  gettextHandle("libc", s)