From a7cd79349c97f623955f4a5cf84921ca8ab9ea42 Mon Sep 17 00:00:00 2001 From: zeertzjq Date: Sat, 11 Mar 2023 12:47:27 +0800 Subject: [PATCH] refactor(runtime.c): factor out find_script_by_name() (#22620) This the refactoring done in Vim patch 8.2.4050. --- src/nvim/runtime.c | 50 +++++++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index 7a3efc5760..3326f4e096 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -2187,6 +2187,25 @@ theend: return retval; } +/// Find an already loaded script "name". +/// If found returns its script ID. If not found returns -1. +static int find_script_by_name(char *name) +{ + assert(script_items.ga_len >= 0); + for (int sid = script_items.ga_len; sid > 0; sid--) { + // We used to check inode here, but that doesn't work: + // - If a script is edited and written, it may get a different + // inode number, even though to the user it is the same script. + // - If a script is deleted and another script is written, with a + // different name, the inode may be re-used. + scriptitem_T *si = SCRIPT_ITEM(sid); + if (si->sn_name != NULL && path_fnamecmp(si->sn_name, name) == 0) { + return sid; + } + } + return -1; +} + /// Check if fname was sourced before to finds its SID. /// If it's new, generate a new SID. /// @@ -2196,28 +2215,19 @@ scriptitem_T *get_current_script_id(char **fnamep, sctx_T *ret_sctx) { static int last_current_SID_seq = 0; - sctx_T script_sctx = { .sc_seq = ++last_current_SID_seq, - .sc_lnum = 0, - .sc_sid = 0 }; - scriptitem_T *si = NULL; - - assert(script_items.ga_len >= 0); - for (script_sctx.sc_sid = script_items.ga_len; script_sctx.sc_sid > 0; script_sctx.sc_sid--) { - // We used to check inode here, but that doesn't work: - // - If a script is edited and written, it may get a different - // inode number, even though to the user it is the same script. - // - If a script is deleted and another script is written, with a - // different name, the inode may be re-used. - si = SCRIPT_ITEM(script_sctx.sc_sid); - if (si->sn_name != NULL && path_fnamecmp(si->sn_name, *fnamep) == 0) { - // Found it! - break; - } - } - if (script_sctx.sc_sid == 0) { - si = new_script_item(*fnamep, &script_sctx.sc_sid); + scriptitem_T *si; + int sid = find_script_by_name(*fnamep); + if (sid > 0) { + si = SCRIPT_ITEM(sid); + } else { + si = new_script_item(*fnamep, &sid); *fnamep = xstrdup(si->sn_name); } + + sctx_T script_sctx = { .sc_seq = ++last_current_SID_seq, + .sc_lnum = 0, + .sc_sid = sid }; + if (ret_sctx != NULL) { *ret_sctx = script_sctx; }