site  contact  subhomenews

Commandline and file IO in Nim

August 29, 2022 — BarryK

There have already been a couple of posts exploring coding in Nim:

Associative arrays in Nim — August 23, 2022

Debian to Puppy package db conversion in Nim — August 26, 2022

As a learning exercise, I have rewritten 'debdb2pupdb' utility in Nim, fragments of which are in the above posts. I then posted how the final debdb2pupdb.nim was cross-compiled in OpenEmbedded|Yocto:

debdb2pupdb.nim cross-compiled in OE — August 28, 2022

This post explains some more code fragments; concerning reading parameters from the commandline and file reading and writing. Also, some notes on string manipulation.

Here is the start of 'debdb2pupdb.nim':

img1

The "os" library module has to be loaded, for commandline access and file I/O. Pretty straightforward. You can lookup the available functions:

https://nim-lang.org/docs/os.html

Here is another fragment, a bit further down in the program. This creates a procedure to reset the values of an associative-array, open files for reading and writing, define some variables, and read from a file line-by-line:

img2

That "open()" function is in the "io" module, that is not explicitly imported. This is because it belongs to the "system" group, that are automatically imported. Documentation:

https://nim-lang.org/docs/io.html

What the program does is read each line from the Debian package database file, line-by-line, as you can see above. The comments show what the end result is to look like, which is the Puppy-format package database.

That "while" loop will read an entire paragraph, reading into the associative array. After reading a paragraph, it will then be converted to one line in Puppy-format.

I won't post the entire 'debdb2pupdb.nim' here, as it is 256 lines. It can be found in the 'pup-tools-20220828.tar.gz' source file here:

https://distro.ibiblio.org/easyos/source/alphabetical/p/

One very important thing to know about functions, is that functions of the same name may be defined in different modules. Same name, but different parameters, so Nim is able to choose the correct one based on the parameters in your source code.

Most of the string manipulation functions I got from the "strutils" module; however, when I wanted a quick way of getting "dirname" and "basename" of a file path, I used "parentDir()" and "extractFilename" from the "os" module. Code fragment:

img3

Notice the convenient "&" to concatenate strings. Here is documentation on "strutils" module:

https://nim-lang.org/docs/strutils.html

Although it took a couple of very long days to write the program, learning Nim coding as I went along, it was fun. Still getting accustomed to indentation instead of { ... }, but do find the code very readable.   

Tags: easy