-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 2 of the License, or
-- (at your option) any later version.

-- | A type for name-version-release of an RPM package
module Data.RPM.NVR (
  NVR(..),
  showNVR,
  readNVR,
  eitherNVR,
  maybeNVR,
  VerRel(..),
  )
where

import Data.Either.Extra
import Data.List.Extra

import Data.RPM.VerRel

-- | An rpm package name-version-release
data NVR = NVR {NVR -> String
nvrName :: String,
                NVR -> VerRel
nvrVerRel :: VerRel}
  deriving NVR -> NVR -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: NVR -> NVR -> Bool
$c/= :: NVR -> NVR -> Bool
== :: NVR -> NVR -> Bool
$c== :: NVR -> NVR -> Bool
Eq

-- | render an name-version-release
showNVR :: NVR -> String
showNVR :: NVR -> String
showNVR (NVR String
nm VerRel
verrel) = String
nm forall a. [a] -> [a] -> [a]
++ String
"-" forall a. [a] -> [a] -> [a]
++ VerRel -> String
showVerRel VerRel
verrel

-- | Either read a package name-version-release or return a failure string
eitherNVR :: String -> Either String NVR
eitherNVR :: String -> Either String NVR
eitherNVR String
s =
  case forall a. [a] -> [a]
reverse (forall a. (Partial, Eq a) => [a] -> [a] -> [[a]]
splitOn String
"-" String
s) of
    String
rel:String
ver:[String]
emaN ->
      if forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
rel Bool -> Bool -> Bool
|| forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
ver Bool -> Bool -> Bool
|| forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
emaN
      then forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ String
"NVR cannot start or end with '-'s: " forall a. [a] -> [a] -> [a]
++ String
s
      else forall a b. b -> Either a b
Right (String -> VerRel -> NVR
NVR (forall a. [a] -> [[a]] -> [a]
intercalate String
"-" forall a b. (a -> b) -> a -> b
$ forall a. [a] -> [a]
reverse [String]
emaN) (String -> String -> VerRel
VerRel String
ver String
rel))
    [String]
_ ->
      forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ String
"malformed NVR string: '" forall a. [a] -> [a] -> [a]
++ String
s forall a. [a] -> [a] -> [a]
++ String
"'"

-- | Maybe read a package name-version-release string
maybeNVR :: String -> Maybe NVR
maybeNVR :: String -> Maybe NVR
maybeNVR = forall a b. Either a b -> Maybe b
eitherToMaybe forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either String NVR
eitherNVR

-- | read an NVR
--
-- Errors if not of the form "name-version-release"
readNVR :: String -> NVR
readNVR :: String -> NVR
readNVR = forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall a. Partial => String -> a
error forall a. a -> a
id forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either String NVR
eitherNVR