0 | ||| We work a lot with Strings of distinct semantics.
   1 | ||| Since I've been bitten by this more than once, we wrap
   2 | ||| the in single field record types to drastically increase
   3 | ||| type safety.
   4 | module Pack.Core.Types
   5 |
   6 | import public Data.FilePath.File
   7 |
   8 | import Data.Either
   9 | import Data.Maybe
  10 | import Derive.Prelude
  11 | import Idris.Package.Types
  12 | import System.File
  13 |
  14 | %default total
  15 | %language ElabReflection
  16 |
  17 | ----------------------------------------------------------------------------------
  18 | ----          Quoted Strings
  19 | ----------------------------------------------------------------------------------
  20 |
  21 | ||| This puts a value in quotes during interpolation.
  22 | |||
  23 | ||| Note: If the interpolated string contains additional quote
  24 | ||| characters, these will *not* be escaped.
  25 | export
  26 | quote : Interpolation a => a -> String
  27 | quote v = "\"\{v}\""
  28 |
  29 | ----------------------------------------------------------------------------------
  30 | ----          Paths
  31 | ----------------------------------------------------------------------------------
  32 |
  33 | ||| Returns the second path, relative to the first one
  34 | ||| For instance, `relativeTo /foo/bar/baz /foo/quux` will return
  35 | ||| `../../quux`.
  36 | export
  37 | relativeTo : (origin, target : Path Abs) -> Path Rel
  38 | relativeTo (PAbs _ sx) (PAbs _ sy) = PRel $ go (sx <>> []) (sy <>> [])
  39 |
  40 |   where
  41 |     go : (o,t : List Body) -> SnocList Body
  42 |     go [>]       t  = Lin <>< t
  43 |     go xs        [] = Lin <>< xs $> ".."
  44 |     go (x :: xs) (y :: ys) = case x == y of
  45 |       True  => go xs ys
  46 |       False => Lin <>< (((x :: xs) $> "..") ++ (y :: ys))
  47 |
  48 | ||| True if the given file path body ends on `.ipkg`
  49 | export
  50 | isIpkgBody : Body -> Bool
  51 | isIpkgBody = (Just "ipkg" ==) . extension
  52 |
  53 | ||| True if the given file path body ends on `.toml`
  54 | export
  55 | isTomlBody : Body -> Bool
  56 | isTomlBody = (Just "toml" ==) . extension
  57 |
  58 | ||| True if the given file path body ends on `.html`
  59 | export
  60 | isHtmlBody : Body -> Bool
  61 | isHtmlBody = (Just "html" ==) . extension
  62 |
  63 | toRelPath : String -> Path Rel
  64 | toRelPath s = case the FilePath (fromString s) of
  65 |   FP (PAbs _ sx) => PRel sx
  66 |   FP (PRel sx)   => PRel sx
  67 |
  68 | ||| Converts a `FilePath` - which might hold a relative
  69 | ||| or an absolute path - to an absolute path by interpreting
  70 | ||| a relative path being relative to the given parent directory.
  71 | export
  72 | toAbsPath : (parent : Path Abs) -> FilePath -> Path Abs
  73 | toAbsPath parent (FP $ PAbs d sx) = PAbs d sx
  74 | toAbsPath parent (FP $ PRel sx) = parent </> PRel sx
  75 |
  76 | ||| Parses a string, converting it to either a relative
  77 | ||| or absolute path and using `toAbsPath` to convert the result
  78 | ||| to an absolute path.
  79 | export
  80 | parse : String -> (parentDir : Path Abs) -> Path Abs
  81 | parse s parentDir = toAbsPath parentDir (fromString s)
  82 |
  83 | export %inline
  84 | Cast String (Path Rel) where
  85 |   cast = toRelPath
  86 |
  87 | export infixl 5 <//>
  88 |
  89 | ||| More flexible version of `</>` (path concatenation).
  90 | export %inline
  91 | (<//>) : Cast a (Path Rel) => Path t -> a -> Path t
  92 | p <//> v = p </> cast v
  93 |
  94 | export infixl 5 //>
  95 |
  96 | ||| More flexible version of `//>`
  97 | ||| (appending a file path body to an absolute path)
  98 | export %inline
  99 | (//>) : Cast a Body => Path t -> a -> Path t
 100 | p //> v = p /> cast v
 101 |
 102 | export infixl 8 <->
 103 |
 104 | ||| Concatenate two file path bodies with a hyphen inbetween.
 105 | export
 106 | (<->) : Cast a Body => Cast b Body => a -> b -> Body
 107 | x <-> y = the Body (cast x) <+> "-" <+> cast y
 108 |
 109 | ||| Convert a package version to a file path body.
 110 | export
 111 | Cast PkgVersion Body where
 112 |   cast = fromMaybe "0" . parse . show
 113 |
 114 | ||| Convert a package version to a file path body.
 115 | export
 116 | Cast (Maybe PkgVersion) Body where
 117 |   cast Nothing  = "0"
 118 |   cast (Just v) = cast v
 119 |
 120 | ||| Convert a relative file path to an absolute one by appending
 121 | ||| it to the given parent directory.
 122 | export %inline
 123 | toAbsFile : Path Abs -> File Rel -> File Abs
 124 | toAbsFile parentDir (MkF p f) = MkF (parentDir </> p) f
 125 |
 126 | export
 127 | Cast (File t) (Path t) where cast = toPath
 128 |
 129 | ----------------------------------------------------------------------------------
 130 | ----          CurDir, PackDir, and TmpDir
 131 | ----------------------------------------------------------------------------------
 132 |
 133 | ||| The directory where package collections, global user settings,
 134 | ||| and cached `.ipkg` files are stored.
 135 | public export
 136 | record PackDirs where
 137 |   [noHints]
 138 |   constructor PD
 139 |
 140 |   ||| Directory with user settings.
 141 |   |||
 142 |   ||| Depending on what environment variables are set, this defaults to
 143 |   ||| (in decreasing order of priority):
 144 |   |||
 145 |   ||| * `PACK_USER_DIR`
 146 |   ||| * `$XDG_CONFIG_HOME/pack`
 147 |   ||| * `$HOME/.config/pack`
 148 |   user    : Path Abs
 149 |
 150 |   ||| Directory with application state (installed compiler and libraries).
 151 |   |||
 152 |   ||| Depending on what environment variables are set, this defaults to
 153 |   ||| (in decreasing order of priority):
 154 |   |||
 155 |   ||| * `PACK_STATE_DIR`
 156 |   ||| * `$XDG_STATE_HOME/pack`
 157 |   ||| * `$HOME/.local/state/pack`
 158 |   state   : Path Abs
 159 |
 160 |   ||| Directory with cached data such as cached `.ipkg` files, git repos,
 161 |   ||| and temporary files used during installation of libs.
 162 |   |||
 163 |   ||| Depending on what environment variables are set, this defaults to
 164 |   ||| (in decreasing order of priority):
 165 |   |||
 166 |   ||| * `PACK_CACHE_DIR`
 167 |   ||| * `$XDG_CACHE_HOME/pack`
 168 |   ||| * `$HOME/.cache/pack`
 169 |   cache   : Path Abs
 170 |
 171 |   ||| Directory where executables will be installed.
 172 |   |||
 173 |   ||| Depending on what environment variables are set, this defaults to
 174 |   ||| (in decreasing order of priority):
 175 |   |||
 176 |   ||| * `PACK_BIN_DIR`
 177 |   ||| * `$HOME/.local/bin`
 178 |   bin     : Path Abs
 179 |
 180 | ||| The directory from which the pack application was invoked.
 181 | public export
 182 | data CurDir : Type where
 183 |   [noHints]
 184 |   CD : (dir : Path Abs) -> CurDir
 185 |
 186 | export %inline
 187 | Interpolation CurDir where
 188 |   interpolate (CD dir) = interpolate dir
 189 |
 190 | ||| Use this when you need access to the current directory's path with
 191 | ||| only a value of type `CurDir` in scope.
 192 | export %inline
 193 | curDir : (cd : CurDir) => Path Abs
 194 | curDir {cd = CD dir} = dir
 195 |
 196 | ||| The directory where temporary files and git repos will be
 197 | ||| kept.
 198 | public export
 199 | data TmpDir : Type where
 200 |   [noHints]
 201 |   TD : (dir : Path Abs) -> TmpDir
 202 |
 203 | export %inline
 204 | Interpolation TmpDir where
 205 |   interpolate (TD dir) = interpolate dir
 206 |
 207 | ||| Use this when you need access to the `PACK_DIR` path with
 208 | ||| only a value of type `PackDir` in scope.
 209 | export %inline
 210 | tmpDir : (td : TmpDir) => Path Abs
 211 | tmpDir {td = TD dir} = dir
 212 |
 213 | ----------------------------------------------------------------------------------
 214 | ----          TTC-Version
 215 | ----------------------------------------------------------------------------------
 216 |
 217 | ||| The TTC-Version currently used by the Idris compiler
 218 | public export
 219 | record TTCVersion where
 220 |   [noHints]
 221 |   constructor TTCV
 222 |   version : Maybe Body
 223 |
 224 | ||| Use this when you need access to the current TTC version
 225 | ||| only a value of type `TTCVersion` in scope.
 226 | export %inline
 227 | ttcVersion : (ttc : TTCVersion) => Maybe Body
 228 | ttcVersion = ttc.version
 229 |
 230 | ----------------------------------------------------------------------------------
 231 | ----          Interpolation
 232 | ----------------------------------------------------------------------------------
 233 |
 234 | ||| Convenience implementation for printing file errors in string
 235 | ||| interpolation
 236 | export
 237 | Interpolation FileError where interpolate = show
 238 |
 239 | ||| Convenience implementation for printing package versions in string
 240 | ||| interpolation
 241 | export
 242 | Interpolation PkgVersion where interpolate = show
 243 |
 244 | --------------------------------------------------------------------------------
 245 | --          URL
 246 | --------------------------------------------------------------------------------
 247 |
 248 | ||| URL mostly used to represent Git repositories.
 249 | public export
 250 | record URL where
 251 |   constructor MkURL
 252 |   value : String
 253 |
 254 | %runElab derive "URL" [Show,Eq,FromString]
 255 |
 256 | export %inline
 257 | Interpolation URL where interpolate = value
 258 |
 259 | export
 260 | Cast URL (Path Rel) where
 261 |   cast (MkURL s) = case unpack s of
 262 |     'h'::'t'::'t'::'p'::'s'::':'::'/'::'/':: t => cast (pack t)
 263 |     'h'::'t'::'t'::'p'::':'::'/'::'/':: t      => cast (pack t)
 264 |     t                                          => cast (pack t)
 265 |
 266 | --------------------------------------------------------------------------------
 267 | --          Commits and Hashes
 268 | --------------------------------------------------------------------------------
 269 |
 270 | ||| A git commit hash or tag.
 271 | public export
 272 | record Commit where
 273 |   constructor MkCommit
 274 |   value : String
 275 |
 276 | %runElab derive "Commit" [Show,Eq,FromString]
 277 |
 278 | export %inline
 279 | Interpolation Commit where interpolate = value
 280 |
 281 | export %inline
 282 | Cast Commit (Path Rel) where
 283 |   cast = toRelPath . value
 284 |
 285 | ||| A hash generated by pack
 286 | public export
 287 | record Hash where
 288 |   constructor MkHash
 289 |   value : String
 290 |
 291 | %runElab derive "Hash" [Show,Eq,FromString]
 292 |
 293 | export %inline
 294 | Interpolation Hash where interpolate = value
 295 |
 296 | export %inline
 297 | Cast Hash (Path Rel) where
 298 |   cast = toRelPath . value
 299 |
 300 | --------------------------------------------------------------------------------
 301 | --          Branches
 302 | --------------------------------------------------------------------------------
 303 |
 304 | ||| A branch in a git repo.
 305 | public export
 306 | record Branch where
 307 |   constructor MkBranch
 308 |   value : String
 309 |
 310 | %runElab derive "Branch" [Show,Eq,FromString]
 311 |
 312 | export %inline
 313 | Interpolation Branch where interpolate = value
 314 |
 315 | export %inline
 316 | Cast Branch (Path Rel) where
 317 |   cast = toRelPath . value
 318 |
 319 | --------------------------------------------------------------------------------
 320 | --          Package Name
 321 | --------------------------------------------------------------------------------
 322 |
 323 | ||| Name of an Idris package
 324 | public export
 325 | record PkgName where
 326 |   constructor MkPkgName
 327 |   value : String
 328 |
 329 | %runElab derive "PkgName" [Show,Eq,Ord,FromString]
 330 |
 331 | export %inline
 332 | Interpolation PkgName where interpolate = value
 333 |
 334 | export %inline
 335 | Cast PkgName (Path Rel) where
 336 |   cast = toRelPath . value
 337 |
 338 | --------------------------------------------------------------------------------
 339 | --          PkgOrIpkg
 340 | --------------------------------------------------------------------------------
 341 |
 342 | ||| Several pack commands operat either on a pack package or a local
 343 | ||| `.ipkg` file. This data type represents such command line arguments.
 344 | public export
 345 | data PkgOrIpkg : Type where
 346 |   Pkg :  PkgName -> PkgOrIpkg
 347 |   Ipkg : File Abs -> PkgOrIpkg
 348 |
 349 | --------------------------------------------------------------------------------
 350 | --          Package Type
 351 | --------------------------------------------------------------------------------
 352 |
 353 | ||| Type of an Idris package (either a library or a binary).
 354 | public export
 355 | data PkgType = PLib | PApp
 356 |
 357 | export
 358 | Interpolation PkgType where
 359 |   interpolate PLib = "lib"
 360 |   interpolate PApp = "app"
 361 |
 362 | export
 363 | Eq PkgType where
 364 |   PLib == PLib = True
 365 |   PApp == PApp = True
 366 |   _    == _    = False
 367 |
 368 | export
 369 | Ord PkgType where
 370 |   compare PLib PApp = LT
 371 |   compare PApp PLib = GT
 372 |   compare _    _    = EQ
 373 |
 374 | --------------------------------------------------------------------------------
 375 | --          Install Type
 376 | --------------------------------------------------------------------------------
 377 |
 378 | ||| What we want to install: A library, an application to
 379 | ||| run it from within pack, or an application, which should
 380 | ||| be available via the `PATH` variable.
 381 | public export
 382 | data InstallType : Type where
 383 |   Library : InstallType
 384 |   App     : (withWrapperScript : Bool) -> InstallType
 385 |
 386 | export %inline
 387 | Interpolation InstallType where
 388 |   interpolate Library = "library"
 389 |   interpolate (App b) = "app"
 390 |
 391 | export
 392 | Eq InstallType where
 393 |   Library == Library = True
 394 |   App b1  == App b2  = b1 == b2
 395 |   _       == _       = False
 396 |
 397 | export
 398 | Ord InstallType where
 399 |   compare Library  (App _)  = LT
 400 |   compare (App _)  Library  = GT
 401 |   compare Library  Library  = EQ
 402 |   compare (App b1) (App b2) = compare b1 b2
 403 |
 404 | --------------------------------------------------------------------------------
 405 | --          DBName
 406 | --------------------------------------------------------------------------------
 407 |
 408 | ||| Name of a package collection. This must be a valid
 409 | ||| file path body.
 410 | public export
 411 | record DBName where
 412 |   constructor MkDBName
 413 |   value : Body
 414 |
 415 | export %inline
 416 | Eq DBName where (==) = (==) `on` value
 417 |
 418 | export %inline
 419 | Ord DBName where compare = compare `on` value
 420 |
 421 | export %inline
 422 | Interpolation DBName where interpolate = interpolate . value
 423 |
 424 | export %inline
 425 | Cast DBName Body where
 426 |   cast = value
 427 |
 428 | export %inline
 429 | Head : DBName
 430 | Head = MkDBName "HEAD"
 431 |
 432 | export %inline
 433 | All : DBName
 434 | All = MkDBName "all"
 435 |
 436 | --------------------------------------------------------------------------------
 437 | --          Machine Type
 438 | --------------------------------------------------------------------------------
 439 |
 440 | ||| Possible compatible machine types (for installation and CI/CD).
 441 | public export
 442 | data MachineType = Ubuntu | MacOS
 443 |
 444 | %runElab derive "MachineType" [Eq,Ord]
 445 |
 446 | machineTypeToNat : MachineType -> Nat
 447 | machineTypeToNat Ubuntu  = 0
 448 | machineTypeToNat MacOS   = 1
 449 |
 450 | export
 451 | Interpolation MachineType where
 452 |   interpolate Ubuntu = "ubuntu"
 453 |   interpolate MacOS  = "macos"
 454 |
 455 | export
 456 | runsOn : Maybe (List MachineType) -> Maybe String
 457 | runsOn = map $ \xs =>
 458 |   "runs-on     = [" ++
 459 |   concat (intersperse ", " $ map quote xs) ++
 460 |   "]"
 461 |
 462 | --------------------------------------------------------------------------------
 463 | --          Desc
 464 | --------------------------------------------------------------------------------
 465 |
 466 | ||| A tagged package desc. We use the tag mainly to make sure that
 467 | ||| the package desc in question has been checked for safety issues.
 468 | ||| Since the tag is parameterized by a `PkgDesc`, we make sure
 469 | ||| we will not inadvertently use a tag for a `PkgDesc` different to
 470 | ||| the one we wrapped.
 471 | public export
 472 | record Desc (t : PkgDesc -> Type) where
 473 |   constructor MkDesc
 474 |   ||| The parsed package desc
 475 |   desc : PkgDesc
 476 |
 477 |   ||| String content of the `.ipkg` file used when reading the package desc
 478 |   cont : String
 479 |
 480 |   ||| Path to the file use when reading the package desc
 481 |   path : File Abs
 482 |
 483 |   ||| Security tag. See `Pack.Runner.Database.check`
 484 |   0 tag : t desc
 485 |
 486 | ||| This is used as a tag for unchecked `Desc`s.
 487 | public export
 488 | 0 U : PkgDesc -> Type
 489 | U d = Unit
 490 |
 491 | namespace PkgDesc
 492 |   ||| Lists the dependencies of a package.
 493 |   export
 494 |   dependencies : PkgDesc -> List PkgName
 495 |   dependencies d = map (MkPkgName . pkgname) $ d.depends
 496 |
 497 | ||| Lists the dependencies of a package.
 498 | export
 499 | dependencies : Desc t -> List PkgName
 500 | dependencies d = dependencies d.desc
 501 |
 502 | --------------------------------------------------------------------------------
 503 | --          CmdArg
 504 | --------------------------------------------------------------------------------
 505 |
 506 | ||| A command line argument of a call to the system shell.
 507 | public export
 508 | data CmdArg : Type where
 509 |
 510 |   ||| Escapable alternative represents a string that should be understood as a
 511 |   ||| single argument disregarding its contents, i.e. the whole string should
 512 |   ||| be passed as an argument even if it contains spaces or characters that
 513 |   ||| are normally understood specially by shell.
 514 |   Escapable : String -> CmdArg
 515 |
 516 |   ||| No escape alternative represents a raw string that is used "as is" at the
 517 |   ||| shell call, thus allowing to pass commands to the shell itself.
 518 |   ||| Be aware that spaces inside these strings would form several actual
 519 |   ||| arguments and quotation marks and backslash symbols may interfere with
 520 |   ||| escaping of other arguments.
 521 |   NoEscape : String -> CmdArg
 522 |
 523 | ||| Interface that is used to mark which types can be used as a source for
 524 | ||| command line arguments when building lists of such.
 525 | ||| This allows to be able to pass different literals and expressions without
 526 | ||| explicit wrapping them into the `CmdArg` type.
 527 | public export
 528 | interface CmdArgable a where
 529 |   toCmdArg : a -> CmdArg
 530 |
 531 | export %inline
 532 | CmdArgable CmdArg where
 533 |   toCmdArg = id
 534 |
 535 | ||| Implementation that allows any type implementing `Interpolation` interface
 536 | ||| to be used as an escapable command line argument.
 537 | export %inline
 538 | Interpolation a => CmdArgable a where
 539 |   toCmdArg = Escapable . interpolate
 540 |
 541 | ||| A list of command line arguments.
 542 | |||
 543 | ||| This type is meant to look syntacitcally as a simple list, however
 544 | ||| containing possibly values of different types which can form a command
 545 | ||| line argument.
 546 | |||
 547 | ||| For example, a call to some command with redirection may look like this:
 548 | ||| `sys ["echo", "a", NoEscape ">", file]`,
 549 | ||| when, say, `file` is a value of type `File Abs`.
 550 | public export
 551 | data CmdArgList : Type where
 552 |   Nil  : CmdArgList
 553 |   (::) : CmdArgable a => a -> CmdArgList -> CmdArgList
 554 |
 555 | cmdArgList : CmdArgList -> List CmdArg
 556 | cmdArgList []      = []
 557 | cmdArgList (x::xs) = toCmdArg x :: cmdArgList xs
 558 |
 559 | ||| Converts a list of command line arguments to a single string
 560 | ||| while putting spaces between arguments and escaping appropriate ones.
 561 | |||
 562 | ||| For example, call `escapeCmd ["echo", "&&", NoEscape "&&", "echo", "yes"]`
 563 | ||| would return a string equivalent to the literal
 564 | ||| `#""echo" "&&" && "echo" "yes""#`.
 565 | export
 566 | escapeCmd : CmdArgList -> String
 567 | escapeCmd = unwords . map manageArg . cmdArgList where
 568 |   manageArg : CmdArg -> String
 569 |   manageArg $ Escapable s = escapeArg s
 570 |   manageArg $ NoEscape s  = s
 571 |
 572 | namespace CmdArg
 573 |
 574 |   ||| Concatenate two command line arguments into one.
 575 |   |||
 576 |   ||| This operation respects meaning of the contents of each argument,
 577 |   ||| whether they should be escaped or not.
 578 |   ||| This allows, say, to form an argument which partially contains something
 579 |   ||| escapable and partially contains a special shell argument, for example
 580 |   ||| `sys ["cp", "-r", Escapable "\{dirName}/" ++ NoEscape "*", dest]` would
 581 |   ||| list files with shell's `*` even if `dirName` contains spaces.
 582 |   export
 583 |   (++) : CmdArg -> CmdArg -> CmdArg
 584 |   Escapable x ++ Escapable y = Escapable $ x ++ y
 585 |   Escapable x ++ NoEscape y  = NoEscape $ escapeArg x ++ y
 586 |   NoEscape x  ++ Escapable y = NoEscape $ x ++ escapeArg y
 587 |   NoEscape x  ++ NoEscape y  = NoEscape $ x ++ y
 588 |
 589 | namespace CmdArgList
 590 |
 591 |   ||| Concatenation operation for command line argument lists.
 592 |   export
 593 |   (++) : CmdArgList -> CmdArgList -> CmdArgList
 594 |   []      ++ ys = ys
 595 |   (x::xs) ++ ys = x :: xs ++ ys
 596 |
 597 |   export
 598 |   Semigroup CmdArgList where
 599 |     (<+>) = (++)
 600 |
 601 |   export
 602 |   Monoid CmdArgList where
 603 |     neutral = []
 604 |
 605 |   ||| Specialised version of `concatMap` from `Foldable` for `CmdArgList`,
 606 |   ||| since `CmdArgList` cannot implement `Foldable`.
 607 |   export
 608 |   concatMap : Monoid m => (CmdArg -> m) -> CmdArgList -> m
 609 |   concatMap f []      = neutral
 610 |   concatMap f (x::xs) = f (toCmdArg x) <+> concatMap f xs
 611 |
 612 |   ||| Function that forms a command line arguments list from a raw list of
 613 |   ||| strings, treating each string as a single escapable argument.
 614 |   export
 615 |   fromStrList : List String -> CmdArgList
 616 |   fromStrList = foldr (\x, xs => x::xs) Nil
 617 |
 618 | --------------------------------------------------------------------------------
 619 | --          LineBufferingCmd
 620 | --------------------------------------------------------------------------------
 621 |
 622 | ||| A wrapper for a command list of a shell command which allows to do
 623 | ||| line buffering.
 624 | public export
 625 | record LineBufferingCmd where
 626 |   [noHints]
 627 |   constructor MkLineBufferingCmd
 628 |   lineBufferingCmd : CmdArgList
 629 |
 630 | --------------------------------------------------------------------------------
 631 | --          Logging
 632 | --------------------------------------------------------------------------------
 633 |
 634 | ||| Level used during logging.
 635 | public export
 636 | data LogLevel : Type where
 637 |   [noHints]
 638 |   Debug   : LogLevel
 639 |   Build   : LogLevel
 640 |   Info    : LogLevel
 641 |   Cache   : LogLevel
 642 |   Warning : LogLevel
 643 |   Silence : LogLevel
 644 |
 645 | llToNat : LogLevel -> Nat
 646 | llToNat Debug   = 0
 647 | llToNat Build   = 1
 648 | llToNat Info    = 2
 649 | llToNat Cache   = 3
 650 | llToNat Warning = 4
 651 | llToNat Silence = 5
 652 |
 653 | export
 654 | Eq LogLevel where (==) = (==) `on` llToNat
 655 |
 656 | export
 657 | Ord LogLevel where compare = compare `on` llToNat
 658 |
 659 | export
 660 | Interpolation LogLevel where
 661 |   interpolate Debug   = "debug"
 662 |   interpolate Build   = "build"
 663 |   interpolate Info    = "info"
 664 |   interpolate Cache   = "cache"
 665 |   interpolate Warning = "warning"
 666 |   interpolate Silence = ""
 667 |
 668 | export
 669 | logLevels : List (String, LogLevel)
 670 | logLevels =
 671 |   [ ("debug"  , Debug  )
 672 |   , ("build"  , Build  )
 673 |   , ("info"   , Info   )
 674 |   , ("cache"  , Cache  )
 675 |   , ("warning", Warning)
 676 |   , ("silence", Silence)
 677 |   ]
 678 |
 679 | ||| Reference `LogLevel` to be used as an auto implicit
 680 | public export
 681 | record LogRef where
 682 |   [noHints]
 683 |   constructor MkLogRef
 684 |   level : LogLevel
 685 |
 686 | --------------------------------------------------------------------------------
 687 | --          Errors
 688 | --------------------------------------------------------------------------------
 689 |
 690 | ||| Error during marshalling from TOML to an Idris type.
 691 | public export
 692 | data TOMLErr : Type where
 693 |   ||| A mandatory key/value pair in a toml file is
 694 |   ||| missing
 695 |   MissingKey : (path : List String) -> TOMLErr
 696 |
 697 |   ||| A value in a toml file has the wrong type
 698 |   WrongType : (path  : List String) -> (type  : String) -> TOMLErr
 699 |
 700 | tomlPath : List String -> String
 701 | tomlPath = concat . intersperse "."
 702 |
 703 | printTOMLErr : TOMLErr -> String
 704 | printTOMLErr (MissingKey path) = "Missing toml key: \{tomlPath path}."
 705 | printTOMLErr (WrongType path type) =
 706 |   "Wrong type at \{tomlPath path}. Expect \{type}."
 707 |
 708 | ||| Prefix the given TOML key to an error message. This allows us to
 709 | ||| specify exactly where in a TOML structure things went wrong.
 710 | export
 711 | prefixKey : (key : String) -> Either TOMLErr a -> Either TOMLErr a
 712 | prefixKey k = mapFst $ \case
 713 |   MissingKey p => MissingKey (k :: p)
 714 |   WrongType p t => WrongType (k :: p) t
 715 |
 716 | ||| Errors that can occur when running pack programs.
 717 | public export
 718 | data PackErr : Type where
 719 |   ||| Failed to get the path of the current directory.
 720 |   NoCurDir   : PackErr
 721 |
 722 |   ||| Failed to get package directory path
 723 |   NoPackDir  : PackErr
 724 |
 725 |   ||| Failed to create temporary directory
 726 |   NoTmpDir  : PackErr
 727 |
 728 |   ||| Failed to create the given directory
 729 |   MkDir      : (path : Path Abs) -> (err : FileError) -> PackErr
 730 |
 731 |   ||| Failed to read the given file
 732 |   ReadFile   : (path : File Abs) -> (err : FileError) -> PackErr
 733 |
 734 |   ||| Failed to write to the given file
 735 |   WriteFile  : (path : File Abs) -> (err : FileError) -> PackErr
 736 |
 737 |   ||| Failed to read the content of a directory
 738 |   DirEntries : (path : Path Abs) -> (err : FileError) -> PackErr
 739 |
 740 |   ||| Error when running the given system command
 741 |   Sys        : (cmd : CmdArgList) -> (err : Int) -> PackErr
 742 |
 743 |   ||| Error when changing into the given directory
 744 |   ChangeDir  : (path : Path Abs) -> PackErr
 745 |
 746 |   ||| The given package is not in the package data base
 747 |   UnknownPkg : (name : PkgName) -> PackErr
 748 |
 749 |   ||| Not enough data has been given for this package
 750 |   IncompletePkg : (name : PkgName) -> PackErr
 751 |
 752 |   ||| The given package is not a local package
 753 |   NotLocalPkg : (name : PkgName) -> PackErr
 754 |
 755 |   ||| The given package is trying to be installed on
 756 |   ||| an incompatible machine type.
 757 |   InstallOnIncompatibleMachinePkg : (mt : MachineType) -> (name : PkgName) -> PackErr
 758 |
 759 |   ||| The given package is not an applicatio
 760 |   ||| (No executable name set in the `.ipkg` file)
 761 |   NoApp      : (rep : PkgName) -> PackErr
 762 |
 763 |   ||| The given package is not an application
 764 |   ||| (No executable name set in the `.ipkg` file)
 765 |   NoAppIpkg  : (path : File Abs) -> PackErr
 766 |
 767 |   ||| An erroneous package description in a package DB file
 768 |   InvalidPackageDesc : (s : String) -> PackErr
 769 |
 770 |   ||| The package database is empty (no header)
 771 |   EmptyPkgDB : PackErr
 772 |
 773 |   ||| Invalid package database header
 774 |   InvalidDBHeader : (s : String) -> PackErr
 775 |
 776 |   ||| Invalid package database header
 777 |   InvalidDBName : (s : String) -> PackErr
 778 |
 779 |   ||| Invalid package type
 780 |   InvalidPkgType : (s : String) -> PackErr
 781 |
 782 |   ||| Invalid package version
 783 |   InvalidPkgVersion : (s : String) -> PackErr
 784 |
 785 |   ||| Invalid log level
 786 |   InvalidLogLevel : (s : String) -> PackErr
 787 |
 788 |   ||| Failed to parse an .ipkg file
 789 |   InvalidIpkgFile  : (path : File Abs) -> PackErr
 790 |
 791 |   ||| Invalid file path body
 792 |   InvalidBody  : (s : String) -> PackErr
 793 |
 794 |   ||| Failed to parse a file path
 795 |   NoFilePath : (str : String) -> PackErr
 796 |
 797 |   ||| The given core package (base, contrib, etc.)
 798 |   ||| is missing from the Idris installation.
 799 |   MissingCorePackage :
 800 |        (name    : PkgName)
 801 |     -> (version : PkgVersion)
 802 |     -> (commit  : Commit)
 803 |     -> PackErr
 804 |
 805 |   ||| Unknown command line argument
 806 |   UnknownArg : (arg : String) -> PackErr
 807 |
 808 |   ||| Invalid command line arguments (in micropack)
 809 |   InvalidArgs : (args : List String) -> PackErr
 810 |
 811 |   ||| Erroneous command line argument
 812 |   ErroneousArg : (err : String) -> PackErr
 813 |
 814 |   ||| Trying to run zero or more than one local package
 815 |   ||| (or something that isn't a local package).
 816 |   BuildMany : List Body -> PackErr
 817 |
 818 |   ||| Unknown pack command
 819 |   UnknownCommand : String -> (usage : String) -> PackErr
 820 |
 821 |   ||| Unknown pack command
 822 |   InvalidCmdArgs :
 823 |        (cmd   : String)
 824 |     -> (args  : List String)
 825 |     -> (usage : String)
 826 |     -> PackErr
 827 |
 828 |   ||| Trying to clone a repository into an existing
 829 |   ||| directory.
 830 |   DirExists : Path Abs -> PackErr
 831 |
 832 |   ||| Error in a toml file.
 833 |   TOMLFile :  (file : File Abs) -> (err : TOMLErr) -> PackErr
 834 |
 835 |   ||| Error in a toml file.
 836 |   TOMLParse : (err : String) -> PackErr
 837 |
 838 |   ||| Number of failures when building packages.
 839 |   BuildFailures : Nat -> PackErr
 840 |
 841 |   ||| User tried to manually install the pack application
 842 |   ManualInstallPackApp : PackErr
 843 |
 844 |   ||| User aborted installation of a lib/app with custom build hooks.
 845 |   SafetyAbort : PackErr
 846 |
 847 |   CyclicDeps : List PkgName -> PackErr
 848 |
 849 | ||| Prints an error that occured during program execution.
 850 | export
 851 | printErr : PackErr -> String
 852 | printErr NoCurDir = "Failed to get current directory."
 853 |
 854 | printErr NoPackDir = """
 855 |   Failed to figure out package directory.
 856 |   This means, that neither environment variable \"PACK_DIR\"
 857 |   nor environment varaible \"HOME\" was set.
 858 |   """
 859 |
 860 | printErr NoTmpDir = """
 861 |   Failed to create temporary directory.
 862 |   Please check directory `PACK_DIR` and make sure to remove
 863 |   all `.tmpXY` directories you no longer need.
 864 |   """
 865 |
 866 | printErr (MkDir path err) =
 867 |   "Error when creating directory \{quote path}: \{err}."
 868 |
 869 | printErr (ReadFile path err) =
 870 |   "Error when reading file \{quote path}: \{err}."
 871 |
 872 | printErr (WriteFile path err) =
 873 |   "Error when writing to file \{quote path}: \{err}."
 874 |
 875 | printErr (DirEntries path err) =
 876 |   "Error when reading directory \{quote path}: \{err}."
 877 |
 878 | printErr (Sys cmd err) = """
 879 |   Error when executing system command.
 880 |   Command: \{escapeCmd cmd}
 881 |   Error code: \{show err}
 882 |   """
 883 |
 884 | printErr (ChangeDir path) =
 885 |   "Failed to change to directory \{quote path}."
 886 |
 887 | printErr (InvalidPackageDesc s) = """
 888 |   Invalid package description: \{quote s}.
 889 |   This should be of the format \"name,url,commit hash,ipkg file\".
 890 |   """
 891 |
 892 | printErr (InvalidDBHeader s) = """
 893 |   Invalid data base header: \{quote s}.
 894 |   This should be of the format \"idris2 commit hash,idris2 version\".
 895 |   """
 896 |
 897 | printErr (InvalidDBName s) = """
 898 |   Invalid data collection name: \{quote s}.
 899 |   This should be a non-empty string without path separators.
 900 |   """
 901 |
 902 | printErr (InvalidBody s) = "Invalid file path body: \{quote s}."
 903 |
 904 | printErr (InvalidPkgType s) = """
 905 |   Invalid package type: \{quote s}.
 906 |   Valid types are `lib` and `bin`.
 907 |   """
 908 |
 909 | printErr (InvalidPkgVersion s) = "Invalid package version: \{quote s}."
 910 |
 911 | printErr (InvalidLogLevel s) = """
 912 |   Invalid log level: \{quote s}. Valid values are
 913 |   \{joinBy "\n" $ ("- " ++) . fst <$> logLevels}
 914 |   """
 915 |
 916 | printErr (UnknownPkg name) = "Unknown package: \{name}"
 917 |
 918 | printErr (IncompletePkg name) = "Incomplete data for custom package: \{name}"
 919 |
 920 | printErr (NotLocalPkg name) = "Not a local package: \{name}"
 921 |
 922 | printErr (InstallOnIncompatibleMachinePkg mt name) = """
 923 |   Trying to install the following package on
 924 |   an incompatible machine type (\{mt}): \{name}
 925 |   """
 926 |
 927 | printErr (NoApp rep) = "Package \{rep} is not an application"
 928 |
 929 | printErr (NoAppIpkg p) = "Package \{p} is not an application"
 930 |
 931 | printErr EmptyPkgDB = "Empty package data base"
 932 |
 933 | printErr (InvalidIpkgFile path) =
 934 |   "Failed to parse .ipkg file: \{path}"
 935 |
 936 | printErr (MissingCorePackage nm v c) =
 937 |   "Core package \{quote nm} missing for Idris2 version \{v} (commit: \{c})"
 938 |
 939 | printErr (UnknownArg arg) = "Unknown command line arg: \{arg}"
 940 |
 941 | printErr (InvalidArgs args) = "Invalid command line args: \{unwords args}"
 942 |
 943 | printErr (ErroneousArg err) = err
 944 |
 945 | printErr (UnknownCommand cmd usage) =
 946 |   """
 947 |   Unknown command: "\{cmd}"
 948 |
 949 |   \{usage}
 950 |   """
 951 |
 952 | printErr (InvalidCmdArgs cmd args usage) =
 953 |   """
 954 |   Invalid argument(s) for command `\{cmd}`.
 955 |
 956 |   \{usage}
 957 |   """
 958 |
 959 | printErr (BuildMany []) = "No local `.ipkg` files found."
 960 | printErr (BuildMany fs@(_::_)) = """
 961 |   Ambiguous `.ipkg` files:
 962 |   \{joinBy "\n" $ ("- " ++) . interpolate <$> fs}
 963 |   Please choose only one.
 964 |   """
 965 |
 966 | printErr (NoFilePath s) = "Not a file path : \{s}"
 967 |
 968 | printErr (DirExists path) = """
 969 |   Failed to clone Git repository into \{path}.
 970 |   Directory already exists.
 971 |   """
 972 |
 973 | printErr (TOMLFile file err) =
 974 |   "Error in file \{file}: \{printTOMLErr err}."
 975 |
 976 | printErr (TOMLParse err) = err
 977 |
 978 | printErr (BuildFailures 1) = "1 package failed to build."
 979 |
 980 | printErr (BuildFailures n) = "\{show n} packages failed to build."
 981 |
 982 | printErr ManualInstallPackApp = """
 983 |   You are not supposed to manually install or remove the pack
 984 |   application. In order to update pack to the latest version on
 985 |   GitHub, run `pack update`.
 986 |
 987 |   Note: If you didn't run `pack install-app pack` or a similar
 988 |   operation, "pack" might be listed as an auto-install application
 989 |   in one of your pack.toml files. Please remove it from there.
 990 |   """
 991 |
 992 | printErr (CyclicDeps ps) =
 993 |  let cycle = fastConcat $ intersperse " -> " (map value ps)
 994 |   in """
 995 |      Dependency cylce detected:
 996 |      \{cycle}
 997 |      """
 998 |
 999 | printErr SafetyAbort = "Aborted."
1000 |
1001 | ||| Tries to convert a string to a `DBName` by first converting
1002 | ||| it to a valid file path body.
1003 | export
1004 | readDBName : String -> Either PackErr DBName
1005 | readDBName s = case Body.parse s of
1006 |   Just b  => Right $ MkDBName b
1007 |   Nothing => Left (InvalidDBName s)
1008 |
1009 | ||| Tries to convert a string to a file path body.
1010 | export
1011 | readBody : String -> Either PackErr Body
1012 | readBody s = case Body.parse s of
1013 |   Just b  => Right b
1014 |   Nothing => Left (InvalidBody s)
1015 |
1016 | ||| Tries to convert a string to a package type.
1017 | export
1018 | readPkgType : String -> Either PackErr PkgType
1019 | readPkgType "lib" = Right PLib
1020 | readPkgType "bin" = Right PApp
1021 | readPkgType "app" = Right PApp
1022 | readPkgType s     = Left (InvalidPkgType s)
1023 |
1024 | ||| Tries to convert a string representing a relative or absolute
1025 | ||| file path. This uses `toAbsPath` internally, so it is somewhat
1026 | ||| tolerant w.r.t. to dubious file paths. It fails, however, if the
1027 | ||| given path does not contain at least one file path body.
1028 | export
1029 | readAbsFile : (curdir : Path Abs) -> String -> Either PackErr (File Abs)
1030 | readAbsFile cd s = case split $ toAbsPath cd (fromString s) of
1031 |   Just (p,b) => Right $ MkF p b
1032 |   Nothing    => Left (NoFilePath s)
1033 |
1034 | export
1035 | readLogLevel : String -> Either PackErr LogLevel
1036 | readLogLevel str = maybeToEither (InvalidLogLevel str) $ lookup str logLevels
1037 |