aboutsummaryrefslogtreecommitdiff
path: root/src/config.nim
blob: fb1f3ae939731557ebddec7d3df36a2601018305 (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
import
  future, options, posix, re, sequtils, sets, strutils, tables,
  utils

type
  ColorMode* {.pure.} = enum
    colorNever = "never",
    colorAuto = "auto",
    colorAlways = "always"

  PreserveBuilt* {.pure.} = enum
    internal = "Internal",
    user = "User",
    disabled = "Disabled"

  CommonConfig* = object of RootObj
    dbs*: seq[string]
    arch*: string
    debug*: bool
    progressBar*: bool
    verbosePkgList*: bool
    downloadTimeout*: bool
    pgpKeyserver*: Option[string]
    defaultRoot*: bool
    ignorePkgs*: HashSet[string]
    ignoreGroups*: HashSet[string]

  PacmanConfig* = object of CommonConfig
    sysrootOption*: Option[string]
    rootRelOption*: Option[string]
    dbRelOption*: Option[string]
    cacheRelOption*: Option[string]
    gpgRelOption*: Option[string]
    colorMode*: ColorMode

  Config* = object of CommonConfig
    root*: string
    db*: string
    cache*: string
    userCacheInitial*: string
    userCacheCurrent*: string
    tmpRootInitial*: string
    tmpRootCurrent*: string
    color*: bool
    aurRepo*: string
    aurComments*: bool
    checkIgnored*: bool
    ignoreArch*: bool
    printAurNotFound*: bool
    printLocalIsNewer*: bool
    sudoExec*: bool
    viewNoDefault*: bool
    preserveBuilt*: PreserveBuilt
    preBuildCommand*: Option[string]

proc readConfigFile*(configFile: string):
  (OrderedTable[string, ref Table[string, string]], bool) =
  var file: File
  var table = initOrderedTable[string, ref Table[string, string]]()
  var category: ref Table[string, string]
  var currentCategory = ""

  let wasError = if file.open(configFile):
      try:
        var matches: array[2, string]

        while true:
          let line = readLine(file).strip(leading = true, trailing = true)
          if line.len > 0 and line[0] != '#':
            if line.match(re"\[(.*)\]", matches):
              currentCategory = matches[0]
              if table.hasKey(currentCategory):
                category = table[currentCategory]
              else:
                category = newTable[string, string]()
                table[currentCategory] = category
            elif currentCategory.len > 0:
              if line.match(re"(\w+)\ *=\ *(.*)", matches):
                category[].add(matches[0], matches[1])
              else:
                category[].add(line, "")

        false
      except EOFError:
        false
      except IOError:
        true
      finally:
        file.close()
    else:
      true

  (table, wasError)

proc ignored*(config: Config, name: string, groups: openArray[string]): bool =
  name in config.ignorePkgs or (config.ignoreGroups * groups.toSet).len > 0

proc get*(colorMode: ColorMode): bool =
  case colorMode:
    of ColorMode.colorNever: false
    of ColorMode.colorAlways: true
    of ColorMode.colorAuto: isatty(1) == 1

proc pacmanRootRel*(config: PacmanConfig): string =
  config.rootRelOption.get("/")

proc pacmanDbRel*(config: PacmanConfig): string =
  if config.dbRelOption.isSome:
    config.dbRelOption.unsafeGet
  else:
    let root = config.pacmanRootRel
    let workRoot = if root == "/": "" else: root
    workRoot & localStateDir & "/lib/pacman/"

proc pacmanCacheRel*(config: PacmanConfig): string =
  config.cacheRelOption.get(localStateDir & "/cache/pacman/pkg")

proc simplifyConfigPath(path: string): string =
  if path.find("//") >= 0:
    simplifyConfigPath(path.replace("//", "/"))
  else:
    path

proc extendRel*(pathRel: string, sysroot: Option[string]): string =
  sysroot.map(s => (s & "/" & pathRel).simplifyConfigPath).get(pathRel)

proc obtainConfig*(config: PacmanConfig): Config =
  let (configTable, _) = readConfigFile(sysConfDir & "/pakku.conf")
  let options = configTable.opt("options").map(t => t[]).get(initTable[string, string]())

  let root = config.pacmanRootRel.extendRel(config.sysrootOption)
  let db = config.pacmanDbRel.extendRel(config.sysrootOption)
  let cache = config.pacmanCacheRel.extendRel(config.sysrootOption)
  let color = config.colorMode.get

  proc handleDirPattern(dirPattern: string, user: User): string =
    dirPattern
      .replace("${UID}", $user.uid)
      .replace("${USER}", user.name)
      .replace("${HOME}", user.home)
      .replace("$$", "$")

  proc obtainUserCacheDir(user: User): string =
    options.opt("UserCacheDir").get("${HOME}/.cache/pakku").handleDirPattern(user)

  proc obtainTmpDir(user: User): string =
    options.opt("TmpDir").get("/tmp/pakku-${USER}").handleDirPattern(user)

  let initialOrCurrentUser = initialUser.get(currentUser)
  let userCacheInitial = obtainUserCacheDir(initialOrCurrentUser)
  let userCacheCurrent = obtainUserCacheDir(currentUser)
  let tmpRootInitial = obtainTmpDir(initialOrCurrentUser)
  let tmpRootCurrent = obtainTmpDir(currentUser)
  let aurRepo = options.opt("AurRepo").get("aur")
  let aurComments = options.hasKey("AurComments")
  let checkIgnored = options.hasKey("CheckIgnored")
  let ignoreArch = options.hasKey("IgnoreArch")
  let printAurNotFound = options.hasKey("PrintAurNotFound")
  let printLocalIsNewer = options.hasKey("PrintLocalIsNewer")
  let sudoExec = options.hasKey("SudoExec")
  let viewNoDefault = options.hasKey("ViewNoDefault")
  let preserveBuilt = toSeq(enumerate[PreserveBuilt]())
    .filter(o => some($o) == options.opt("PreserveBuilt"))
    .optLast.get(PreserveBuilt.disabled)
  let preBuildCommand = options.opt("PreBuildCommand")

  if config.dbs.find(aurRepo) >= 0:
    raise commandError(tr"repo '$#' can not be used as fake AUR repository" % [aurRepo],
      colorNeeded = some(color))

  if aurRepo.find('/') >= 0:
    raise commandError(trp("could not register '%s' database (%s)\n") %
      [aurRepo, tra"wrong or NULL argument passed"], colorNeeded = some(color))

  Config(dbs: config.dbs, arch: config.arch, debug: config.debug,
    progressBar: config.progressBar, verbosePkgList: config.verbosePkgList,
    downloadTimeout: config.downloadTimeout, pgpKeyserver: config.pgpKeyserver,
    defaultRoot: config.defaultRoot and config.sysrootOption.isNone,
    ignorePkgs: config.ignorePkgs, ignoreGroups: config.ignoreGroups,
    root: root, db: db, cache: cache, userCacheInitial: userCacheInitial,
    userCacheCurrent: userCacheCurrent, tmpRootInitial: tmpRootInitial,
    tmpRootCurrent: tmpRootCurrent, color: color, aurRepo: aurRepo, aurComments: aurComments,
    checkIgnored: checkIgnored, ignoreArch: ignoreArch, printAurNotFound: printAurNotFound,
    printLocalIsNewer: printLocalIsNewer, sudoExec: sudoExec, viewNoDefault: viewNoDefault,
    preserveBuilt: preserveBuilt, preBuildCommand: preBuildCommand)

template withAlpmConfig*(config: Config, passDbs: bool,
  handle: untyped, alpmDbs: untyped, errors: untyped, body: untyped): untyped =
  withAlpm(config.root, config.db, if passDbs: config.dbs else: @[], config.arch,
    handle, alpmDbs, errors, body)