[project @ 2004-12-03 13:57:19 by simonmar]
[ghc-hetmet.git] / ghc / utils / ghc-pkg / Main.hs
index b83dd8e..466806a 100644 (file)
@@ -19,8 +19,8 @@ module Main (main) where
 import Version ( version, targetOS, targetARCH )
 import Distribution.InstalledPackageInfo
 import Distribution.Compat.ReadP
+import Distribution.ParseUtils ( showError )
 import Distribution.Package
-import Distribution.License
 import Distribution.Version
 import Compat.Directory        ( getAppUserDataDirectory )
 import Control.Exception       ( evaluate )
@@ -28,8 +28,6 @@ import qualified Control.Exception as Exception
 
 import Prelude
 
-import Package -- the old package config type
-
 #if __GLASGOW_HASKELL__ < 603
 #include "config.h"
 #endif
@@ -47,14 +45,12 @@ import qualified Exception
 import Data.Char       ( isSpace )
 import Monad
 import Directory
-import System  ( getEnv, getArgs, getProgName,
+import System  ( getArgs, getProgName,
                  system, exitWith,
                  ExitCode(..)
                )
-import IO
-import List ( isPrefixOf, isSuffixOf )
-
-import ParsePkgConfLite
+import System.IO
+import Data.List ( isPrefixOf, isSuffixOf, intersperse )
 
 #include "../../includes/ghcconfig.h"
 
@@ -108,6 +104,7 @@ data Flag
   | FlagConfig FilePath
   | FlagGlobalConfig FilePath
   | FlagForce
+  | FlagAutoGHCiLibs
   deriving Eq
 
 flags :: [OptDescr Flag]
@@ -122,6 +119,8 @@ flags = [
        "location of the global package config",
   Option [] ["force"] (NoArg FlagForce)
        "ignore missing dependencies, directories, and libraries",
+  Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
+       "automatically build libs for GHCi (with register)",
   Option ['?'] ["help"] (NoArg FlagHelp)
        "display this help and exit",
    Option ['V'] ["version"] (NoArg FlagVersion)
@@ -179,16 +178,17 @@ runit cli nonopts = do
   db_stack <- mapM readParseDatabase dbs
   let
        force = FlagForce `elem` cli
+       auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
   --
   -- first, parse the command
   case nonopts of
     ["register", filename] -> 
-       registerPackage filename [] db_stack False False force
+       registerPackage filename [] db_stack auto_ghci_libs False force
     ["update", filename] -> 
-       registerPackage filename [] db_stack False True force
+       registerPackage filename [] db_stack auto_ghci_libs True force
     ["unregister", pkgid_str] -> do
        pkgid <- readPkgId pkgid_str
-       unregisterPackage db_stack pkgid
+       unregisterPackage pkgid db_stack
     ["expose", pkgid_str] -> do
        pkgid <- readPkgId pkgid_str
        exposePackage pkgid db_stack
@@ -212,8 +212,8 @@ runit cli nonopts = do
 
 parseCheck :: ReadP a a -> String -> String -> IO a
 parseCheck parser str what = 
-  case readP_to_S parser str of
-    [(x,ys)] | all isSpace ys -> return x
+  case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
+    [x] -> return x
     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
 
 readPkgId :: String -> IO PackageIdentifier
@@ -290,7 +290,7 @@ readParseDatabase filename = do
   let packages = read str
   evaluate packages
     `Exception.catch` \_ -> 
-       die (filename ++ ": parse error in package config file\n")
+       die (filename ++ ": parse error in package config file")
   return (filename,packages)
 
 emptyPackageConfig :: String
@@ -319,14 +319,14 @@ registerPackage input defines db_stack auto_ghci_libs update force = do
        putStr "Reading package info from stdin... "
         getContents
       f   -> do
-        putStr ("Reading package info from " ++ show f)
+        putStr ("Reading package info from " ++ show f ++ " ")
        readFile f
 
   pkg <- parsePackageInfo s defines force
   putStrLn "done."
 
   validatePackageConfig pkg db_stack auto_ghci_libs update force
-  new_details <- updatePackageDB (snd db_to_operate_on) pkg
+  new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
   savePackageConfig db_filename
   maybeRestoreOldConfig db_filename $
     writeNewConfig db_filename new_details
@@ -339,95 +339,43 @@ parsePackageInfo
 parsePackageInfo str defines force =
   case parseInstalledPackageInfo str of
     Right ok -> return ok
-    Left err -> do
-       old_pkg <- evaluate (parseOnePackageConfig str)
-                           `Exception.catch` \_ -> parse_failed
-       putStr "Expanding embedded variables... "
-       new_old_pkg <- expandEnvVars old_pkg defines force
-       return (convertOldPackage old_pkg)
- where
-   parse_failed = die "parse error in package info\n"
-
-convertOldPackage :: PackageConfig -> InstalledPackageInfo
-convertOldPackage
-   Package {
-       name            = name,
-       auto            = auto,
-       import_dirs     = import_dirs,
-       source_dirs     = source_dirs,
-       library_dirs    = library_dirs,
-       hs_libraries    = hs_libraries,
-       extra_libraries = extra_libraries,
-       include_dirs    = include_dirs,
-       c_includes      = c_includes,
-       package_deps    = package_deps,
-       extra_ghc_opts  = extra_ghc_opts,
-       extra_cc_opts   = extra_cc_opts,
-       extra_ld_opts   = extra_ld_opts,
-       framework_dirs  = framework_dirs,
-       extra_frameworks= extra_frameworks
-    }
-   = InstalledPackageInfo {
-        package          = pkgNameToId name,
-        license          = AllRightsReserved,
-        copyright        = "",
-        maintainer       = "",
-       author           = "",
-        stability        = "",
-       homepage         = "",
-       pkgUrl           = "",
-       description      = "",
-       category         = "",
-        exposed          = auto,
-       exposedModules   = [],
-       hiddenModules    = [],
-        importDirs       = import_dirs,
-        libraryDirs      = library_dirs,
-        hsLibraries      = hs_libraries,
-        extraLibraries   = extra_libraries,
-        includeDirs      = include_dirs,
-        includes        = c_includes,
-        depends          = map pkgNameToId package_deps,
-        extraHugsOpts    = [],
-        extraCcOpts      = extra_cc_opts,
-        extraLdOpts      = extra_ld_opts,
-        frameworkDirs    = framework_dirs,
-        extraFrameworks  = extra_frameworks,
-       haddockInterfaces = [],
-       haddockHTMLs      = []
-    }
-
-
--- Used for converting old versionless package names to new PackageIdentifiers.
--- "Version [] []" is special: it means "no version" or "any version"
+    Left err -> die (showError err)
+
+-- Used for converting versionless package names to new
+-- PackageIdentifiers.  "Version [] []" is special: it means "no
+-- version" or "any version"
 pkgNameToId :: String -> PackageIdentifier
 pkgNameToId name = PackageIdentifier name (Version [] [])
 
 -- -----------------------------------------------------------------------------
--- Unregistering
-
-unregisterPackage :: PackageDBStack -> PackageIdentifier -> IO ()
-unregisterPackage [] _ = error "unregisterPackage"
-unregisterPackage ((db_name, pkgs) : _) pkgid = do  
-  checkConfigAccess db_name
-  when (pkgid `notElem` map package pkgs)
-       (die (db_name ++ ": package '" ++ showPackageId pkgid
-                ++ "' not found\n"))
-  savePackageConfig db_name
-  maybeRestoreOldConfig db_name $
-    writeNewConfig db_name (filter ((/= pkgid) . package) pkgs)
-
--- -----------------------------------------------------------------------------
--- Exposing
+-- Exposing, Hiding, Unregistering are all similar
 
 exposePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
-exposePackage = error "TODO"
-
--- -----------------------------------------------------------------------------
--- Hiding
+exposePackage = modifyPackage (\p -> [p{exposed=True}])
 
 hidePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
-hidePackage = error "TODO"
+hidePackage = modifyPackage (\p -> [p{exposed=False}])
+
+unregisterPackage :: PackageIdentifier ->  PackageDBStack -> IO ()
+unregisterPackage = modifyPackage (\p -> [])
+
+modifyPackage
+  :: (InstalledPackageInfo -> [InstalledPackageInfo])
+  -> PackageIdentifier
+  -> PackageDBStack
+  -> IO ()
+modifyPackage _ _ [] = error "modifyPackage"
+modifyPackage fn pkgid ((db_name, pkgs) : _) = do
+  checkConfigAccess db_name
+  p <- findPackage [(db_name,pkgs)] pkgid
+  let pid = package p
+  savePackageConfig db_name
+  let new_config = concat (map modify pkgs)
+      modify pkg
+       | package pkg == pid = fn pkg
+       | otherwise          = [pkg]
+  maybeRestoreOldConfig db_name $
+    writeNewConfig db_name new_config
 
 -- -----------------------------------------------------------------------------
 -- Listing packages
@@ -453,12 +401,21 @@ describePackage db_stack pkgid = do
 
 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
 findPackage db_stack pkgid
-  = case [ p | p <- all_pkgs, pkgid == package p ] of
-       [] -> die ("cannot find package " ++ showPackageId pkgid)
-       (p:ps) -> return p
+  = case [ p | p <- all_pkgs, pkgid `matches` p ] of
+       []  -> die ("cannot find package " ++ showPackageId pkgid)
+       [p] -> return p
+       ps  -> die ("package " ++ showPackageId pkgid ++ 
+                       " matches multiple packages: " ++ 
+                       concat (intersperse ", " (
+                                map (showPackageId.package) ps)))
   where
        all_pkgs = concat (map snd db_stack)
 
+matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
+pid `matches` p = 
+ pid == package p || 
+ not (realVersion pid) && pkgName pid == pkgName (package p)
+
 -- -----------------------------------------------------------------------------
 -- Field
 
@@ -496,7 +453,7 @@ checkConfigAccess :: FilePath -> IO ()
 checkConfigAccess filename = do
   access <- getPermissions filename
   when (not (writable access))
-      (die (filename ++ ": you don't have permission to modify this file\n"))
+      (die (filename ++ ": you don't have permission to modify this file"))
 
 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
 maybeRestoreOldConfig filename io
@@ -573,7 +530,7 @@ checkDuplicates db_stack pkg update = do
   -- Check whether this package id already exists in this DB
   --
   when (not update && (package pkg `elem` map package pkgs)) $
-       die ("package " ++ showPackageId pkgid ++ " is already installed\n")
+       die ("package " ++ showPackageId pkgid ++ " is already installed")
   --
   -- if we are exposing this new package, then check that
   -- there are no other exposed packages with the same name.
@@ -592,23 +549,26 @@ checkDir force d
  | otherwise = do
    there <- doesDirectoryExist d
    when (not there)
-       (dieOrForce force (d ++ " doesn't exist or isn't a directory\n"))
+       (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
 
 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
 checkDep db_stack force pkgid
   | real_version && pkgid `elem` pkgids = return ()
   | not real_version && pkgName pkgid `elem` pkg_names = return ()
   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
-                                       ++ " doesn't exist\n")
+                                       ++ " doesn't exist")
   where
        -- for backwards compat, we treat 0.0 as a special version,
        -- and don't check that it actually exists.
-       real_version = versionBranch (pkgVersion pkgid) /= []
+       real_version = realVersion pkgid
        
        all_pkgs = concat (map snd db_stack)
        pkgids = map package all_pkgs
        pkg_names = map pkgName pkgids
 
+realVersion :: PackageIdentifier -> Bool
+realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
+
 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
 checkHSLib dirs auto_ghci_libs force lib = do
   let batch_lib_file = "lib" ++ lib ++ ".a"
@@ -660,11 +620,25 @@ autoBuildGHCiLib dir batch_file ghci_file = do
 -- Updating the DB with the new package.
 
 updatePackageDB
-       :: [InstalledPackageInfo]
+       :: PackageDBStack
+       -> [InstalledPackageInfo]
        -> InstalledPackageInfo
        -> IO [InstalledPackageInfo]
-updatePackageDB pkgs new_pkg = do
+updatePackageDB db_stack pkgs new_pkg = do
   let
+       -- we update dependencies without version numbers to
+       -- match the actual versions of the relevant packages instaled.
+       updateDeps p = p{depends = map resolveDep (depends p)}
+
+       resolveDep pkgid
+          | realVersion pkgid  = pkgid
+          | otherwise          = lookupDep (pkgName pkgid)
+       
+       lookupDep name
+          = head [ pid | p <- concat (map snd db_stack), 
+                         let pid = package p,
+                         pkgName pid == name ]
+
        is_exposed = exposed new_pkg
        pkgid      = package new_pkg
        name       = pkgName pkgid
@@ -679,7 +653,45 @@ updatePackageDB pkgs new_pkg = do
          | is_exposed && pkgName (package p) == name = p{ exposed = False }
          | otherwise = p
   --
-  return (pkgs'++[new_pkg])
+  return (pkgs'++[updateDeps new_pkg])
+
+-- -----------------------------------------------------------------------------
+-- Searching for modules
+
+#if not_yet
+
+findModules :: [FilePath] -> IO [String]
+findModules paths = 
+  mms <- mapM searchDir paths
+  return (concat mms)
+
+searchDir path prefix = do
+  fs <- getDirectoryEntries path `catch` \_ -> return []
+  searchEntries path prefix fs
+
+searchEntries path prefix [] = return []
+searchEntries path prefix (f:fs)
+  | looks_like_a_module  =  do
+       ms <- searchEntries path prefix fs
+       return (prefix `joinModule` f : ms)
+  | looks_like_a_component  =  do
+        ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
+        ms' <- searchEntries path prefix fs
+       return (ms ++ ms')      
+  | otherwise
+       searchEntries path prefix fs
+
+  where
+       (base,suffix) = splitFileExt f
+       looks_like_a_module = 
+               suffix `elem` haskell_suffixes && 
+               all okInModuleName base
+       looks_like_a_component =
+               null suffix && all okInModuleName base
+
+okInModuleName c
+
+#endif
 
 -- -----------------------------------------------------------------------------
 -- The old command-line syntax, supported for backwards compatibility
@@ -767,7 +779,7 @@ oldRunit clis = do
     [ OF_ListLocal ] -> listPackages db_stack
     [ OF_Add upd ]   -> registerPackage input_file defines db_stack
                                auto_ghci_libs upd force
-    [ OF_Remove p ]  -> unregisterPackage db_stack (pkgNameToId p)
+    [ OF_Remove p ]  -> unregisterPackage (pkgNameToId p) db_stack
     [ OF_Show p ]
        | null fields -> describePackage db_stack (pkgNameToId p)
        | otherwise   -> mapM_ (describeField db_stack (pkgNameToId p)) fields
@@ -776,6 +788,8 @@ oldRunit clis = do
 
 -- ---------------------------------------------------------------------------
 
+#ifdef OLD_STUFF
+-- ToDo: reinstate
 expandEnvVars :: PackageConfig -> [(String, String)]
        -> Bool -> IO PackageConfig
 expandEnvVars pkg defines force = do
@@ -859,6 +873,7 @@ wordsBy :: (Char -> Bool) -> String -> [String]
 wordsBy p s = case dropWhile p s of
   "" -> []
   s' -> w : wordsBy p s'' where (w,s'') = break p s'
+#endif
 
 -----------------------------------------------------------------------------
 
@@ -875,13 +890,13 @@ die :: String -> IO a
 die s = do 
   hFlush stdout
   prog <- getProgramName
-  hPutStr stderr (prog ++ ": " ++ s)
+  hPutStrLn stderr (prog ++ ": " ++ s)
   exitWith (ExitFailure 1)
 
 dieOrForce :: Bool -> String -> IO ()
 dieOrForce force s 
   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
-  | otherwise = die (s ++ "\n")
+  | otherwise = die s
 
 
 -----------------------------------------------------------------------------