From 9488e8618e856e8f8a3f84f87ff2b1818bdfe506 Mon Sep 17 00:00:00 2001 From: Ranjeet Kumar Ranjan Date: Mon, 25 Jul 2022 17:30:15 +0530 Subject: [PATCH] Fix review comments --- src/Streamly/Coreutils/Basename.hs | 35 ++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/Streamly/Coreutils/Basename.hs b/src/Streamly/Coreutils/Basename.hs index 4c542d6..e8ea7eb 100644 --- a/src/Streamly/Coreutils/Basename.hs +++ b/src/Streamly/Coreutils/Basename.hs @@ -7,31 +7,42 @@ -- Portability : GHC -- -- Return pathe with any leading directory components removed. --- If specified, also remove a trailing suffix (.extension). +-- If specified, also remove a trailing suffix. module Streamly.Coreutils.Basename ( basename + , basenameWith -- * Options , Basename + , Suffix(..) , suffix ) where -import System.FilePath (takeBaseName, takeFileName) -import Streamly.Coreutils.Common (Switch(..)) +import Data.List (stripPrefix) -newtype Basename = Basename {keepSuffix :: Switch} +data Suffix = None | Suffix [Char] -suffix :: Switch -> Basename -> Basename -suffix opt cfg = cfg {keepSuffix = opt} +newtype Basename = Basename {removeSuffix :: Suffix} + +suffix :: Suffix -> Basename -> Basename +suffix opt cfg = cfg {removeSuffix = opt} defaultConfig :: Basename -defaultConfig = Basename On +defaultConfig = Basename None -basename :: (Basename -> Basename) -> FilePath -> String -basename f path = +basenameWith :: (Basename -> Basename) -> FilePath -> String +basenameWith f path = let opt = f defaultConfig - in case keepSuffix opt of - Off -> takeBaseName path - On -> takeFileName path + base = reverse $ takeWhile (/= '/') $ reverse path + in case removeSuffix opt of + None -> base + Suffix x -> + let suf = reverse x + val0 = stripPrefix suf $ takeWhile (/= '/') $ reverse path + val = maybe base reverse val0 + in val + +basename :: FilePath -> String +basename = basenameWith id