cabal-flatpak-1.0.0: src/domain/Distribution/Flatpak/AppId.hs
module Distribution.Flatpak.AppId
( AppId (..)
, inferAppId
) where
import Data.Char
import Data.Text (Text)
import Data.Text qualified as T
import Distribution.Flatpak.Location
data AppId = AppId
{ value :: Text
, placeholder :: Bool
}
deriving stock (Eq, Show)
inferAppId :: Text -> Maybe Text -> AppId
inferAppId package homepage =
case homepage >>= parseLocation of
Just location -> case codeHost location of
Just components -> AppId (render components) False
Nothing -> AppId (render (reverseDomain location, package)) True
Nothing -> AppId ("com.example." <> sanitizeLast package) True
where
render = T.intercalate "." . sanitize
reverseDomain :: Location -> [Text]
reverseDomain location = reverse (filter (not . T.null) (T.splitOn "." location.host))
codeHost :: Location -> Maybe ([Text], Text)
codeHost location =
case (location.host, location.segments) of
("github.com", user : repo : _) -> Just (["io", "github", user], repo)
("gitlab.com", user : repo : _) -> Just (["io", "gitlab", user], repo)
("codeberg.org", user : repo : _) -> Just (["page", "codeberg", user], repo)
("framagit.org", user : repo : _) -> Just (["io", "frama", user], repo)
("sourceforge.net", "projects" : project : _) -> Just (["io", "sourceforge"], project)
_ -> Nothing
sanitize :: ([Text], Text) -> [Text]
sanitize (inner, lastComponent) = map sanitizeInner inner <> [sanitizeLast lastComponent]
sanitizeInner :: Text -> Text
sanitizeInner = guardDigit . T.map (\c -> if isInner c then c else '_') . T.toLower
where
isInner c = isAsciiLower c || isDigit c || c == '_'
sanitizeLast :: Text -> Text
sanitizeLast = guardDigit . T.map (\c -> if isLast c then c else '_')
where
isLast c = isAsciiLower c || isAsciiUpper c || isDigit c || c == '_' || c == '-'
guardDigit :: Text -> Text
guardDigit s = case T.uncons s of
Just (c, _) | isDigit c -> T.cons '_' s
_ -> s