Skip to content

Commit

Permalink
Edited (formatting) and added some comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
yuki-was-taken committed May 6, 2024
1 parent 4c015c2 commit 9880586
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 36 deletions.
1 change: 1 addition & 0 deletions src/catnip.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ when not defined release:
import times
let t0 = epochTime()

# Help text
proc printHelp(cfg: Config) =
echo "Usage:"
echo " catnip [options] [arguments]"
Expand Down
18 changes: 9 additions & 9 deletions src/catniplib/drawing/render.nim
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@ proc getStat(stats: TomlValueRef, key: string): TomlValueRef =
return nil

proc Render*(config: Config, fetchinfo: FetchInfo) =
## Function that Renders a FetchInfo object to the console
# Function that Renders a FetchInfo object to the console

##### Define Margins #####
# Define Margins
let
margin_top = fetchinfo.logo.margin[0]
margin_left = fetchinfo.logo.margin[1]
margin_right = fetchinfo.logo.margin[2]

##### Load Config #####
# Load Config
let layout = config.misc["layout"].getStr()

##### Build distro_art buffer #####
# Build distro_art buffer
var distro_art: seq[string]

# Fill distro_art buffer with fetchinfo.logo.art
Expand All @@ -41,7 +41,7 @@ proc Render*(config: Config, fetchinfo: FetchInfo) =
for _ in countup(1, margin_top):
distro_art = " ".repeat(l) & distro_art

##### Build stat_block buffer #####
# Build stat_block buffer
var stats: Stats = newStats()

for stat_name in STATNAMES:
Expand All @@ -62,7 +62,7 @@ proc Render*(config: Config, fetchinfo: FetchInfo) =
# Build the stat_block buffer
var stats_block = buildStatBlock(ORDERED_STATNAMES, stats, fetchinfo)

##### Merge buffers and output #####
# Merge buffers and output
case layout:
of "Inline": # Handle Inline Layout
if not config.misc["imageMode"]["enable"].getBool():
Expand All @@ -78,7 +78,7 @@ proc Render*(config: Config, fetchinfo: FetchInfo) =
for idx in countup(0, distro_art.len - 1):
echo distro_art[idx] & stats_block[idx]
else:
### IMAGE mode ###
# Image mode
let
scale = config.misc["imageMode"]["scale"].getInt()
path = config.misc["imageMode"]["path"].getStr()
Expand Down Expand Up @@ -111,7 +111,7 @@ proc Render*(config: Config, fetchinfo: FetchInfo) =
for idx in countup(0, stats_block.len - 1):
echo stats_block[idx]
else:
### IMAGE mode ###
# Image mode
let
scale = config.misc["imageMode"]["scale"].getInt()
path = config.misc["imageMode"]["path"].getStr()
Expand Down Expand Up @@ -139,7 +139,7 @@ proc Render*(config: Config, fetchinfo: FetchInfo) =
for idx in countup(0, distro_art.len - 1):
echo distro_art[idx]
else:
### IMAGE mode ###
# Image mode
let
scale = config.misc["imageMode"]["scale"].getInt()
path = config.misc["imageMode"]["path"].getStr()
Expand Down
6 changes: 3 additions & 3 deletions src/catniplib/generation/stats.nim
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ import unicode
import tables

proc newStat*(icon: string, name: string, color: Color): Stat =
## Create a new Stat object
# Create a new Stat object
result.icon = icon
result.name = name
result.color = color

proc newStats*(): Stats =
## Create a new Stanamets object
# Create a new Stanamets object
result.maxlen = 0
for name in STATNAMES:
result.list[name] = newStat("", "", "")

proc setStat*(stats: var Stats, stat_name: string, rawstat: TomlValueRef) =
## Function that generates a Stat object an parses it to the related stats field
# Function that generates a Stat object an parses it to the related stats field
if rawstat != nil: # Set to empty stat
# Merge icon with stat name and color
let l = uint(unicode.runeLen(rawstat["icon"].getStr()) + unicode.runeLen(rawstat["name"].getStr()) + 1)
Expand Down
11 changes: 6 additions & 5 deletions src/catniplib/generation/utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ from "stats" import newStat
import "../terminal/colors"

proc repeat*(s: string, i: int): string =
## Repeats a string 's', 'i' times
# Repeats a string 's', 'i' times
for _ in countup(0, i):
result &= s

proc reallen*(s: string): int =
## Get the length of a string without ansi color codes
# Get the length of a string without ansi color codes
result = Uncolorize(s).runeLen

proc buildStatBlock*(stat_names: seq[string], stats: Stats, fi: FetchInfo): seq[string] =
## Build output lines from Stats object and FetchInfo object
# Build output lines from Stats object and FetchInfo object

var sb: seq[string]
proc addStat(stat: Stat, value: string) =
## Function to add a stat/value pair to the result
# Function to add a stat/value pair to the result
var line = stat.icon & " " & stat.name
while uint(line.runeLen) < stats.maxlen:
line &= " "
Expand Down Expand Up @@ -52,7 +52,8 @@ proc buildStatBlock*(stat_names: seq[string], stats: Stats, fi: FetchInfo): seq[

if stats.list[stat] != NIL_STAT:
addStat(stats.list[stat], fi.list[stat])


# Color stat
if stats.list["colors"] != NIL_STAT:
addStat(stats.list["colors"], colorval)
sb.add("" & "".repeat(int(stats.maxlen + 1)) & "")
Expand Down
14 changes: 8 additions & 6 deletions src/catniplib/global/config.nim
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const ALLOWED_NAME_CHARS = {'A' .. 'Z', 'a' .. 'z', '0' .. '9', '_'}
const VALID_TERMS = @["mlterm","yaft-256color","foot","foot-extra","st-256color","xterm","xterm-256color", "alacritty"]

proc isImageTerm(): bool =
## Returns true if terminal supports image mode
# Returns true if terminal supports image mode
var term = ""
if getEnv("TERM_PROGRAM") != "":
term = getEnv("TERM_PROGRAM")
Expand All @@ -19,18 +19,20 @@ proc isImageTerm(): bool =
return (term in VALID_TERMS or "iTerm" in term or "WezTerm" in term or "mintty" in term or "kitty" in term)

proc LoadConfig*(cfgPath: string, dstPath: string): Config =
## Lads a config file and validates it
# Lads a config file and validates it

### Validate the config file ###
# Validate the config file
if not fileExists(cfgPath):
logError(&"{cfgPath} - file not found!")


# Validate the art file
if not fileExists(dstPath):
logError(&"{dstPath} - file not found!")

let tcfg = parsetoml.parseFile(cfgPath)
let tdistros = parsetoml.parseFile(dstPath)


# Error out if stats missing
if not tcfg.contains("stats"):
logError(&"{cfgPath} - missing 'stats'!")

Expand Down Expand Up @@ -76,7 +78,7 @@ proc LoadConfig*(cfgPath: string, dstPath: string): Config =
if tcfg["misc"]["imageMode"]["enable"].getBool() and not isImageTerm():
tcfg["misc"]["imageMode"]["enable"] = parsetoml.parseString(&"val = false")["val"]

### Fill out the result object ###
# Fill out the result object
result.configFile = cfgPath
result.distrosFile = dstPath

Expand Down
1 change: 1 addition & 0 deletions src/catniplib/global/definitions.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import parsetoml
import os
import tables

# Define all stats here
type
Color* = string

Expand Down
24 changes: 14 additions & 10 deletions src/catniplib/platform/probe.nim
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ from "../global/definitions" import DistroId, PKGMANAGERS, PKGCOUNTCOMMANDS
import "../terminal/logging"

proc getDistro*(): string =
## Returns the name of the running linux distro
# Returns the name of the running linux distro
result = "/etc/os-release".loadConfig.getSectionValue("", "PRETTY_NAME") & " " & uname().machine

proc getDistroId*(): DistroId =
## Returns the DistroId of the running linux distro
# Returns the DistroId of the running linux distro
if fileExists("/boot/issue.txt"): # Check if raspbian else get distroid from /etc/os-release
result.id = "raspbian"
result.like = "debian"
Expand All @@ -24,7 +24,7 @@ proc getDistroId*(): DistroId =
result.like = "/etc/os-release".loadConfig.getSectionValue("", "ID_LIKE").toLower()

proc getUptime*(): string =
## Returns the system uptime as a string (DAYS, HOURS, MINUTES)
# Returns the system uptime as a string (DAYS, HOURS, MINUTES)

# Uptime in sec
let uptime = "/proc/uptime".open.readLine.split(".")[0]
Expand All @@ -43,15 +43,15 @@ proc getUptime*(): string =
result = &"{utd}d {uth}h {utm}m" # return days, hours and mins

proc getHostname*(): string =
## Returns the system hostname
# Returns the system hostname
result = uname().nodename

proc getUser*(): string =
## Returns the current username
# Returns the current username
result = getEnv("USER")

proc getKernel*(): string =
## Returns the active kernel version
# Returns the active kernel version
result = "/proc/version".open.readLine.split(" ")[2]

proc getParentPid(pid: int): int =
Expand All @@ -72,17 +72,17 @@ proc getProcessName(pid: int): string =
return stat[1].strip()

proc getTerminal*(): string =
## Returns the currently running terminal emulator
# Returns the currently running terminal emulator
result = getCurrentProcessID().getParentPid().getParentPid().getProcessName()
if result == "login" or result == "sshd":
result = "tty"

proc getShell*(): string =
## Returns the system shell
# Returns the system shell
result = getCurrentProcessID().getParentPid().getProcessName()

proc getDesktop*(): string =
## Returns the running desktop env
# Returns the running desktop env
result = getEnv("XDG_CURRENT_DESKTOP") # Check Current Desktop (Method 1)

if result == "": # Check Current Desktop (Method 2)
Expand All @@ -103,7 +103,7 @@ proc getDesktop*(): string =
result = "Unknown"

proc getMemory*(mb: bool): string =
## Returns statistics about the memory
# Returns statistics about the memory
let
fileSeq: seq[string] = "/proc/meminfo".readLines(3)

Expand All @@ -121,6 +121,7 @@ proc getMemory*(mb: bool): string =
result = &"{memUsedInt}/{memTotalInt} {suffix}"

proc getDisk*(): string =
# Returns disk space usage
proc getTotalDiskSpace(): cfloat {.importc, varargs, header: "getDiskSpace.hpp".}
proc getUsedDiskSpace(): cfloat {.importc, varargs, header: "getDiskSpace.hpp".}

Expand All @@ -130,6 +131,7 @@ proc getDisk*(): string =
result = &"{used} / {total} GB ({percentage}%)"

proc getCpu*(): string =
# Returns CPU model
let rawLines = readFile("/proc/cpuinfo").split("\n")

var key_name = "model name"
Expand All @@ -148,6 +150,7 @@ proc getCpu*(): string =
break

proc getPkgManager(distroId: DistroId): string =
# Returns main package manager of distro
for key in PKGMANAGERS.keys:
if distroId.id == key:
return PKGMANAGERS[key]
Expand All @@ -159,6 +162,7 @@ proc getPkgManager(distroId: DistroId): string =
return "unknown"

proc getPackages*(distroId: DistroId): string =
# Return install package count of the main package manager of the distro
let pkgManager = getPkgManager(distroId)
if pkgManager == "unknown":
return "unknown"
Expand Down
2 changes: 0 additions & 2 deletions src/catniplib/terminal/colors.nim
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ proc initForeground(): ColorSet = # (..)
result.Cyan = "\e[36m" # CN
result.White = "\e[37m" # WE


proc initForegroundBright(): ColorSet = # {..}
result.Black = "\e[30;1m" # BK
result.Red = "\e[31;1m" # RD
Expand Down Expand Up @@ -43,7 +42,6 @@ proc initBackgroundBright(): ColorSet = # <..>
result.Cyan = "\e[46;1m" # CN
result.White = "\e[47;1m" # WE


# Global ColorSets:
const
Foreground*: ColorSet = initForeground()
Expand Down
2 changes: 1 addition & 1 deletion tests/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
./../bin/catnip -c ../config/config.toml -a ../config/distros.toml -fe on
# test figletlogos margin
./../bin/catnip -c ../config/config.toml -a ../config/distros.toml -fe on -fm 1,2,3
# test figletlogos font
# test figletlogos font with example figlet font file
./../bin/catnip -c ../config/config.toml -a ../config/distros.toml -fe on -ff basic.flf

0 comments on commit 9880586

Please sign in to comment.