Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 559 lines (505 sloc) 21.905 kb
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.InstallDirs
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This manages everything to do with where files get installed (though does
-- not get involved with actually doing any installation). It provides an
-- 'InstallDirs' type which is a set of directories for where to install
-- things. It also handles the fact that we use templates in these install
-- dirs. For example most install dirs are relative to some @$prefix@ and by
-- changing the prefix all other dirs still end up changed appropriately. So it
-- provides a 'PathTemplate' type and functions for substituting for these
-- templates.

module Distribution.Simple.InstallDirs (
        InstallDirs(..),
        InstallDirTemplates,
        defaultInstallDirs,
        combineInstallDirs,
        absoluteInstallDirs,
        CopyDest(..),
        prefixRelativeInstallDirs,
        substituteInstallDirTemplates,

        PathTemplate,
        PathTemplateVariable(..),
        PathTemplateEnv,
        toPathTemplate,
        fromPathTemplate,
        substPathTemplate,
        initialPathTemplateEnv,
        platformTemplateEnv,
        compilerTemplateEnv,
        packageTemplateEnv,
        installDirsTemplateEnv,
  ) where


import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Data.Monoid (Monoid(..))
import System.Directory (getAppUserDataDirectory)
import System.FilePath ((</>), isPathSeparator, pathSeparator)
import System.FilePath (dropDrive)

import Distribution.Package
         ( PackageIdentifier, packageName, packageVersion )
import Distribution.System
         ( OS(..), buildOS, Platform(..) )
import Distribution.Compiler
         ( CompilerId, CompilerFlavor(..) )
import Distribution.Text
         ( display )

#if mingw32_HOST_OS
import Foreign
import Foreign.C
#endif

-- ---------------------------------------------------------------------------
-- Installation directories


-- | The directories where we will install files for packages.
--
-- We have several different directories for different types of files since
-- many systems have conventions whereby different types of files in a package
-- are installed in different directories. This is particularly the case on
-- Unix style systems.
--
data InstallDirs dir = InstallDirs {
        prefix :: dir,
        bindir :: dir,
        libdir :: dir,
        libsubdir :: dir,
        dynlibdir :: dir,
        libexecdir :: dir,
        progdir :: dir,
        includedir :: dir,
        datadir :: dir,
        datasubdir :: dir,
        docdir :: dir,
        mandir :: dir,
        htmldir :: dir,
        haddockdir :: dir,
        sysconfdir :: dir
    } deriving (Read, Show)

instance Functor InstallDirs where
  fmap f dirs = InstallDirs {
    prefix = f (prefix dirs),
    bindir = f (bindir dirs),
    libdir = f (libdir dirs),
    libsubdir = f (libsubdir dirs),
    dynlibdir = f (dynlibdir dirs),
    libexecdir = f (libexecdir dirs),
    progdir = f (progdir dirs),
    includedir = f (includedir dirs),
    datadir = f (datadir dirs),
    datasubdir = f (datasubdir dirs),
    docdir = f (docdir dirs),
    mandir = f (mandir dirs),
    htmldir = f (htmldir dirs),
    haddockdir = f (haddockdir dirs),
    sysconfdir = f (sysconfdir dirs)
  }

instance Monoid dir => Monoid (InstallDirs dir) where
  mempty = InstallDirs {
      prefix = mempty,
      bindir = mempty,
      libdir = mempty,
      libsubdir = mempty,
      dynlibdir = mempty,
      libexecdir = mempty,
      progdir = mempty,
      includedir = mempty,
      datadir = mempty,
      datasubdir = mempty,
      docdir = mempty,
      mandir = mempty,
      htmldir = mempty,
      haddockdir = mempty,
      sysconfdir = mempty
  }
  mappend = combineInstallDirs mappend

combineInstallDirs :: (a -> b -> c)
                   -> InstallDirs a
                   -> InstallDirs b
                   -> InstallDirs c
combineInstallDirs combine a b = InstallDirs {
    prefix = prefix a `combine` prefix b,
    bindir = bindir a `combine` bindir b,
    libdir = libdir a `combine` libdir b,
    libsubdir = libsubdir a `combine` libsubdir b,
    dynlibdir = dynlibdir a `combine` dynlibdir b,
    libexecdir = libexecdir a `combine` libexecdir b,
    progdir = progdir a `combine` progdir b,
    includedir = includedir a `combine` includedir b,
    datadir = datadir a `combine` datadir b,
    datasubdir = datasubdir a `combine` datasubdir b,
    docdir = docdir a `combine` docdir b,
    mandir = mandir a `combine` mandir b,
    htmldir = htmldir a `combine` htmldir b,
    haddockdir = haddockdir a `combine` haddockdir b,
    sysconfdir = sysconfdir a `combine` sysconfdir b
  }

appendSubdirs :: (a -> a -> a) -> InstallDirs a -> InstallDirs a
appendSubdirs append dirs = dirs {
    libdir = libdir dirs `append` libsubdir dirs,
    datadir = datadir dirs `append` datasubdir dirs,
    libsubdir = error "internal error InstallDirs.libsubdir",
    datasubdir = error "internal error InstallDirs.datasubdir"
  }

-- | The installation directories in terms of 'PathTemplate's that contain
-- variables.
--
-- The defaults for most of the directories are relative to each other, in
-- particular they are all relative to a single prefix. This makes it
-- convenient for the user to override the default installation directory
-- by only having to specify --prefix=... rather than overriding each
-- individually. This is done by allowing $-style variables in the dirs.
-- These are expanded by textual substitution (see 'substPathTemplate').
--
-- A few of these installation directories are split into two components, the
-- dir and subdir. The full installation path is formed by combining the two
-- together with @\/@. The reason for this is compatibility with other Unix
-- build systems which also support @--libdir@ and @--datadir@. We would like
-- users to be able to configure @--libdir=\/usr\/lib64@ for example but
-- because by default we want to support installing multiple versions of
-- packages and building the same package for multiple compilers we append the
-- libsubdir to get: @\/usr\/lib64\/$pkgid\/$compiler@.
--
-- An additional complication is the need to support relocatable packages on
-- systems which support such things, like Windows.
--
type InstallDirTemplates = InstallDirs PathTemplate

-- ---------------------------------------------------------------------------
-- Default installation directories

defaultInstallDirs :: CompilerFlavor -> Bool -> Bool -> IO InstallDirTemplates
defaultInstallDirs comp userInstall _hasLibs = do
  installPrefix <-
      if userInstall
      then getAppUserDataDirectory "cabal"
      else case buildOS of
           Windows -> do windowsProgramFilesDir <- getWindowsProgramFilesDir
                         return (windowsProgramFilesDir </> "Haskell")
           _ -> return "/usr/local"
  installLibDir <-
      case buildOS of
      Windows -> return "$prefix"
      _ -> case comp of
                 LHC | userInstall -> getAppUserDataDirectory "lhc"
                 _ -> return ("$prefix" </> "lib")
  return $ fmap toPathTemplate $ InstallDirs {
      prefix = installPrefix,
      bindir = "$prefix" </> "bin",
      libdir = installLibDir,
      libsubdir = case comp of
           Hugs -> "hugs" </> "packages" </> "$pkg"
           JHC -> "$compiler"
           LHC -> "$compiler"
           UHC -> "$pkgid"
           _other -> "$arch-$os-$compiler" </> "$pkgid",
      dynlibdir = "$libdir",
      libexecdir = case buildOS of
        Windows -> "$prefix" </> "$pkgid"
        _other -> "$prefix" </> "libexec",
      progdir = "$libdir" </> "hugs" </> "programs",
      includedir = "$libdir" </> "$libsubdir" </> "include",
      datadir = case buildOS of
        Windows -> "$prefix"
        _other -> "$prefix" </> "share",
      datasubdir = "$arch-$os-$compiler" </> "$pkgid",
      docdir = "$datadir" </> "doc" </> "$arch-$os-$compiler" </> "$pkgid",
      mandir = "$datadir" </> "man",
      htmldir = "$docdir" </> "html",
      haddockdir = "$htmldir",
      sysconfdir = "$prefix" </> "etc"
  }

-- ---------------------------------------------------------------------------
-- Converting directories, absolute or prefix-relative

-- | Substitute the install dir templates into each other.
--
-- To prevent cyclic substitutions, only some variables are allowed in
-- particular dir templates. If out of scope vars are present, they are not
-- substituted for. Checking for any remaining unsubstituted vars can be done
-- as a subsequent operation.
--
-- The reason it is done this way is so that in 'prefixRelativeInstallDirs' we
-- can replace 'prefix' with the 'PrefixVar' and get resulting
-- 'PathTemplate's that still have the 'PrefixVar' in them. Doing this makes it
-- each to check which paths are relative to the $prefix.
--
substituteInstallDirTemplates :: PathTemplateEnv
                              -> InstallDirTemplates -> InstallDirTemplates
substituteInstallDirTemplates env dirs = dirs'
  where
    dirs' = InstallDirs {
      -- So this specifies exactly which vars are allowed in each template
      prefix = subst prefix [],
      bindir = subst bindir [prefixVar],
      libdir = subst libdir [prefixVar, bindirVar],
      libsubdir = subst libsubdir [],
      dynlibdir = subst dynlibdir [prefixVar, bindirVar, libdirVar],
      libexecdir = subst libexecdir prefixBinLibVars,
      progdir = subst progdir prefixBinLibVars,
      includedir = subst includedir prefixBinLibVars,
      datadir = subst datadir prefixBinLibVars,
      datasubdir = subst datasubdir [],
      docdir = subst docdir prefixBinLibDataVars,
      mandir = subst mandir (prefixBinLibDataVars ++ [docdirVar]),
      htmldir = subst htmldir (prefixBinLibDataVars ++ [docdirVar]),
      haddockdir = subst haddockdir (prefixBinLibDataVars ++
                                      [docdirVar, htmldirVar]),
      sysconfdir = subst sysconfdir prefixBinLibVars
    }
    subst dir env' = substPathTemplate (env'++env) (dir dirs)

    prefixVar = (PrefixVar, prefix dirs')
    bindirVar = (BindirVar, bindir dirs')
    libdirVar = (LibdirVar, libdir dirs')
    libsubdirVar = (LibsubdirVar, libsubdir dirs')
    datadirVar = (DatadirVar, datadir dirs')
    datasubdirVar = (DatasubdirVar, datasubdir dirs')
    docdirVar = (DocdirVar, docdir dirs')
    htmldirVar = (HtmldirVar, htmldir dirs')
    prefixBinLibVars = [prefixVar, bindirVar, libdirVar, libsubdirVar]
    prefixBinLibDataVars = prefixBinLibVars ++ [datadirVar, datasubdirVar]

-- | Convert from abstract install directories to actual absolute ones by
-- substituting for all the variables in the abstract paths, to get real
-- absolute path.
absoluteInstallDirs :: PackageIdentifier -> CompilerId -> CopyDest -> Platform
                    -> InstallDirs PathTemplate
                    -> InstallDirs FilePath
absoluteInstallDirs pkgId compilerId copydest platform dirs =
    (case copydest of
       CopyTo destdir -> fmap ((destdir </>) . dropDrive)
       _ -> id)
  . appendSubdirs (</>)
  . fmap fromPathTemplate
  $ substituteInstallDirTemplates env dirs
  where
    env = initialPathTemplateEnv pkgId compilerId platform


-- |The location prefix for the /copy/ command.
data CopyDest
  = NoCopyDest
  | CopyTo FilePath
  deriving (Eq, Show)

-- | Check which of the paths are relative to the installation $prefix.
--
-- If any of the paths are not relative, ie they are absolute paths, then it
-- prevents us from making a relocatable package (also known as a \"prefix
-- independent\" package).
--
prefixRelativeInstallDirs :: PackageIdentifier -> CompilerId -> Platform
                          -> InstallDirTemplates
                          -> InstallDirs (Maybe FilePath)
prefixRelativeInstallDirs pkgId compilerId platform dirs =
    fmap relative
  . appendSubdirs combinePathTemplate
  $ -- substitute the path template into each other, except that we map
    -- \$prefix back to $prefix. We're trying to end up with templates that
    -- mention no vars except $prefix.
    substituteInstallDirTemplates env dirs {
      prefix = PathTemplate [Variable PrefixVar]
    }
  where
    env = initialPathTemplateEnv pkgId compilerId platform

    -- If it starts with $prefix then it's relative and produce the relative
    -- path by stripping off $prefix/ or $prefix
    relative dir = case dir of
      PathTemplate cs -> fmap (fromPathTemplate . PathTemplate) (relative' cs)
    relative' (Variable PrefixVar : Ordinary (s:rest) : rest')
                      | isPathSeparator s = Just (Ordinary rest : rest')
    relative' (Variable PrefixVar : rest) = Just rest
    relative' _ = Nothing

-- ---------------------------------------------------------------------------
-- Path templates

-- | An abstract path, possibly containing variables that need to be
-- substituted for to get a real 'FilePath'.
--
newtype PathTemplate = PathTemplate [PathComponent]

data PathComponent =
       Ordinary FilePath
     | Variable PathTemplateVariable
     deriving Eq

data PathTemplateVariable =
       PrefixVar -- ^ The @$prefix@ path variable
     | BindirVar -- ^ The @$bindir@ path variable
     | LibdirVar -- ^ The @$libdir@ path variable
     | LibsubdirVar -- ^ The @$libsubdir@ path variable
     | DatadirVar -- ^ The @$datadir@ path variable
     | DatasubdirVar -- ^ The @$datasubdir@ path variable
     | DocdirVar -- ^ The @$docdir@ path variable
     | HtmldirVar -- ^ The @$htmldir@ path variable
     | PkgNameVar -- ^ The @$pkg@ package name path variable
     | PkgVerVar -- ^ The @$version@ package version path variable
     | PkgIdVar -- ^ The @$pkgid@ package Id path variable, eg @foo-1.0@
     | CompilerVar -- ^ The compiler name and version, eg @ghc-6.6.1@
     | OSVar -- ^ The operating system name, eg @windows@ or @linux@
     | ArchVar -- ^ The CPU architecture name, eg @i386@ or @x86_64@
     | ExecutableNameVar -- ^ The executable name; used in shell wrappers
     | TestSuiteNameVar -- ^ The name of the test suite being run
     | TestSuiteResultVar -- ^ The result of the test suite being run, eg
                          -- @pass@, @fail@, or @error@.
     | BenchmarkNameVar -- ^ The name of the benchmark being run
  deriving Eq

type PathTemplateEnv = [(PathTemplateVariable, PathTemplate)]

-- | Convert a 'FilePath' to a 'PathTemplate' including any template vars.
--
toPathTemplate :: FilePath -> PathTemplate
toPathTemplate = PathTemplate . read

-- | Convert back to a path, any remaining vars are included
--
fromPathTemplate :: PathTemplate -> FilePath
fromPathTemplate (PathTemplate template) = show template

combinePathTemplate :: PathTemplate -> PathTemplate -> PathTemplate
combinePathTemplate (PathTemplate t1) (PathTemplate t2) =
  PathTemplate (t1 ++ [Ordinary [pathSeparator]] ++ t2)

substPathTemplate :: PathTemplateEnv -> PathTemplate -> PathTemplate
substPathTemplate environment (PathTemplate template) =
    PathTemplate (concatMap subst template)

    where subst component@(Ordinary _) = [component]
          subst component@(Variable variable) =
              case lookup variable environment of
                  Just (PathTemplate components) -> components
                  Nothing -> [component]

-- | The initial environment has all the static stuff but no paths
initialPathTemplateEnv :: PackageIdentifier -> CompilerId -> Platform
                       -> PathTemplateEnv
initialPathTemplateEnv pkgId compilerId platform =
     packageTemplateEnv pkgId
  ++ compilerTemplateEnv compilerId
  ++ platformTemplateEnv platform

packageTemplateEnv :: PackageIdentifier -> PathTemplateEnv
packageTemplateEnv pkgId =
  [(PkgNameVar, PathTemplate [Ordinary $ display (packageName pkgId)])
  ,(PkgVerVar, PathTemplate [Ordinary $ display (packageVersion pkgId)])
  ,(PkgIdVar, PathTemplate [Ordinary $ display pkgId])
  ]

compilerTemplateEnv :: CompilerId -> PathTemplateEnv
compilerTemplateEnv compilerId =
  [(CompilerVar, PathTemplate [Ordinary $ display compilerId])
  ]

platformTemplateEnv :: Platform -> PathTemplateEnv
platformTemplateEnv (Platform arch os) =
  [(OSVar, PathTemplate [Ordinary $ display os])
  ,(ArchVar, PathTemplate [Ordinary $ display arch])
  ]

installDirsTemplateEnv :: InstallDirs PathTemplate -> PathTemplateEnv
installDirsTemplateEnv dirs =
  [(PrefixVar, prefix dirs)
  ,(BindirVar, bindir dirs)
  ,(LibdirVar, libdir dirs)
  ,(LibsubdirVar, libsubdir dirs)
  ,(DatadirVar, datadir dirs)
  ,(DatasubdirVar, datasubdir dirs)
  ,(DocdirVar, docdir dirs)
  ,(HtmldirVar, htmldir dirs)
  ]


-- ---------------------------------------------------------------------------
-- Parsing and showing path templates:

-- The textual format is that of an ordinary Haskell String, eg
-- "$prefix/bin"
-- and this gets parsed to the internal representation as a sequence of path
-- spans which are either strings or variables, eg:
-- PathTemplate [Variable PrefixVar, Ordinary "/bin" ]

instance Show PathTemplateVariable where
  show PrefixVar = "prefix"
  show BindirVar = "bindir"
  show LibdirVar = "libdir"
  show LibsubdirVar = "libsubdir"
  show DatadirVar = "datadir"
  show DatasubdirVar = "datasubdir"
  show DocdirVar = "docdir"
  show HtmldirVar = "htmldir"
  show PkgNameVar = "pkg"
  show PkgVerVar = "version"
  show PkgIdVar = "pkgid"
  show CompilerVar = "compiler"
  show OSVar = "os"
  show ArchVar = "arch"
  show ExecutableNameVar = "executablename"
  show TestSuiteNameVar = "test-suite"
  show TestSuiteResultVar = "result"
  show BenchmarkNameVar = "benchmark"

instance Read PathTemplateVariable where
  readsPrec _ s =
    take 1
    [ (var, drop (length varStr) s)
    | (varStr, var) <- vars
    , varStr `isPrefixOf` s ]
    where vars = [("prefix", PrefixVar)
                 ,("bindir", BindirVar)
                 ,("libdir", LibdirVar)
                 ,("libsubdir", LibsubdirVar)
                 ,("datadir", DatadirVar)
                 ,("datasubdir", DatasubdirVar)
                 ,("docdir", DocdirVar)
                 ,("htmldir", HtmldirVar)
                 ,("pkgid", PkgIdVar)
                 ,("pkg", PkgNameVar)
                 ,("version", PkgVerVar)
                 ,("compiler", CompilerVar)
                 ,("os", OSVar)
                 ,("arch", ArchVar)
                 ,("executablename", ExecutableNameVar)
                 ,("test-suite", TestSuiteNameVar)
                 ,("result", TestSuiteResultVar)
                 ,("benchmark", BenchmarkNameVar)]

instance Show PathComponent where
  show (Ordinary path) = path
  show (Variable var) = '$':show var
  showList = foldr (\x -> (shows x .)) id

instance Read PathComponent where
  -- for some reason we collapse multiple $ symbols here
  readsPrec _ = lex0
    where lex0 [] = []
          lex0 ('$':'$':s') = lex0 ('$':s')
          lex0 ('$':s') = case [ (Variable var, s'')
                               | (var, s'') <- reads s' ] of
                            [] -> lex1 "$" s'
                            ok -> ok
          lex0 s' = lex1 [] s'
          lex1 "" "" = []
          lex1 acc "" = [(Ordinary (reverse acc), "")]
          lex1 acc ('$':'$':s) = lex1 acc ('$':s)
          lex1 acc ('$':s) = [(Ordinary (reverse acc), '$':s)]
          lex1 acc (c:s) = lex1 (c:acc) s
  readList [] = [([],"")]
  readList s = [ (component:components, s'')
                | (component, s') <- reads s
                , (components, s'') <- readList s' ]

instance Show PathTemplate where
  show (PathTemplate template) = show (show template)

instance Read PathTemplate where
  readsPrec p s = [ (PathTemplate template, s')
                  | (path, s') <- readsPrec p s
                  , (template, "") <- reads path ]

-- ---------------------------------------------------------------------------
-- Internal utilities

getWindowsProgramFilesDir :: IO FilePath
getWindowsProgramFilesDir = do
#if mingw32_HOST_OS
  m <- shGetFolderPath csidl_PROGRAM_FILES
#else
  let m = Nothing
#endif
  return (fromMaybe "C:\\Program Files" m)

#if mingw32_HOST_OS
shGetFolderPath :: CInt -> IO (Maybe FilePath)
shGetFolderPath n =
  allocaArray long_path_size $ \pPath -> do
     r <- c_SHGetFolderPath nullPtr n nullPtr 0 pPath
     if (r /= 0)
        then return Nothing
        else do s <- peekCWString pPath; return (Just s)
  where
    long_path_size = 1024 -- MAX_PATH is 260, this should be plenty

csidl_PROGRAM_FILES :: CInt
csidl_PROGRAM_FILES = 0x0026
-- csidl_PROGRAM_FILES_COMMON :: CInt
-- csidl_PROGRAM_FILES_COMMON = 0x002b

foreign import stdcall unsafe "shlobj.h SHGetFolderPathW"
            c_SHGetFolderPath :: Ptr ()
                              -> CInt
                              -> Ptr ()
                              -> CInt
                              -> CWString
                              -> IO CInt
#endif
Something went wrong with that request. Please try again.