From 18fa42df7e62fc26468614c09a8d68a8f4452583 Mon Sep 17 00:00:00 2001
From: Eamon Burns <me@eamonburns.com>
Date: Thu, 11 Jul 2024 15:03:41 -0700
Subject: [PATCH] fix: Termux compatible `is_readable_directory` function (#42)

* feat(util): use test command to check directory

* fix: use single quotes in util/file.lua

* feat(util): add type hints and documentation, remove old function

* feat(parsers): move all parsers to their own submodule (#43)

BREAKING CHANGE: Parser modules have been moved

Add `check` functions to all parser modules

* feat(util): use old "readable directory" method when not in Termux
---
 lua/util/file.lua | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)

diff --git a/lua/util/file.lua b/lua/util/file.lua
index d18a2fe..9807bb5 100644
--- a/lua/util/file.lua
+++ b/lua/util/file.lua
@@ -2,9 +2,24 @@ local M = {}
 
 local bit = require('bit')
 
-function M.is_readable_directory(file)
-  local s = vim.loop.fs_stat(file)
-  return s ~= nil and s.type == 'directory' and bit.band(s.mode, 4) == 4
+---Check if there is a readable directory at the given file path.
+---Warning: the `path` may be substituted onto the command line,
+---so the input _must_ be trusted.
+---@param path string
+---@return boolean
+function M.is_readable_directory(path)
+  if not os.getenv('TERMUX_VERSION') then
+    -- When not running in Termux
+    local s = vim.loop.fs_stat(path)
+    return (
+      s ~= nil -- File exists
+      and s.type == 'directory' -- File is a directory
+      and bit.band(s.mode, 4) == 4 -- File is readable (Minimum permissions: ------r--)
+    )
+  else
+    -- In Termux, use the `test` command
+    return os.execute('test -d \''..path..'\' && test -r \''..path..'\'') == 0
+  end
 end
 
 return M