From e79e856733f8a021b894c910cfabab7fcadcd2ef Mon Sep 17 00:00:00 2001 From: William Boman Date: Tue, 13 Jun 2023 05:46:41 +0200 Subject: [PATCH] fix(functional): strip_prefix and strip_suffix should not use patterns --- lua/mason-core/functional/string.lua | 22 +++++++++++++-------- tests/mason-core/functional/string_spec.lua | 13 ++++++++++-- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/lua/mason-core/functional/string.lua b/lua/mason-core/functional/string.lua index e9e060f7a..c641dcbc2 100644 --- a/lua/mason-core/functional/string.lua +++ b/lua/mason-core/functional/string.lua @@ -108,21 +108,27 @@ _.trim_end_matches = fun.curryN(function(pattern, str) end, 2) _.strip_prefix = fun.curryN(function(prefix_pattern, str) - local _, start = string.find(str, "^" .. prefix_pattern) - if start then - return str:sub(start + 1) - else + if #prefix_pattern > #str then return str end + for i = 1, #prefix_pattern do + if str:sub(i, i) ~= prefix_pattern:sub(i, i) then + return str + end + end + return str:sub(#prefix_pattern + 1) end, 2) _.strip_suffix = fun.curryN(function(suffix_pattern, str) - local stop = string.find(str, suffix_pattern .. "$") - if stop then - return str:sub(1, stop - 1) - else + if #suffix_pattern > #str then return str end + for i = 1, #suffix_pattern do + if str:sub(-i, -i) ~= suffix_pattern:sub(-i, -i) then + return str + end + end + return str:sub(1, -#suffix_pattern - 1) end, 2) return _ diff --git a/tests/mason-core/functional/string_spec.lua b/tests/mason-core/functional/string_spec.lua index 30dea0698..9ceb38e87 100644 --- a/tests/mason-core/functional/string_spec.lua +++ b/tests/mason-core/functional/string_spec.lua @@ -66,11 +66,20 @@ Ipsum it("should strip_prefix", function() assert.equals("withthewind", _.strip_prefix("gone", "gonewiththewind")) assert.equals("1.3.0", _.strip_prefix("v", "v1.3.0")) + assert.equals("-30", _.strip_prefix("2023-05", "2023-05-30")) + assert.equals("The same", _.strip_prefix("Not Equals", "The same")) + assert.equals("long_pattern", _.strip_prefix("long_pattern_here", "long_pattern")) + assert.equals("", _.strip_prefix("pattern_here", "pattern_here")) + assert.equals("s", _.strip_prefix("pattern_here", "pattern_heres")) end) it("should strip_suffix", function() assert.equals("gone", _.strip_suffix("withtthewind", "gonewithtthewind")) - assert.equals("name", _.strip_suffix("%.tar%.gz", "name.tar.gz")) - assert.equals("name", _.strip_suffix(".tar.*", "name.tar.gz")) + assert.equals("name", _.strip_suffix(".tar.gz", "name.tar.gz")) + assert.equals("2023", _.strip_suffix("-05-30", "2023-05-30")) + assert.equals("The same", _.strip_suffix("Not Equals", "The same")) + assert.equals("pattern_here", _.strip_suffix("long_pattern_here", "pattern_here")) + assert.equals("", _.strip_suffix("pattern_here", "pattern_here")) + assert.equals("s", _.strip_suffix("pattern_here", "spattern_here")) end) end)