-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
3595 lines (2869 loc) · 108 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Plugin to make some Yazi commands smarter
-- Written in Lua 5.4
-- Type aliases
-- The type for the arguments
---@alias Arguments table<string|number, string|number|boolean>
-- The type for the function to handle a command
--
-- Description of the function parameters:
-- args: The arguments to pass to the command
-- config: The configuration object
---@alias CommandFunction fun(
--- args: Arguments,
--- config: Configuration): nil
-- The type of the command table
---@alias CommandTable table<SupportedCommands, CommandFunction>
-- The type for the extractor list items command
---@alias ExtractorListItemsCommand fun(
--- self: Extractor,
---): output: CommandOutput|nil, error: Error|nil
-- The type for the extractor get items function
---@alias ExtractorGetItems fun(
--- self: Extractor,
---): files: string[], directories: string[], error: string|nil
-- The type for the extractor extract function.
---@alias ExtractorExtract fun(
--- self: Extractor,
--- has_only_one_file: boolean|nil,
---): ExtractionResult
-- The type for the extractor function
---@alias ExtractorCommand fun(): output: CommandOutput|nil, error: Error|nil
-- Custom types
-- The type of the user configuration table
-- The user configuration for the plugin
---@class (exact) UserConfiguration
---@field prompt boolean Whether or not to prompt the user
---@field default_item_group_for_prompt ItemGroup The default prompt item group
---@field smart_enter boolean Whether to use smart enter
---@field smart_paste boolean Whether to use smart paste
---@field smart_tab_create boolean Whether to use smart tab create
---@field smart_tab_switch boolean Whether to use smart tab switch
---@field open_file_after_creation boolean Whether to open after creation
---@field enter_directory_after_creation boolean Whether to enter after creation
---@field use_default_create_behaviour boolean Use Yazi's create behaviour?
---@field enter_archives boolean Whether to enter archives
---@field extract_retries number How many times to retry extracting
---@field recursively_extract_archives boolean Extract inner archives or not
---@field preserve_file_permissions boolean Whether to preserve file permissions
---@field must_have_hovered_item boolean Whether to stop when no item is hovered
---@field skip_single_subdirectory_on_enter boolean Skip single subdir on enter
---@field skip_single_subdirectory_on_leave boolean Skip single subdir on leave
---@field wraparound_file_navigation boolean Have wraparound navigation or not
-- The full configuration for the plugin
---@class (exact) Configuration: UserConfiguration
-- The type for the state
---@class (exact) State
---@field config Configuration The configuration object
-- The type for the extractor function result
---@class (exact) ExtractionResult
---@field successful boolean Whether the extractor function was successful
---@field output string|nil The output of the extractor function
---@field cancelled boolean|nil boolean Whether the extraction was cancelled
---@field error string|nil The error message
---@field archive_path string|nil The path to the archive
---@field destination_path string|nil The path to the destination
---@field extracted_items_path string|nil The path to the extracted items
-- The name of the plugin
---@type string
local PLUGIN_NAME = "augment-command"
-- The enum for the supported commands
---@enum SupportedCommands
local Commands = {
Open = "open",
Extract = "extract",
Enter = "enter",
Leave = "leave",
Rename = "rename",
Remove = "remove",
Create = "create",
Shell = "shell",
Paste = "paste",
TabCreate = "tab_create",
TabSwitch = "tab_switch",
Arrow = "arrow",
ParentArrow = "parent_arrow",
Editor = "editor",
Pager = "pager",
}
-- The enum for which group of items to operate on
---@enum ItemGroup
local ItemGroup = {
Hovered = "hovered",
Selected = "selected",
None = "none",
Prompt = "prompt",
}
-- The default configuration for the plugin
---@type UserConfiguration
local DEFAULT_CONFIG = {
prompt = false,
default_item_group_for_prompt = ItemGroup.Hovered,
smart_enter = true,
smart_paste = false,
smart_tab_create = false,
smart_tab_switch = false,
open_file_after_creation = false,
enter_directory_after_creation = false,
use_default_create_behaviour = false,
enter_archives = true,
extract_retries = 3,
recursively_extract_archives = true,
preserve_file_permissions = false,
must_have_hovered_item = true,
skip_single_subdirectory_on_enter = true,
skip_single_subdirectory_on_leave = true,
wraparound_file_navigation = false,
}
-- The default input options for this plugin
local DEFAULT_INPUT_OPTIONS = {
position = { "top-center", x = 0, y = 2, w = 50, h = 3 },
}
-- The default confirm options for this plugin
local DEFAULT_CONFIRM_OPTIONS = {
pos = { "center", x = 0, y = 0, w = 50, h = 15 },
}
-- The default notification options for this plugin
local DEFAULT_NOTIFICATION_OPTIONS = {
title = "Augment Command Plugin",
timeout = 5,
}
-- The tab preference keys.
-- The values are just dummy values
-- so that I don't have to maintain two
-- different types for the same thing.
---@type tab.Preference
local TAB_PREFERENCE_KEYS = {
sort_by = "alphabetical",
sort_sensitive = false,
sort_reverse = false,
sort_dir_first = true,
sort_translit = false,
linemode = "none",
show_hidden = false,
}
-- The table of input options for the prompt
---@type table<ItemGroup, string>
local INPUT_OPTIONS_TABLE = {
[ItemGroup.Hovered] = "(H/s)",
[ItemGroup.Selected] = "(h/S)",
[ItemGroup.None] = "(h/s)",
}
-- The extractor names
---@enum ExtractorName
local ExtractorName = {
SevenZip = "7z",
Tar = "tar",
}
-- The extract behaviour flags
---@enum ExtractBehaviour
local ExtractBehaviour = {
Overwrite = "overwrite",
Rename = "rename",
}
-- The list of archive file extensions
---@type table<string, boolean>
local ARCHIVE_FILE_EXTENSIONS = {
["7z"] = true,
boz = true,
bz = true,
bz2 = true,
bzip2 = true,
cb7 = true,
cbr = true,
cbt = true,
cbz = true,
gz = true,
gzip = true,
rar = true,
s7z = true,
tar = true,
tbz = true,
tbz2 = true,
tgz = true,
txz = true,
xz = true,
zip = true,
}
-- The error for the base extractor class
-- which is an abstract base class that
-- does not implement any functionality
---@type string
local BASE_EXTRACTOR_ERROR = table.concat({
"The Extractor class is does not implement any functionality.",
"How did you even manage to get here?",
}, "\n")
-- Class definitions
-- The base extractor that all extractors inherit from
---@class Extractor
---@field name string The name of the extractor
---@field command string The shell command for the extractor
---@field commands string[] The possible extractor commands
---
--- Whether the extractor supports preserving file permissions
---@field supports_file_permissions boolean
---
--- The map of the extract behaviour strings to the command flags
---@field extract_behaviour_map table<ExtractBehaviour, string>
local Extractor = {
name = "BaseExtractor",
command = "",
commands = {},
supports_file_permissions = false,
extract_behaviour_map = {},
}
-- The function to create a subclass of the abstract base extractor
---@param subclass table The subclass to create
---@return Extractor subclass Subclass of the base extractor
function Extractor:subclass(subclass)
--
-- Create a new instance
local instance = setmetatable(subclass or {}, self)
-- Set where to find the object's methods or properties
self.__index = self
-- Return the instance
return instance
end
-- The method to get the archive items
---@type ExtractorGetItems
function Extractor:get_items() return {}, {}, BASE_EXTRACTOR_ERROR end
-- The method to extract the archive
---@type ExtractorExtract
function Extractor:extract(_)
return {
successful = false,
error = BASE_EXTRACTOR_ERROR,
}
end
-- The 7z extractor
---@class SevenZip: Extractor
---@field password string The password to the archive
local SevenZip = Extractor:subclass({
name = ExtractorName.SevenZip,
commands = { "7z", "7zz" },
-- https://documentation.help/7-Zip/overwrite.htm
extract_behaviour_map = {
[ExtractBehaviour.Overwrite] = "-aoa",
[ExtractBehaviour.Rename] = "-aou",
},
password = "",
})
-- The tar extractor
---@class Tar: Extractor
local Tar = Extractor:subclass({
name = ExtractorName.Tar,
commands = { "gtar", "tar" },
supports_file_permissions = true,
-- https://www.man7.org/linux/man-pages/man1/tar.1.html
-- https://ss64.com/mac/tar.html
extract_behaviour_map = {
-- Tar overwrites by default
[ExtractBehaviour.Overwrite] = "",
[ExtractBehaviour.Rename] = "-k",
},
})
-- The default extractor, which is set to 7zip
---@class DefaultExtractor: SevenZip
local DefaultExtractor = SevenZip:subclass({})
-- The table of archive mime types
---@type table<string, Extractor>
local ARCHIVE_MIME_TYPE_TO_EXTRACTOR_MAP = {
["application/zip"] = DefaultExtractor,
["application/gzip"] = DefaultExtractor,
["application/tar"] = Tar,
["application/bzip"] = DefaultExtractor,
["application/bzip2"] = DefaultExtractor,
["application/7z-compressed"] = DefaultExtractor,
["application/rar"] = DefaultExtractor,
["application/xz"] = DefaultExtractor,
}
-- Patterns
-- The list of mime type prefixes to remove
--
-- The prefixes are used in a lua pattern
-- to match on the mime type, so special
-- characters need to be escaped
---@type string[]
local MIME_TYPE_PREFIXES_TO_REMOVE = {
"x%-",
"vnd%.",
}
-- The pattern template to get the mime type without a prefix
---@type string
local get_mime_type_without_prefix_template_pattern =
"^(%%a-)/%s([%%-%%d%%a]-)$"
-- The pattern to get the file extension
---@type string
local file_extension_pattern = "%.([%a]+)$"
-- The pattern to get the shell variables in a command
---@type string
local shell_variable_pattern = "[%$%%][%*@0]"
-- The pattern to match the bat command with the pager option passed
---@type string
local bat_command_with_pager_pattern = "%f[%a]bat%f[%A].*%-%-pager%s+"
-- Utility functions
-- Function to merge tables.
--
-- The key-value pairs of the tables given later
-- in the argument list WILL OVERRIDE
-- the tables given earlier in the argument list.
--
-- The list items in the table will be added in order,
-- with the items in the first table being added first,
-- and the items in the second table being added second,
-- and so on.
---@param ... table<any, any>[] The tables to merge
---@return table<any, any> merged_table The merged table
local function merge_tables(...)
--
-- Initialise a new table
local new_table = {}
-- Initialise the index variable
local index = 1
-- Iterates over the tables given
for _, table in ipairs({ ... }) do
--
-- Iterate over all of the keys and values
for key, value in pairs(table) do
--
-- If the key is a number, then add using the index
-- instead of the key.
-- This is to allow lists to be merged.
if type(key) == "number" then
--
-- Set the value mapped to the index
new_table[index] = value
-- Increment the index
index = index + 1
-- Otherwise, the key isn't a number
else
--
-- Set the key in the new table to the value given
new_table[key] = value
end
end
end
-- Return the new table
return new_table
end
-- Function to split a string into a list
---@param given_string string The string to split
---@param separator string|nil The character to split the string by
---@return string[] splitted_strings The list of strings split by the character
local function string_split(given_string, separator)
--
-- If the separator isn't given, set it to the whitespace character
separator = separator or "%s"
-- Initialise the list of splitted strings
local splitted_strings = {}
-- Iterate over all of the strings found by pattern
for string in string.gmatch(given_string, "([^" .. separator .. "]+)") do
--
-- Add the string to the list of splitted strings
table.insert(splitted_strings, string)
end
-- Return the list of splitted strings
return splitted_strings
end
-- Function to trim a string
---@param string string The string to trim
---@return string trimmed_string The trimmed string
local function string_trim(string)
--
-- Return the string with the whitespace characters
-- removed from the start and end
return string:match("^%s*(.-)%s*$")
end
-- Function to get a value from a table
-- and return the default value if the key doesn't exist
---@param table table The table to get the value from
---@param key string|number The key to get the value from
---@param default any The default value to return if the key doesn't exist
local function table_get(table, key, default) return table[key] or default end
-- Function to pop a key from a table
---@param table table The table to pop from
---@param key string|number The key to pop
---@param default any The default value to return if the key doesn't exist
---@return any value The value of the key or the default value
local function table_pop(table, key, default)
--
-- Get the value of the key from the table
local value = table[key]
-- Remove the key from the table
table[key] = nil
-- Return the value if it exist,
-- otherwise return the default value
return value or default
end
-- Function to escape a percentage sign %
-- in the string that is being replaced
---@param replacement_string string The string to escape
---@return string replacement_result The escaped string
local function escape_replacement_string(replacement_string)
--
-- Get the result of the replacement
local replacement_result = replacement_string:gsub("%%", "%%%%")
-- Return the result of the replacement
return replacement_result
end
-- Function to parse the number arguments to the number type
---@param args Arguments The arguments to parse
---@return Arguments parsed_args The parsed arguments
local function parse_number_arguments(args)
--
-- The parsed arguments
---@type Arguments
local parsed_args = {}
-- Iterate over the arguments given
for arg_name, arg_value in pairs(args) do
--
-- Try to convert the argument to a number
local number_arg_value = tonumber(arg_value)
-- Set the argument to the number argument value
-- if the argument is a number,
-- otherwise just set it to the given argument value
parsed_args[arg_name] = number_arg_value or arg_value
end
-- Return the parsed arguments
return parsed_args
end
-- Function to convert a table of arguments to a string
---@param args Arguments The arguments to convert
---@return string args_string The string of the arguments
local function convert_arguments_to_string(args)
--
-- The table of string arguments
---@type string[]
local string_arguments = {}
-- Iterate all the items in the argument table
for key, value in pairs(args) do
--
-- If the key is a number
if type(key) == "number" then
--
-- Add the stringified value to the string arguments table
table.insert(string_arguments, tostring(value))
-- Otherwise, if the key is a string
elseif type(key) == "string" then
--
-- Replace the underscores and spaces in the key with dashes
local key_with_dashes = key:gsub("_", "-"):gsub("%s", "-")
-- If the value is a boolean and the boolean is true,
-- add the value to the string
if type(value) == "boolean" and value then
table.insert(
string_arguments,
string.format("--%s", key_with_dashes)
)
-- Otherwise, just add the key and the value to the string
else
table.insert(
string_arguments,
string.format("--%s=%s", key_with_dashes, value)
)
end
end
end
-- Combine the string arguments into a single string
local string_args = table.concat(string_arguments, " ")
-- Return the string arguments
return string_args
end
-- Function to show a warning
---@param warning_message string The warning message
---@param options YaziNotificationOptions|nil Options for the notification
---@return nil
local function show_warning(warning_message, options)
return ya.notify(merge_tables(DEFAULT_NOTIFICATION_OPTIONS, options or {}, {
content = warning_message,
level = "warn",
}))
end
-- Function to show an error
---@param error_message string The error message
---@param options YaziNotificationOptions|nil Options for the notification
---@return nil
local function show_error(error_message, options)
return ya.notify(merge_tables(DEFAULT_NOTIFICATION_OPTIONS, options or {}, {
content = error_message,
level = "error",
}))
end
-- Function to get the user's input
---@param prompt string The prompt to show to the user
---@param options YaziInputOptions|nil Options for the input
---@return string|nil user_input The user's input
---@return InputEvent event The event for the input function
local function get_user_input(prompt, options)
return ya.input(merge_tables(DEFAULT_INPUT_OPTIONS, options or {}, {
title = prompt,
}))
end
-- Function to get the user's confirmation
-- TODO: Remove the `ya.input` version once `ya.confirm` is stable
---@param prompt string The prompt to show to the user
---@param title string|ui.Line The title of the confirmation prompt
---@param content string|ui.Text The content of the confirmation prompt
---@return boolean confirmation Whether the user has confirmed or not
local function get_user_confirmation(prompt, title, content)
--
-- If the ya.confirm API exists, use it
if ya.confirm then
--
-- Get the user's confirmation
local confirmation = ya.confirm(merge_tables(DEFAULT_CONFIRM_OPTIONS, {
title = title,
content = content,
}))
-- Return the result of the confirmation
return confirmation
end
-- TODO: Remove everything after this when `ya.confirm` is stable
-- Get the user's input
local user_input, event = get_user_input(prompt)
-- If the user has not confirmed the input,
-- or the user input is nil,
-- then return false
if not user_input or event ~= 1 then return false end
-- Lowercase the user's input
user_input = user_input:lower()
-- If the user input starts with a "y", then return true
if user_input:find("^y") then return true end
-- Otherwise, return false
return false
end
-- Function to merge the given configuration table with the default one
---@param config UserConfiguration|nil The configuration table to merge
---@return UserConfiguration merged_config The merged configuration table
local function merge_configuration(config)
--
-- If the configuration isn't given, then use the default one
if config == nil then return DEFAULT_CONFIG end
-- Initialise the list of invalid configuration options
local invalid_configuration_options = {}
-- Initialise the merged configuration
local merged_config = {}
-- Iterate over the default configuration table
for key, value in pairs(DEFAULT_CONFIG) do
--
-- Add the default configuration to the merged configuration
merged_config[key] = value
end
-- Iterate over the given configuration table
for key, value in pairs(config) do
--
-- If the key is not in the merged configuration
if merged_config[key] == nil then
--
-- Add the key to the list of invalid configuration options
table.insert(invalid_configuration_options, key)
-- Continue the loop
goto continue
end
-- Otherwise, overwrite the value in the merged configuration
merged_config[key] = value
-- The label to continue the loop
::continue::
end
-- If there are no invalid configuration options,
-- then return the merged configuration
if #invalid_configuration_options <= 0 then return merged_config end
-- Otherwise, warn the user of the invalid configuration options
show_warning(
"Invalid configuration options: "
.. table.concat(invalid_configuration_options, ", ")
)
-- Return the merged configuration
return merged_config
end
-- Function to initialise the configuration
---@type fun(
--- user_config: Configuration|nil, -- The configuration object
---): Configuration The initialised configuration object
local initialise_config = ya.sync(function(state, user_config)
--
-- Merge the default configuration with the user given one,
-- as well as the additional data given,
-- and set it to the state.
state.config = merge_configuration(user_config)
-- Return the configuration object for async functions
return state.config
end)
-- Function to try if a shell command exists
---@param shell_command string The shell command to check
---@param args string[]|nil The arguments to the shell command
---@return boolean shell_command_exists Whether the shell command exists
local function async_shell_command_exists(shell_command, args)
--
-- Get the output of the shell command with the given arguments
local output = Command(shell_command)
:args(args or {})
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:output()
-- Return true if there's an output and false otherwise
return output ~= nil
end
-- Function to emit a plugin command
---@param command string The plugin command to emit
---@param args Arguments The arguments to pass to the plugin command
---@return nil
local function emit_plugin_command(command, args)
return ya.manager_emit("plugin", {
PLUGIN_NAME,
args = string.format(
"%s %s",
command,
convert_arguments_to_string(args)
),
})
end
-- Function to subscribe to the augmented-extract event
---@type fun(): nil
local subscribe_to_augmented_extract_event = ya.sync(function(_)
return ps.sub_remote("augmented-extract", function(args)
--
-- If the arguments given isn't a table,
-- exit the function
if type(args) ~= "table" then return end
-- Iterate over the arguments
for _, arg in ipairs(args) do
--
-- Emit the command to call the plugin's extract function
-- with the given arguments and flags
emit_plugin_command("extract", {
archive_path = ya.quote(arg),
})
end
end)
end)
-- Function to initialise the plugin
---@param opts Configuration|nil The options given to the plugin
---@return Configuration config The initialised configuration object
local function initialise_plugin(opts)
--
-- Subscribe to the augmented extract event
subscribe_to_augmented_extract_event()
-- Initialise the configuration object
local config = initialise_config(opts)
-- Return the configuration object
return config
end
-- Function to standardise the mime type of a file.
-- This function will follow what Yazi does to standardise
-- mime types returned by the file command.
---@param mime_type string The mime type of the file
---@return string standardised_mime_type The standardised mime type of the file
local function standardise_mime_type(mime_type)
--
-- Trim the whitespace from the mime type
local trimmed_mime_type = string_trim(mime_type)
-- Iterate over the mime type prefixes to remove
for _, prefix in ipairs(MIME_TYPE_PREFIXES_TO_REMOVE) do
--
-- Get the pattern to remove the mime type prefix
local pattern =
get_mime_type_without_prefix_template_pattern:format(prefix)
-- Remove the prefix from the mime type
local mime_type_without_prefix, replacement_count =
trimmed_mime_type:gsub(pattern, "%1/%2")
-- If the replacement count is greater than zero,
-- return the mime type without the prefix
if replacement_count > 0 then return mime_type_without_prefix end
end
-- Return the mime type with whitespace removed
return trimmed_mime_type
end
-- Function to check if a given mime type is an archive
---@param mime_type string|nil The mime type of the file
---@return boolean is_archive Whether the mime type is an archive
local function is_archive_mime_type(mime_type)
--
-- If the mime type is nil, return false
if not mime_type then return false end
-- Standardise the mime type
local standardised_mime_type = standardise_mime_type(mime_type)
-- Get the archive extractor for the mime type
local archive_extractor =
ARCHIVE_MIME_TYPE_TO_EXTRACTOR_MAP[standardised_mime_type]
-- Return if an extractor exists for the mime type
return archive_extractor ~= nil
end
-- Function to check if a given file extension
-- is an archive file extension
---@param file_extension string|nil The file extension of the file
---@return boolean is_archive Whether the file extension is an archive
local function is_archive_file_extension(file_extension)
--
-- If the file extension is nil, return false
if not file_extension then return false end
-- Make the file extension lower case
file_extension = file_extension:lower()
-- Trim the whitespace from the file extension
file_extension = string_trim(file_extension)
-- Get if the file extension is an archive
local is_archive = table_get(ARCHIVE_FILE_EXTENSIONS, file_extension, false)
-- Return if the file extension is an archive file extension
return is_archive
end
-- Function to get the mime type of a file
---@param file_path string The path to the file
---@return string mime_type The mime type of the file
local function get_mime_type(file_path)
--
-- Get the output of the file command
local output, _ = Command("file")
:args({
-- Don't prepend file names to the output
"-b",
-- Print the mime type of the file
"--mime-type",
-- The file path to get the mime type of
file_path,
})
:stdout(Command.PIPED)
:stderr(Command.PIPED)
:output()
-- If there is no output, then return an empty string
if not output then return "" end
-- Otherwise, get the mime type from the standard output
local mime_type = string_trim(output.stdout)
-- Standardise the mime type
local standardised_mime_type = standardise_mime_type(mime_type)
-- Return the standardised mime type
return standardised_mime_type
end
-- Function to get a temporary name.
-- The code is taken from Yazi's source code.
---@param path string The path to the item to create a temporary name
---@return string temporary_name The temporary name for the item
local function get_temporary_name(path)
return ".tmp_"
.. ya.hash(string.format("extract//%s//%.10f", path, ya.time()))
end
-- Function to get a temporary directory url
-- for the given file path
---@param path string The path to the item to create a temporary directory
---@param destination_given boolean|nil Whether the destination was given
---@return Url|nil url The url of the temporary directory
local function get_temporary_directory_url(path, destination_given)
--
-- Get the url of the path given
---@type Url
local path_url = Url(path)
-- Initialise the parent directory to be the path given
---@type Url
local parent_directory_url = path_url
-- If the destination is not given
if not destination_given then
--
-- Get the parent directory of the given path
parent_directory_url = Url(path):parent()
-- If the parent directory doesn't exist, return nil
if not parent_directory_url then return nil end
end
-- Create the temporary directory path
local temporary_directory_url =
fs.unique_name(parent_directory_url:join(get_temporary_name(path)))
-- Return the temporary directory path
return temporary_directory_url
end
-- Function to get the configuration from an async function
---@type fun(): Configuration The configuration object
local get_config = ya.sync(function(state)
--
-- Returns the configuration object
return state.config
end)
-- Function to get the current working directory
---@type fun(): string Returns the current working directory as a string
local get_current_directory = ya.sync(
function(_) return tostring(cx.active.current.cwd) end
)
-- Function to get the path of the hovered item
---@type fun(
--- quote: boolean|nil, -- Whether to escape the characters in the path
---): string|nil The path of the hovered item
local get_path_of_hovered_item = ya.sync(function(_, quote)
--
-- Get the hovered item
local hovered_item = cx.active.current.hovered
-- If there is no hovered item, exit the function
if not hovered_item then return end
-- Convert the url of the hovered item to a string
local hovered_item_path = tostring(cx.active.current.hovered.url)
-- If the quote flag is passed,
-- then quote the path of the hovered item
if quote then hovered_item_path = ya.quote(hovered_item_path) end
-- Return the path of the hovered item
return hovered_item_path
end)
-- Function to get if the hovered item is a directory
---@type fun(): boolean
local hovered_item_is_dir = ya.sync(function(_)
--
-- Get the hovered item
local hovered_item = cx.active.current.hovered
-- Return if the hovered item exists and is a directory
return hovered_item and hovered_item.cha.is_dir
end)
-- Function to get if the hovered item is an archive
---@type fun(): boolean
local hovered_item_is_archive = ya.sync(function(_)
--
-- Get the hovered item
local hovered_item = cx.active.current.hovered