From f500b3274b4c937d315a652aad3bfcdd808b49ec Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Tue, 2 Nov 2021 15:18:05 +0200 Subject: Add $sort() function Available overloads: $sort( [, ]) $sort( [, ]) $sort( [, ]) $sort( [, ]) $sort( [, ]) The following flag is supported by the all overloads: dedup - in addition to sorting also remove duplicates Additionally, the strings overload also support the following flag: icase - sort ignoring case Note that on case-insensitive filesystem the paths and dir_paths overload's order is case-insensitive. --- libbuild2/functions-string.cxx | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'libbuild2/functions-string.cxx') diff --git a/libbuild2/functions-string.cxx b/libbuild2/functions-string.cxx index b430ebf..6e39c44 100644 --- a/libbuild2/functions-string.cxx +++ b/libbuild2/functions-string.cxx @@ -77,6 +77,52 @@ namespace build2 return names {name (ucase (convert (move (s))))}; }; + // $sort( [, ]) + // + // Sort strings in ascending order. + // + // The following flags are supported: + // + // icase - sort ignoring case + // + // dedup - in addition to sorting also remove duplicates + // + f["sort"] += [](strings v, optional fs) + { + bool ic (false); + bool dd (false); + if (fs) + { + for (name& f: *fs) + { + string s (convert (move (f))); + + if (s == "icase") + ic = true; + else if (s == "dedup") + dd = true; + else + throw invalid_argument ("invalid flag '" + s + "'"); + } + } + + sort (v.begin (), v.end (), + [ic] (const string& x, const string& y) + { + return (ic ? icasecmp (x, y) : x.compare (y)) < 0; + }); + + if (dd) + v.erase (unique (v.begin(), v.end(), + [ic] (const string& x, const string& y) + { + return (ic ? icasecmp (x, y) : x.compare (y)) == 0; + }), + v.end ()); + + return v; + }; + // String-specific overloads from builtins. // function_family b (m, "builtin"); -- cgit v1.1