aboutsummaryrefslogtreecommitdiffstats
path: root/common/src/Version.hs
blob: cb568e6eba37b9dc682006f3c321a0928710dc98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module Version
  ( Version (..),
    versionToString,
    versionFromText,
    versionFromString,
  )
where

import Data.Aeson qualified as A
import Data.Aeson.Types qualified as A
import Data.List
import Data.List.Split
import Data.Text qualified as T

data Version = Version Int Int Int
  deriving (Show, Eq)

instance A.ToJSON Version where
  toJSON =
    A.toJSON . versionToString

instance A.FromJSON Version where
  parseJSON (A.String (versionFromText -> Just version)) = pure version
  parseJSON v = A.typeMismatch "version" v

versionToString :: Version -> String
versionToString (Version major minor patch) =
  intercalate "." (map show [major, minor, patch])

versionFromString :: String -> Maybe Version
versionFromString (map read . splitOn "." -> [major, minor, patch]) =
  Just (Version major minor patch)
versionFromString _ = Nothing

versionFromText :: T.Text -> Maybe Version
versionFromText = versionFromString . T.unpack