In case anyone is looking for a fun little way to contribute to the Elm ecosystem, one thing I’ve thought for a while would be useful would be something like an elm-regex-literal package that would contain:
A function Regex.Literal.literal or similar with signature String -> Regex and implementation Regex.fromString >> Maybe.withDefault Regex.never
A corresponding elm-review rule that checked whether the argument was indeed a string literal and whether it actually compiled as a regex properly (i.e. Regex.fromString doesn’t return Nothing)
This way code can use Regex.Literal.literal (or even just Regex.literal, if you use the import Regex.Literal as Regex trick) on literal strings that are guaranteed to compile OK, without the extra noise of Maybe.withDefault Regex.never…and the elm-review rule would then make that safe against typos when you’re writing the regex initially.
Yes, it’s usually better to reach for a proper parser instead of a regex…but for some things like simple validation a regex is simpler, and I’ve found they can also be significantly faster.
I’d be tempted to write this myself, but having a one-year-old at home is making it hard enough to keep up with working on my existing Elm packages (Sorry for the lack of updates recently! I haven’t forgotten about them, and I’m writing Elm full-time at work so I’m definitely still invested in the ecosystem…just juggling a few more priorities than I used to!)
The post is a bit out of date and is using old things (like Scope.addModuleVisitors) which have been replaced by newer things, so maybe I should update the blog post (but it should still work).
The reason why I didn’t publish this is because it’s possible for people to add the package containing Regex.Literal.literalwithout enabling the related elm-review rule, which leads to a worse result than without the package.
I think that it is probably ok to publish it, since people are already going to have things like this in their code anyway. Perhaps just make sure that the first line of the README describes the risk and points users towards the review rule?
Hahaha I had a feeling I’d seen something like this posted at some point but then couldn’t see any published package for it
But yes I’d be tempted to publish it even with the risk of using Regex.literal without the corresponding rule…at least if it’s in its own package where the README makes it very clear that you should also use the corresponding rule, then it’s safer than if literal was just an extra function in a elm-regex-extra package or similar. (In that case it would be easier to install the package for some unrelated reason, then later discover the literal function by autocomplete or whatever and start using it.)