feat(mime-ext): make FILES and EXTS configurable, add option to fallback to preset mime plugin (#26)

Co-authored-by: sxyazi <sxyazi@gmail.com>
This commit is contained in:
dm9pZCAq
2024-10-01 04:56:27 +00:00
committed by GitHub
parent 6c11a97ed6
commit 74a837c6ea
2 changed files with 61 additions and 6 deletions

View File

@@ -23,9 +23,32 @@ run = "mime-ext"
prio = "high"
```
## Advanced
Or you can customize it in your `~/.config/yazi/init.lua`:
```lua
require("mime-ext"):setup {
-- Expand the existing filename database (lowercase), for example:
with_files = {
makefile = "text/x-makefile",
-- ...
},
-- Expand the existing extension database (lowercase), for example:
with_exts = {
mk = "text/x-makefile",
-- ...
},
-- If the mime-type is not in both filename and extension databases,
-- then fallback to Yazi's preset `mime` plugin, which uses `file(1)`
fallback_file1 = false,
}
```
## TODO
- Add more file types (PRs welcome!).
- Allow configuring the plugin and overriding some of its rules.
- Eliminating `x-` as part of Yazi v0.4 as it's discouraged as per [rfc6838#section-3.4](https://datatracker.ietf.org/doc/html/rfc6838#section-3.4)
- Compress mime-type tables.

View File

@@ -1026,18 +1026,45 @@ local EXTS = {
zsh = "text/shellscript",
}
local function fetch(self)
local updates = {}
local options = ya.sync(
function(st)
return {
with_files = st.with_files,
with_exts = st.with_exts,
fallback_file1 = st.fallback_file1,
}
end
)
local M = {}
function M:setup(opts)
opts = opts or {}
self.with_files = opts.with_files
self.with_exts = opts.with_exts
self.fallback_file1 = opts.fallback_file1
end
function M:fetch()
local opts = options()
local merged_files = ya.dict_merge(FILES, opts.with_files or {})
local merged_exts = ya.dict_merge(EXTS, opts.with_exts or {})
local updates, unknown = {}, {}
for _, file in ipairs(self.files) do
local mime
if file.cha.len == 0 then
mime = "inode/x-empty"
else
mime = FILES[(file.url:name() or ""):lower()]
mime = mime or EXTS[(file.url:ext() or ""):lower()]
mime = merged_files[(file.url:name() or ""):lower()]
mime = mime or merged_exts[(file.url:ext() or ""):lower()]
end
if mime then
updates[tostring(file.url)] = mime
elseif opts.fallback_file1 then
unknown[#unknown + 1] = file
end
end
@@ -1045,7 +1072,12 @@ local function fetch(self)
ya.manager_emit("update_mimetype", { updates = updates })
end
if #unknown > 0 then
self.files = unknown
return require("mime").fetch(self)
end
return 1
end
return { fetch = fetch }
return M