robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief 2--- 3--- Install, update, and delete external plugins. WARNING: It is still considered 4--- experimental, yet should be stable enough for daily use. 5--- 6---Manages plugins only in a dedicated [vim.pack-directory]() (see |packages|): 7---`site/pack/core/opt` subdirectory of "data" |standard-path|. Subdirectory `site` of "data" 8---standard path needs to be part of 'packpath'. It usually is, but might not be 9---in cases like |--clean| or setting |$XDG_DATA_HOME| during startup. 10---Plugin's subdirectory name matches plugin's name in specification. 11---It is assumed that all plugins in the directory are managed exclusively by `vim.pack`. 12--- 13---Uses Git to manage plugins and requires present `git` executable. 14---Target plugins should be Git repositories with versions as named tags 15---following semver convention `v<major>.<minor>.<patch>` (with or without `v` prefix). 16---Like `v1.2.0` or `1.2.0`, but not `1.2` or `v1`. 17--- 18---The latest state of all managed plugins is stored inside a [vim.pack-lockfile]() 19---located at |'packlockfile'|. 20---It is a JSON file that is used to persistently track data about plugins. 21---For a more robust config treat lockfile like its part: put under version control, etc. 22---In this case all plugins from the lockfile will be installed at once (in alphabetical order) and 23---at lockfile's revision (instead of inferring from `version`). This is done on the very first 24---`vim.pack` function call to ensure that lockfile is aligned with what is actually on the disk. 25---Lockfile should not be edited by hand. Corrupted data for installed plugins is repaired 26---(including after deleting whole file), but `version` fields will be missing 27---for not yet added plugins. 28--- 29---[vim.pack-examples]() 30--- 31---Basic install and management ~ 32--- 33---- Add |vim.pack.add()| call(s) to 'init.lua': 34---```lua 35--- 36---vim.pack.add({ 37--- -- Install "plugin1" and use default branch (usually `main` or `master`) 38--- 'https://github.com/user/plugin1', 39--- 40--- -- Same as above, but using a table (allows setting other options) 41--- { src = 'https://github.com/user/plugin1' }, 42--- 43--- -- Specify plugin's name (here the plugin will be called "plugin2" 44--- -- instead of "generic-name") 45--- { src = 'https://github.com/user/generic-name', name = 'plugin2' }, 46--- 47--- -- Specify version to follow during install and update 48--- { 49--- src = 'https://github.com/user/plugin3', 50--- -- Version constraint, see |vim.version.range()| 51--- version = vim.version.range('1.0'), 52--- }, 53--- { 54--- src = 'https://github.com/user/plugin4', 55--- -- Git branch, tag, or commit hash 56--- version = 'main', 57--- }, 58---}) 59--- 60----- Plugin's code can be used directly after `add()` 61---plugin1 = require('plugin1') 62---``` 63--- 64---- Restart Nvim (for example, with |:restart|). Plugins that were not yet 65---installed will be available on disk after `add()` call. Their revision is 66---taken from |vim.pack-lockfile| (if present) or inferred from the `version`. 67--- 68---- To update all plugins with new changes: 69--- - Execute |:packupdate|. This will download updates from source and 70--- show confirmation buffer in a separate tabpage. 71--- - Review changes. To confirm all updates execute |:write|. 72--- To discard updates execute |:quit|. 73--- - (Optionally) |:restart| to start using code from updated plugins. 74--- 75---Use shorter source ~ 76--- 77--- Create custom Lua helpers: 78--- 79---```lua 80--- 81---local gh = function(x) return 'https://github.com/' .. x end 82---local cb = function(x) return 'https://codeberg.org/' .. x end 83---vim.pack.add({ gh('user/plugin1'), cb('user/plugin2') }) 84---``` 85--- 86---Another approach is to utilize Git's `insteadOf` configuration: 87---- `git config --global url."https://github.com/".insteadOf "gh:"` 88---- `git config --global url."https://codeberg.org/".insteadOf "cb:"` 89---- In 'init.lua': `vim.pack.add({ 'gh:user/plugin1', 'cb:user/plugin2' })`. 90--- These sources will be used verbatim in |vim.pack-lockfile|, so reusing 91--- the config on different machine will require the same Git configuration. 92--- 93---Explore installed plugins ~ 94--- 95---- `:packupdate ++offline` 96---- Navigate between plugins with `[[` and `]]`. List them with `gO` 97--- (|vim.lsp.buf.document_symbol()|). 98--- 99---Switch plugin's version and/or source ~ 100--- 101---- Update 'init.lua' for plugin to have desired `version` and/or `src`. 102--- Let's say, the switch is for plugin named 'plugin1'. 103---- |:restart|. The plugin's state on disk (revision and/or tracked source) 104--- is not yet changed. Only plugin's `version` in |vim.pack-lockfile| is updated. 105---- Execute `:packupdate plugin1`. The plugin's source is updated. If only 106--- switching version, also pass the `++offline` argument. 107---- Review changes and either confirm or discard them. If discarded, revert 108--- `version` change in 'init.lua' as well or you will be prompted again next time 109--- you run `:packupdate`. 110--- 111---Freeze plugin from being updated ~ 112--- 113---- Update 'init.lua' for plugin to have `version` set to current revision. 114---Get it from |vim.pack-lockfile| (plugin's field `rev`; looks like `abc12345`). 115---- |:restart|. 116--- 117---Unfreeze plugin to start receiving updates ~ 118--- 119---- Update 'init.lua' for plugin to have `version` set to whichever version 120---you want it to be updated. 121---- |:restart|. 122--- 123---Revert plugin after an update ~ 124--- 125---- Revert the |vim.pack-lockfile| to the state before the update: 126--- - If Git tracked: `git checkout HEAD -- nvim-pack-lock.json` 127--- - If not tracked: examine log file ("nvim-pack.log" at "log" |standard-path|), 128--- locate the revisions before the latest update, and (carefully) adjust 129--- current lockfile to have those revisions. 130---- |:restart|. 131---- `:packupdate ++offline ++lockfile plugin`. 132--- Read and confirm. 133--- 134---Synchronize config across machines ~ 135--- 136---- On main machine: 137--- - Add |vim.pack-lockfile| to VCS. 138--- - Push to the remote server. 139---- On secondary machine: 140--- - Pull from the server. 141--- - |:restart|. New plugins (not present locally, but present in the lockfile) 142--- are installed at proper revision. If some installation has failed but 143--- you know it should not (like due to bad Internet connection), 144--- revert |vim.pack-lockfile| and |:restart| again. 145--- - `:packupdate ++lockfile`. Read and confirm. 146--- - Manually delete outdated plugins (present locally, but were not present 147--- in the lockfile prior to restart) with `:packdel plugin`. 148--- They can be located by examining the VCS difference of the lockfile 149--- (`git diff -- nvim-pack-lock.json` for Git). 150--- 151---Remove plugins from disk ~ 152--- 153---- Remove plugin specs from |vim.pack.add()| calls in 'init.lua' or they will be 154--- reinstalled later. 155---- |:restart|. 156---- Use |:packdel| with plugin names to remove. Use `:packdel ++all` to delete 157--- all inactive plugins. 158--- 159---Check for pending updates ~ 160--- 161---- Run `vim.pack.get(nil, { offline = false })` and check the output for items 162--- with different `rev` and `rev_to` fields. To not download new updates 163--- from source, use plain `vim.pack.get()`. 164--- 165---Check for issues ~ 166--- 167---- Run `:checkhealth vim.pack` and follow recommendations in case of detected issues. 168--- 169--- <pre>help 170--- Commands *vim.pack-commands* *E5807* 171--- 172--- *:packu* *:packupdate* *E5808* 173--- :packu[pdate][!] [++offline] [++lockfile] [name] 174--- 175--- Interactively update the specified plugins. Skips confirmation when `!` is 176--- given. If no plugin names are provided, update all plugins. 177--- 178--- When `++offline` is given, skip downloading new updates. 179--- 180--- When `++lockfile` is given, use revisions from the lockfile. 181--- 182--- *:packd* *:packdel* *E5809* *E5810* *E5811* 183--- :packd[el][!] {name} 184--- 185--- Remove the specified plugins. Can only remove inactive plugins unless `!` 186--- is given. 187--- 188--- :packd[el][!] ++all 189--- 190--- Remove all inactive plugins. When `!` is given, instead remove all plugins. 191--- </pre> 192--- 193---[vim.pack-events]() 194--- 195---Performing actions via `vim.pack` functions can trigger these events: 196---- [PackChangedPre]() - before trying to change plugin's state. 197---- [PackChanged]() - after plugin's state has changed. 198--- 199---Events are triggered in bulk respecting order of plugins in which they are supplied. 200---First all `PackChangedPre`, then perform all actions, and only after - all 201---`PackChanged` for successful actions. This provides more control for connected 202---plugins, like by specifying dependencies before the plugin itself. 203--- 204---The |event-data| has these keys (type: `vim.event.packchanged.data`): 205---- `active` - whether plugin was added via |vim.pack.add()| to current session. 206---- `kind` - one of "install" (install on disk; before loading), 207--- "update" (update already installed plugin; might be not loaded), 208--- "delete" (delete from disk). 209---- `spec` - plugin's specification with defaults made explicit. 210---- `path` - full path to plugin's directory. 211--- 212--- These events can be used to execute plugin hooks. For example: 213---```lua 214---local hooks = function(ev) 215--- -- Use available |event-data| 216--- local name, kind = ev.data.spec.name, ev.data.kind 217--- 218--- -- Run build script after plugin's code has changed 219--- if name == 'plug-1' and (kind == 'install' or kind == 'update') then 220--- -- Append `:wait()` if you need synchronous execution 221--- vim.system({ 'make' }, { cwd = ev.data.path }) 222--- end 223--- 224--- -- If action relies on code from the plugin (like user command or 225--- -- Lua code), make sure to explicitly load it first 226--- if name == 'plug-2' and kind == 'update' then 227--- if not ev.data.active then 228--- vim.cmd.packadd('plug-2') 229--- end 230--- vim.cmd('PlugTwoUpdate') 231--- require('plug2').after_update() 232--- end 233---end 234--- 235----- If hooks need to run on install, run this before `vim.pack.add()` 236----- To act on install from lockfile, run before very first `vim.pack.add()` 237---vim.api.nvim_create_autocmd('PackChanged', { callback = hooks }) 238---``` 239---[vim.pack-manifest]() 240--- 241---Plugins can come with a special top level `pkg.json` manifest file with extra 242---information. If present, `vim.pack` uses it for improved user experience: 243---- Apply |:source| for scripts after triggering corresponding |vim.pack-events|. 244--- This allows plugins to define hooks that will be executed during plugin's lifetime. 245--- Sourcing is done with special context: 246--- - The |current-directory| is temporarily set to plugin's root (to make 247--- it easier to run |vim.system()| commands). 248--- - Plugin's path is temporarily ensured to be inside |'runtimepath'| (so script 249--- can use |require()| with plugin's module, possibly with explicit |package.loaded| 250--- reset inside `"update"` scripts). 251---- Running |:checkhealth| for `vim.pack` will perform extra checks to ensure 252--- healthy plugin installation. 253--- 254---Full specification see at https://packspec.org/. See also |vim.pack.Manifest|. 255---A simple example: 256---```json 257---{ 258--- "name": "best-plugin.nvim", 259--- "description": "The best plugin for Neovim", 260--- "engines": { 261--- "nvim": ">=0.13.0", 262--- "vim": ">=9.1.0" 263--- }, 264--- "scripts": { 265--- "install": "scripts/install.lua", 266--- "preupdate": "scripts/preupdate.vim", 267--- "update": "scripts/update.vim", 268--- "preuninstall": "scripts/preuninstall.lua" 269--- } 270---} 271---``` 272 273local api =vim . api 274local uv =vim . uv 275---@diagnostic disable-next-line: no-unknown 276local async =require ( 'vim.async' ) 277local util =require ( 'vim._core.util' ) 278local nvim_on =util . nvim_on 279local N_ =vim . fn . gettext 280 281local M ={} 282 283--- @nodoc 284--- @class vim.pack.LockData 285--- @field rev string Latest recorded revision. 286--- @field src string Plugin source. 287--- @field version? string|vim.VersionRange Plugin `version`, as supplied in `spec`. 288 289--- @nodoc 290--- @class vim.pack.Lock 291--- @field plugins table<string, vim.pack.LockData> Map from plugin name to its lock data. 292 293--- @type vim.pack.Lock 294local plugin_lock 295 296--- @return string 297local function get_plug_dir () 298return vim . fs . joinpath ( vim . fn . stdpath ( 'data' ), 'site' , 'pack' , 'core' , 'opt' ) 299end 300 301-- Git ------------------------------------------------------------------------ 302 303--- @async 304--- @param cmd string[] 305--- @param cwd? string 306--- @return string 307local function git_cmd ( cmd , cwd ) 308-- Use '-c gc.auto=0' to disable `stderr` "Auto packing..." messages 309cmd =vim . list_extend ( { 'git' , '-c' , 'gc.auto=0' } , cmd ) 310local env =vim . fn . environ () --- @type table<string,string> 311env . GIT_DIR , env . GIT_WORK_TREE , env . GIT_INDEX_FILE =nil , nil , nil 312local sys_opts ={ cwd =cwd , text =true , env =env , clear_env =true } 313local out =async . await ( 3 , vim . system , cmd , sys_opts ) --- @type vim.SystemCompleted 314async . await ( 1 , vim . schedule ) 315local stderr =out . stderr or '' 316if out . code ~= 0 then 317error ( stderr ) 318end 319if stderr ~= '' then 320vim . schedule ( function () 321vim . notify ( stderr : gsub ( '\n+$' , '' ), vim . log . levels . WARN ) 322end ) 323end 324return ( assert ( out . stdout ): gsub ( '\n+$' , '' )) 325end 326 327--- @param x string 328local function parse_semver ( x ) 329return vim . version . parse ( x , { strict =true } ) 330end 331 332--- @type vim.Version 333local git_version 334 335local function git_ensure_exec () 336local ok , sys =pcall ( vim . system , { 'git' , 'version' } ) 337if not ok then 338error ( 'No `git` executable' ) 339end 340git_version =vim . version . parse ( assert ( sys : wait (). stdout )) --[[@as vim.Version]] 341end 342 343--- @async 344--- @param url string 345--- @param path string 346local function git_clone ( url , path ) 347local cmd ={ 'clone' , '--quiet' , '--no-checkout' } 348 349if vim . startswith ( url , 'file://' ) then 350cmd [ # cmd + 1 ] ='--no-hardlinks' 351elseif git_version >= parse_semver ( '2.27.0' ) then 352cmd [ # cmd + 1 ] ='--filter=blob:none' 353end 354 355vim . list_extend ( cmd , { '--origin' , 'origin' , url , path } ) 356git_cmd ( cmd , uv . cwd ()) 357end 358 359--- @async 360--- @param ref string 361--- @param cwd string 362--- @return string 363local function git_get_hash ( ref , cwd ) 364-- Using `rev-list -1` shows a commit of reference, while `rev-parse` shows 365-- hash of reference. Those are different for annotated tags. 366return git_cmd ( { 'rev-list' , '-1' , ref } , cwd ) 367end 368 369--- @async 370--- @param cwd string 371local function git_fetch ( cwd ) 372-- Using '--tags --force' means conflicting tags will be synced with remote 373local args ={ 'fetch' , '--quiet' , '--tags' , '--force' , '--recurse-submodules=yes' , 'origin' } 374git_cmd ( args , cwd ) 375end 376 377--- @async 378--- @param cwd string 379--- @return string 380local function git_get_default_branch ( cwd ) 381local res =git_cmd ( { 'rev-parse' , '--abbrev-ref' , 'origin/HEAD' } , cwd ) 382return ( res : gsub ( '^origin/' , '' )) 383end 384 385--- @async 386--- @param cwd string 387--- @return string[] 388local function git_get_branches ( cwd ) 389local def_branch =git_get_default_branch ( cwd ) 390local cmd ={ 'branch' , '--remote' , '--list' , '--format=%(refname:short)' , '--' , 'origin/**' } 391local stdout =git_cmd ( cmd , cwd ) 392local res ={} --- @type string[] 393for l in vim . gsplit ( stdout , '\n' ) do 394local branch =l : match ( '^origin/(.+)$' ) 395local pos =branch == def_branch and 1 or ( # res + 1 ) 396table . insert ( res , pos , branch ) 397end 398return res 399end 400 401--- @async 402--- @param cwd string 403--- @return string[] 404local function git_get_tags ( cwd ) 405local tags =git_cmd ( { 'tag' , '--list' , '--sort=-v:refname' } , cwd ) 406return tags == '' and {} or vim . split ( tags , '\n' ) 407end 408 409-- Plugin operations ---------------------------------------------------------- 410 411--- @param msg string|string[] 412--- @param level ('DEBUG'|'TRACE'|'INFO'|'WARN'|'ERROR')? 413local function notify ( msg , level ) 414msg =type ( msg ) == 'table' and table . concat ( msg , '\n' ) or msg 415vim . notify ( 'vim.pack: ' .. msg , vim . log . levels [ level or 'INFO' ]) 416vim . cmd . redraw () 417end 418 419--- @param x string|vim.VersionRange 420--- @return boolean 421local function is_version ( x ) 422return type ( x ) == 'string' or ( type ( x ) == 'table' and pcall ( x . has , x , '1' )) 423end 424 425--- @param x string 426--- @return boolean 427local function is_semver ( x ) 428return parse_semver ( x ) ~= nil 429end 430 431--- @param x any 432local function is_nonempty_string ( x ) 433return type ( x ) == 'string' and x ~= '' 434end 435 436--- @return string 437local function get_timestamp () 438return vim . fn . strftime ( '%Y-%m-%d %H:%M:%S' ) 439end 440 441--- @class vim.pack.Spec 442--- 443--- URI from which to install and pull updates. Any format supported by `git clone` is allowed. 444--- @field src string 445--- 446--- Name of plugin. Will be used as directory name. Default: `src` repository name. 447--- @field name? string 448--- 449--- Version to use for install and updates. Can be: 450--- - `nil` (no value, default) to use repository's default branch (usually `main` or `master`). 451--- - String to use specific branch, tag, or commit hash. 452--- - Output of |vim.version.range()| to install the greatest/last semver tag 453--- inside the version constraint. 454--- @field version? string|vim.VersionRange 455--- 456--- @field data? any Arbitrary data associated with a plugin. 457 458--- @alias vim.pack.SpecResolved { src: string, name: string, version: nil|string|vim.VersionRange, data: any|nil } 459 460--- @param spec string|vim.pack.Spec 461--- @return vim.pack.SpecResolved 462local function normalize_spec ( spec ) 463-- and/or narrowing: EmmyLuaLs/emmylua-analyzer-rust#1260 464spec =( type ( spec ) == 'string' and { src =spec } or spec ) --[[@as vim.pack.Spec]] 465vim . validate ( 'spec' , spec , 'table' ) 466vim . validate ( 'spec.src' , spec . src , is_nonempty_string , false , 'non-empty string' ) 467local name =spec . name or spec . src : gsub ( '%.git$' , '' ) 468name =( type ( name ) == 'string' and name or '' ): match ( '[^/]+$' ) or '' 469vim . validate ( 'spec.name' , name , is_nonempty_string , true , 'non-empty string' ) 470vim . validate ( 'spec.version' , spec . version , is_version , true , 'string or vim.VersionRange' ) 471return { src =spec . src , name =name , version =spec . version , data =spec . data } 472end 473 474--- @class (private) vim.pack.PlugInfo 475--- @field err string The latest error when working on plugin. If non-empty, 476--- all further actions should not be done (including triggering events). 477--- @field installed? boolean Whether plugin was successfully installed. 478--- @field updated? boolean Whether plugin was successfully updated. 479--- @field version_str? string `spec.version` with resolved version range. 480--- @field version_ref? string Resolved version as Git reference (if different 481--- from `version_str`). 482--- @field sha_head? string Git hash of HEAD. 483--- @field sha_target? string Git hash of `version_ref`. 484--- @field update_details? string Details about the update:: changelog if HEAD 485--- and target are different, available newer tags otherwise. 486 487--- @class (private) vim.pack.Plug 488--- @field spec vim.pack.SpecResolved 489--- @field path string 490--- @field info vim.pack.PlugInfo Gathered information about plugin. 491 492--- @param spec string|vim.pack.Spec 493--- @param plug_dir string? 494--- @return vim.pack.Plug 495local function new_plug ( spec , plug_dir ) 496local spec_resolved =normalize_spec ( spec ) 497local path =vim . fs . joinpath ( plug_dir or get_plug_dir (), spec_resolved . name ) 498local info ={ err ='' , installed =plugin_lock . plugins [ spec_resolved . name ] ~= nil } 499return { spec =spec_resolved , path =path , info =info } 500end 501 502--- Normalize plug array: gather non-conflicting data from duplicated entries. 503--- @param plugs vim.pack.Plug[] 504--- @return vim.pack.Plug[] 505local function normalize_plugs ( plugs ) 506--- @type table<string, { plug: vim.pack.Plug, id: integer }> 507local plug_map ={} 508local n =0 509for _ , p in ipairs ( plugs ) do 510-- Collect 511if not plug_map [ p . path ] then 512n =n + 1 513plug_map [ p . path ] ={ plug =p , id =n } 514end 515local p_data =plug_map [ p . path ] 516-- TODO(echasnovski): if both versions are `vim.VersionRange`, collect as 517-- their intersection. Needs `vim.version.intersect`. 518p_data . plug . spec . version =vim . nonnil ( p_data . plug . spec . version , p . spec . version ) 519 520-- Ensure no conflicts 521local spec_ref =p_data . plug . spec 522local spec =p . spec 523if spec_ref . src ~= spec . src then 524local src_1 =tostring ( spec_ref . src ) 525local src_2 =tostring ( spec . src ) 526error (( 'Conflicting `src` for `%s`:\n%s\n%s' ): format ( spec . name , src_1 , src_2 )) 527end 528if spec_ref . version ~= spec . version then 529local ver_1 =tostring ( spec_ref . version ) 530local ver_2 =tostring ( spec . version ) 531error (( 'Conflicting `version` for `%s`:\n%s\n%s' ): format ( spec . name , ver_1 , ver_2 )) 532end 533end 534 535--- @type vim.pack.Plug[] 536local res ={} 537for _ , p_data in pairs ( plug_map ) do 538res [ p_data . id ] =p_data . plug 539end 540assert ( # res == n ) 541return res 542end 543 544--- @param names? string[] 545--- @return vim.pack.Plug[] 546local function plug_list_from_names ( names ) 547local p_data_list =M . get ( names , { info =false } ) 548local plug_dir =get_plug_dir () 549local plugs ={} --- @type vim.pack.Plug[] 550for _ , p_data in ipairs ( p_data_list ) do 551plugs [ # plugs + 1 ] =new_plug ( p_data . spec , plug_dir ) 552end 553return plugs 554end 555 556--- Map from plugin path to its data. 557--- Use map and not array to avoid linear lookup during startup. 558--- @type table<string, { plug: vim.pack.Plug, id: integer }?> 559local active_plugins ={} 560local n_active_plugins =0 561 562--- @class vim.pack.ManifestEngines 563--- @inlinedoc 564--- @field nvim? string Version range for Nvim. 565--- @field vim? string Version range for Vim. 566 567--- @class vim.pack.ManifestScripts 568--- @inlinedoc 569--- @field install? string Post install script. 570--- @field preupdate? string Pre update script. 571--- @field update? string Post update script. 572--- @field preuninstall? string Pre delete script. 573 574--- @class vim.pack.Manifest 575--- @field name? string Plugin name 576--- @field description? string Plugin description 577--- Supported engine versions. Values should be |vim.version.range()| compatible specs. 578--- @field engines? vim.pack.ManifestEngines 579--- Script locations (relative to plugin's root) to |:source| after triggering 580--- corresponding |vim.pack-events|. 581--- @field scripts? vim.pack.ManifestScripts 582 583--- @param path string 584--- @return vim.pack.Manifest? 585local function manifest_read ( path ) 586local manifest_path =vim . fs . joinpath ( path , 'pkg.json' ) 587local stat =uv . fs_stat ( manifest_path ) 588if not stat then 589return nil 590end 591 592local fd =uv . fs_open ( manifest_path , 'r' , 438 ) 593if not fd then 594return {} 595end 596 597local data =assert ( uv . fs_read ( fd , stat . size , 0 )) 598assert ( uv . fs_close ( fd )) 599local ok , res =pcall ( vim . json . decode , data ) 600return ( ok and type ( res ) == 'table' ) and res or {} 601end 602 603--- @param p vim.pack.Plug 604--- @param name string 605local function source_manifest_script ( p , name ) 606local manifest =manifest_read ( p . path ) 607if not ( type ( manifest ) == 'table' and ( manifest . scripts or {} )[ name ]) then 608return 609end 610 611local script_path =vim . fs . joinpath ( p . path , ( manifest . scripts or {} )[ name ]) 612vim . _with ( { cwd =p . path , o ={ runtimepath =vim . o . runtimepath } } , function () 613vim . cmd . packadd ( { p . spec . name , bang =true } ) 614---@diagnostic disable-next-line: no-unknown 615local ok , err =pcall ( vim . cmd . source , { script_path , magic ={ file =false , bar =false } } ) 616if not ok then 617notify ( err , 'WARN' ) 618end 619end ) 620end 621 622local manifest_script_name_map ={ 623PackChangedPre ={ update ='preupdate' , delete ='preuninstall' } , 624PackChanged ={ install ='install' , update ='update' } , 625} 626 627--- @param plugs vim.pack.Plug[] 628--- @param event_name 'PackChangedPre'|'PackChanged' 629--- @param kind 'install'|'update'|'delete' 630local function trigger_events ( plugs , event_name , kind ) 631local manifest_script_name =manifest_script_name_map [ event_name ][ kind ] 632for _ , p in ipairs ( plugs ) do 633local active =active_plugins [ p . path ] ~= nil 634local data ={ active =active , kind =kind , spec =vim . deepcopy ( p . spec ), path =p . path } 635api . nvim_exec_autocmds ( event_name , { pattern =p . path , data =data } ) 636 637if manifest_script_name then 638source_manifest_script ( p , manifest_script_name ) 639end 640end 641end 642 643--- @param action string 644--- @return fun(kind: 'begin'|'report'|'end', percent: integer, fmt: string, ...:any): nil 645local function new_progress_report ( action ) 646local progress ={ kind ='progress' , source ='vim.pack' , title ='vim.pack' } 647local headless =# api . nvim_list_uis () == 0 648 649return vim . schedule_wrap ( function ( kind , percent , fmt , ... ) 650progress . status =kind == 'end' and 'success' or 'running' 651progress . percent =percent 652local msg =( '%s %s' ): format ( action , fmt : format ( ... )) 653progress . id =api . nvim_echo ( { { msg } } , kind ~= 'report' , progress ) 654-- Force redraw to show installation progress during startup 655-- TODO: redraw! not needed with ui2. 656if not headless then 657vim . cmd . redraw ( { bang =true } ) 658end 659end ) 660end 661 662local copcall =package . loaded . jit and pcall or require ( 'coxpcall' ). pcall 663local max_timeout =120000 664 665--- @param funs (async fun())[] 666local function async_join_run_wait ( funs ) 667local n_threads =2 * ( uv . available_parallelism () or 1 ) 668--- @async 669local function joined_f () 670---@diagnostic disable-next-line: no-unknown 671local semaphore =async . semaphore ( n_threads ) 672---@param f async fun() 673local function run_one ( f ) 674-- Isolate job failures. Task return still observes cancellation. 675copcall ( semaphore . with , semaphore , f ) 676end 677for _ , f in ipairs ( funs ) do 678async . run ( run_one , f ) 679end 680end 681async . run ( joined_f ): wait ( max_timeout ) 682end 683 684--- Execute function in parallel for each non-errored plugin in the list 685--- @param plug_list vim.pack.Plug[] 686--- @param f async fun(p: vim.pack.Plug) 687--- @param progress_action string 688local function run_list ( plug_list , f , progress_action ) 689local report_progress =new_progress_report ( progress_action ) 690 691-- Construct array of functions to execute in parallel 692local n_finished =0 693local funs ={} --- @type (async fun())[] 694for _ , p in ipairs ( plug_list ) do 695-- Run only for plugins which didn't error before 696if p . info . err == '' then 697--- @async 698funs [ # funs + 1 ] =function () 699---@diagnostic disable-next-line: no-unknown 700local ok , err =async . pawait ( async . run ( f , p )) 701if not ok then 702p . info . err =err --- @as string 703end 704 705-- Show progress 706n_finished =n_finished + 1 707local percent =math . floor ( 100 * n_finished / # funs ) 708report_progress ( 'report' , percent , '(%d/%d) - %s' , n_finished , # funs , p . spec . name ) 709end 710end 711end 712 713if # funs == 0 then 714return 715end 716 717-- Run async in parallel but wait for all to finish/timeout 718report_progress ( 'begin' , 0 , '(0/%d)' , # funs ) 719async_join_run_wait ( funs ) 720report_progress ( 'end' , 100 , '(%d/%d)' , # funs , # funs ) 721end 722 723local confirm_all =false 724 725--- @param plug_list vim.pack.Plug[] 726--- @return boolean 727local function confirm_install ( plug_list ) 728if confirm_all then 729return true 730end 731 732-- Gather pretty aligned list of plugins to install 733local name_width , name_max_width ={} , 0 --- @type integer[], integer 734for i , p in ipairs ( plug_list ) do 735name_width [ i ] =api . nvim_strwidth ( p . spec . name ) 736name_max_width =math . max ( name_max_width , name_width [ i ]) 737end 738local lines ={} --- @type string[] 739for i , p in ipairs ( plug_list ) do 740local pad =( ' ' ): rep ( name_max_width - assert ( name_width [ i ]) + 1 ) 741lines [ i ] =( '%s%sfrom %s' ): format ( p . spec . name , pad , p . spec . src ) 742end 743 744local text =table . concat ( lines , '\n' ) 745local confirm_msg =( 'These plugins will be installed:\n\n%s\n' ): format ( text ) 746local choice =vim . fn . confirm ( confirm_msg , 'Proceed? &Yes\n&No\n&Always' , 1 , 'Question' ) 747confirm_all =choice == 3 748vim . cmd . redraw () 749return choice ~= 2 750end 751 752--- @param tags string[] 753--- @param version_range vim.VersionRange 754local function get_last_semver_tag ( tags , version_range ) 755local last_tag , last_ver_tag --- @type string, vim.Version 756for _ , tag in ipairs ( tags ) do 757local ver_tag =parse_semver ( tag ) 758if ver_tag then 759if version_range : has ( ver_tag ) and ( not last_ver_tag or ver_tag > last_ver_tag ) then 760last_tag , last_ver_tag =tag , ver_tag 761end 762end 763end 764return last_tag 765end 766 767--- @async 768--- @param p vim.pack.Plug 769local function resolve_version ( p ) 770--- @param name string 771--- @param list string[] 772local function list_in_line ( name , list ) 773return ( '\n%s: %s' ): format ( name , table . concat ( list , ', ' )) 774end 775 776-- Resolve only once 777if p . info . version_str then 778return 779end 780local version =p . spec . version 781 782-- Default branch 783if not version then 784p . info . version_str =git_get_default_branch ( p . path ) 785p . info . version_ref ='origin/' .. p . info . version_str 786return 787end 788 789-- Non-version-range like version: branch, tag, or commit hash 790local branches =git_get_branches ( p . path ) 791local tags =git_get_tags ( p . path ) 792if type ( version ) == 'string' then 793local is_branch =vim . tbl_contains ( branches , version ) 794---@diagnostic disable-next-line: no-unknown 795local is_tag_or_hash =async . pawait ( async . run ( git_get_hash , version , p . path )) 796if not ( is_branch or is_tag_or_hash ) then 797local err =( '`%s` is not a branch/tag/commit. Available:' ): format ( version ) 798.. list_in_line ( 'Tags' , tags ) 799.. list_in_line ( 'Branches' , branches ) 800error ( err ) 801end 802 803p . info . version_str =version 804p . info . version_ref =( is_branch and 'origin/' or '' ) .. version 805return 806end 807--- @cast version vim.VersionRange 808 809-- Choose the greatest/last version among all matching semver tags 810p . info . version_str =get_last_semver_tag ( tags , version ) 811if p . info . version_str == nil then 812local semver_tags =vim . tbl_filter ( is_semver , tags ) 813table . sort ( semver_tags , vim . version . gt ) 814local err ='No versions fit constraint. Relax it or switch to branch. Available:' 815.. list_in_line ( 'Versions' , semver_tags ) 816.. list_in_line ( 'Branches' , branches ) 817error ( err ) 818end 819end 820 821--- @async 822--- @param p vim.pack.Plug 823local function infer_revisions ( p ) 824p . info . sha_head =p . info . sha_head or git_get_hash ( 'HEAD' , p . path ) 825 826resolve_version ( p ) 827local target_ref =p . info . version_ref or p . info . version_str --[[@as string]] 828p . info . sha_target =p . info . sha_target or git_get_hash ( target_ref , p . path ) 829end 830 831--- Keep repos in detached HEAD state. Infer commit from resolved version. 832--- No local branches are created, branches from "origin" remote are used directly. 833--- @async 834--- @param p vim.pack.Plug 835--- @param timestamp string 836--- @param skip_stash? boolean 837local function checkout ( p , timestamp , skip_stash ) 838infer_revisions ( p ) 839 840if not skip_stash then 841local stash_cmd ={ 'stash' } 842if git_version > parse_semver ( '2.13.0' ) then 843-- Use 'push' to avoid a 'stash -m' bug in versions prior to git v2.26 844stash_cmd [ # stash_cmd + 1 ] ='push' 845stash_cmd [ # stash_cmd + 1 ] ='--message' 846stash_cmd [ # stash_cmd + 1 ] =( 'vim.pack: %s Stash before checkout' ): format ( timestamp ) 847end 848stash_cmd [ # stash_cmd + 1 ] ='--quiet' 849git_cmd ( stash_cmd , p . path ) 850end 851 852git_cmd ( { 'checkout' , '--quiet' , p . info . sha_target } , p . path ) 853 854local submodule_cmd ={ 'submodule' , 'update' , '--init' , '--recursive' } 855if git_version >= parse_semver ( '2.36.0' ) then 856submodule_cmd [ # submodule_cmd + 1 ] ='--filter=blob:none' 857end 858git_cmd ( submodule_cmd , p . path ) 859 860plugin_lock . plugins [ p . spec . name ]. rev =p . info . sha_target 861 862-- (Re)Generate help tags according to the current help files. 863-- Also use `pcall()` because `:helptags` errors if 'doc/' has no help files. 864local doc_dir =vim . fs . joinpath ( p . path , 'doc' ) 865vim . fn . delete ( vim . fs . joinpath ( doc_dir , 'tags' )) 866if vim . fn . isdirectory ( doc_dir ) == 1 then 867copcall ( vim . cmd . helptags , { doc_dir , magic ={ file =false } } ) 868end 869end 870 871--- @param plug_list vim.pack.Plug[] 872--- @param confirm? boolean 873local function install_list ( plug_list , confirm ) 874local timestamp =get_timestamp () 875--- @async 876--- @param p vim.pack.Plug 877local function do_install ( p ) 878git_clone ( p . spec . src , p . path ) 879 880plugin_lock . plugins [ p . spec . name ]. src =p . spec . src 881 882-- Prefer revision from the lockfile instead of using `version` 883p . info . sha_target =( plugin_lock . plugins [ p . spec . name ] or {} ). rev 884 885checkout ( p , timestamp , true ) 886p . info . installed =true 887end 888 889-- Install possibly after user confirmation 890if not confirm or confirm_install ( plug_list ) then 891trigger_events ( plug_list , 'PackChangedPre' , 'install' ) 892run_list ( plug_list , do_install , 'Installing plugins' ) 893local installed =vim . tbl_filter ( function ( p ) 894return p . info . installed == true 895end , plug_list ) 896trigger_events ( installed , 'PackChanged' , 'install' ) 897end 898 899-- Ensure that not fully installed plugins are absent on disk and in lockfile 900for _ , p in ipairs ( plug_list ) do 901if not ( p . info . installed and uv . fs_stat ( p . path ) ~= nil ) then 902plugin_lock . plugins [ p . spec . name ] =nil 903vim . fs . rm ( p . path , { recursive =true , force =true } ) 904end 905end 906end 907 908--- @async 909--- @param p vim.pack.Plug 910local function infer_update_details ( p ) 911p . info . update_details ='' 912infer_revisions ( p ) 913local sha_head =assert ( p . info . sha_head ) 914local sha_target =assert ( p . info . sha_target ) 915 916-- Try showing log of changes (if any) 917if sha_head ~= sha_target then 918local range =sha_head .. '...' .. sha_target 919local format ='--pretty=format:%m %h │ %s%d' 920-- Show only tags near commits (not `origin/main`, etc.) 921local decorate ='--decorate-refs=refs/tags' 922-- `--topo-order` makes showing divergent branches nicer, but by itself 923-- doesn't ensure that reverted ("left", shown with `<`) and added 924-- ("right", shown with `>`) commits have fixed order. 925local l =git_cmd ( { 'log' , format , '--topo-order' , '--left-only' , decorate , range } , p . path ) 926local r =git_cmd ( { 'log' , format , '--topo-order' , '--right-only' , decorate , range } , p . path ) 927p . info . update_details =l == '' and r or ( r == '' and l or ( l .. '\n' .. r )) 928return 929end 930 931-- Suggest newer semver tags (i.e. greater than greatest past semver tag) 932local all_semver_tags =vim . tbl_filter ( is_semver , git_get_tags ( p . path )) 933if # all_semver_tags == 0 then 934return 935end 936 937local older_tags ='' 938if git_version >= parse_semver ( '2.13.0' ) then 939older_tags =git_cmd ( { 'tag' , '--list' , '--no-contains' , sha_head } , p . path ) 940end 941local cur_tags =git_cmd ( { 'tag' , '--list' , '--points-at' , sha_head } , p . path ) 942local past_tags =vim . split ( older_tags , '\n' ) 943vim . list_extend ( past_tags , vim . split ( cur_tags , '\n' )) 944 945local any_version =vim . version . range ( '*' ) --[[@as vim.VersionRange]] 946local last_version =get_last_semver_tag ( past_tags , any_version ) 947 948local newer_semver_tags =vim . tbl_filter ( function ( x ) 949return vim . version . gt ( x , last_version ) 950end , all_semver_tags ) 951 952table . sort ( newer_semver_tags , vim . version . gt ) 953p . info . update_details =table . concat ( newer_semver_tags , '\n' ) 954end 955 956--- @param plug vim.pack.Plug 957--- @param load? boolean|fun(plug_data: {spec: vim.pack.Spec, path: string}) 958local function pack_add ( plug , load ) 959-- Add plugin only once, i.e. no overriding of spec. This allows users to put 960-- plugin first to fully control its spec. 961if active_plugins [ plug . path ] then 962return 963end 964 965n_active_plugins =n_active_plugins + 1 966active_plugins [ plug . path ] ={ plug =plug , id =n_active_plugins } 967 968if vim . is_callable ( load ) then 969---@cast load -boolean, -nil 970load ( { spec =vim . deepcopy ( plug . spec ), path =plug . path } ) 971return 972end 973 974-- NOTE: The `:packadd` specifically seems to not handle spaces in dir name 975vim . cmd . packadd ( { vim . fn . escape ( plug . spec . name , ' ' ), bang =not load , magic ={ file =false } } ) 976 977-- The `:packadd` only sources plain 'plugin/' files. Execute 'after/' scripts 978-- if not during startup (when they will be sourced later, even if 979-- `vim.pack.add` is inside user's 'plugin/') 980-- See https://github.com/vim/vim/issues/15584 981-- Deliberately do so after executing all currently known 'plugin/' files. 982if vim . v . vim_did_enter == 1 and load then 983local after_paths =vim . fn . glob ( plug . path .. '/after/plugin/**/*.{vim,lua}' , false , true ) 984--- @param path string 985vim . tbl_map ( function ( path ) 986vim . cmd . source ( { path , magic ={ file =false } } ) 987end , after_paths ) 988end 989end 990 991local function lock_write () 992-- Serialize `version` 993local lock =vim . deepcopy ( plugin_lock ) 994for _ , l_data in pairs ( lock . plugins ) do 995local version =l_data . version 996if version then 997l_data . version =type ( version ) == 'string' and ( "'%s'" ): format ( version ) or tostring ( version ) 998end 999end 1000 1001vim . fn . mkdir ( vim . fs . dirname ( M . _plugin_lock_path ), 'p' ) 1002local fd =assert ( uv . fs_open ( M . _plugin_lock_path , 'w' , 438 )) 1003 1004local data =vim . json . encode ( lock , { indent =' ' , sort_keys =true } ) 1005assert ( uv . fs_write ( fd , data .. '\n' )) 1006assert ( uv . fs_close ( fd )) 1007end 1008 1009--- @param names string[] 1010--- @param plug_dir string 1011local function lock_repair ( names , plug_dir ) 1012--- @async 1013local function f () 1014for _ , name in ipairs ( names ) do 1015local path =vim . fs . joinpath ( plug_dir , name ) 1016-- Try reusing existing table to preserve maybe present `version` 1017local data =plugin_lock . plugins [ name ] or {} 1018data . rev =git_get_hash ( 'HEAD' , path ) 1019data . src =git_cmd ( { 'remote' , 'get-url' , 'origin' } , path ) 1020plugin_lock . plugins [ name ] =data 1021end 1022end 1023async . run ( f ): wait ( max_timeout ) 1024end 1025 1026--- Sync lockfile data and installed plugins: 1027--- - Install plugins that have proper lockfile data but are not on disk. 1028--- - Repair corrupted lock data for installed plugins. 1029--- - Remove unrepairable corrupted lock data and plugins. 1030--- @param confirm boolean 1031--- @param specs (string|vim.pack.Spec)[] Plugin specs provided by the user. Can contain 1032--- fields outside of what is in the lockfile to be passed down to events. 1033local function lock_sync ( confirm , specs ) 1034if type ( plugin_lock . plugins ) ~= 'table' then 1035plugin_lock . plugins ={} 1036end 1037 1038-- Compute installed plugins 1039local plug_dir =get_plug_dir () 1040if uv . fs_stat ( plug_dir ) == nil then 1041vim . fn . mkdir ( plug_dir , 'p' ) 1042end 1043 1044-- NOTE: The directory traversal is done on every startup, but it is very fast. 1045-- Also, single `vim.fs.dir()` scales better than on demand `uv.fs_stat()` checks. 1046local installed ={} --- @type table<string,string> 1047for name , fs_type in vim . fs . dir ( plug_dir ) do 1048installed [ name ] =fs_type 1049plugin_lock . plugins [ name ] =plugin_lock . plugins [ name ] or {} 1050end 1051 1052-- Traverse once optimizing for "regular startup" (no repair, no install) 1053local to_install ={} --- @type vim.pack.Plug[] 1054local to_repair ={} --- @type string[] 1055local to_remove ={} --- @type string[] 1056for name , data in pairs ( plugin_lock . plugins ) do 1057if type ( data ) ~= 'table' then 1058data ={} ---@diagnostic disable-line: missing-fields 1059plugin_lock . plugins [ name ] =data 1060end 1061 1062-- Deserialize `version` 1063local version =data . version 1064if type ( version ) == 'string' then 1065data . version =version : match ( "^'(.+)'$" ) or vim . version . range ( version ) 1066end 1067 1068-- Synchronize 1069local is_bad_lock =type ( data . rev ) ~= 'string' or type ( data . src ) ~= 'string' 1070local is_bad_plugin =installed [ name ] and installed [ name ] ~= 'directory' 1071if is_bad_lock or is_bad_plugin then 1072local t =installed [ name ] == 'directory' and to_repair or to_remove 1073t [ # t + 1 ] =name 1074elseif not installed [ name ] then 1075local spec ---@type vim.pack.Spec 1076-- Try reusing spec from user's `vim.pack.add()` (matters for events) 1077-- Delay until this point when shaving milliseconds shouldn't matter much 1078for _ , s in ipairs ( specs ) do 1079local ok , s_norm =pcall ( normalize_spec , s ) 1080if ok and s_norm . name == name then 1081spec =vim . deepcopy ( s_norm ) 1082end 1083end 1084 1085-- Force fields relevant to actual installation, try to preserve others 1086spec =spec or {} 1087spec . src =data . src 1088spec . name =name 1089spec . version =spec . version or data . version 1090 1091to_install [ # to_install + 1 ] =new_plug ( spec , plug_dir ) 1092end 1093end 1094 1095-- Perform actions if needed 1096if # to_install > 0 then 1097table . sort ( to_install , function ( a , b ) 1098return a . spec . name < b . spec . name 1099end ) 1100git_ensure_exec () 1101install_list ( to_install , confirm ) 1102end 1103 1104if # to_repair > 0 then 1105lock_repair ( to_repair , plug_dir ) 1106table . sort ( to_repair ) 1107notify ( 'Repaired corrupted lock data for plugins: ' .. table . concat ( to_repair , ', ' ), 'WARN' ) 1108lock_write () 1109end 1110 1111if # to_remove > 0 then 1112for _ , name in ipairs ( to_remove ) do 1113plugin_lock . plugins [ name ] =nil 1114vim . fs . rm ( vim . fs . joinpath ( plug_dir , name ), { recursive =true , force =true } ) 1115end 1116table . sort ( to_remove ) 1117notify ( 'Removed corrupted lock data for plugins: ' .. table . concat ( to_remove , ', ' ), 'WARN' ) 1118lock_write () 1119end 1120end 1121 1122--- @param confirm? boolean 1123--- @param specs? (string|vim.pack.Spec)[] 1124local function lock_read ( confirm , specs ) 1125if plugin_lock then 1126return 1127end 1128 1129M . _plugin_lock_path =vim . go . packlockfile 1130local fd =uv . fs_open ( M . _plugin_lock_path , 'r' , 438 ) 1131if fd then 1132local stat =assert ( uv . fs_fstat ( fd )) 1133local data =assert ( uv . fs_read ( fd , stat . size , 0 )) 1134assert ( uv . fs_close ( fd )) 1135plugin_lock =vim . json . decode ( data ) 1136else 1137plugin_lock ={ plugins ={} } 1138end 1139 1140lock_sync ( confirm ~= false , specs or {} ) 1141end 1142 1143--- @class vim.pack.keyset.add 1144--- @inlinedoc 1145--- Load `plugin/` files and `ftdetect/` scripts. If `false`, works like `:packadd!`. 1146--- If function, called with plugin data and is fully responsible for loading plugin. 1147--- Default `false` during |init.lua| sourcing and `true` afterwards. 1148--- @field load? boolean|fun(plug_data: {spec: vim.pack.Spec, path: string}) 1149--- 1150--- @field confirm? boolean Whether to ask user to confirm initial install. Default `true`. 1151 1152--- Add plugin to current session 1153--- 1154--- - For each specification check that plugin exists on disk in |vim.pack-directory|: 1155--- - If exists, check if its `src` is the same as input. If not - delete 1156--- immediately to clean install from the new source. Otherwise do nothing. 1157--- - If doesn't exist, install it by downloading from `src` into `name` 1158--- subdirectory (via partial blobless `git clone`) and update revision 1159--- to match `version` (via `git checkout`). Plugin will not be on disk if 1160--- any step resulted in an error. 1161--- - For each plugin execute |:packadd| (or customizable `load` function) making 1162--- it reachable by Nvim. 1163--- 1164--- Notes: 1165--- - Installation is done in parallel, but waits for all to finish before 1166--- continuing next code execution. 1167--- - If plugin is already present on disk, there are no checks about its current revision. 1168--- The specified `version` can be not the one actually present on disk. 1169--- Execute |vim.pack.update()| to synchronize. 1170--- - Adding plugin second and more times during single session does nothing: 1171--- only the data from the first adding is registered. 1172--- 1173--- @param specs (string|vim.pack.Spec)[] List of plugin specifications. String item 1174--- is treated as `src`. 1175--- @param opts? vim.pack.keyset.add 1176function M . add ( specs , opts ) 1177vim . validate ( 'specs' , specs , vim . islist , false , 'list' ) 1178opts =vim . tbl_extend ( 'force' , { load =vim . v . vim_did_init == 1 , confirm =true } , opts or {} ) 1179vim . validate ( 'opts' , opts , 'table' ) 1180 1181lock_read ( opts . confirm , specs ) 1182 1183local plug_dir =get_plug_dir () 1184local plugs ={} --- @type vim.pack.Plug[] 1185for i =1 , # specs do 1186plugs [ i ] =new_plug ( specs [ i ], plug_dir ) 1187end 1188plugs =normalize_plugs ( plugs ) 1189 1190-- Pre-process 1191local plugs_to_install ={} --- @type vim.pack.Plug[] 1192local needs_lock_write =false 1193for _ , p in ipairs ( plugs ) do 1194-- Detect `version` change 1195local p_lock =plugin_lock . plugins [ p . spec . name ] or {} 1196needs_lock_write =needs_lock_write or p_lock . version ~= p . spec . version 1197p_lock . version =p . spec . version 1198plugin_lock . plugins [ p . spec . name ] =p_lock 1199 1200-- Register for install 1201if not p . info . installed then 1202plugs_to_install [ # plugs_to_install + 1 ] =p 1203needs_lock_write =true 1204end 1205end 1206 1207-- Install 1208if # plugs_to_install > 0 then 1209git_ensure_exec () 1210install_list ( plugs_to_install , opts . confirm ) 1211end 1212 1213if needs_lock_write then 1214lock_write () 1215end 1216 1217-- Register and load those actually on disk while collecting errors 1218-- Delay showing all errors to have "good" plugins added first 1219local errors ={} --- @type string[] 1220for _ , p in ipairs ( plugs ) do 1221if p . info . installed then 1222local ok , err =pcall ( pack_add , p , opts . load ) --[[@as string]] 1223if not ok then 1224p . info . err =err 1225end 1226end 1227if p . info . err ~= '' then 1228errors [ # errors + 1 ] =( '`%s`:\n%s' ): format ( p . spec . name , p . info . err ) 1229end 1230end 1231 1232if # errors > 0 then 1233local error_str =table . concat ( errors , '\n\n' ) 1234error (( 'vim.pack:\n\n%s' ): format ( error_str )) 1235end 1236end 1237 1238--- @param p vim.pack.Plug 1239--- @return string 1240local function compute_feedback_lines_single ( p ) 1241local active_suffix =active_plugins [ p . path ] ~= nil and '' or ' (not active)' 1242if p . info . err ~= '' then 1243return ( '## %s%s\n\n %s' ): format ( p . spec . name , active_suffix , p . info . err : gsub ( '\n' , '\n ' )) 1244end 1245 1246local parts ={ ( '## %s%s\n' ): format ( p . spec . name , active_suffix ) } 1247local version_suffix =p . info . version_str == '' and '' or ( ' (%s)' ): format ( p . info . version_str ) 1248 1249if p . info . sha_head == p . info . sha_target then 1250parts [ # parts + 1 ] =table . concat ( { 1251'Path: ' .. p . path , 1252'Source: ' .. p . spec . src , 1253'Revision: ' .. p . info . sha_target .. version_suffix , 1254} , '\n' ) 1255 1256local update_details =assert ( p . info . update_details ) 1257if update_details ~= '' then 1258local details =update_details : gsub ( '\n' , '\n• ' ) 1259parts [ # parts + 1 ] ='\n\nAvailable newer versions:\n• ' .. details 1260end 1261else 1262parts [ # parts + 1 ] =table . concat ( { 1263'Path: ' .. p . path , 1264'Source: ' .. p . spec . src , 1265'Revision before: ' .. p . info . sha_head , 1266'Revision after: ' .. p . info . sha_target .. version_suffix , 1267'' , 1268'Pending updates:' , 1269p . info . update_details , 1270} , '\n' ) 1271end 1272 1273return table . concat ( parts , '' ) 1274end 1275 1276--- @param plug_list vim.pack.Plug[] 1277--- @param skip_same_sha boolean 1278--- @return string[] 1279local function compute_feedback_lines ( plug_list , skip_same_sha ) 1280-- Construct plugin line groups for better report 1281local report_err , report_update , report_same ={} , {} , {} 1282for _ , p in ipairs ( plug_list ) do 1283--- @type string[] 1284local group_arr =p . info . err ~= '' and report_err 1285or ( p . info . sha_head ~= p . info . sha_target and report_update or report_same ) 1286group_arr [ # group_arr + 1 ] =compute_feedback_lines_single ( p ) 1287end 1288 1289local lines ={} 1290--- @param header string 1291--- @param arr string[] 1292local function append_report ( header , arr ) 1293if # arr == 0 then 1294return 1295end 1296header =header .. ' ' .. string . rep ( '─' , 79 - header : len ()) 1297table . insert ( lines , header ) 1298vim . list_extend ( lines , arr ) 1299end 1300append_report ( '# Error' , report_err ) 1301append_report ( '# Update' , report_update ) 1302if not skip_same_sha then 1303append_report ( '# Same' , report_same ) 1304end 1305 1306return vim . split ( table . concat ( lines , '\n\n' ), '\n' ) 1307end 1308 1309--- @param plug_list vim.pack.Plug[] 1310local function feedback_log ( plug_list ) 1311local lines ={ ( '========== Update %s ==========' ): format ( get_timestamp ()) } 1312vim . list_extend ( lines , compute_feedback_lines ( plug_list , true )) 1313lines [ # lines + 1 ] ='' 1314 1315local log_path =vim . fn . stdpath ( 'log' ) .. '/nvim-pack.log' 1316vim . fn . mkdir ( vim . fs . dirname ( log_path ), 'p' ) 1317vim . fn . writefile ( lines , log_path , 'a' ) 1318end 1319 1320--- @param lines string[] 1321--- @param on_finish fun(bufnr: integer) 1322local function show_confirm_buf ( lines , on_finish ) 1323-- Show buffer in a separate tabpage 1324local bufnr =api . nvim_create_buf ( true , true ) 1325api . nvim_buf_set_name ( bufnr , 'nvim-pack://confirm#' .. bufnr ) 1326api . nvim_buf_set_lines ( bufnr , 0 , - 1 , false , lines ) 1327vim . cmd . sbuffer ( { bufnr , mods ={ tab =vim . fn . tabpagenr () } } ) 1328local win_id =api . nvim_get_current_win () 1329 1330local delete_buffer =vim . schedule_wrap ( function () 1331pcall ( api . nvim_win_close , win_id , true ) 1332pcall ( api . nvim_buf_delete , bufnr , { force =true } ) 1333vim . cmd . redraw () 1334end ) 1335 1336-- Define action on accepting confirm 1337local function finish () 1338on_finish ( bufnr ) 1339delete_buffer () 1340end 1341-- - Use `nested` to allow other events (useful for statuslines) 1342nvim_on ( 'BufWriteCmd' , nil , { buf =bufnr , nested =true } , finish ) 1343 1344-- Define action to cancel confirm 1345--- @type integer 1346local cancel_au_id 1347--- @param data vim.api.keyset.create_autocmd.callback_args 1348local function on_cancel ( data ) 1349if vim . _tointeger ( data . match ) ~= win_id then 1350return 1351end 1352pcall ( api . nvim_del_autocmd , cancel_au_id ) 1353delete_buffer () 1354end 1355cancel_au_id =nvim_on ( 'WinClosed' , nil , { nested =true } , on_cancel ) 1356 1357-- Set buffer-local options last (so that user autocmmands could override) 1358vim . bo [ bufnr ]. modified =false 1359vim . bo [ bufnr ]. modifiable =false 1360vim . bo [ bufnr ]. buftype ='acwrite' 1361vim . bo [ bufnr ]. filetype ='nvim-pack' 1362 1363-- Attach in-process LSP for more capabilities 1364vim . lsp . buf_attach_client ( bufnr , require ( 'vim.pack._lsp' ). client_id ) 1365end 1366 1367--- Get map of plugin names that need update based on confirmation buffer 1368--- content: all plugin sections present in "# Update" section. 1369--- @param bufnr integer 1370--- @return table<string,boolean> 1371local function get_update_map ( bufnr ) 1372local lines =api . nvim_buf_get_lines ( bufnr , 0 , - 1 , false ) 1373--- @type table<string,boolean>, boolean 1374local res , is_in_update ={} , false 1375for _ , l in ipairs ( lines ) do 1376local name =l : match ( '^## (.+)$' ) 1377if name and is_in_update then 1378res [ name : gsub ( ' %(not active%)$' , '' )] =true 1379end 1380 1381local group =l : match ( '^# (%S+)' ) 1382if group then 1383is_in_update =group == 'Update' 1384end 1385end 1386return res 1387end 1388 1389--- Checkout plugins to the update target 1390--- @param plug_list vim.pack.Plug[] 1391local function update_list ( plug_list ) 1392trigger_events ( plug_list , 'PackChangedPre' , 'update' ) 1393 1394local timestamp =get_timestamp () 1395--- @async 1396--- @param p vim.pack.Plug 1397local function do_update ( p ) 1398checkout ( p , timestamp ) 1399p . info . updated =true 1400end 1401run_list ( plug_list , do_update , 'Applying updates' ) 1402 1403local updated =vim . tbl_filter ( function ( p ) 1404return p . info . updated == true 1405end , plug_list ) 1406trigger_events ( updated , 'PackChanged' , 'update' ) 1407end 1408 1409--- @class vim.pack.keyset.update 1410--- @inlinedoc 1411--- @field package _ex? boolean 1412--- @field force? boolean Whether to skip confirmation and make updates immediately. Default `false`. 1413--- 1414--- @field offline? boolean Whether to skip downloading new updates. Default: `false`. 1415--- 1416--- How to compute a new plugin revision. One of: 1417--- - "version" (default): use latest revision matching `version` from plugin specification. 1418--- - "lockfile": use revision from the lockfile. For reverting or performing controlled update. 1419--- @field target? string 1420 1421--- Update plugins 1422--- 1423--- - Download new changes from source. 1424--- - Infer update info (current/target revisions, changelog, etc.). 1425--- - If `force` is `false` (default), show confirmation buffer. 1426--- If `force` is `true`, make updates right away. 1427--- 1428--- Notes: 1429--- - Every actual update is logged in "nvim-pack.log" file inside "log" |standard-path|. 1430--- - It doesn't update source's default branch if it has changed (like from `master` to `main`). 1431--- To have `version = nil` point to a new default branch, re-install the plugin 1432--- (|vim.pack.del()| + |vim.pack.add()|). 1433--- 1434--- Confirmation buffer ~ 1435--- 1436--- The goal of the confirmation buffer is to show update details for the user to read, confirm 1437--- (execute |:write|) or deny (execute |:quit|) the update. 1438--- 1439--- Pending changes starting with `>` will be applied while the ones starting with `<` will be 1440--- reverted. 1441--- 1442--- There are convenience buffer-local mappings: 1443--- - |]]| and |[[| to navigate through plugin sections. 1444--- 1445--- Some features are provided via LSP: 1446--- - 'textDocument/documentLink' - compute links for plugin paths, sources, 1447--- commits, and tags. Makes a best effort educated guess about a link structure. 1448--- Use |gx| to open a link to an object at cursor. 1449--- - 'textDocument/documentSymbol' (`gO` via |lsp-defaults| or |vim.lsp.buf.document_symbol()|) - 1450--- show structure of the buffer. 1451--- - 'textDocument/hover' (`K` via |lsp-defaults| or |vim.lsp.buf.hover()|) - show more 1452--- information at cursor. Like details of particular pending change or newer tag. 1453--- - 'textDocument/codeAction' (`gra` via |lsp-defaults| or |vim.lsp.buf.code_action()|) - show 1454--- code actions relevant for "plugin at cursor". Like "delete" (after extra confirmation for 1455--- active plugins), "update" or "skip updating" (if there are pending updates). 1456--- 1457--- @param names? string[] List of plugin names to update. Must be managed 1458--- by |vim.pack|, not necessarily already added to current session. 1459--- Default: names of all plugins managed by |vim.pack|. 1460--- @param opts? vim.pack.keyset.update 1461function M . update ( names , opts ) 1462vim . validate ( 'names' , names , vim . islist , true , 'list' ) 1463opts =vim . tbl_extend ( 'force' , { force =false , offline =false , target ='version' } , opts or {} ) 1464 1465local plug_list =plug_list_from_names ( names ) 1466if # plug_list == 0 then 1467if opts . _ex then 1468util . echo_err ( N_ ( 'E5808: Nothing to update' )) 1469end 1470return 1471end 1472git_ensure_exec () 1473lock_read () 1474 1475-- Infer update details 1476local needs_lock_write =opts . force or false 1477 1478--- @async 1479--- @param p vim.pack.Plug 1480local function infer_details ( p ) 1481local l_data =plugin_lock . plugins [ p . spec . name ] 1482-- Ensure proper `origin` if needed 1483if l_data . src ~= p . spec . src then 1484git_cmd ( { 'remote' , 'set-url' , 'origin' , p . spec . src } , p . path ) 1485plugin_lock . plugins [ p . spec . name ]. src =p . spec . src 1486needs_lock_write =true 1487end 1488 1489-- Fetch 1490if not opts . offline then 1491git_fetch ( p . path ) 1492end 1493 1494-- Compute change info: changelog if any, new tags if nothing to update 1495if opts . target == 'lockfile' then 1496p . info . version_str ='*lockfile*' 1497p . info . sha_target =l_data . rev 1498end 1499infer_update_details ( p ) 1500end 1501local infer_title =opts . offline and 'Computing updates' or 'Downloading updates' 1502run_list ( plug_list , infer_details , infer_title ) 1503 1504-- Update and show report 1505if opts . force then 1506local plugs_to_update =vim . tbl_filter ( function ( p ) 1507return p . info . sha_head ~= p . info . sha_target 1508end , plug_list ) 1509update_list ( plugs_to_update ) 1510end 1511 1512if needs_lock_write then 1513lock_write () 1514end 1515 1516if opts . force then 1517feedback_log ( plug_list ) 1518return 1519end 1520 1521-- Show report in new buffer in separate tabpage 1522local lines =compute_feedback_lines ( plug_list , false ) 1523show_confirm_buf ( lines , function ( bufnr ) 1524local to_update =get_update_map ( bufnr ) 1525if not next ( to_update ) then 1526notify ( 'Nothing to update' , 'WARN' ) 1527return 1528end 1529 1530--- @param p vim.pack.Plug 1531local plugs_to_update =vim . tbl_filter ( function ( p ) 1532return to_update [ p . spec . name ] 1533end , plug_list ) 1534update_list ( plugs_to_update ) 1535 1536lock_write () 1537feedback_log ( plugs_to_update ) 1538end ) 1539end 1540 1541--- @class vim.pack.keyset.del 1542--- @inlinedoc 1543--- @field package _ex? boolean 1544--- @field force? boolean Whether to allow deleting an active plugin. Default `false`. 1545 1546--- Remove plugins from disk 1547--- 1548--- @param names string[] List of plugin names to remove from disk. Must be managed 1549--- by |vim.pack|, not necessarily already added to current session. 1550--- @param opts? vim.pack.keyset.del 1551function M . del ( names , opts ) 1552vim . validate ( 'names' , names , vim . islist , false , 'list' ) 1553opts =vim . tbl_extend ( 'force' , { force =false } , opts or {} ) 1554 1555local plug_list =plug_list_from_names ( names ) 1556if # plug_list == 0 then 1557if opts . _ex then 1558util . echo_err ( N_ ( 'E5809: Nothing to remove' )) 1559end 1560return 1561end 1562 1563lock_read () 1564 1565trigger_events ( plug_list , 'PackChangedPre' , 'delete' ) 1566 1567local deleted ={} --- @type vim.pack.Plug[] 1568local deleted_names ={} --- @type string[] 1569local not_deleted_names ={} --- @type string[] 1570for _ , p in ipairs ( plug_list ) do 1571if not active_plugins [ p . path ] or opts . force then 1572vim . fs . rm ( p . path , { recursive =true , force =true } ) 1573active_plugins [ p . path ] =nil 1574plugin_lock . plugins [ p . spec . name ] =nil 1575 1576deleted [ # deleted + 1 ] =p 1577deleted_names [ # deleted_names + 1 ] =p . spec . name 1578else 1579not_deleted_names [ # not_deleted_names + 1 ] =p . spec . name 1580end 1581end 1582trigger_events ( deleted , 'PackChanged' , 'delete' ) 1583 1584lock_write () 1585 1586if # deleted_names > 0 then 1587local suffix =# deleted_names == 1 and '' or 's' 1588local plugs =table . concat ( deleted_names , ', ' ) 1589notify (( 'Removed plugin%s: %s' ): format ( suffix , plugs ), 'INFO' ) 1590end 1591 1592if # not_deleted_names > 0 then 1593local plugs =table . concat ( not_deleted_names , ', ' ) 1594if opts . _ex then 1595util . echo_err ( N_ ( 'E5810: Some plugins are active and were not deleted: %s' ): format ( plugs )) 1596return 1597else 1598local msg =( 'Some plugins are active and were not deleted: %s.' ): format ( plugs ) 1599.. ' Remove them from init.lua, restart, and try again.' 1600error ( msg ) 1601end 1602end 1603end 1604 1605--- @inlinedoc 1606--- @class vim.pack.PlugData 1607--- @field active boolean Whether plugin was added via |vim.pack.add()| to current session. 1608--- @field branches? string[] Available Git branches (first is default). Missing if `info=false`. 1609--- Data from the |vim.pack-manifest|. Empty in case of reading error. Missing if `info=false`. 1610--- @field manifest? vim.pack.Manifest 1611--- @field path string Plugin's path on disk. 1612--- @field rev string Current Git revision. Taken from |vim.pack-lockfile| if `info=false`. 1613--- Git revision of a pending update. The same as used during |vim.pack.update()| and which 1614--- points to a resolved `spec.version`. Missing if `info=false`. 1615--- @field rev_to? string 1616--- @field spec vim.pack.SpecResolved A |vim.pack.Spec| with resolved `name`. 1617--- @field tags? string[] Available Git tags. Missing if `info=false`. 1618 1619--- @class vim.pack.keyset.get 1620--- @inlinedoc 1621--- @field info? boolean Whether to include extra plugin info. Default `true`. 1622--- Whether to skip downloading new updates. Requires `info=true`. Default: `true`. 1623--- @field offline? boolean 1624 1625--- @param p_data_list vim.pack.PlugData[] 1626--- @param offline? boolean 1627local function add_p_data_info ( p_data_list , offline ) 1628local funs ={} --- @type (async fun())[] 1629local plug_dir =get_plug_dir () 1630for i , p_data in ipairs ( p_data_list ) do 1631local plug =new_plug ( p_data . spec , plug_dir ) 1632local path =p_data . path 1633--- @async 1634funs [ i ] =function () 1635p_data . branches =git_get_branches ( path ) 1636p_data . tags =git_get_tags ( path ) 1637p_data . manifest =manifest_read ( path ) 1638 1639if not offline then 1640git_fetch ( path ) 1641end 1642 1643infer_revisions ( plug ) 1644p_data . rev =plug . info . sha_head 1645p_data . rev_to =plug . info . sha_target 1646end 1647end 1648async_join_run_wait ( funs ) 1649end 1650 1651--- Gets |vim.pack| plugin info, optionally filtered by `names`. 1652--- @param names? string[] List of plugin names. Default: all plugins managed by |vim.pack|. 1653--- @param opts? vim.pack.keyset.get 1654--- @return vim.pack.PlugData[] 1655function M . get ( names , opts ) 1656vim . validate ( 'names' , names , vim . islist , true , 'list' ) 1657opts =vim . tbl_extend ( 'force' , { info =true , offline =true } , opts or {} ) 1658 1659-- Process active plugins in order they were added. Take into account that 1660-- there might be "holes" after `vim.pack.del()`. 1661local active ={} --- @type table<integer,vim.pack.Plug?> 1662for _ , p_active in pairs ( active_plugins ) do 1663active [ p_active . id ] =p_active . plug 1664end 1665 1666lock_read () 1667local res ={} --- @type vim.pack.PlugData[] 1668local used_names ={} --- @type table<string,boolean> 1669for i =1 , n_active_plugins do 1670if active [ i ] and ( not names or vim . tbl_contains ( names , active [ i ]. spec . name )) then 1671local name =active [ i ]. spec . name 1672local spec =vim . deepcopy ( active [ i ]. spec ) 1673local rev =( plugin_lock . plugins [ name ] or {} ). rev 1674res [ # res + 1 ] ={ spec =spec , path =active [ i ]. path , rev =rev , active =true } 1675used_names [ name ] =true 1676end 1677end 1678 1679local plug_dir =get_plug_dir () 1680for name , l_data in vim . spairs ( plugin_lock . plugins ) do 1681local path =vim . fs . joinpath ( plug_dir , name ) 1682local is_in_names =not names or vim . tbl_contains ( names , name ) 1683if not active_plugins [ path ] and is_in_names then 1684local spec ={ name =name , src =l_data . src , version =l_data . version } 1685res [ # res + 1 ] ={ spec =spec , path =path , rev =l_data . rev , active =false } 1686used_names [ name ] =true 1687end 1688end 1689 1690if names ~= nil then 1691-- Align result with input 1692local names_order ={} --- @type table<string,integer> 1693for i , n in ipairs ( names ) do 1694if not used_names [ n ] then 1695error (( 'Plugin `%s` is not installed' ): format ( tostring ( n ))) 1696end 1697names_order [ n ] =i 1698end 1699table . sort ( res , function ( a , b ) 1700return names_order [ a . spec . name ] < names_order [ b . spec . name ] 1701end ) 1702end 1703 1704if opts . info then 1705git_ensure_exec () 1706add_p_data_info ( res , opts . offline ) 1707end 1708 1709return res 1710end 1711 1712--- @param skip_inactive? boolean 1713--- @return string[] plugin_names 1714function M . _get_names ( skip_inactive ) 1715local names ={} --- @type string[] 1716for _ , plugin_data in ipairs ( vim . pack . get ( nil , { info =false } )) do 1717if not ( skip_inactive and plugin_data . active ) then 1718names [ # names + 1 ] =plugin_data . spec . name 1719end 1720end 1721return names 1722end 1723 1724return M