module Data.GI.CodeGen.PkgConfig
    ( pkgConfigGetVersion
    , tryPkgConfig
    , pkgConfigModVersions
    , TaggedPkgConfigVersions(..)
    , checkDepVersions
    ) where

import Control.Monad (when)
import qualified Data.List as L
import Data.Maybe (catMaybes)
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid (First(..), (<>))
#else
import Data.Monoid (First(..))
#endif
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Data.Text (Text)
import System.Environment (lookupEnv)
import System.Exit (ExitCode(..), exitFailure)
import System.IO (hPutStr, hPutStrLn, stderr)
import System.Process (readProcessWithExitCode)

-- | The versions of the pkg-config packages that the bindings for a
-- dependency were generated against, as recorded in the
-- @pkgConfigVersions@ entry of its @GI.<Name>.Config@ module.
data TaggedPkgConfigVersions =
  TaggedPkgConfigVersions { TaggedPkgConfigVersions -> Text
pkgConfigTag :: Text
                            -- ^ Tag for the dependency, for error
                            -- reporting purposes.
                          , TaggedPkgConfigVersions -> Map Text Text
pkgConfigVersionMap :: M.Map Text Text
                            -- ^ Map from pkg-config package names to
                            -- the version of the package at the time
                            -- the dependency bindings were generated.
                          }

-- | Try asking pkg-config for the version of a given module, and
-- return the package name together with its version.
tryPkgConfig :: Text -> IO (Maybe (Text, Text))
tryPkgConfig :: Text -> IO (Maybe (Text, Text))
tryPkgConfig Text
pkgName = do
  (exitcode, stdout, _) <-
      String -> [String] -> String -> IO (ExitCode, String, String)
readProcessWithExitCode String
"pkg-config" [String
"--modversion", Text -> String
T.unpack Text
pkgName] String
""
  case exitcode of
    ExitCode
ExitSuccess -> case String -> [String]
lines String
stdout of
                     [String
v] -> Maybe (Text, Text) -> IO (Maybe (Text, Text))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((Text, Text) -> Maybe (Text, Text)
forall a. a -> Maybe a
Just (Text
pkgName, String -> Text
T.pack String
v))
                     [String]
_ -> Maybe (Text, Text) -> IO (Maybe (Text, Text))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Text, Text)
forall a. Maybe a
Nothing
    ExitFailure Int
_ -> Maybe (Text, Text) -> IO (Maybe (Text, Text))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Text, Text)
forall a. Maybe a
Nothing

-- | Ask pkg-config for the installed version of each of the given
-- packages. Packages unknown to pkg-config are omitted from the
-- result.
pkgConfigModVersions :: [Text] -> IO (M.Map Text Text)
pkgConfigModVersions :: [Text] -> IO (Map Text Text)
pkgConfigModVersions [Text]
pkgs =
  [(Text, Text)] -> Map Text Text
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList ([(Text, Text)] -> Map Text Text)
-> ([Maybe (Text, Text)] -> [(Text, Text)])
-> [Maybe (Text, Text)]
-> Map Text Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Maybe (Text, Text)] -> [(Text, Text)]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe (Text, Text)] -> Map Text Text)
-> IO [Maybe (Text, Text)] -> IO (Map Text Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> IO (Maybe (Text, Text)))
-> [Text] -> IO [Maybe (Text, Text)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Text -> IO (Maybe (Text, Text))
tryPkgConfig [Text]
pkgs

-- | Get the pkg-config name and associated installed version of a given
-- gobject-introspection namespace. Since the mapping is not
-- one-to-one some guessing is involved, although in most cases the
-- required information is listed in the GIR file.
pkgConfigGetVersion :: Text     -- name
                    -> Text     -- version
                    -> [Text]   -- known package names
                    -> Bool     -- verbose
                    -> M.Map Text Text -- suggested overrides
                    -> IO (Maybe (Text, Text))
pkgConfigGetVersion :: Text
-> Text
-> [Text]
-> Bool
-> Map Text Text
-> IO (Maybe (Text, Text))
pkgConfigGetVersion Text
name Text
version [Text]
packages Bool
verbose Map Text Text
overridenNames = do
  let lowerName :: Text
lowerName = Text -> Text
T.toLower Text
name
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
verbose (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
           String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ Text -> String
T.unpack (Text
"Querying pkg-config for " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>
                              Text
" version " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
version)
  let alternatives :: [Text]
alternatives = case Text -> Map Text Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
lowerName Map Text Text
overridenNames of
                       Maybe Text
Nothing -> [Text]
packages [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text
lowerName Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
version,
                                               Text
lowerName]
                       Just Text
n -> [Text
n Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"-" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
version, Text
n]
      firstJust :: [Maybe a] -> Maybe a
firstJust = First a -> Maybe a
forall a. First a -> Maybe a
getFirst (First a -> Maybe a)
-> ([Maybe a] -> First a) -> [Maybe a] -> Maybe a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [First a] -> First a
forall a. Monoid a => [a] -> a
mconcat ([First a] -> First a)
-> ([Maybe a] -> [First a]) -> [Maybe a] -> First a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe a -> First a) -> [Maybe a] -> [First a]
forall a b. (a -> b) -> [a] -> [b]
map Maybe a -> First a
forall a. Maybe a -> First a
First
  (Text -> IO (Maybe (Text, Text)))
-> [Text] -> IO [Maybe (Text, Text)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Text -> IO (Maybe (Text, Text))
tryPkgConfig [Text]
alternatives IO [Maybe (Text, Text)]
-> ([Maybe (Text, Text)] -> IO (Maybe (Text, Text)))
-> IO (Maybe (Text, Text))
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Maybe (Text, Text) -> IO (Maybe (Text, Text))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe (Text, Text) -> IO (Maybe (Text, Text)))
-> ([Maybe (Text, Text)] -> Maybe (Text, Text))
-> [Maybe (Text, Text)]
-> IO (Maybe (Text, Text))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Maybe (Text, Text)] -> Maybe (Text, Text)
forall {a}. [Maybe a] -> Maybe a
firstJust

-- | What to do when the versions of the pkg-config packages that the
-- dependencies were generated against do not agree with the
-- currently installed ones.
data OnVersionMismatch = IgnoreMismatch -- ^ Do nothing.
                       | WarnOnMismatch -- ^ Print a warning and continue.
                       | AbortOnMismatch -- ^ Print a warning and abort.

-- | Name of the environment variable controlling what to do on a
-- version mismatch.
onVersionMismatchEnvVar :: String
onVersionMismatchEnvVar :: String
onVersionMismatchEnvVar = String
"HASKELL_GI_ON_VERSION_MISMATCH"

-- | Read the desired behaviour on version mismatches from the
-- environment, defaulting to `WarnOnMismatch`.
getOnVersionMismatch :: IO OnVersionMismatch
getOnVersionMismatch :: IO OnVersionMismatch
getOnVersionMismatch =
  String -> IO (Maybe String)
lookupEnv String
onVersionMismatchEnvVar IO (Maybe String)
-> (Maybe String -> IO OnVersionMismatch) -> IO OnVersionMismatch
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Maybe String
Nothing -> OnVersionMismatch -> IO OnVersionMismatch
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return OnVersionMismatch
WarnOnMismatch
    Just String
v -> case Text -> Text
T.toLower (Text -> Text
T.strip (String -> Text
T.pack String
v)) of
      Text
"" -> OnVersionMismatch -> IO OnVersionMismatch
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return OnVersionMismatch
WarnOnMismatch
      Text
"ignore" -> OnVersionMismatch -> IO OnVersionMismatch
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return OnVersionMismatch
IgnoreMismatch
      Text
"warn" -> OnVersionMismatch -> IO OnVersionMismatch
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return OnVersionMismatch
WarnOnMismatch
      Text
"abort" -> OnVersionMismatch -> IO OnVersionMismatch
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return OnVersionMismatch
AbortOnMismatch
      Text
_ -> do
        Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"Error: unknown value \"" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
v String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"\" for "
          String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
onVersionMismatchEnvVar
          String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
". Valid values are \"ignore\", \"warn\" (the default) and \"abort\"."
        IO OnVersionMismatch
forall a. IO a
exitFailure

-- | Check that the versions of the pkg-config packages that the
-- bindings for the dependencies were generated against agree with
-- the versions currently reported by pkg-config for the given
-- packages (typically, those listed in the loaded GIR files for the
-- dependencies). What happens if they do not is controlled by the
-- @HASKELL_GI_ON_VERSION_MISMATCH@ environment variable, see
-- `getOnVersionMismatch`.
checkDepVersions :: Text -- ^ Name of the package being generated
                 -> Bool -- ^ verbose
                 -> [Text] -- ^ pkg-config packages to check
                 -> [TaggedPkgConfigVersions] -- ^ Dependency versions
                 -> IO ()
checkDepVersions :: Text -> Bool -> [Text] -> [TaggedPkgConfigVersions] -> IO ()
checkDepVersions Text
pkgName Bool
verbosity [Text]
packages [TaggedPkgConfigVersions]
deps =
  IO OnVersionMismatch
getOnVersionMismatch IO OnVersionMismatch -> (OnVersionMismatch -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    OnVersionMismatch
IgnoreMismatch -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    OnVersionMismatch
WarnOnMismatch -> IO [(Text, Text, Text, Text)]
findMismatches IO [(Text, Text, Text, Text)]
-> ([(Text, Text, Text, Text)] -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
      [] -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      [(Text, Text, Text, Text)]
mismatches -> [(Text, Text, Text, Text)] -> [Text] -> IO ()
printWarning [(Text, Text, Text, Text)]
mismatches
        [ Text
"Continuing anyway. Set " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
envVar Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"=abort to make this"
        , Text
"an error, or " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
envVar Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"=ignore to silence this warning." ]
    OnVersionMismatch
AbortOnMismatch -> IO [(Text, Text, Text, Text)]
findMismatches IO [(Text, Text, Text, Text)]
-> ([(Text, Text, Text, Text)] -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
      [] -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      [(Text, Text, Text, Text)]
mismatches -> do
        [(Text, Text, Text, Text)] -> [Text] -> IO ()
printWarning [(Text, Text, Text, Text)]
mismatches
          [ Text
"Aborting, since " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
envVar Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"=abort."]
        IO ()
forall a. IO a
exitFailure

  where
    envVar :: Text
    envVar :: Text
envVar = String -> Text
T.pack String
onVersionMismatchEnvVar

    findMismatches :: IO [(Text, Text, Text, Text)]
    findMismatches :: IO [(Text, Text, Text, Text)]
findMismatches = do
      let recorded :: Map Text Text
recorded = [Map Text Text] -> Map Text Text
forall (f :: * -> *) k a.
(Foldable f, Ord k) =>
f (Map k a) -> Map k a
M.unions ((TaggedPkgConfigVersions -> Map Text Text)
-> [TaggedPkgConfigVersions] -> [Map Text Text]
forall a b. (a -> b) -> [a] -> [b]
map TaggedPkgConfigVersions -> Map Text Text
pkgConfigVersionMap [TaggedPkgConfigVersions]
deps)
          pcPkgs :: [Text]
pcPkgs = (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Text -> Map Text Text -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.member` Map Text Text
recorded) ([Text] -> [Text]
forall a. Eq a => [a] -> [a]
L.nub [Text]
packages)
      current <- [Text] -> IO (Map Text Text)
pkgConfigModVersions [Text]
pcPkgs

      when verbosity $
        putStrLn $ "Checking dependency versions against pkg-config: "
        <> show (M.toList current)

      return [ (tag, pkg, recorded, installed)
             | TaggedPkgConfigVersions tag versions <- deps
             , (pkg, recorded) <- M.toList versions
             , Just installed <- [M.lookup pkg current]
             , installed /= recorded ]

    printWarning :: [(Text, Text, Text, Text)] -> [Text] -> IO ()
    printWarning :: [(Text, Text, Text, Text)] -> [Text] -> IO ()
printWarning [(Text, Text, Text, Text)]
mismatches [Text]
outcome =
      Handle -> String -> IO ()
hPutStr Handle
stderr (String -> IO ()) -> (Text -> String) -> Text -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$
        [ Text
banner
        , Text
"WARNING: VERSION MISMATCH WHILE GENERATING BINDINGS FOR " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
T.toUpper Text
pkgName
        , Text
banner
        , Text
""
        , Text
"The Haskell bindings for the following dependencies were generated"
        , Text
"against a different version of the underlying library than the one"
        , Text
"currently reported by pkg-config:"
        , Text
""
        ] [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<>
        [ Text
"  * " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
tag Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": generated against " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
pkg Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
recorded
          Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", but pkg-config reports " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
pkg Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
installed
        | (Text
tag, Text
pkg, Text
recorded, Text
installed) <- [(Text, Text, Text, Text)]
mismatches ] [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<>
        [ Text
""
        , Text
"The bindings for " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
pkgName Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" are generated from the currently"
        , Text
"installed introspection data, so they may refer to types, methods"
        , Text
"or functions that are missing from the dependency bindings listed"
        , Text
"above. This typically shows up later as compilation errors of the"
        , Text
"form \"Not in scope: type constructor or class ...\" or \"module ..."
        , Text
"does not export ...\"."
        , Text
""
        , Text
"If this happens, rebuild the dependency bindings listed above"
        , Text
"against the currently installed libraries."
        , Text
""
        ] [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text]
outcome [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<>
        [ Text
banner ]

    banner :: Text
    banner :: Text
banner = Int -> Text -> Text
T.replicate Int
72 Text
"*"