robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local uv =vim . uv 2local log =vim . log . new ( { name ='nvim-watch' } ) 3 4local M ={} 5 6--- @enum vim._watch.FileChangeType 7--- Types of events watchers will emit. 8M . FileChangeType ={ 9Created =1 , 10Changed =2 , 11Deleted =3 , 12} 13 14--- A glob string or compiled LPeg pattern. Strings match full paths using `/` separators. 15--- Glob syntax follows [vim.glob] (LSP 3.17). 16--- @alias vim._watch.Pattern string|vim.lpeg.Pattern 17 18--- A list matches if any of its patterns matches. An empty list matches nothing. 19--- @alias vim._watch.Filter vim._watch.Pattern|vim._watch.Pattern[] 20 21--- Option and rule tables must not be modified while watching. 22--- @class vim._watch.Opts 23--- 24--- @field debounce? integer ms 25--- 26--- Handles watcher failures and invalid globs, with root and pattern context in the message. 27--- Invalid globs are skipped. Defaults to logging at ERROR in nvim-watch.log. 28--- @field on_error? fun(err: string) 29--- 30--- Only changes matching this filter are reported. Parent directories remain watched for matching 31--- descendants. See vim._watch.Pattern for glob syntax. When nil, matches any path. 32--- @field include_pattern? vim._watch.Filter 33--- 34--- Changes matching this filter are not reported. With watchdirs(), excluding a subdirectory 35--- excludes its entire subtree. When nil, matches nothing. 36--- @field exclude_pattern? vim._watch.Filter 37 38--- @alias vim._watch.Callback fun(path: string, change_type: vim._watch.FileChangeType) 39 40--- @class vim._watch.watch.Opts : vim._watch.Opts 41--- @field uvflags? uv.fs_event_start.flags See |uv.fs_event_start()|. 42 43--- Rules sharing a root use one backend watcher. Each event is reported once per root if any 44--- rule matches, subject to the include_pattern and exclude_pattern options. 45--- @class vim._watch.Rule 46--- @field path string Root to watch. 47--- @field pattern? vim._watch.Filter Matches full paths; nil matches everything. 48--- @field events? vim._watch.FileChangeType[] Defaults to all event types. 49 50--- @class (private) vim._watch.BackendOpts : vim._watch.watch.Opts 51--- @field include_pattern? vim.lpeg.Pattern 52--- @field exclude_pattern? vim.lpeg.Pattern 53--- @field on_error fun(err: string) 54 55--- @alias vim._watch.Backend fun(path: string, opts: vim._watch.BackendOpts, callback: vim._watch.Callback): (fun())? 56 57--- @class (private) vim._watch.Subscriber 58--- @field callback vim._watch.Callback 59--- @field on_error fun(err: string) 60 61--- @class (private) vim._watch.Shared 62--- @field key table 63--- @field stat? uv.fs_stat.result 64--- @field failed boolean 65--- @field subscribers table<vim._watch.Subscriber, true> 66--- @field cancel? fun() 67 68--- @type table<'watch'|'watchdirs'|'inotify', table<string, table<vim._watch.Shared, true>>> 69local shared ={ watch ={} , watchdirs ={} , inotify ={} } 70 71--- Counts backend watchers with outstanding subscriptions, excluding failed starts. 72--- @return {watch: integer, watchdirs: integer, inotify: integer} 73function M . active () 74local active ={ watch =0 , watchdirs =0 , inotify =0 } 75 76for name , paths in pairs ( shared ) do 77for _ , entries in pairs ( paths ) do 78active [ name ] =active [ name ] + vim . tbl_count ( entries ) 79end 80end 81 82return active 83end 84 85--- An omitted filter matches everything; invalid or empty filters return nil. 86--- @param filter vim._watch.Filter? 87--- @param on_error fun(err: string) 88--- @return vim.lpeg.Pattern? 89local function compile ( filter , on_error ) 90if filter == nil then 91return vim . lpeg . P ( true ) 92elseif type ( filter ) == 'userdata' then 93return filter --[[@as vim.lpeg.Pattern]] 94elseif type ( filter ) == 'string' then 95local ok , pattern =pcall ( vim . glob . to_lpeg , filter ) 96if not ok then 97on_error (( 'Invalid glob %q: %s' ): format ( filter , pattern )) 98return nil 99end 100 101return pattern 102end 103 104local pattern --- @type vim.lpeg.Pattern? 105 106for _ , item in ipairs ( filter ) do 107local p =compile ( item , on_error ) 108if p then 109pattern =pattern and pattern + p or p 110end 111end 112 113return pattern 114end 115 116--- @param entry vim._watch.Shared 117--- @param method 'callback'|'on_error' 118--- @param ... any 119local function emit ( entry , method , ... ) 120local first_error 121 122-- Callbacks can subscribe or cancel other subscriptions while handling an event. 123for _ , subscriber in ipairs ( vim . tbl_keys ( entry . subscribers )) do 124if entry . subscribers [ subscriber ] then 125-- EmmyLua rejects the union of callback signatures passed to pcall. 126--- @diagnostic disable-next-line: param-type-mismatch 127local ok , err =pcall ( subscriber [ method ], ... ) 128if not ok then 129first_error =first_error or tostring ( err ) 130end 131end 132end 133 134if first_error then 135error ( first_error ) 136end 137end 138 139--- @param name 'watch'|'watchdirs'|'inotify' 140--- @param backend vim._watch.Backend 141--- @param path string 142--- @param opts vim._watch.watch.Opts 143--- @param rules {pattern: vim._watch.Filter?, events: vim._watch.FileChangeType[]?}[] 144--- @param subscriber vim._watch.Subscriber 145--- @return fun() 146local function subscribe ( name , backend , path , opts , rules , subscriber ) 147local key ={ 148include_pattern =opts . include_pattern , 149exclude_pattern =opts . exclude_pattern , 150debounce =name == 'watchdirs' and ( opts . debounce or 500 ) or nil , 151uvflags =name == 'watch' and ( opts . uvflags or {} ) or nil , 152rules =rules , 153} 154 155-- Validate every subscription, even when reusing a backend. Invalid globs do not mean the 156-- backend has failed, and each subscriber should receive its own diagnostics. 157local include_pattern =compile ( key . include_pattern , subscriber . on_error ) 158local exclude_pattern =key . exclude_pattern and compile ( key . exclude_pattern , subscriber . on_error ) 159local compiled ={} --- @type {pattern: vim.lpeg.Pattern, events: vim._watch.FileChangeType[]?}[] 160local include =vim . lpeg . P ( false ) 161 162for _ , rule in ipairs ( key . rules ) do 163local pattern =compile ( rule . pattern , subscriber . on_error ) 164if pattern then 165compiled [ # compiled + 1 ] ={ pattern =pattern , events =rule . events } 166include =include + pattern 167end 168end 169 170if not include_pattern or # compiled == 0 then 171return function () end 172end 173 174local stat =uv . fs_stat ( path ) 175local entry --- @type vim._watch.Shared? 176 177for r in pairs ( shared [ name ][ path ] or {} ) do 178if 179not r . failed 180and stat 181and r . stat 182and stat . dev == r . stat . dev 183and stat . ino == r . stat . ino 184and vim . deep_equal ( r . key , key ) 185then 186entry =r 187break 188end 189end 190 191if entry then 192entry . subscribers [ subscriber ] =true 193else 194entry ={ key =key , stat =stat , failed =false , subscribers ={ [ subscriber ] =true } } 195 196--- @type vim._watch.BackendOpts 197local backend_opts ={ 198debounce =key . debounce , 199uvflags =key . uvflags , 200-- Both filters must match from the beginning of the full path. 201-- EmmyLua does not infer the LPeg length operator's result type. 202---@diagnostic disable-next-line: assign-type-mismatch 203include_pattern =# include_pattern * include , 204exclude_pattern =exclude_pattern , 205on_error =function ( err ) 206entry . failed =true 207emit ( entry , 'on_error' , err ) 208end , 209} 210 211entry . cancel =backend ( path , backend_opts , function ( fullpath , change_type ) 212for _ , rule in ipairs ( compiled ) do 213if 214rule . pattern : match ( fullpath ) ~= nil 215and ( not rule . events or vim . list_contains ( rule . events , change_type )) 216then 217emit ( entry , 'callback' , fullpath , change_type ) 218return 219end 220end 221end ) 222 223if not entry . cancel then 224return function () end 225end 226 227-- Publish only after setup completes, so reentrant calls cannot reuse partial watchers. 228shared [ name ][ path ] =shared [ name ][ path ] or {} 229shared [ name ][ path ][ entry ] =true 230end 231 232return function () 233if not entry . subscribers [ subscriber ] then 234return 235end 236 237entry . subscribers [ subscriber ] =nil 238 239if not next ( entry . subscribers ) then 240shared [ name ][ path ][ entry ] =nil 241if not next ( shared [ name ][ path ]) then 242shared [ name ][ path ] =nil 243end 244 245assert ( entry . cancel )() 246end 247end 248end 249 250--- Compatible calls share a backend until their last subscription is cancelled. Glob descriptions 251--- are compared by value, LPeg patterns by identity. Failed or replaced roots are never reused. 252--- @param name 'watch'|'watchdirs'|'inotify' 253--- @param backend vim._watch.Backend 254--- @param path string|vim._watch.Rule[] 255--- @param opts vim._watch.watch.Opts? 256--- @param callback vim._watch.Callback 257--- @return fun() 258local function start_watch ( name , backend , path , opts , callback ) 259vim . validate ( 'path' , path , { 'string' , 'table' } ) 260vim . validate ( 'opts' , opts , 'table' , true ) 261vim . validate ( 'callback' , callback , 'function' ) 262 263opts =opts or {} 264local on_error =opts . on_error or log . error 265 266if type ( path ) == 'string' then 267path ={ { path =path } } 268end 269 270--- @type table<string, {pattern: vim._watch.Filter?, events: vim._watch.FileChangeType[]?}[]> 271local by_path =vim . defaulttable () 272 273for _ , rule in ipairs ( path ) do 274table . insert ( 275by_path [ vim . fs . normalize ( rule . path )], 276{ pattern =rule . pattern , events =rule . events } 277) 278end 279 280local cancels ={} --- @type (fun())[] 281 282local function cancel_all () 283for _ , cancel in ipairs ( cancels ) do 284cancel () 285end 286end 287 288for root , rules in pairs ( by_path ) do 289local ok , result =pcall ( subscribe , name , backend , root , opts , rules , { 290callback =callback , 291on_error =function ( err ) 292on_error (( '%s (watching %s)' ): format ( err , root )) 293end , 294} ) 295 296if not ok then 297cancel_all () 298error ( result , 0 ) 299end 300 301cancels [ # cancels + 1 ] =result 302end 303 304return cancel_all 305end 306 307--- Decides if `path` should be skipped. 308--- 309--- @param path string 310--- @param opts vim._watch.BackendOpts 311--- @param directory? boolean Ignore include_pattern when traversing directories. 312local function skip ( path , opts , directory ) 313if not directory and opts . include_pattern and opts . include_pattern : match ( path ) == nil then 314return true 315end 316 317if opts . exclude_pattern and opts . exclude_pattern : match ( path ) ~= nil then 318return true 319end 320 321return false 322end 323 324--- Initializes and starts a |uv_fs_event_t| 325--- 326--- @param path string The path to watch 327--- @param opts vim._watch.BackendOpts Additional options: 328--- - uvflags (table|nil) 329--- Same flags as accepted by |uv.fs_event_start()| 330--- @param callback vim._watch.Callback Callback for new events 331--- @return fun()? cancel Stops the watcher; nil if startup failed. 332local function watch ( path , opts , callback ) 333local on_error =opts . on_error 334local handle =assert ( uv . new_fs_event ()) 335 336local watching_dir =( uv . fs_stat ( path ) or {} ). type == 'directory' 337 338local _ , start_err =handle : start ( path , opts . uvflags or {} , function ( err , filename , events ) 339if err then 340return on_error ( err ) 341end 342local fullpath =path 343if filename and watching_dir then 344fullpath =vim . fs . normalize ( vim . fs . joinpath ( fullpath , filename )) 345end 346 347if skip ( fullpath , opts ) then 348return 349end 350 351--- @type vim._watch.FileChangeType 352local change_type 353if events . rename then 354local _ , staterr , staterrname =uv . fs_stat ( fullpath ) 355if staterrname == 'ENOENT' then 356change_type =M . FileChangeType . Deleted 357else 358if staterr then 359return on_error ( staterr ) 360end 361change_type =M . FileChangeType . Created 362end 363elseif events . change then 364change_type =M . FileChangeType . Changed 365end 366callback ( fullpath , change_type ) 367end ) 368 369if start_err then 370handle : close () 371on_error ( start_err ) 372return nil 373end 374 375return function () 376local _ , stop_err =handle : stop () 377assert ( not stop_err , stop_err ) 378local is_closing , close_err =handle : is_closing () 379assert ( not close_err , close_err ) 380if not is_closing then 381handle : close () 382end 383end 384end 385 386--- Initializes and starts a |uv_fs_event_t| recursively watching every directory underneath the 387--- directory at path. 388--- 389--- @param path string The path to watch. Must refer to a directory. 390--- @param opts vim._watch.BackendOpts Additional options 391--- @param callback vim._watch.Callback Callback for new events 392--- @return fun()? cancel Stops all directory watchers; nil if startup failed. 393local function watchdirs ( path , opts , callback ) 394local on_error =opts . on_error 395local debounce =opts . debounce or 500 396local cancelled =false 397 398---@type table<string, uv.uv_fs_event_t> handle by fullpath 399local handles ={} 400 401local timer =assert ( uv . new_timer ()) 402 403--- Map of file path to boolean indicating if the file has been changed 404--- at some point within the debounce cycle. 405--- @type table<string, boolean> 406local filechanges ={} 407 408local process_changes --- @type fun() 409 410--- @param filepath string 411--- @return uv.fs_event_start.callback 412local function create_on_change ( filepath ) 413return function ( err , filename , events ) 414if cancelled then 415return 416end 417if err then 418return on_error ( err ) 419end 420 421local fullpath =vim . fs . joinpath ( filepath , filename ) 422if skip ( fullpath , opts ) then 423-- An unmatched directory can contain matching descendants. Track its creation/deletion 424-- even when no event for the directory itself will be reported. 425if 426skip ( fullpath , opts , true ) 427or not events . rename 428or ( not handles [ fullpath ] and ( uv . fs_stat ( fullpath ) or {} ). type ~= 'directory' ) 429then 430return 431end 432end 433 434if not filechanges [ fullpath ] then 435filechanges [ fullpath ] =events . change or false 436end 437timer : start ( debounce , 0 , process_changes ) 438end 439end 440 441process_changes =function () 442-- Since the callback is debounced it may have also been deleted later on 443-- so we always need to check the existence of the file: 444-- stat succeeds, changed=true -> Changed 445-- stat succeeds, changed=false -> Created 446-- stat fails -> Removed 447for fullpath , changed in pairs ( filechanges ) do 448uv . fs_stat ( fullpath , function ( _ , stat ) 449if cancelled then 450return 451end 452 453---@type vim._watch.FileChangeType 454local change_type 455if stat then 456change_type =changed and M . FileChangeType . Changed or M . FileChangeType . Created 457if stat . type == 'directory' then 458local handle =handles [ fullpath ] 459if not handle then 460handle =assert ( uv . new_fs_event ()) 461handles [ fullpath ] =handle 462local _ , err , errname =handle : start ( fullpath , {} , create_on_change ( fullpath )) 463if err then 464handle : close () 465handles [ fullpath ] =nil 466-- The directory may have disappeared since fs_stat(). 467if errname ~= 'ENOENT' then 468on_error ( err ) 469end 470end 471end 472end 473else 474change_type =M . FileChangeType . Deleted 475local handle =handles [ fullpath ] 476if handle then 477if not handle : is_closing () then 478handle : close () 479end 480handles [ fullpath ] =nil 481end 482end 483 484if not skip ( fullpath , opts ) then 485callback ( fullpath , change_type ) 486end 487end ) 488end 489filechanges ={} 490end 491 492local root_handle =assert ( uv . new_fs_event ()) 493handles [ path ] =root_handle 494local _ , start_err =root_handle : start ( path , {} , create_on_change ( path )) 495 496if start_err then 497root_handle : close () 498timer : close () 499on_error ( start_err ) 500return nil 501end 502 503--- "640K ought to be enough for anyone" 504--- Who has folders this deep? 505local max_depth =100 506 507for name , type in 508vim . fs . dir ( path , { 509depth =max_depth , 510skip =function ( dir ) 511return not opts . exclude_pattern 512or opts . exclude_pattern : match ( vim . fs . joinpath ( path , dir )) == nil 513end , 514} ) 515do 516if type == 'directory' then 517local filepath =vim . fs . joinpath ( path , name ) 518if not skip ( filepath , opts , true ) then 519local handle =assert ( uv . new_fs_event ()) 520handles [ filepath ] =handle 521local _ , err , errname =handle : start ( filepath , {} , create_on_change ( filepath )) 522if err then 523handle : close () 524handles [ filepath ] =nil 525-- The directory may have disappeared since it was listed. 526if errname ~= 'ENOENT' then 527on_error ( err ) 528end 529end 530end 531end 532end 533 534return function () 535cancelled =true 536for fullpath , handle in pairs ( handles ) do 537if not handle : is_closing () then 538handle : close () 539end 540handles [ fullpath ] =nil 541end 542timer : stop () 543timer : close () 544end 545end 546 547--- @param data string 548--- @param opts vim._watch.BackendOpts 549--- @param callback vim._watch.Callback 550local function on_inotifywait_output ( data , opts , callback ) 551local d =vim . split ( data , '%s+' ) 552 553-- only consider the last reported event 554local path , event , file =assert ( d [ 1 ]), d [ 2 ], d [ # d ] 555local fullpath =vim . fs . joinpath ( path , file ) 556 557if skip ( fullpath , opts ) then 558return 559end 560 561--- @type integer 562local change_type 563 564if event == 'CREATE' then 565change_type =M . FileChangeType . Created 566elseif event == 'DELETE' then 567change_type =M . FileChangeType . Deleted 568elseif event == 'MODIFY' then 569change_type =M . FileChangeType . Changed 570elseif event == 'MOVED_FROM' then 571change_type =M . FileChangeType . Deleted 572elseif event == 'MOVED_TO' then 573change_type =M . FileChangeType . Created 574end 575 576if change_type then 577callback ( fullpath , change_type ) 578end 579end 580 581--- @param path string The path to watch. Must refer to a directory. 582--- @param opts vim._watch.BackendOpts 583--- @param callback vim._watch.Callback Callback for new events 584--- @return fun()? cancel Stops the process; nil if startup failed. 585local function inotify ( path , opts , callback ) 586local on_error =opts . on_error 587local cancelled =false 588local ok , obj =pcall ( vim . system , { 589'inotifywait' , 590'--quiet' , -- suppress startup messages 591'--no-dereference' , -- don't follow symlinks 592'--monitor' , -- keep listening for events forever 593'--recursive' , 594'--event' , 595'create' , 596'--event' , 597'delete' , 598'--event' , 599'modify' , 600'--event' , 601'move' , 602string . format ( '@%s/.git' , path ), -- ignore git directory 603path , 604} , { 605stderr =function ( err , data ) 606if err then 607on_error ( err ) 608return 609end 610 611if data and # vim . trim ( data ) > 0 then 612if vim . fn . has ( 'linux' ) == 1 and vim . startswith ( data , 'Failed to watch' ) then 613data ='inotify(7) limit reached, see :h inotify-limitations for more info.' 614end 615on_error ( data ) 616end 617end , 618stdout =function ( err , data ) 619if err then 620on_error ( err ) 621return 622end 623 624for line in vim . gsplit ( data or '' , '\n' , { plain =true , trimempty =true } ) do 625on_inotifywait_output ( line , opts , callback ) 626end 627end , 628-- --latency is locale dependent but tostring() isn't and will always have '.' as decimal point. 629env ={ LC_NUMERIC ='C' } , 630} , function ( result ) 631if not cancelled then 632on_error (( 'inotifywait exited with code %d' ): format ( result . code )) 633end 634end ) 635 636if not ok then 637on_error ( obj ) 638return nil 639end 640 641return function () 642cancelled =true 643obj : kill ( 2 ) 644end 645end 646 647--- Watches a path or set of rules. Compatible subscriptions share a backend watcher. 648--- @param path string|vim._watch.Rule[] 649--- @param opts? vim._watch.watch.Opts 650--- @param callback vim._watch.Callback 651--- @return fun() cancel Releases this subscription; the last cancellation stops the backend. 652function M . watch ( path , opts , callback ) 653return start_watch ( 'watch' , watch , path , opts , callback ) 654end 655 656--- Recursively watches directories. Compatible subscriptions share a backend watcher. 657--- @param path string|vim._watch.Rule[] Roots must be directories. 658--- @param opts? vim._watch.Opts 659--- @param callback vim._watch.Callback 660--- @return fun() cancel Releases this subscription; the last cancellation stops the backend. 661function M . watchdirs ( path , opts , callback ) 662return start_watch ( 'watchdirs' , watchdirs , path , opts , callback ) 663end 664 665--- Recursively watches directories using inotifywait. Compatible subscriptions share a process. 666--- @param path string|vim._watch.Rule[] Roots must be directories. 667--- @param opts? vim._watch.Opts 668--- @param callback vim._watch.Callback 669--- @return fun() cancel Releases this subscription; the last cancellation stops the backend. 670function M . inotify ( path , opts , callback ) 671return start_watch ( 'inotify' , inotify , path , opts , callback ) 672end 673 674return M