aboutsummaryrefslogtreecommitdiff
path: root/src/lapis.nim
blob: ba8f4ff595b2635708faf45d5282dbc534d8abd3 (plain)
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import std / [ 
  macros, 
  strformat,
  strutils
]

macro tessera*(packageName: untyped, body: untyped): untyped =
  ## Small declerative DSL for defining packages
  ## The schema is:
  ##   package "name":
  ##     source: "<url>"
  ##     patches: @[...] (if any)
  ##     dependencies: @[...] (if any)
  ##     build: @[...]
  ##     result: @[...]
  ##
  ## The macro expands at compile time into a build() procedure. 
  ## When run it:
  ##   - verifies the `dependencies` are installed properly
  ##     ( this rn means that it checks $PATH, 
  ##       since I haven't worked on mosaic yet )
  ##     ( if a dependency isn't installed, it installs it )
  ##   - uses cURL to fetch the tarball from the `sourceURL`
  ##   - extracts the tarball, and cd's into it 
  ##   - applies `patches` (if any)
  ##   - runs the build commands defined in `build: @[...]` 
 
  if packageName.kind == nnkIdent:
    error("Name of package must be a string: {packageName}->\"{packageName}\"")
   
  body.expectKind nnkStmtList

  var 
    nameLit = newLit($toStrLit(packageName))
    sourceNode = newLit("")
    patchesNode = newLit(newSeq[string]())
    depsNode = newLit(newSeq[string]())
    buildNode = newLit(newSeq[string]())
    resultNode = newLit("")

  for stmt in body:
    if stmt.kind == nnkCall:
      let key = $stmt[0]
      let value = stmt[1]
      case key:
      of "source": sourceNode = value
      of "patches": patchesNode = value
      of "dependencies": depsNode = value
      of "build": buildNode = value
      of "result": resultNode = value
      else:
        error("tessera: unknown field {key}".fmt)
    else:
      error("tessera: unexpected statement in package block: {stmt.repr}".fmt)

  let buildIdent = ident("build_{packageName}".fmt)

  result = quote do:
    import os, osproc, strutils

    const
      pkgName = `nameLit` 
      pkgSource = `sourceNode`
      pkgPatches = `patchesNode`
      pkgDeps = `depsNode`
      pkgBuild = `buildNode`
      pkgResult = `resultNode`

    # Helper procs
    proc extractFilename(url: string): string =
      if url.len == 0: 
        return ""
      let parts = url.split('/')
      result = parts[^1]

    proc stripExtension(filename: string): string =
      result = filename
      # list of tar suffixes from Wikipedia
      let suffixList = @[
        ".tar.gz", 
        ".tar.xz", 
        ".tar.bz2",
        ".tar.lz",
        ".tar.lzma",
        ".tar.lzo",
        ".tar.Z",
        ".tar.zst",
        ".tb2",
        ".tbz",
        ".tbz2",
        ".tz2",
        ".taz",
        ".tgz",
        ".tlz",
        ".txz",
        ".tZ",
        ".taZ",
        ".tzst"
      ] 
      for suffix in suffixList:
        if result.endsWith(suffix):
          result.removeSuffix(suffix)

    proc isExecutable(filename: string): bool =
      let permissions = getFilePermissions(filename)
      result = ((fpUserExec in permissions) or (fpGroupExec in permissions))

    proc isInstalled(name: string): bool =
      result = false
      let possibleFolders = @["/usr/bin/", "/usr/sbin/", "/usr/lib/"]
      for folder in possibleFolders:
        if fileExists(folder & name):
          result = true

    # TODO: Make this not depend on the tar file
    proc ensureDependency(dependency: string, tarFile: string) =
        if dependency.len > 0:
          # TODO: When I fix the declerativeness, I must also fix this
          let localInstaller = "/mosaic/panel/" & $dependency
          echo "checking " & localInstaller & "..."

          if not (fileExists(localInstaller) or isExecutable(localInstaller)):
            quit("dependency \"" & $dependency & "\" not defined yet.")
     
          let
            installProcess = startProcess("/mosaic/panel/" & $dependency)
          
          for line in installProcess.lines:
            echo "[CMD] Installing " & $dependency & " | " & line 

    # TODO: Add quits (again) after exitCode != 0
    proc `buildIdent`() = 
      echo "Building " & $pkgName

      let 
        mosaicSourceFolder = "/mosaic/quarry/"
        sourceFile = $mosaicSourceFolder & extractFilename(url=pkgSource)
      
      # Step 1: check dependencies
      if isInstalled(pkgResult):
        echo pkgName & " already installed..."
        return

      if pkgDeps.len > 0:
        for dependency in pkgDeps:
          echo "checking dependency: " & $dependency
          ensureDependency(dependency=dependency, tarFile=sourceFile)

      # Step 2: fetch source via cURL
      var expectedFolder = stripExtension(sourceFile) & "/"
      echo "Making " & expectedFolder & "..."
      createDir(expectedFolder)

      if not fileExists(sourceFile): 
        echo "Fetching source: " & $pkgSource & " -> " & sourceFile
        let
          wgetCmd = "wget " & $pkgSource
          # For some reason startProcess fails????????????????????????
          (wgetOutput, wgetExitCode) = execCmdEx(wgetCmd, workingDir=mosaicSourceFolder)

        echo "[WGET] " & $wgetOutput
      else:
        echo $sourceFile & " exists. Continuing..."

      # Step 3: untar
      echo "extracting " & $sourceFile & "..."

      let
        tarCmd = "tar -xf " & $sourceFile & " -C " & $expectedFolder
        (tarOutput, tarExitCode) = execCmdEx(tarCmd, workingDir=mosaicSourceFolder)

      echo "[TAR] " & $tarOutput
      
      var untarFolders: seq[string] = @[]
      for folder in walkDir(expectedFolder):
        untarFolders.add(folder.path)

      echo untarFolders
      if untarFolders.len == 0:
        quit("No folders produces in untarring step (?)... Quitting...")
      if untarFolders.len == 1:
        expectedFolder = untarFolders[0]

      # Step 5
      if pkgPatches.len > 0:
        for patchURL in pkgPatches:
          if patchURL.len > 0:
            let patchFile = extractFilename(url=patchURL)

            echo "Fetching patch: " & $patchURL & " -> " & $patchFile
            
            let 
              patchWgetCmd = "wget " & $patchURL
              (patchOutput, patchExitCode) = execCmdEx(patchWgetCmd, workingDir=mosaicSourceFolder)

            echo "[PATCH] " & $patchOutput

            assert fileExists($mosaicsourceFolder & $patchFile)

      # Step 6: Run the build commands:
      if pkgBuild.len == 0:
        quit("No commands given to run for " & $pkgName & "... Nothing to do.")
     
      var newWorkingFolder = expectedFolder 
      for command in pkgBuild:
        if command.startsWith("cd "):
          newWorkingFolder = newWorkingFolder & command[3..^1] 
          echo "[INFO] Working Folder set" & $newWorkingFolder
          continue

        let
          (cmdOutput, cmdExitCode) = execCmdEx(command, workingDir=newWorkingFolder) 

        echo "[CMD] " & cmdOutput 
      
      echo "tessera " & $pkgName & " built."

    when isMainModule:
      `buildIdent`()
Directive (EU) 2019/790, Article 4(3); all rights regarding Text and Data Mining (TDM) are reserved.