From e0672df2bbab038fedd1bb11a4c3ad89b874af18 Mon Sep 17 00:00:00 2001 From: sammyette Date: Fri, 25 Apr 2025 20:20:52 -0400 Subject: [PATCH] feat: add basics for man parser --- .hilbishrc.lua | 4 ++++ nature/human.lua | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 nature/human.lua diff --git a/.hilbishrc.lua b/.hilbishrc.lua index 249f97e..e26f79c 100644 --- a/.hilbishrc.lua +++ b/.hilbishrc.lua @@ -47,3 +47,7 @@ end) bait.catch('hilbish.notification', function(notif) doNotifyPrompt() end) + +local human = require 'nature.human' +local manfile = human.where('man', {1}) +human.parse(manfile) diff --git a/nature/human.lua b/nature/human.lua new file mode 100644 index 0000000..7d618c3 --- /dev/null +++ b/nature/human.lua @@ -0,0 +1,42 @@ +local fs = require 'fs' + +local M = {} + +-- Find where a manpage is. +function M.where(name, sections) + local manpath = os.getenv 'MANPATH' + if not manpath then + manpath = '/usr/local/share/man:/usr/share/man' + end + + local paths = string.split(manpath, ':') + for _, path in ipairs(paths) do + -- man directory structure: + -- /man[sectionNumber]/manpage.[sectionNumber].gz + -- example: /man1/Xorg.1.gz + local manSubPaths = fs.glob(fs.join(path, string.format('man%s/', sections and '[' .. table.concat(sections, '') .. ']' or '*'))) + for _, subPath in ipairs(manSubPaths) do + local currentSection = subPath:match '/man([%w%d]+)$' + local assumedPath = fs.join(subPath, string.format('%s%s', name, '.*' .. currentSection .. '.gz')) + local globbedPages = fs.glob(assumedPath) + if globbedPages[1] then + return globbedPages[1] + end + end + end +end + +function M.parse(path) + assert(fs.stat(path), 'file does not exist') + + local _, contents = hilbish.run(string.format('gzip -d %s -c', path), false) + local sections = {} + local sectionPattern = '\n%.SH%s+([^\n]+)\n(.-)\n%.SH' + for sectionName, sectionContent in string.gmatch(contents, sectionPattern) do + sections[string.lower(sectionName)] = sectionContent + end + + return sections +end + +return M