robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local api =vim . api 2local uv =vim . uv 3local notify =require ( 'vim._core.util' ). notify 4 5local M ={} 6 7---@return string?, string? 8local function unzip () 9local command =vim . fn . exepath ( 'unzip' ) 10if command == '' then 11return nil , 'unzip executable not found' 12end 13-- Windows searches the current directory before $PATH, so an archive could be opened with an 14-- `unzip` shipped next to it. 15if vim . fn . has ( 'win32' ) == 1 then 16local dir =uv . fs_realpath ( vim . fs . dirname ( vim . fs . normalize ( command ))) 17local cwd =uv . fs_realpath ( vim . fn . getcwd ()) 18if dir and cwd and dir == cwd then 19return nil , 'refusing to run unzip from the current directory' 20end 21end 22return command 23end 24 25--- Escape a path so that Info-ZIP matches it literally. 26--- 27--- Info-ZIP matches `*`, `?`, and `[]` in a member selector itself, so this is not shell 28--- quoting: passing argv already avoids the shell. For example, unescaped `a[a].txt` 29--- silently reads `aa.txt`, and `a?.txt` matches every four-character name. A literal `[` 30--- cannot be backslash-escaped, so it is wrapped in a class instead, as is a leading `-`, 31--- which would otherwise parse as an option. 32--- https://github.com/neovim/neovim/blob/7ba955fe079d4aa2554fea8e7235651fafd40efb/runtime/autoload/zip.vim#L316-L339 33---@param value string 34---@return string 35local function literal_pattern ( value ) 36return ( 37value 38: gsub ( '\\' , '\\\\' ) 39: gsub ( '%?' , '\\?' ) 40: gsub ( '%*' , '\\*' ) 41: gsub ( '%[' , '[[]' ) 42: gsub ( '^%-' , '[-]' ) 43) 44end 45 46---@param source string 47---@return string[]?, string?, boolean? 48local function list_archive ( source ) 49local command , command_err =unzip () 50if not command then 51return nil , command_err , false 52end 53local ok , system =pcall ( 54vim . system , 55{ command , '-Z1' , '--' , literal_pattern ( source ) } , 56{ text =true } 57) 58if not ok then 59return nil , tostring ( system ), false 60end 61local result =system : wait () 62if result . code ~= 0 then 63if vim . trim ( result . stdout or '' ) == 'Empty zipfile.' then 64return {} 65end 66return nil , vim . trim ( result . stderr or '' ), true 67end 68return vim . split ( result . stdout or '' , '\n' , { plain =true , trimempty =true } ) 69end 70 71--- Keep absolute and dot-segment entries visible without treating them as UI navigation. 72---@param path string 73---@return boolean 74local function opaque_path ( path ) 75if path : sub ( 1 , 1 ) == '/' or path : match ( '^%a:[/\\]' ) then 76return true 77end 78for component in path : gmatch ( '[^/]+' ) do 79if component == '.' or component == '..' then 80return true 81end 82end 83return false 84end 85 86--- Project the flat archive path list into one navigable directory level. 87---@param paths string[] Raw entry paths from the archive. 88---@param prefix string Raw archive-directory prefix, including its trailing slash. 89---@return nvim.dir.Entry[] 90local function entries_at ( paths , prefix ) 91local entries ={} ---@type nvim.dir.Entry[] 92local seen ={} ---@type table<string,true> 93for _ , path in ipairs ( paths ) do 94if prefix == '' and opaque_path ( path ) then 95local key ='opaque:' .. path 96if not seen [ key ] then 97seen [ key ] =true 98entries [ # entries + 1 ] ={ name =path , dir =false } 99end 100elseif vim . startswith ( path , prefix ) then 101local rest =path : sub ( # prefix + 1 ) 102local separator =rest : find ( '/' , 1 , true ) 103local name =separator and rest : sub ( 1 , separator - 1 ) or rest 104if name ~= '' then 105local dir =separator ~= nil 106local entry_path =( '%s%s%s' ): format ( prefix , name , dir and '/' or '' ) 107local key =( dir and 'dir:' or 'file:' ) .. entry_path 108if not seen [ key ] then 109seen [ key ] =true 110entries [ # entries + 1 ] ={ name =name , dir =dir } 111end 112end 113end 114end 115return entries 116end 117 118---@param source string 119---@return boolean?, string? 120local function has_magic ( source ) 121local fd , err =uv . fs_open ( source , 'r' , 438 ) 122if not fd then 123return nil , err 124end 125local magic , read_err =uv . fs_read ( fd , 2 , 0 ) 126uv . fs_close ( fd ) 127if not magic then 128return nil , read_err 129end 130return magic == 'PK' 131end 132 133---@param buf integer 134---@param source string 135local function read_normally ( buf , source ) 136api . nvim_buf_call ( buf , function () 137api . nvim_cmd ( { 138cmd ='edit' , 139args ={ source } , 140mods ={ noautocmd =true , noswapfile =true } , 141magic ={ file =false , bar =false } , 142} , {} ) 143end ) 144end 145 146--- Describe an Info-ZIP failure. It reports some conditions only through the exit code, and 147--- says nothing on stderr, so the code is preferred where it is meaningful. 148---@param code integer 149---@param stderr string 150---@return string 151local function unzip_error ( code , stderr ) 152if code == 81 then 153return 'unsupported compression or encryption' 154elseif code == 82 then 155return 'incorrect password' 156end 157return stderr ~= '' and stderr or ( 'unzip exited with %d' ): format ( code ) 158end 159 160--- Returned when the empty password `extract_path` supplies is rejected, so a real one is 161--- needed. It cannot go in `-P`, which would expose it in the process arguments, and Info-ZIP 162--- reads a password from nowhere but a terminal, so it is asked for on a pty. 163local ENCRYPTED ='zip:encrypted' 164 165--- Extract one entry into `dir`, prompting for the archive password on a pty. 166--- 167--- Info-ZIP writes the prompt to the terminal and re-prompts on a wrong password, so the 168--- exchange is driven until it extracts, gives up, or the user cancels. The password reaches 169--- it over the pty and never appears in the process arguments. 170---@param command string 171---@param source string 172---@param path string 173---@param dir string Empty directory to extract into. 174---@return string? error 175local function extract_with_password ( command , source , path , dir ) 176local buffered , exited ='' , nil ---@type string, integer? 177local ok , job =pcall ( vim . fn . jobstart , { 178command , 179'-o' , 180'-j' , 181'-d' , 182dir , 183'--' , 184literal_pattern ( source ), 185literal_pattern ( path ), 186} , { 187pty =true , 188env ={ LC_ALL ='C' } , 189on_stdout =function ( _ , data ) 190buffered =buffered .. table . concat ( data , '' ) 191end , 192on_exit =function ( _ , code ) 193exited =code 194end , 195} ) 196if not ok or job <= 0 then 197return 'could not start unzip' 198end 199 200-- Info-ZIP prints the prompt before disabling echo, and disables it with TCSAFLUSH, which 201-- drops a password sent in that window. Echo is still on there, so an echo means "resend". 202local sent ='' 203local function echoed () 204return sent ~= '' and buffered : find ( sent .. '\r' , 1 , true ) ~= nil 205end 206 207local function wanted () 208return exited ~= nil 209or buffered : find ( 'password: ' , 1 , true ) ~= nil 210or buffered : find ( 'reenter: ' , 1 , true ) ~= nil 211or echoed () 212end 213 214local reenter =false 215while exited == nil do 216local ready , reason =vim . wait ( 10000 , wanted , 50 ) 217if not ready then 218vim . fn . jobstop ( job ) 219-- -2 is CTRL-C. 220return reason == - 2 and 'cancelled' or 'timed out waiting for unzip' 221end 222if exited ~= nil then 223break 224end 225if echoed () then 226-- Wait for its read(), else the resend is dropped too. 227vim . wait ( 10 ) 228else 229local label =reenter and 'Password incorrect, try again: ' 230or ( 'Password for %s: ' ): format ( path ) 231sent =vim . fn . inputsecret ( label ) 232if sent == '' then 233vim . fn . jobstop ( job ) 234return 'cancelled' 235end 236reenter =true 237end 238buffered ='' 239vim . fn . chansend ( job , sent .. '\r' ) 240end 241--- @cast exited -? 242 243if exited ~= 0 then 244return unzip_error ( exited , '' ) 245end 246end 247 248---@param command string 249---@param source string 250---@param path string 251---@param target string 252---@return string? 253local function extract_path ( command , source , path , target ) 254local file , err =io . open ( target , 'wb' ) 255if not file then 256return err 257end 258local write_err ---@type string? 259-- An empty `-P` inhibits the prompt Info-ZIP would open a terminal for. 260local ok , system =pcall ( 261vim . system , 262{ command , '-p' , '-P' , '' , '--' , literal_pattern ( source ), literal_pattern ( path ) } , 263{ 264stdout =function ( pipe_err , data ) 265if pipe_err then 266write_err =pipe_err 267elseif data and not write_err then 268local written , file_err =file : write ( data ) 269if not written then 270write_err =file_err 271end 272end 273end , 274} 275) 276if not ok then 277file : close () 278return tostring ( system ) 279end 280local result =system : wait () 281file : close () 282if write_err then 283return write_err 284end 285if result . code == 82 then 286return ENCRYPTED 287end 288if result . code ~= 0 then 289return unzip_error ( result . code , vim . trim ( result . stderr or '' )) 290end 291end 292 293---@param buf integer 294local function set_readonly ( buf ) 295if not api . nvim_buf_is_valid ( buf ) then 296return 297end 298api . nvim_set_option_value ( 'swapfile' , false , { buf =buf } ) 299api . nvim_set_option_value ( 'modified' , false , { buf =buf } ) 300api . nvim_set_option_value ( 'buftype' , 'nowrite' , { buf =buf } ) 301api . nvim_set_option_value ( 'readonly' , true , { buf =buf } ) 302api . nvim_set_option_value ( 'modifiable' , false , { buf =buf } ) 303end 304 305--- Read extracted bytes through Nvim's normal reader to preserve encoding, EOL, and binary behavior. 306---@param buf integer Target archive entry buffer. 307---@param temp string Temporary file containing the extracted bytes. 308local function read_tempfile ( buf , temp ) 309api . nvim_buf_call ( buf , function () 310local name =api . nvim_buf_get_name ( buf ) 311api . nvim_set_option_value ( 'swapfile' , false , { buf =buf } ) 312api . nvim_cmd ( { 313cmd ='file' , 314args ={ temp } , 315mods ={ keepalt =true , silent =true } , 316magic ={ file =false , bar =false } , 317} , {} ) 318api . nvim_cmd ( { cmd ='edit' , bang =true , mods ={ keepjumps =true , silent =true } } , {} ) 319api . nvim_cmd ( { 320cmd ='file' , 321args ={ name } , 322mods ={ keepalt =true , silent =true } , 323magic ={ file =false , bar =false } , 324} , {} ) 325api . nvim_cmd ( { cmd ='filetype' , args ={ 'detect' } } , {} ) 326end ) 327set_readonly ( buf ) 328end 329 330--- Resolve a `zip://` buffer name, as used by quickfix and direct `:edit`. 331--- 332--- The archive path and the entry path are simply joined, so the split is found by walking 333--- components: the first one that is a regular file is the archive, because a regular file 334--- cannot have children on disk. Entry paths may therefore contain any character. 335---@param name string `zip://{archive}/{path}` 336---@return string?, string? archive and entry path 337local function resolve_uri ( name ) 338if not vim . startswith ( name , 'zip://' ) then 339return 340end 341local value =name : sub ( 7 ) 342local offset =1 343while true do 344local separator =value : find ( '/' , offset + 1 , true ) 345if not separator then 346return 347end 348local archive =value : sub ( 1 , separator - 1 ) 349local stat =uv . fs_stat ( archive ) 350if stat and stat . type == 'file' then 351return archive , value : sub ( separator + 1 ) 352end 353offset =separator 354end 355end 356 357---@class (private) nvim.zip.State 358---@field source string Path to the archive. 359---@field path? string Archive path shown by a `zip://` buffer. 360---@field paths? string[] Entry paths carried over from the initial listing. 361---@field prefix? string Archive directory currently listed. 362---@field pending_prefix? string Prefix to commit once the backend succeeds. 363 364---@param buf integer 365---@return nvim.zip.State? 366local function get_state ( buf ) 367return vim . b [ buf ]. nvim_zip 368end 369 370---@param buf integer 371---@param state nvim.zip.State 372local function set_state ( buf , state ) 373vim . b [ buf ]. nvim_zip =state 374end 375 376--- Open a local archive as a read-only `nvim.dir` listing. 377---@param buf integer Target archive buffer. 378---@param source string Expanded path to the archive. 379function M . browse ( buf , source ) 380buf =vim . _resolve_bufnr ( buf ) 381if vim . b [ buf ]. nvim_dir ~= nil and get_state ( buf ) ~= nil then 382return 383end 384local magic , magic_err =has_magic ( source ) 385if magic == nil then 386notify ( 'zip' , ( 'File not readable <%s>: %s' ): format ( source , magic_err )) 387return 388end 389if not magic then 390read_normally ( buf , source ) 391return 392end 393local paths , err , fallback =list_archive ( source ) 394if not paths then 395if err then 396notify ( 397'zip' , 398fallback and ( '%s is not a zip file: %s' ): format ( source , err ) or err , 399fallback and vim . log . levels . WARN or vim . log . levels . ERROR 400) 401end 402if fallback then 403read_normally ( buf , source ) 404end 405return 406end 407set_state ( buf , { source =source , paths =paths , prefix ='' } ) 408local name =vim . fn . bufname ( buf ) 409require ( 'nvim.dir' ). open ( buf , name ~= '' and name or source , M ) 410end 411 412--- Read one archive entry into a read-only buffer. 413---@param buf integer Target entry buffer. 414---@param name string `zip://` buffer name. 415function M . read ( buf , name ) 416buf =vim . _resolve_bufnr ( buf ) 417local state =get_state ( buf ) 418local source , path =state and state . source , state and state . path 419if not source or not path then 420source , path =resolve_uri ( name ) 421end 422if not source or not path then 423set_readonly ( buf ) 424notify ( 'zip' , ( 'could not parse buffer name %q' ): format ( name )) 425return 426end 427local command , command_err =unzip () 428if not command then 429set_readonly ( buf ) 430notify ( 'zip' , command_err or 'unzip executable not found' ) 431return 432end 433local temp =vim . fn . tempname () 434local dir ---@type string? 435local err =extract_path ( command , source , path , temp ) 436if err == ENCRYPTED then 437vim . fn . delete ( temp ) 438dir =vim . fn . tempname () 439vim . fn . mkdir ( dir , 'p' ) 440err =extract_with_password ( command , source , path , dir ) 441-- `-j` discards the archive path, so the directory holds exactly the extracted entry. 442local entry =not err and vim . iter ( vim . fs . dir ( dir )): next () or nil 443if entry then 444temp =vim . fs . joinpath ( dir , entry ) 445else 446err =err or 'no entry was extracted' 447end 448end 449if err then 450vim . fn . delete ( dir or temp , dir and 'rf' or '' ) 451set_readonly ( buf ) 452notify ( 'zip' , ( 'unable to read %s from %s: %s' ): format ( path , source , err )) 453return 454end 455local ok , read_err =pcall ( read_tempfile , buf , temp ) 456vim . fn . delete ( dir or temp , dir and 'rf' or '' ) 457if not ok then 458set_readonly ( buf ) 459notify ( 'zip' , tostring ( read_err )) 460end 461end 462 463--- List the requested archive level and commit its prefix only after the backend succeeds. 464---@param buf integer 465---@param _ string 466---@param cb fun(err?: string, entries?: nvim.dir.Entry[]) 467function M . list ( buf , _ , cb ) 468local state =get_state ( buf ) 469if not state then 470cb ( 'zip source is not set' ) 471return 472end 473local paths =state . paths 474state . paths =nil 475local err ---@type string? 476if not paths then 477paths , err =list_archive ( state . source ) 478end 479if not paths then 480state . pending_prefix =nil 481set_state ( buf , state ) 482cb ( err ) 483return 484end 485state . prefix =state . pending_prefix or state . prefix or '' 486state . pending_prefix =nil 487set_state ( buf , state ) 488cb ( nil , entries_at ( paths , state . prefix )) 489end 490 491---@param buf integer 492---@param name string 493---@param entry nvim.dir.Entry 494function M . open ( buf , name , entry ) 495local state =get_state ( buf ) 496if not state then 497return 498end 499local path =( state . prefix or '' ) .. entry . name .. ( entry . dir and '/' or '' ) 500if entry . dir then 501state . pending_prefix =path 502set_state ( buf , state ) 503require ( 'nvim.dir' ). open ( buf , name , M ) 504return 505end 506local uri =( 'zip://%s/%s' ): format ( state . source , path ) 507local entry_buf =vim . fn . bufadd ( uri ) 508set_state ( entry_buf , { source =state . source , path =path } ) 509api . nvim_cmd ( { 510cmd ='edit' , 511args ={ uri } , 512mods ={ noswapfile =true , keepalt =true } , 513magic ={ file =false , bar =false } , 514} , {} ) 515end 516 517---@param buf integer 518---@param name string 519function M . open_parent ( buf , name ) 520local state =get_state ( buf ) 521if not state then 522return 523end 524local prefix =state . prefix or '' 525if prefix ~= '' then 526local path =prefix : sub ( 1 , - 2 ) 527local child =assert ( path : match ( '([^/]+)$' )) 528state . pending_prefix =path : match ( '^(.*[/])' ) or '' 529set_state ( buf , state ) 530require ( 'nvim.dir' ). open ( buf , name , M , { name =child , dir =true } ) 531return 532end 533if name : match ( '^%a[%w+.-]*://' ) then 534return 535end 536require ( 'nvim.dir.fs' ). open_parent_path ( state . source ) 537end 538 539--- Extract the entry under the cursor into the current directory. 540--- `-j` discards the archive path, so the destination is always a name in the 541--- current directory and cannot be redirected by a hostile entry. 542function M . _extract () 543local buf =api . nvim_get_current_buf () 544local state =get_state ( buf ) 545if not state then 546return 547end 548local command , command_err =unzip () 549if not command then 550notify ( 'zip' , command_err or 'unzip executable not found' ) 551return 552end 553local line =api . nvim_get_current_line () 554if line == '' then 555return 556end 557if line : sub ( - 1 ) == '/' then 558notify ( 'zip' , 'please specify a file, not a directory' ) 559return 560end 561local path =( state . prefix or '' ) .. line 562local directory =vim . fn . getcwd () 563local target =vim . fs . joinpath ( directory , vim . fs . basename ( path )) 564if uv . fs_stat ( target ) then 565notify ( 'zip' , ( '%s already exists, not overwriting' ): format ( target )) 566return 567end 568local ok , system =pcall ( vim . system , { 569command , 570'-o' , 571'-j' , 572'-P' , 573'' , 574'--' , 575literal_pattern ( state . source ), 576literal_pattern ( path ), 577} , { cwd =directory , text =true } ) 578if not ok then 579notify ( 'zip' , tostring ( system )) 580return 581end 582local result =system : wait () 583if not uv . fs_stat ( target ) then 584notify ( 585'zip' , 586( 'unable to extract %s from %s: %s' ): format ( path , state . source , vim . trim ( result . stderr or '' )) 587) 588return 589end 590notify ( 'zip' , ( 'extracted %s' ): format ( target ), vim . log . levels . INFO ) 591end 592 593---@param buf integer 594function M . init ( buf ) 595api . nvim_set_option_value ( 'filetype' , 'zip' , { buf =buf } ) 596if vim . fn . hasmapto ( '<Plug>(nvim-zip-extract)' , 'n' ) == 0 then 597vim . keymap . set ( 'n' , 'x' , '<Plug>(nvim-zip-extract)' , { buffer =buf , silent =true } ) 598end 599api . nvim_buf_call ( buf , function () 600vim . wo . wrap =false 601end ) 602end 603 604return M