packages feed

shelly 1.9.0 → 1.10.0

raw patch · 23 files changed

+595/−561 lines, 23 filesdep −faildep −unixdep ~HUnitdep ~basedep ~bytestringPVP ok

version bump matches the API change (PVP)

Dependencies removed: fail, unix

Dependency ranges changed: HUnit, base, bytestring, containers, directory, exceptions, hspec, lifted-base, monad-control, mtl, process, text, time, transformers, unix-compat

API changes (from Hackage documentation)

- Shelly: instance (s Data.Type.Equality.~ Data.Text.Internal.Text, GHC.Show.Show s) => Shelly.ShellCmd (Shelly.Base.Sh s)
- Shelly.Lifted: data family ShM m a :: *;
- Shelly.Lifted: instance (Control.Monad.Trans.Error.Error e, Shelly.Lifted.MonadSh m) => Shelly.Lifted.MonadSh (Control.Monad.Trans.Error.ErrorT e m)
- Shelly.Lifted: instance (Shelly.Lifted.MonadSh m, s Data.Type.Equality.~ Data.Text.Internal.Text, GHC.Show.Show s) => Shelly.ShellCmd (m s)
- Shelly.Lifted: instance (Shelly.Lifted.MonadShControl m, Control.Monad.Trans.Error.Error e) => Shelly.Lifted.MonadShControl (Control.Monad.Trans.Error.ErrorT e m)
- Shelly.Lifted: instance Shelly.Lifted.MonadSh m => Shelly.Lifted.MonadSh (Control.Monad.Trans.List.ListT m)
- Shelly.Lifted: instance Shelly.Lifted.MonadShControl m => Shelly.Lifted.MonadShControl (Control.Monad.Trans.List.ListT m)
- Shelly.Pipe: instance (s Data.Type.Equality.~ Data.Text.Internal.Text, GHC.Show.Show s) => Shelly.Pipe.ShellCommand (Shelly.Pipe.Sh s)
+ Shelly: instance (s GHC.Types.~ Data.Text.Internal.Text, GHC.Show.Show s) => Shelly.ShellCmd (Shelly.Base.Sh s)
+ Shelly.Lifted: data ShM m a;
+ Shelly.Lifted: instance (Shelly.Lifted.MonadSh m, s GHC.Types.~ Data.Text.Internal.Text, GHC.Show.Show s) => Shelly.ShellCmd (m s)
+ Shelly.Lifted: instance Shelly.Lifted.MonadSh m => Shelly.Lifted.MonadSh (Control.Monad.Trans.Except.ExceptT e m)
+ Shelly.Lifted: instance Shelly.Lifted.MonadShControl m => Shelly.Lifted.MonadShControl (Control.Monad.Trans.Except.ExceptT e m)
+ Shelly.Pipe: instance (s GHC.Types.~ Data.Text.Internal.Text, GHC.Show.Show s) => Shelly.Pipe.ShellCommand (Shelly.Pipe.Sh s)

Files

ChangeLog.md view
@@ -1,49 +1,122 @@+# 1.10.0++Andreas Abel, 2022-01-30+* Allow `transformers-0.6`:+  - Replace `ErrorT` by `ExceptT`.+  - Remove `MonadSh` and `MonadShControl` instance for `ListT`.+    [#211](https://github.com/gregwebs/Shelly.hs/pull/211)+* Bump lower bounds of dependencies, keeping all versions that build with GHC >= 8.0.+* Remove unused `unix` dependency.+* Allow `time-1.12`.+* Builds warning-free with GHC 8.0 - 9.2.1.++# 1.9.0++Greg Weber, 2019-08-29+* Drop dependencies `system-fileio` and `system-filepath` in favor of `filepath`:+  The `FilePath` type changed to a synonym of `String`.+* Allow `time >= 1.9`.+* Builds with GHC >= 8.0 (tested up to 9.2).+ # 1.8.1 -There is a new function `cp_should_follow_symlinks` to specify whether a copy should follow symlinks.+Greg Weber, 2018-05-30+* New function `cp_should_follow_symlinks` to specify whether a copy should follow symlinks.  # 1.8.0 -* `cp_r` now uses upper case R: `cp -R`+Greg Weber, 2018-05-09+* `cp_r` now uses upper case R: `cp -R`.  # 1.7.2 -* Support exceptions-0.9+Greg Weber, 2018-03-17+* Fix handling of case-insensitive environment variables on Windows.+  [#166](https://github.com/yesodweb/Shelly.hs/issues/166) +# 1.7.1++Greg Weber, 2018-03-06+* Support `exceptions-0.9`.+ # 1.7.0.1 -* Fix FindSpec.hs tests. Fixes [#150](https://github.com/yesodweb/Shelly.hs/issues/150), [#162](https://github.com/yesodweb/Shelly.hs/issues/162)+Greg Weber, 2018-01-23+* Fix `FindSpec.hs` tests.+  Fixes [#150](https://github.com/yesodweb/Shelly.hs/issues/150)+  and [#162](https://github.com/yesodweb/Shelly.hs/issues/162). +# 1.7.0++Greg Weber, 2017-12-10+* Quote `ssh` remote commands aggressively with single quotes.+  [#160](https://github.com/yesodweb/Shelly.hs/issues/160)++# 1.6.9++Greg Weber, 2017-12-07+* Strongly escape `ssh` commands.+* Add `sshPairsP`: parallel execution of `ssh` commands.+ # 1.6.8.7 -* Relax unix-compat constraints+Sibi Prabakaran, 2017-11-26+* Relax `unix-compat` constraints.  # 1.6.8.6 +Sibi Prabakaran, 2017-11-19 * Fix Build issue [#156](https://github.com/yesodweb/Shelly.hs/issues/156)  # 1.6.8.5 +Sibi Prabakaran, 2017-11-12 * Fix Windows build [#155](https://github.com/yesodweb/Shelly.hs/pull/155) +# 1.6.8.4++Greg Weber, 2017-08-07+* Option `followSymlink` for find-command.+* Allow `time-1.7/8`.++# 1.6.8.3++Greg Weber, 2017-03-03+* Support GHC 8.0.2++# 1.6.8.2++Greg Weber, 2017-03-03+* Allow `time-1.6`and `directory-1.3`++# 1.6.8.1++Greg Weber, 2016-10-02+* _changelog missing_+ # 1.6.8 -* added sshPairsWithOptions function+Greg Weber, 2016-06-26+* Added `sshPairsWithOptions` function.  # 1.6.7 -* flush stdout when using `echo`, not just `echo_n`-* fix should be able to silence stderr when using `runHandle`-* expose RunFailed+Greg Weber, 2016-06-24+* Flush `stdout` when using `echo`, not just `echo_n`.+* Fix should be able to silence `stderr` when using `runHandle`.+* Expose `RunFailed`.  # 1.6.6 -* add prependToPath function+Greg Weber, 2016-04-21+* Add `prependToPath` function.  # 1.6.5 -* expose MonadShControl+Greg Weber, 2015-12-10+* Expose `MonadShControl`.  # 1.6.4.1 -* add writeBinary function+Greg Weber, 2015-12-01+* Add `writeBinary` function.
README.md view
@@ -1,37 +1,33 @@ # Shelly -[![Build Status](https://travis-ci.org/yesodweb/Shelly.hs.svg?branch=master)](https://travis-ci.org/yesodweb/Shelly.hs)+[![Build Status](https://github.com/gregwebs/Shelly.hs/actions/workflows/haskell-ci.yml/badge.svg?branch=master)](https://github.com/gregwebs/Shelly.hs/actions/workflows/haskell-ci.yml)+[![Build Status](https://github.com/gregwebs/Shelly.hs/actions/workflows/mac-win-ci.yml/badge.svg?branch=master)](https://github.com/gregwebs/Shelly.hs/actions/workflows/mac-win-ci.yml) [![Hackage](https://img.shields.io/hackage/v/shelly.svg)](https://hackage.haskell.org/package/shelly) [![Stackage Nightly](http://stackage.org/package/shelly/badge/nightly)](http://stackage.org/nightly/package/shelly) [![Stackage LTS](http://stackage.org/package/shelly/badge/lts)](http://stackage.org/lts/package/shelly)  Shelly provides a single module for convenient systems programming in Haskell. -* is aimed at convenience and getting things done rather than being a demonstration of elegance.-* has detailed and useful error messages-* maintains its own environment, making it thread-safe-* is modern, using Text and system-filepath/system-fileio-* has low memory usage-  * `run_` and other underscore variants that don't return stdout-  * `runFoldLines` to run a fold operation over each line rather than loading all of stdout into memory-  * `runHandle` and `runHandles` for complete control over handles--Looking to put your Haskell learning to immediate practical use? You don't have to create artifical intelligence, try just automating some of your boring tasks.+* Shelly is aimed at convenience and getting things done rather than being a demonstration of elegance.+* It has detailed and useful error messages.+* It maintains its own environment, making it thread-safe.+* It has low memory usage:  It has+  * `run_` and other underscore variants that do not return stdout,+  * `runFoldLines` to run a fold operation over each line rather than loading all of stdout into memory,+  * `runHandle` and `runHandles` for complete control over handles.  The focus of this library on convenience combined with good error messages should make shelly approachable for newer users of Haskell.-I have published [an introductory article to scripting with shelly, targeted towards those not familiar with Haskell](http://www.linux-magazin.de/Online-Artikel/Shell-scripting-with-type-safety-using-Haskell/). There is a paid version in German from Linux Magazin.-That article uses the version `shelly < 1.0` which uses lazy text. `shelly > 1.0` uses strict text.    ## More shelly packages -The [shelly-extra](http://hackage.haskell.org/package/shelly-extra) package has some additional functionality that requires additional dependencies, currently including a convenient concurrency/futures implementation. If you are following along the above article you need to install it.+The [shelly-extra](https://hackage.haskell.org/package/shelly-extra) package has some additional functionality that requires additional dependencies, currently including a convenient concurrency/futures implementation.   ## Examples -* [A small deployment script](http://www.alfredodinapoli.com/posts/2015-11-03-how-i-deploy-haskell-code.html)+* [A small deployment script](https://adinapoli.github.io/alfredodinapoli.com/posts/2015-11-03-how-i-deploy-haskell-code.html) * [Yesod development installer](https://github.com/yesodweb/scripts/blob/master/install.hs) * [cabal-meta, a haskell install tool](https://github.com/yesodweb/cabal-meta/blob/master/main.hs) * [antigen-hs, a zsh plugin manager](https://github.com/Tarrasch/antigen-hs)@@ -39,12 +35,12 @@  ### Blog Posts -* [Shelly automation with Literate Haskell](http://www.scholarslab.org/dh-developer/shell-programming-in-haskell-converting-s5-slides-to-pdf/)+* [Shelly automation with Literate Haskell](https://scholarslab.lib.virginia.edu/blog/shell-programming-in-haskell-converting-s5-slides-to-pdf/)   ### Testimonials -* [a beginning Haskeller does automation](http://www.reddit.com/r/haskell/comments/w86gu/my_current_job_task_is_boring_so_i_wrote_a_simple/)+* [A beginning Haskeller does automation](https://www.reddit.com/r/haskell/comments/w86gu/my_current_job_task_is_boring_so_i_wrote_a_simple/)  ### Help @@ -55,15 +51,16 @@ ### Haskell shell scripting libraries  -* [HSH](http://hackage.haskell.org/package/HSH) - A good alternative if you want to mixup usage of String and ByteString rather than just use Text.-* [HsShellScript](http://hackage.haskell.org/packages/archive/hsshellscript/3.1.0/doc/html/HsShellScript.html) - Has extensive low-level shell capabilities.-* [shell-conduit](http://hackage.haskell.org/package/shell-conduit) - efficient streaming via conduits. Makes some portability sacrifices by-  * encouraging one to just use the shell instead of cross-platform Haskell code-  * encouraging one to use a convenience function that searches the PATH at compile-time-* [shell-monad](http://hackage.haskell.org/package/shell-monad) - compile Haskell code down to shell script. This is a different approach from all the rest of the libraries. Writing your script is not as user-friendly as the other Haskell libraries, but it nicely solves the deployment issue.-* [turtle](http://hackage.haskell.org/package/turtle) - In some sense a [redesign of Shelly designed for beginner-friendliness](http://www.reddit.com/r/haskell/comments/2u6b8m/use_haskell_for_shell_scripting/co5ucq9)+* [HSH](https://hackage.haskell.org/package/HSH): A good alternative if you want to mixup usage of `String` and `ByteString` rather than just use `Text`.+* [HsShellScript](https://hackage.haskell.org/packages/archive/hsshellscript/3.1.0/doc/html/HsShellScript.html): Has extensive low-level shell capabilities.+* [shell-conduit](https://hackage.haskell.org/package/shell-conduit): Efficient streaming via conduits. Makes some portability sacrifices by+  * encouraging one to just use the shell instead of cross-platform Haskell code, and+  * encouraging one to use a convenience function that searches the `PATH` at compile-time.+* [shell-monad](https://hackage.haskell.org/package/shell-monad): Compile Haskell code down to shell script. This is a different approach from all the rest of the libraries. Writing your script is not as user-friendly as the other Haskell libraries, but it nicely solves the deployment issue.+* [shh](https://hackage.haskell.org/package/shh): Shell-like syntax with native piping. Can be used from GHCi as an interactive shell replacement.+* [turtle](https://hackage.haskell.org/package/turtle): In some sense a [redesign of Shelly designed for beginner-friendliness](https://www.reddit.com/r/haskell/comments/2u6b8m/use_haskell_for_shell_scripting/co5ucq9). -HSH and HsShellScript (unlike Shelly currently) implement very efficient mechanisms for piping/redirecting in the system.+HSH, HsShellScript and shh (unlike Shelly currently) implement very efficient mechanisms for piping/redirecting in the system. turtle, like Shelly offers folding as a way to efficiently deal with a stream.  None of the alternatives to Shelly offer command tracing.@@ -72,8 +69,8 @@  ### Haskell file-finding supplements -* [find-conduit](http://hackage.haskell.org/package/find-conduit) - uses conduits, similar speed to GNU find-* [FileManip](hackage.haskell.org/package/FileManip) - uses Lazy IO+* [find-conduit](https://hackage.haskell.org/package/find-conduit): Uses conduits, similar speed to GNU find.+* [FileManip](https://hackage.haskell.org/package/FileManip): Uses Lazy IO.  Shelly's finders load all files into memory. This is simpler to use if you control the filesystem structure and know the system is bounded in size. However, if the filesystem structure is unbounded it consumes unbounded memory. @@ -83,9 +80,9 @@ Shelly does not change the nature of shell scripting (text in, text out). If you want something more revolutionary you might try these: -* PowerShell is probably the best known.-* [Haskell project](https://github.com/pkamenarsky/ytools) using typed JSON-* [RecordStream](https://github.com/benbernard/RecordStream) untyped JSON]+* [PowerShell](https://github.com/PowerShell/PowerShell) is probably the best known.+* A [Haskell project](https://github.com/pkamenarsky/ytools) using typed JSON.+* [RecordStream](https://github.com/benbernard/RecordStream) using untyped JSON.   ## Usage@@ -94,28 +91,31 @@ There should be a primitive for every shell operation you need so you can easily build abstractions, so there are many of the usual file and environment operations.  There are 2 main entry points for running arbitrary commands: `run` and `cmd`.-They take a FilePath as their first argument. `run` takes a [Text] as its second argument.-`cmd` takes a variadic number of arguments, and they can be either Text or FilePath.+They take a FilePath as their first argument. `run` takes a `[Text]` as its second argument.+`cmd` takes a variadic number of arguments, and they can be either `Text` or `FilePath`. -Fun Example: shows an infectious script: it uploads itself to a server and runs itself over ssh.+Fun Example: shows an infectious script: it uploads itself to a server and runs itself over `ssh`. Of course, the development machine may need to be exactly the same OS as the server.  I recommend using the boilerplate at the top of this example in your projects. This includes setting line buffering if you are dealing with text and not binary data. -~~~~~ {.haskell}+```haskell     {-# LANGUAGE OverloadedStrings #-}     {-# LANGUAGE ExtendedDefaultRules #-}     {-# OPTIONS_GHC -fno-warn-type-defaults #-}+     import Shelly+    import System.IO     import Data.Text as T     default (T.Text) +    main :: IO ()     main =  do       hSetBuffering stdout LineBuffering       shelly $ verbosely $ do         host <- run "uname" ["-n"]-        if T.stripEnd host === "local-machine"+        if T.stripEnd host == "local-machine"           then do d <- cmd "date"                   c <- escaping False $ cmd "git" "log -1 | head -1 | awk '{print $2}'"                   appendfile "log/deploy.log" $ T.intercalate " - " [T.stripEnd d, c]@@ -129,8 +129,9 @@     uploads :: Text -> [Text] -> Sh ()     uploads remote locals = rsync $ ["--relative"] ++ locals ++ [remote] +    rsync :: [Text] -> Sh ()     rsync args = run_ "rsync" $ ["--delete", "-avz", "--no-g"] ++ args-~~~~~+```  ### Variadic arguments to cmd @@ -138,33 +139,35 @@ I find `cmd` to be more convenient, but I often use `run` and `command` variants when I am building up abstractions. Building up abstractions with cmd will require type signatures. +```haskell     -- easy signature, but only allows one argument     let cabal = cmd "cabal" :: Text -> Sh Text      -- more complex signature that allows partial application of cmd     let cabal = cmd "cabal" :: Shelly.ShellCmd result => result-+```   ### Escaping  By default, all commands are shell escaped.-If you want the shell to interpret special characters such as `*`, just use `escaping False $ do ...`+If you want the shell to interpret special characters such as `*`, just use `escaping False $ do ...`.  ### Using Text and FilePath together -Shelly's usage of system-filepath means you may need to convert between Text and FilePath sometimes.-This should be infrequent though because+Shelly's usage of `Text` means you may need to convert between `Text` and `FilePath` sometimes.+This should be infrequent though because: -* `cmd` will convert FilePath to Text-* The `</>` and `<.>` combinators convert String/Text into a FilePath automatically+* `cmd` will convert `FilePath` to `Text`.+* The `</>` and `<.>` combinators convert `Text` into a `FilePath` automatically.  Manual conversion is done through `toTextIgnore` or `toTextWarn`.   ### Thread-safe working directory and relative paths -`cd` does not change the process working directory (essentially a global variable), but instead changes the shelly state (which is thread safe).+Command `cd` does not change the process working directory (essentially a global variable),+but instead changes the shelly state (which is thread safe). All of the Shelly API takes this into account, internally shelly converts all paths to absolute paths. You can turn a relative path into an absolute with `absPath` or `canonic` or you can make a path relative to the Shelly working directory with `relPath`.  @@ -173,15 +176,10 @@ Haskell's #1 weakness for IO code is a lack of stack traces. Shelly gives you something different: detailed logging. In most cases this should be more useful than a stack trace.-Shelly keeps a log of API usage and saves it to a .shelly directory on failure.-If you use `shellyNoDir`, the log will instead be printed to stderr.+Shelly keeps a log of API usage and saves it to a `.shelly` directory on failure.+If you use `shellyNoDir`, the log will instead be printed to `stderr`. This is in addition to the `verbosely` settings that will print out commands and their output as the program is running. Shelly's own error messages are detailed and in some cases it will catch Haskell exceptions and re-throw them with better messages. -If you make your own primitive functions that don't use the existing Shelly API, you can create a wrapper in the Sh monad that use `trace` or `tag` to log what they are doing.+If you make your own primitive functions that do not use the existing Shelly API, you can create a wrapper in the Sh monad that use `trace` or `tag` to log what they are doing. You can turn tracing off (not generally recommended) by setting `tracing False`.---## Future plans--* Don't use the filepath library
shelly.cabal view
@@ -1,20 +1,18 @@ Name:       shelly -Version:     1.9.0+Version:     1.10.0 Synopsis:    shell-like (systems) programming in Haskell  Description: Shelly provides convenient systems programming in Haskell,              similar in spirit to POSIX shells. Shelly:              .                * is aimed at convenience and getting things done rather than-                 being a demonstration of elegance.+                 being a demonstration of elegance,              .-               * has detailed and useful error messages+               * has detailed and useful error messages,              .                * maintains its own environment, making it thread-safe.              .-               * is modern, using Text filepath/directory-             .              Shelly is originally forked from the Shellish package.              .              See the shelly-extra package for additional functionality.@@ -26,56 +24,81 @@ License:             BSD3 License-file:        LICENSE Author:              Greg Weber, Petr Rockai-Maintainer:          Greg Weber <greg@gregweber.info>+Maintainer:          Greg Weber <greg@gregweber.info>, Andreas Abel Category:            Development Build-type:          Simple-Cabal-version:       >=1.8+Cabal-version:       >=1.10 +tested-with:+  GHC == 8.0.2+  GHC == 8.2.2+  GHC == 8.4.4+  GHC == 8.6.5+  GHC == 8.8.4+  GHC == 8.10.7+  GHC == 9.0.2+  GHC == 9.2.1+ -- for the sdist of the test suite-extra-source-files: test/src/*.hs-                    test/examples/*.sh-                    test/examples/*.hs-                    test/data/zshrc-                    test/data/nonascii.txt-                    test/data/symlinked_dir/hoge_file-                    test/testall-                    README.md-                    ChangeLog.md+extra-source-files:+  test/src/*.hs+  test/examples/*.sh+  test/examples/*.hs+  test/data/zshrc+  test/data/nonascii.txt+  test/data/symlinked_dir/hoge_file+  test/testall+  README.md+  ChangeLog.md  Library-  Exposed-modules: Shelly, Shelly.Lifted, Shelly.Pipe, Shelly.Unix-  other-modules:   Shelly.Base, Shelly.Find, Shelly.Directory+  Exposed-modules:+    Shelly+    Shelly.Lifted+    Shelly.Pipe+    Shelly.Unix++  other-modules:+    Shelly.Base+    Shelly.Find+    Shelly.Directory+   hs-source-dirs: src +  -- Andreas Abel, 2021-11-20:+  -- Unless other constraints exist, lower bounds are chosen+  -- such that all versions that build with GHC 8+  -- (according to matrix.hackage.haskell.org) are included.   Build-depends:-    containers                >= 0.4.2.0,-    time                      >= 1.3 && < 1.10,-    directory                 >= 1.3.0.0 && < 1.4.0.0,-    mtl                       >= 2,-    process                   >= 1.0,-    unix-compat               < 0.6,-    unix,-    filepath,-    monad-control             >= 0.3.2 && < 1.1,-    lifted-base,-    lifted-async,-    exceptions                >= 0.6,-    enclosed-exceptions,-    text, bytestring, async, transformers, transformers-base--  if impl(ghc >= 7.6.1)-    build-depends:-        base >= 4.6 && < 5-  else-    build-depends:-      base >= 4 && < 5+      base                      >= 4.9       && < 5+        -- support GHC >= 8+    , async+    , bytestring                >= 0.10.6.0+    , containers                >= 0.5.7.0+    , directory                 >= 1.3.0.0   && < 1.4.0.0+    , enclosed-exceptions+    , exceptions                >= 0.8.2.1+    , filepath+    , lifted-async+    , lifted-base               >= 0.2.3.2+    , monad-control             >= 0.3.2     && < 1.1+    , mtl                       >= 2.2.2+    , process                   >= 1.4+    , text                      >= 1.2.2.0+    , time                      >= 1.3       && < 1.13+    , transformers              >= 0.5.0.0+    , transformers-base+    , unix-compat               >= 0.4.1.1   && < 0.6 -  ghc-options: -Wall+  ghc-options:+    -Wall+    -Wcompat -  if impl(ghc >= 7.6.1)-      CPP-Options: -DNO_PRELUDE_CATCH+  cpp-options:+    -DNO_PRELUDE_CATCH -  extensions:+  default-language: Haskell2010+  default-extensions:     CPP  source-repository head@@ -87,9 +110,9 @@    Default: False  Test-Suite shelly-testsuite-  type: exitcode-stdio-1.0-  hs-source-dirs: src test/src-  main-is: TestMain.hs+  type:           exitcode-stdio-1.0+  hs-source-dirs: test/src+  main-is:        TestMain.hs   other-modules:     CopySpec     EnvSpec@@ -102,51 +125,43 @@     RmSpec     RunSpec     SshSpec-    Shelly-    Shelly.Base-    Shelly.Find-    Shelly.Lifted     TestInit     WhichSpec     WriteSpec -  ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -threaded-               -fno-warn-unused-do-bind -fno-warn-type-defaults-+  ghc-options:+    -threaded+    -Wall+    -Wcompat+    -fwarn-tabs+    -funbox-strict-fields+    -fno-warn-type-defaults -  extensions: OverloadedStrings, ExtendedDefaultRules+  default-language: Haskell2010+  default-extensions:+    OverloadedStrings+    ExtendedDefaultRules    if flag(lifted)      cpp-options: -DLIFTED    build-depends:-    base                      >= 4.6,-    text                      >= 0.11,-    async,-    bytestring                >= 0.10,-    containers                >= 0.5.0.0,-    directory                 >= 1.3.0.0 && < 1.4.0.0,-    process                   >= 1.1.0,-    unix-compat               < 0.6,-    unix,-    time                      >= 1.3 && < 1.10,-    mtl                       >= 2,-    HUnit                     >= 1.2,-    hspec                     >= 2.0,-    hspec-contrib,-    transformers,-    transformers-base,-    filepath,-    monad-control,-    lifted-base,-    lifted-async,-    enclosed-exceptions,-    exceptions--  if impl(ghc < 8.0)-    build-depends:       fail >= 4.9 && < 4.10+    shelly+    , base+    , bytestring+    , directory+    , filepath+    , lifted-async+    , mtl+    , text+    , transformers+    , unix-compat+    -- additional dependencies+    , hspec                     >= 2.2.2+    , hspec-contrib+    , HUnit                     >= 1.2.5.2 -  extensions:+  default-extensions:     CPP  Flag build-examples@@ -154,19 +169,20 @@    Default: False    Manual: True --- demonstarated that command output in Shellish was not shown until after the command finished+-- demonstrated that command output in Shellish was not shown until after the command finished -- not necessary anymore Executable drain   hs-source-dirs: test/examples   main-is: drain.hs+  default-language: Haskell2010   if flag(build-examples)     buildable: True -    build-depends: base                      >= 4.6+    build-depends: base                  , shelly                  , text -    extensions:+    default-extensions:       CPP   else     buildable: False@@ -174,14 +190,15 @@ Executable run-handles   hs-source-dirs: test/examples   main-is: run-handles.hs+  default-language: Haskell2010   if flag(build-examples)     buildable: True -    build-depends: base                      >= 4.6+    build-depends: base                  , shelly                  , text -    extensions:+    default-extensions:       CPP   else     buildable: False@@ -189,10 +206,11 @@ Executable Color   hs-source-dirs: test/examples   main-is: color.hs+  default-language: Haskell2010   if flag(build-examples)     buildable: True -    build-depends: base                      >= 4.6+    build-depends: base                  , process                  , shelly                  , text
src/Shelly.hs view
@@ -1,6 +1,10 @@-{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable, OverloadedStrings,-             FlexibleInstances, IncoherentInstances,-             TypeFamilies, ExistentialQuantification #-}+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE IncoherentInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}  -- | A module for shell-like programming in Haskell. -- Shelly's focus is entirely on ease of use for those coming from shell scripting.@@ -20,16 +24,17 @@ -- > import Shelly -- > import qualified Data.Text as T -- > default (T.Text)+ module Shelly        (-         -- * Entering Sh.+         -- * Entering Sh          Sh, ShIO, shelly, shellyNoDir, shellyFailDir, asyncSh, sub          , silently, verbosely, escaping, print_stdout, print_stderr, print_commands          , onCommandHandles          , tracing, errExit          , log_stdout_with, log_stderr_with -         -- * Running external commands.+         -- * Running external commands          , run, run_, runFoldLines, cmd, FoldCallback          , bash, bash_, bashPipeFail          , (-|-), lastStderr, setStdin, lastExitCode@@ -45,7 +50,7 @@          -- * Handle manipulation          , HandleInitializer, StdInit(..), initOutputHandles, initAllHandles -         -- * Modifying and querying environment.+         -- * Modifying and querying environment          , setenv, get_env, get_env_text, getenv, get_env_def, get_env_all, get_environment, appendToPath, prependToPath           -- * Environment directory@@ -55,14 +60,14 @@          , echo, echo_n, echo_err, echo_n_err, inspect, inspect_err          , tag, trace, show_command -         -- * Querying filesystem.+         -- * Querying filesystem          , ls, lsT, test_e, test_f, test_d, test_s, test_px, which           -- * Filename helpers          , absPath, (</>), (<.>), canonic, canonicalize, relPath, relativeTo, path          , hasExt -         -- * Manipulating filesystem.+         -- * Manipulating filesystem          , mv, rm, rm_f, rm_rf, cp, cp_r, mkdir, mkdir_p, mkdirTree           -- * reading/writing Files@@ -96,61 +101,57 @@ import Shelly.Base import Shelly.Directory import Shelly.Find++import Control.Applicative+import Control.Concurrent+import Control.Concurrent.Async (async, wait, Async)+import Control.Exception import Control.Monad ( when, unless, void, forM, filterM, liftM2 ) import Control.Monad.Trans ( MonadIO ) import Control.Monad.Reader (ask)-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706-import Prelude hiding ( readFile, FilePath, catch)-#else-import Prelude hiding ( readFile, FilePath)++import Data.ByteString ( ByteString )+import Data.Char       ( isAlphaNum, isDigit, isSpace )+#if defined(mingw32_HOST_OS)+import Data.Char       ( toLower ) #endif-import Data.Char ( isAlphaNum, isSpace, toLower )-import Data.Typeable+import Data.Foldable   ( toList ) import Data.IORef-import Data.Sequence (Seq, (|>))-import Data.Foldable (toList) import Data.Maybe-import System.IO ( hClose, stderr, stdout, openTempFile)-import System.IO.Error (isPermissionError, catchIOError, isEOFError, isIllegalOperation)-import System.Exit-import System.Environment-import Control.Applicative-import Control.Exception-import Control.Concurrent-import Control.Concurrent.Async (async, wait, Async)-import Data.Time.Clock( getCurrentTime, diffUTCTime  )+#if !MIN_VERSION_base(4,11,0)+import Data.Semigroup  ( (<>) )+#endif+import Data.Sequence   ( Seq, (|>) )+import Data.Set        ( Set )+import Data.Time.Clock ( getCurrentTime, diffUTCTime  )+import Data.Tree       ( Tree(..) )+import Data.Typeable +import qualified Data.ByteString as BS+import qualified Data.List as List+import qualified Data.Set as Set+import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Data.Text.Encoding as TE import qualified Data.Text.Encoding.Error as TE-import System.Process( CmdSpec(..), StdStream(CreatePipe, UseHandle), CreateProcess(..), createProcess, waitForProcess, terminateProcess, ProcessHandle, StdStream(..) ) -import qualified Data.Text as T-import qualified Data.ByteString as BS-import Data.ByteString (ByteString)--import Data.Monoid (Monoid, mempty, mappend)-#if __GLASGOW_HASKELL__ < 704-infixr 5 <>-(<>) :: Monoid m => m -> m -> m-(<>) = mappend-#else-import Data.Monoid ((<>))-#endif-+import System.Directory+  ( setPermissions, getPermissions, Permissions(..), getTemporaryDirectory, pathIsSymbolicLink+  , copyFile, removeFile, doesFileExist, doesDirectoryExist, listDirectory+  , renameFile, renameDirectory, removeDirectoryRecursive, createDirectoryIfMissing+  , getCurrentDirectory+  )+import System.Environment+import System.Exit import System.FilePath hiding ((</>), (<.>)) import qualified System.FilePath as FP--import System.Directory ( setPermissions, getPermissions, Permissions(..), getTemporaryDirectory, pathIsSymbolicLink-                        , copyFile, removeFile, doesFileExist, doesDirectoryExist, listDirectory-                        , renameFile, renameDirectory, removeDirectoryRecursive, createDirectoryIfMissing-                        , getCurrentDirectory )-import System.IO (Handle)-import Data.Char (isDigit)--import Data.Tree(Tree(..))-import qualified Data.Set as S-import qualified Data.List as L+import System.IO ( Handle, hClose, stderr, stdout, openTempFile)+import System.IO.Error (isPermissionError, catchIOError, isEOFError, isIllegalOperation)+import System.Process+  ( CmdSpec(..), StdStream(CreatePipe, UseHandle), CreateProcess(..)+  , createProcess, waitForProcess, terminateProcess+  , ProcessHandle, StdStream(..)+  )  {- GHC won't default to Text with this, even with extensions!  - see: http://hackage.haskell.org/trac/ghc/ticket/6030@@ -176,14 +177,14 @@ -}  -- | Argument converter for the variadic argument version of 'run' called 'cmd'.--- Useful for a type signature of a function that uses 'cmd'+-- Useful for a type signature of a function that uses 'cmd'. class CmdArg a where toTextArg :: a -> Text instance CmdArg Text     where toTextArg = id instance CmdArg String   where toTextArg = T.pack --- | For the variadic function 'cmd'+-- | For the variadic function 'cmd'. ----- partially applied variadic functions require type signatures+-- Partially applied variadic functions require type signatures. class ShellCmd t where     cmdAll :: FilePath -> [Text] -> t @@ -205,12 +206,13 @@   --- | variadic argument version of 'run'.+-- | Variadic argument version of 'run'. -- Please see the documenation for 'run'. ----- The syntax is more convenient, but more importantly it also allows the use of a FilePath as a command argument.--- So an argument can be a Text or a FilePath without manual conversions.--- a FilePath is automatically converted to Text with 'toTextIgnore'.+-- The syntax is more convenient, but more importantly+-- it also allows the use of a 'FilePath' as a command argument.+-- So an argument can be a 'Text' or a 'FilePath' without manual conversions.+-- a 'FilePath' is automatically converted to 'Text' with 'toTextIgnore'. -- -- Convenient usage of 'cmd' requires the following: --@@ -224,7 +226,7 @@ cmd :: (ShellCmd result) => FilePath -> result cmd fp = cmdAll fp [] --- | Convert Text to a FilePath-+-- | Convert 'Text' to a 'FilePath'. fromText :: Text -> FilePath fromText = T.unpack @@ -236,11 +238,11 @@ instance ToFilePath Text     where toFilePath = T.unpack  --- | uses System.FilePath, but can automatically convert a Text+-- | Uses "System.FilePath", but can automatically convert a 'Text'. (</>) :: (ToFilePath filepath1, ToFilePath filepath2) => filepath1 -> filepath2 -> FilePath x </> y = toFilePath x FP.</> toFilePath y --- | uses System.FilePath, but can automatically convert a Text+-- | Uses "System.FilePath", but can automatically convert a 'Text'. (<.>) :: (ToFilePath filepath) => filepath -> Text -> FilePath x <.> y = toFilePath x FP.<.> T.unpack y @@ -254,7 +256,7 @@  -- | Transfer from one handle to another -- For example, send contents of a process output to stdout.--- does not close the write handle.+-- Does not close the write handle. -- -- Also, return the complete contents being streamed line by line. transferLinesAndCombine :: Handle -> (Text -> IO ()) -> IO Text@@ -270,9 +272,9 @@  -- | Transfer from one handle to another -- For example, send contents of a process output to stdout.--- does not close the write handle.+-- Does not close the write handle. ----- Also, fold over the contents being streamed line by line+-- Also, fold over the contents being streamed line by line. transferFoldHandleLines :: a -> FoldCallback a -> Handle -> (Text -> IO ()) -> IO a transferFoldHandleLines start foldLine readHandle putWrite = go start   where@@ -298,7 +300,7 @@         Nothing -> return acc         Just line -> go $ foldLine acc line --- | same as 'trace', but use it combinator style+-- | Same as 'trace', but for use in combinator style: @action `tag` message@. tag :: Sh a -> Text -> Sh a tag action msg = do   trace msg@@ -320,7 +322,7 @@   where     findExe :: FilePath -> Sh FilePath     findExe-#if defined(mingw32_HOST_OS) || (defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708)+#if defined(mingw32_HOST_OS)       fp #else       _fp@@ -335,14 +337,14 @@           -- non-Windows < 7.8 has a bug for read-only file systems           -- https://github.com/yesodweb/Shelly.hs/issues/56           -- it would be better to specifically detect that bug-#if defined(mingw32_HOST_OS) || (defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708)+#if defined(mingw32_HOST_OS)           Left _ -> return fp #else           Left err -> liftIO $ throwIO $ userError err #endif  -+-- process >= 1.4 is used  shellyProcess :: [StdHandle] -> State -> CmdSpec -> IO (Handle, Handle, Handle, ProcessHandle) shellyProcess reusedHandles st cmdSpec =  do@@ -354,21 +356,13 @@         , std_out = createUnless mOutH         , std_err = createUnless mErrorH         , close_fds = False-#if MIN_VERSION_process(1,1,0)         , create_group = False-#endif-#if MIN_VERSION_process(1,2,0)         , delegate_ctlc = False-#endif-#if MIN_VERSION_process(1,3,0)         , detach_console = False         , create_new_console = False         , new_session = False-#endif-#if MIN_VERSION_process(1,4,0)         , child_group = Nothing         , child_user = Nothing-#endif #if MIN_VERSION_process(1,5,0)         , use_process_jobs = False #endif@@ -386,6 +380,7 @@     toHandle (Just (UseHandle h)) = Just h     toHandle (Just CreatePipe)    = error "shelly process creation failure CreatePipe"     toHandle (Just Inherit)       = error "cannot access an inherited pipe"+    toHandle (Just NoStream)      = error "shelly process creation failure NoStream"     toHandle Nothing              = error "error in shelly creating process"      createUnless Nothing = CreatePipe@@ -458,16 +453,16 @@     toHandler :: (Sh a -> IO a) -> ShellyHandler a -> Handler a     toHandler runner (ShellyHandler handler) = Handler (\e -> runner (handler e)) --- | Catch any exception in the Sh monad.+-- | Catch any exception in the 'Sh' monad. catchany_sh :: Sh a -> (SomeException -> Sh a) -> Sh a catchany_sh = catch_sh --- | Handle any exception in the Sh monad.+-- | Handle any exception in the 'Sh' monad. handleany_sh :: (SomeException -> Sh a) -> Sh a -> Sh a handleany_sh = handle_sh --- | Change current working directory of Sh. This does *not* change the--- working directory of the process we are running it. Instead, Sh keeps+-- | Change current working directory of 'Sh'. This does /not/ change the+-- working directory of the process we are running it. Instead, 'Sh' keeps -- track of its own working directory and builds absolute paths internally -- instead of passing down relative paths. cd :: FilePath -> Sh ()@@ -479,28 +474,19 @@       where         tdir = toTextIgnore dir --- | 'cd', execute a Sh action in the new directory and then pop back to the original directory+-- | 'cd', execute a 'Sh' action in the new directory+-- and then pop back to the original directory. chdir :: FilePath -> Sh a -> Sh a chdir dir action = do   d <- gets sDirectory   cd dir   action `finally_sh` cd d --- | 'chdir', but first create the directory if it does not exit+-- | 'chdir', but first create the directory if it does not exit. chdir_p :: FilePath -> Sh a -> Sh a chdir_p d action = mkdir_p d >> chdir d action  --- | apply a String IO operations to a Text FilePath-{--liftStringIO :: (String -> IO String) -> FilePath -> Sh FilePath-liftStringIO f = liftIO . f . unpack >=> return . pack---- | @asString f = pack . f . unpack@-asString :: (String -> String) -> FilePath -> FilePath-asString f = pack . f . unpack--}- pack :: String -> FilePath pack = id @@ -516,7 +502,7 @@   to_dir <- test_d to   let to_loc = if not to_dir then to else to FP.</> (FP.takeFileName from)   liftIO $ createDirectoryIfMissing True (takeDirectory to_loc)-  if not from_dir +  if not from_dir     then liftIO $ renameFile from to_loc       `catchany` (\e -> throwIO $         ReThrownException e (extraMsg to_loc from)@@ -529,29 +515,29 @@     extraMsg :: String -> String -> String     extraMsg t f = "during copy from: " ++ f ++ " to: " ++ t --- | Get back [Text] instead of [FilePath]+-- | Get back @[Text]@ instead of @[FilePath]@. lsT :: FilePath -> Sh [Text] lsT = ls >=> mapM toTextWarn --- | Obtain the current (Sh) working directory.+-- | Obtain the current 'Sh' working directory. pwd :: Sh FilePath pwd = gets sDirectory `tag` "pwd" --- | exit 0 means no errors, all other codes are error conditions+-- | @'exit' 0@ means no errors, all other codes are error conditions. exit :: Int -> Sh a exit 0 = liftIO exitSuccess `tag` "exit 0" exit n = liftIO (exitWith (ExitFailure n)) `tag` ("exit " <> T.pack (show n)) --- | echo a message and exit with status 1+-- | Echo a message and 'exit' with status 1. errorExit :: Text -> Sh a errorExit msg = echo msg >> exit 1 --- | for exiting with status > 0 without printing debug information+-- | For exiting with status > 0 without printing debug information. quietExit :: Int -> Sh a quietExit 0 = exit 0 quietExit n = throw $ QuietExit n --- | fail that takes a Text+-- | 'fail' that takes a 'Text'. terror :: Text -> Sh a terror = fail . T.unpack @@ -609,9 +595,9 @@ whichEith :: FilePath -> Sh (Either String FilePath) whichEith originalFp = whichFull #if defined(mingw32_HOST_OS)-    $ case extension originalFp of-        Nothing -> originalFp <.> "exe"-        Just _ -> originalFp+    $ case takeExtension originalFp of+        "" -> originalFp <.> "exe"+        _ -> originalFp #else     originalFp #endif@@ -655,12 +641,12 @@         lookupCache = do             pathExecutables <- cachedPathExecutables             return $ fmap (flip (</>) fp . fst) $-                L.find (S.member fp . snd) pathExecutables+                List.find (Set.member fp . snd) pathExecutables           pathDirs = mapM absPath =<< ((map T.unpack . filter (not . T.null) . T.split (== searchPathSeparator)) `fmap` get_env_text "PATH") -        cachedPathExecutables :: Sh [(FilePath, S.Set FilePath)]+        cachedPathExecutables :: Sh [(FilePath, Set FilePath)]         cachedPathExecutables = do           mPathExecutables <- gets sPathExecutables           case mPathExecutables of@@ -671,7 +657,7 @@                     files <- (liftIO . listDirectory) dir `catch_sh` (\(_ :: IOError) -> return [])                     exes <- fmap (map snd) $ liftIO $ filterM (isExecutable . fst) $                       map (\f -> (f, takeFileName f)) files-                    return $ S.fromList exes+                    return $ Set.fromList exes                   )                 let cachedExecutables = zip dirs executables                 modify $ \x -> x { sPathExecutables = Just cachedExecutables }@@ -763,15 +749,15 @@ path_env :: Text path_env = normalizeEnvVarNameText "PATH" --- | add the filepath onto the PATH env variable+-- | Add the filepath onto the PATH env variable. appendToPath :: FilePath -> Sh () appendToPath = traceAbsPath ("appendToPath: " <>) >=> \filepath -> do   tp <- toTextWarn filepath   pe <- get_env_text path_env   setPath $ pe <> T.singleton searchPathSeparator <> tp --- | prepend the filepath to the PATH env variable--- similar to 'appendToPath' but gives high priority to the filepath instead of low priority.+-- | Prepend the filepath to the PATH env variable.+-- Similar to 'appendToPath' but gives high priority to the filepath instead of low priority. prependToPath :: FilePath -> Sh () prependToPath = traceAbsPath ("prependToPath: " <>) >=> \filepath -> do   tp <- toTextWarn filepath@@ -782,33 +768,22 @@ get_environment = gets sEnvironment {-# DEPRECATED get_environment "use get_env_all" #-} --- | get the full environment+-- | Get the full environment. get_env_all :: Sh [(String, String)] get_env_all = gets sEnvironment +normalizeEnvVarNameText :: Text -> Text+#if defined(mingw32_HOST_OS) -- On Windows, normalize all environment variable names (to lowercase) -- to account for case insensitivity.-#if defined(mingw32_HOST_OS)--normalizeEnvVarNameText :: Text -> Text normalizeEnvVarNameText = T.toLower--normalizeEnvVarNameString :: String -> String-normalizeEnvVarNameString = fmap toLower---- On other systems, keep the variable names as-is. #else--normalizeEnvVarNameText :: Text -> Text+-- On other systems, keep the variable names as-is. normalizeEnvVarNameText = id--normalizeEnvVarNameString :: String -> String-normalizeEnvVarNameString = id- #endif  -- | Fetch the current value of an environment variable.--- if non-existant or empty text, will be Nothing+-- If non-existant or empty text, will be 'Nothing'. get_env :: Text -> Sh (Maybe Text) get_env k = do   mval <- return@@ -821,7 +796,6 @@   where   normK = normalizeEnvVarNameText k --- | deprecated getenv :: Text -> Sh Text getenv k = get_env_def k "" {-# DEPRECATED getenv "use get_env or get_env_text" #-}@@ -832,16 +806,16 @@ get_env_text = get_env_def ""  -- | Fetch the current value of an environment variable. Both empty and--- non-existent variables give the default Text value as a result+-- non-existent variables give the default 'Text' value as a result. get_env_def :: Text -> Text -> Sh Text get_env_def d = get_env >=> return . fromMaybe d {-# DEPRECATED get_env_def "use fromMaybe DEFAULT get_env" #-} --- | Apply a single initializer to the two output process handles (stdout and stderr)+-- | Apply a single initializer to the two output process handles (stdout and stderr). initOutputHandles :: HandleInitializer -> StdInit initOutputHandles f = StdInit (const $ return ()) f f --- | Apply a single initializer to all three standard process handles (stdin, stdout and stderr)+-- | Apply a single initializer to all three standard process handles (stdin, stdout and stderr). initAllHandles :: HandleInitializer -> StdInit initAllHandles f = StdInit f f f @@ -929,8 +903,8 @@        }  -- | Create a sub-Sh where commands are not traced--- Defaults to True.--- You should only set to False temporarily for very specific reasons+-- Defaults to @True@.+-- You should only set to @False@ temporarily for very specific reasons. tracing :: Bool -> Sh a -> Sh a tracing shouldTrace action = sub $ do   modify $ \st -> st { sTracing = shouldTrace }@@ -985,7 +959,7 @@ #if defined(mingw32_HOST_OS)   -- On Windows, normalize all environment variable names (to lowercase)   -- to account for case insensitivity.-  fmap (\(a, b) -> (normalizeEnvVarNameString a, b)) <$> getEnvironment+  fmap (\(a, b) -> (map toLower a, b)) <$> getEnvironment #else   -- On other systems, keep the environment as-is.   getEnvironment@@ -1106,19 +1080,18 @@  data SshMode = ParSsh | SeqSsh --- | same as 'sshPairs', but returns ()+-- | Same as 'sshPairs', but returns @()@. sshPairs_ :: Text -> [(FilePath, [Text])] -> Sh () sshPairs_ _ [] = return () sshPairs_ server cmds = sshPairs' run_ server cmds --- | same as 'sshPairsP', but returns ()-+-- | Same as 'sshPairsPar', but returns @()@. sshPairsPar_ :: Text -> [(FilePath, [Text])] -> Sh () sshPairsPar_ _ [] = return () sshPairsPar_ server cmds = sshPairsPar' run_ server cmds --- | run commands over SSH.--- An ssh executable is expected in your path.+-- | Run commands over SSH.+-- An @ssh@ executable is expected in your path. -- Commands are in the same form as 'run', but given as pairs -- -- > sshPairs "server-name" [("cd", "dir"), ("rm",["-r","dir2"])]@@ -1132,12 +1105,13 @@ -- if there are a single or double quotes in your arguments, they need not -- to be quoted manually. ----- Internally the list of commands are combined with the string @&&@ before given to ssh.+-- Internally the list of commands are combined with the string @&&@ before given to @ssh@. sshPairs :: Text -> [(FilePath, [Text])] -> Sh Text sshPairs _ [] = return "" sshPairs server cmds = sshPairsWithOptions' run server [] cmds SeqSsh --- | Same as sshPairs, but combines commands with the string @&@, so they will be started in parallell.+-- | Same as 'sshPairs', but combines commands with the string @&@,+-- so they will be started in parallel. sshPairsPar :: Text -> [(FilePath, [Text])] -> Sh Text sshPairsPar _ [] = return "" sshPairsPar server cmds = sshPairsWithOptions' run server [] cmds ParSsh@@ -1148,9 +1122,9 @@ sshPairs' :: (FilePath -> [Text] -> Sh a) -> Text -> [(FilePath, [Text])] -> Sh a sshPairs' run' server actions = sshPairsWithOptions' run' server [] actions SeqSsh --- | Like 'sshPairs', but allows for arguments to the call to ssh.+-- | Like 'sshPairs', but allows for arguments to the call to @ssh@. sshPairsWithOptions :: Text                  -- ^ Server name.-                    -> [Text]                -- ^ Arguments to ssh (e.g. ["-p","22"]).+                    -> [Text]                -- ^ Arguments to @ssh@ (e.g. @["-p","22"]@).                     -> [(FilePath, [Text])]  -- ^ Pairs of commands to run on the remote.                     -> Sh Text               -- ^ Returns the standard output. sshPairsWithOptions _ _ [] = return ""@@ -1186,7 +1160,7 @@ -- -- 'stdout' and 'stderr' are collected. The 'stdout' is returned as -- a result of 'run', and complete stderr output is available after the fact using--- 'lastStderr'+-- 'lastStderr'. If the output does not end with a newline, it is automatically added. -- -- All of the stdout output will be loaded into memory. -- You can avoid this if you don't need stdout by using 'run_',@@ -1201,12 +1175,12 @@ -- given, Shelly cannot look in the @PATH@ for it. -- a @PATH@ modified by setenv is not taken into account when finding the exe name. -- Instead the original Haskell program @PATH@ is used.--- On a Posix system the @env@ command can be used to make the 'setenv' PATH used when 'escaping' is set to False. @env echo hello@ instead of @echo hello@+-- On a Posix system the @env@ command can be used to make the 'setenv' PATH used when 'escaping' is set to False. @env echo hello@ instead of @echo hello@. -- run :: FilePath -> [Text] -> Sh Text run fp args = return . lineSeqToText =<< runFoldLines mempty (|>) fp args --- | Like 'run', but it invokes the user-requested program with _bash_.+-- | Like 'run', but it invokes the user-requested program with @bash@. bash :: FilePath -> [Text] -> Sh Text bash fp args = escaping False $ run "bash" $ bashArgs fp args @@ -1218,42 +1192,42 @@   where     sanitise = T.replace "'" "\'" . T.intercalate " " --- | Use this with 'bash' to set _pipefail_+-- | Use this with 'bash' to set @pipefail@. -- -- > bashPipeFail $ bash "echo foo | echo" bashPipeFail :: (FilePath -> [Text] -> Sh a) -> FilePath -> [Text] -> Sh a bashPipeFail runner fp args = runner "set -o pipefail;" (toTextIgnore fp : args) --- | bind some arguments to 'run' for re-use. Example:+-- | Bind some arguments to 'run' for re-use. Example: -- -- > monit = command "monit" ["-c", "monitrc"] -- > monit ["stop", "program"] command :: FilePath -> [Text] -> [Text] -> Sh Text command com args more_args = run com (args ++ more_args) --- | bind some arguments to 'run_' for re-use. Example:+-- | Bind some arguments to 'run_' for re-use. Example: -- -- > monit_ = command_ "monit" ["-c", "monitrc"] -- > monit_ ["stop", "program"] command_ :: FilePath -> [Text] -> [Text] -> Sh () command_ com args more_args = run_ com (args ++ more_args) --- | bind some arguments to 'run' for re-use, and require 1 argument. Example:+-- | Bind some arguments to 'run' for re-use, and require 1 argument. Example: -- -- > git = command1 "git" [] -- > git "pull" ["origin", "master"] command1 :: FilePath -> [Text] -> Text -> [Text] -> Sh Text command1 com args one_arg more_args = run com (args ++ [one_arg] ++ more_args) --- | bind some arguments to 'run_' for re-use, and require 1 argument. Example:+-- | Bind some arguments to 'run_' for re-use, and require 1 argument. Example: -- -- > git_ = command1_ "git" [] -- > git "pull" ["origin", "master"] command1_ :: FilePath -> [Text] -> Text -> [Text] -> Sh () command1_ com args one_arg more_args = run_ com (args ++ [one_arg] ++ more_args) --- | the same as 'run', but return @()@ instead of the stdout content--- stdout will be read and discarded line-by-line+-- | The same as 'run', but return @()@ instead of the stdout content.+-- The stdout will be read and discarded line-by-line. run_ :: FilePath -> [Text] -> Sh () run_ exe args = do     state <- get@@ -1278,9 +1252,9 @@  -- | Similar to 'run' but gives the raw stdout handle in a callback. -- If you want even more control, use 'runHandles'.-runHandle :: FilePath -- ^ command-          -> [Text] -- ^ arguments-          -> (Handle -> Sh a) -- ^ stdout handle+runHandle :: FilePath         -- ^ Command.+          -> [Text]           -- ^ Arguments.+          -> (Handle -> Sh a) -- ^ 'stdout' handle.           -> Sh a runHandle exe args withHandle = runHandles exe args [] $ \_ outH errH -> do     state <- get@@ -1294,13 +1268,14 @@ -- | Similar to 'run' but gives direct access to all input and output handles. -- -- Be careful when using the optional input handles.--- If you specify Inherit for a handle then attempting to access the handle in your--- callback is an error-runHandles :: FilePath -- ^ command-           -> [Text] -- ^ arguments-           -> [StdHandle] -- ^ optionally connect process i/o handles to existing handles-           -> (Handle -> Handle -> Handle -> Sh a) -- ^ stdin, stdout and stderr-           -> Sh a+-- If you specify 'Inherit' for a handle then attempting to access the handle in your+-- callback is an error.+runHandles+  :: FilePath                             -- ^ Command.+  -> [Text]                               -- ^ Arguments.+  -> [StdHandle]                          -- ^ Optionally connect process i/o handles to existing handles.+  -> (Handle -> Handle -> Handle -> Sh a) -- ^ 'stdin', 'stdout' and 'stderr'.+  -> Sh a runHandles exe args reusedHandles withHandles = do     -- clear stdin before beginning command execution     origstate <- get@@ -1352,8 +1327,8 @@       )  --- | used by 'run'. fold over stdout line-by-line as it is read to avoid keeping it in memory--- stderr is still being placed in memory under the assumption it is always relatively small+-- | Used by 'run'. Folds over 'stdout' line-by-line as it is read to avoid keeping it in memory.+-- 'stderr' is still being placed in memory under the assumption it is always relatively small. runFoldLines :: a -> FoldCallback a -> FilePath -> [Text] -> Sh a runFoldLines start cb exe args =   runHandles exe args [] $ \inH outH errH -> do@@ -1368,11 +1343,12 @@     liftIO $ wait outVar  -putHandleIntoMVar :: a -> FoldCallback a-                  -> Handle -- ^ out handle-                  -> (Text -> IO ()) -- ^ in handle-                  -> Bool  -- ^ should it be printed while transfered?-                  -> IO (Async a)+putHandleIntoMVar+  :: a -> FoldCallback a+  -> Handle           -- ^ Out handle.+  -> (Text -> IO ())  -- ^ In handle.+  -> Bool             -- ^ Should it be printed while transfered?+  -> IO (Async a) putHandleIntoMVar start cb outH putWrite shouldPrint = liftIO $ async $ do   if shouldPrint     then transferFoldHandleLines start cb outH putWrite@@ -1388,11 +1364,11 @@ lastExitCode :: Sh Int lastExitCode = gets sCode --- | set the stdin to be used and cleared by the next 'run'.+-- | Set the 'stdin' to be used and cleared by the next 'run'. setStdin :: Text -> Sh () setStdin input = modify $ \st -> st { sStdin = Just input } --- | Pipe operator. set the stdout the first command as the stdin of the second.+-- | Pipe operator. Set the 'stdout' the first command as the 'stdin' of the second. -- This does not create a shell-level pipe, but hopefully it will in the future. -- To create a shell level pipe you can set @escaping False@ and use a pipe @|@ character in a command. (-|-) :: Sh Text -> Sh b -> Sh b@@ -1402,7 +1378,7 @@   two  -- | Copy a file, or a directory recursively.--- uses 'cp'+-- Uses 'cp'. cp_r :: FilePath -> FilePath -> Sh () cp_r from' to' = do     from <- absPath from'@@ -1415,11 +1391,11 @@        when (from == to) $ liftIO $ throwIO $ userError $ show $ "cp_r: " <>          toTextIgnore from <> " and " <> toTextIgnore to <> " are identical" -       finalTo <- if not toIsDir then do -            mkdir to -            return to +       finalTo <- if not toIsDir then do+            mkdir to+            return to           else do-            -- this takes the name of the from directory +            -- this takes the name of the from directory             -- because filepath has no builtin function like `dirname`             let d = to </> (last . splitPath $ takeDirectory (addTrailingPathSeparator from))             mkdir_p d >> return d@@ -1450,7 +1426,7 @@           ReThrownException e (extraMsg to from)         ) --- | Create a temporary directory and pass it as a parameter to a Sh+-- | Create a temporary directory and pass it as a parameter to a 'Sh' -- computation. The directory is nuked afterwards. withTmpDir :: (FilePath -> Sh a) -> Sh a withTmpDir act = do@@ -1464,7 +1440,7 @@   mkdir p   act p `finally_sh` rm_rf p --- | Write a Text to a file.+-- | Write a 'Text' to a file. writefile :: FilePath -> Text -> Sh () writefile f' bits = do   f <- traceAbsPath ("writefile " <>) f'@@ -1479,7 +1455,7 @@ touchfile :: FilePath -> Sh () touchfile = traceAbsPath ("touch " <>) >=> flip appendfile "" --- | Append a Text to a file.+-- | Append a 'Text' to a file. appendfile :: FilePath -> Text -> Sh () appendfile f' bits = do   f <- traceAbsPath ("appendfile " <>) f'@@ -1490,17 +1466,17 @@   readBinary fp >>=     return . TE.decodeUtf8With TE.lenientDecode --- | wraps ByteSting readFile+-- | Wraps 'BS.readFile'. readBinary :: FilePath -> Sh ByteString readBinary = traceAbsPath ("readBinary " <>)          >=> liftIO . BS.readFile --- | flipped hasExtension for Text+-- | Flipped 'hasExtension' for 'Text'. hasExt :: Text -> FilePath -> Bool hasExt ext fp = T.pack (FP.takeExtension fp) == ext --- | Run a Sh computation and collect timing information.---   The value returned is the amount of _real_ time spent running the computation+-- | Run a 'Sh' computation and collect timing information.+--   The value returned is the amount of *real* time spent running the computation --   in seconds, as measured by the system clock. --   The precision is determined by the resolution of `getCurrentTime`. time :: Sh a -> Sh (Double, a)@@ -1511,11 +1487,11 @@   t' <- liftIO getCurrentTime   return (realToFrac $ diffUTCTime t' t, res) --- | threadDelay wrapper that uses seconds+-- | 'threadDelay' wrapper that uses seconds. sleep :: Int -> Sh () sleep = liftIO . threadDelay . (1000 * 1000 *) --- | spawn an asynchronous action with a copy of the current state+-- | Spawn an asynchronous action with a copy of the current state. asyncSh :: Sh a -> Sh (Async a) asyncSh proc = do   state <- get
src/Shelly/Base.hs view
@@ -9,9 +9,7 @@ {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE InstanceSigs#-}--- | I started exposing multiple module (starting with one for finding)--- Base prevented circular dependencies--- However, Shelly went back to exposing a single module+ module Shelly.Base   (     Sh(..), ShIO, runSh, State(..), ReadOnlyState(..), StdHandle(..),@@ -31,30 +29,24 @@     , addTrailingSlash   ) where -#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706-import Prelude hiding (FilePath, catch)-#else-import Prelude hiding (FilePath)-#endif- import Data.Text (Text)-import System.Process( ProcessHandle, StdStream(..) )+import System.Process( StdStream(..) ) import System.IO ( Handle, hFlush, stderr, stdout ) -import Control.Monad (when, (>=>),-         liftM-       )+import Control.Monad ( when, (>=>) )+#if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail (MonadFail)+import Control.Applicative (Applicative, (<$>))+import Data.Monoid (mappend)+#endif import Control.Monad.Base import Control.Monad.Trans.Control-import Control.Applicative (Applicative, (<$>)) import System.Directory( doesDirectoryExist, listDirectory) import System.PosixCompat.Files( getSymbolicLinkStatus, isSymbolicLink )-import System.FilePath  ( FilePath, isRelative)+import System.FilePath  ( isRelative) import qualified System.FilePath as FP import qualified System.Directory as FS import Data.IORef (readIORef, modifyIORef, IORef)-import Data.Monoid (mappend) import qualified Data.Text as T import qualified Data.Text.IO as TIO import Control.Exception (SomeException, catch, throwIO, Exception)@@ -130,10 +122,10 @@                | OutHandle StdStream                | ErrorHandle StdStream --- | Initialize a handle before using it+-- | Initialize a handle before using it. type HandleInitializer = Handle -> IO () --- | A collection of initializers for the three standard process handles+-- | A collection of initializers for the three standard process handles. data StdInit =     StdInit {       inInit :: HandleInitializer,@@ -141,13 +133,13 @@       errInit :: HandleInitializer     } --- | A monadic-conditional version of the "when" guard.+-- | A monadic-conditional version of the 'when' guard. whenM :: Monad m => m Bool -> m () -> m () whenM c a = c >>= \res -> when res a --- | Makes a relative path relative to the current Sh working directory.+-- | Makes a relative path relative to the current 'Sh' working directory. -- An absolute path is returned as is.--- To create an absolute path, use 'absPath'+-- To create an absolute path, use 'absPath'. relPath :: FilePath -> Sh FilePath relPath fp = do   wd  <- gets sDirectory@@ -156,9 +148,10 @@     Right p -> p     Left  p -> p -eitherRelativeTo :: FilePath -- ^ anchor path, the prefix-                 -> FilePath -- ^ make this relative to anchor path-                 -> Sh (Either FilePath FilePath) -- ^ Left is canonic of second path+eitherRelativeTo+  :: FilePath                       -- ^ Anchor path, the prefix.+  -> FilePath                       -- ^ Make this relative to anchor path.+  -> Sh (Either FilePath FilePath)  -- ^ 'Left' is canonic of second path. eitherRelativeTo relativeFP fp = do   let fullFp = relativeFP FP.</> fp   let relDir = addTrailingSlash relativeFP@@ -177,20 +170,20 @@       -> Sh (Either FilePath FilePath)     stripIt rel toStrip nada =       let stripped = FP.makeRelative rel toStrip-      in if stripped == toStrip -        then nada +      in if stripped == toStrip+        then nada         else return $ Right stripped --- | make the second path relative to the first--- Uses 'Filesystem.stripPrefix', but will canonicalize the paths if necessary-relativeTo :: FilePath -- ^ anchor path, the prefix-           -> FilePath -- ^ make this relative to anchor path+-- | Make the second path relative to the first.+-- Will canonicalize the paths if necessary.+relativeTo :: FilePath -- ^ Anchor path, the prefix.+           -> FilePath -- ^ Make this relative to anchor path.            -> Sh FilePath relativeTo relativeFP fp =   fmap (fromMaybe fp) $ maybeRelativeTo relativeFP fp -maybeRelativeTo :: FilePath -- ^ anchor path, the prefix-                 -> FilePath -- ^ make this relative to anchor path+maybeRelativeTo :: FilePath  -- ^ Anchor path, the prefix.+                 -> FilePath -- ^ Make this relative to anchor path.                  -> Sh (Maybe FilePath) maybeRelativeTo relativeFP fp = do   epath <- eitherRelativeTo relativeFP fp@@ -199,23 +192,23 @@              Left _ -> Nothing  --- | add a trailing slash to ensure the path indicates a directory+-- | Add a trailing slash to ensure the path indicates a directory. addTrailingSlash :: FilePath -> FilePath addTrailingSlash = FP.addTrailingPathSeparator --- | makes an absolute path.--- Like 'canonicalize', but on an exception returns 'absPath'+-- | Make an absolute path.+-- Like 'canonicalize', but on an exception returns 'absPath'. canonic :: FilePath -> Sh FilePath canonic fp = do   p <- absPath fp   liftIO $ canonicalizePath p `catchany` \_ -> return p  -- | Obtain a (reasonably) canonic file path to a filesystem object. Based on--- "canonicalizePath" in system-fileio.+-- 'canonicalizePath'. canonicalize :: FilePath -> Sh FilePath canonicalize = absPath >=> liftIO . canonicalizePath --- | bugfix older version of canonicalizePath (system-fileio <= 0.3.7) loses trailing slash+-- | Version of 'FS.canonicalizePath' that keeps a trailing slash. canonicalizePath :: FilePath -> IO FilePath canonicalizePath p = let was_dir = null (FP.takeFileName p) in    if not was_dir then FS.canonicalizePath p@@ -231,12 +224,11 @@ -- To create a relative path, use 'relPath'. absPath :: FilePath -> Sh FilePath absPath p | null p = liftIO $ throwIO EmptyFilePathError-          | isRelative p = do +          | isRelative p = do             cwd <-  gets sDirectory             return (cwd FP.</> p)           | otherwise = return p --- | deprecated path :: FilePath -> Sh FilePath path = absPath {-# DEPRECATED path "use absPath, canonic, or relPath instead" #-}@@ -267,14 +259,14 @@   state <- ask   liftIO (modifyIORef state f) --- | internally log what occurred.+-- | Internally log what occurred. -- Log will be re-played on failure. trace :: Text -> Sh () trace msg =   whenM (gets sTracing) $ modify $     \st -> st { sTrace = sTrace st `mappend` msg `mappend` "\n" } --- | List directory contents. Does *not* include \".\" and \"..\", but it does+-- | List directory contents. Does /not/ include @.@ and @..@, but it does -- include (other) hidden files. ls :: FilePath -> Sh [FilePath] -- it is important to use path and not absPath so that the listing can remain relative@@ -289,24 +281,24 @@   let relativized = map (\p -> FP.joinPath [f, p]) files   return (relativized, absolute) --- | silently uses the Right or Left value of "Filesystem.Path.CurrentOS.toText" toTextIgnore :: FilePath -> Text toTextIgnore = T.pack --- | a print lifted into 'Sh'-inspect :: (Show s) => s -> Sh ()+-- | 'print' lifted into 'Sh'.+inspect :: Show s => s -> Sh () inspect x = do-  (trace . T.pack . show) x-  liftIO $ print x+  trace $ T.pack s+  liftIO $ putStrLn s+  where s = show x --- | a print lifted into 'Sh' using stderr-inspect_err :: (Show s) => s -> Sh ()+-- | A 'print' lifted into 'Sh' using stderr.+inspect_err :: Show s => s -> Sh () inspect_err x = do   let shown = T.pack $ show x   trace shown   echo_err shown --- | Echo text to standard (error, when using _err variants) output. The _n+-- | Echo text to standard (error, when using @_err@ variants) output. The @_n@ -- variants do not print a final newline. echo, echo_n, echo_err, echo_n_err :: Text -> Sh () echo       msg = traceEcho msg >> liftIO (TIO.putStrLn msg >> hFlush stdout)@@ -321,4 +313,3 @@ -- @... `catch` \(e :: SomeException) -> ...@). catchany :: IO a -> (SomeException -> IO a) -> IO a catchany = catch-
src/Shelly/Directory.hs view
@@ -2,31 +2,18 @@ module Shelly.Directory where  import System.IO.Error (modifyIOError, ioeSetLocation, ioeGetLocation)-import qualified System.Directory as FP -#ifdef mingw32_HOST_OS-import qualified System.Win32 as Win32-#else-import qualified System.Posix as Posix-#endif+import qualified System.PosixCompat as Posix  createFileLink :: String -> String -> IO () createFileLink target link =   (`ioeAddLocation` "createFileLink") `modifyIOError` do-#ifdef mingw32_HOST_OS-    Win32.createSymbolicLink False target link-#else     Posix.createSymbolicLink target link-#endif  getSymbolicLinkTarget :: String -> IO String getSymbolicLinkTarget path =   (`ioeAddLocation` "getSymbolicLinkTarget") `modifyIOError` do-#ifdef mingw32_HOST_OS-    Win32.readSymbolicLink path-#else     Posix.readSymbolicLink path-#endif  ioeAddLocation :: IOError -> String -> IOError ioeAddLocation e loc = do
src/Shelly/Find.hs view
@@ -1,8 +1,10 @@ {-# LANGUAGE OverloadedStrings #-}+ -- | File finding utiliites for Shelly -- The basic 'find' takes a dir and gives back a list of files. -- If you don't just want a list, use the folding variants like 'findFold'. -- If you want to avoid traversing certain directories, use the directory filtering variants like 'findDirFilter'+ module Shelly.Find   ( find   , findWhen@@ -13,10 +15,11 @@   ) where -import           Prelude                 hiding ( FilePath ) import           Shelly.Base import           Control.Monad                  ( foldM )+#if !MIN_VERSION_base(4,13,0) import           Data.Monoid                    ( mappend )+#endif import           System.PosixCompat.Files       ( getSymbolicLinkStatus                                                 , isSymbolicLink                                                 )@@ -40,14 +43,14 @@ findFold folder startValue =   findFoldDirFilter folder startValue (const $ return True) --- | 'find' that filters out directories as it finds+-- | 'find' that filters out directories as it finds. -- Filtering out directories can make a find much more efficient by avoiding entire trees of files. findDirFilter :: (FilePath -> Sh Bool) -> FilePath -> Sh [FilePath] findDirFilter filt = findDirFilterWhen filt (const $ return True) --- | similar 'findWhen', but also filter out directories--- Alternatively, similar to 'findDirFilter', but also filter out files--- Filtering out directories makes the find much more efficient+-- | Similar to 'findWhen', but also filter out directories.+-- Alternatively, similar to 'findDirFilter', but also filter out files.+-- Filtering out directories makes the find much more efficient. findDirFilterWhen   :: (FilePath -> Sh Bool) -- ^ directory filter   -> (FilePath -> Sh Bool) -- ^ file filter@@ -59,23 +62,22 @@     yes <- fileFilter fp     return $ if yes then paths ++ [fp] else paths --- | like 'findDirFilterWhen' but use a folding function rather than a filter--- The most general finder: you likely want a more specific one+-- | Like 'findDirFilterWhen' but use a folding function rather than a filter.+-- The most general finder: you likely want a more specific one. findFoldDirFilter   :: (a -> FilePath -> Sh a) -> a -> (FilePath -> Sh Bool) -> FilePath -> Sh a findFoldDirFilter folder startValue dirFilter dir = do   absDir <- absPath dir   trace ("find " `mappend` toTextIgnore absDir)-  files <- ls absDir   filt <- dirFilter absDir   if not filt     then return startValue     -- use possible relative path, not absolute so that listing will remain relative     else do       (rPaths, aPaths) <- lsRelAbs dir-      foldM traverse startValue (zip rPaths aPaths)+      foldM traverse' startValue (zip rPaths aPaths)  where-  traverse acc (relativePath, absolutePath) = do+  traverse' acc (relativePath, absolutePath) = do     -- optimization: don't use Shelly API since our path is already good     isDir  <- liftIO $ doesDirectoryExist absolutePath     sym    <- liftIO $ fmap isSymbolicLink $ getSymbolicLinkStatus absolutePath
src/Shelly/Lifted.hs view
@@ -32,13 +32,13 @@          -- please make the same updates here and implements the corresponding          -- lifted functions. -         -- * Entering Sh.+         -- * Entering Sh          Sh, ShIO, S.shelly, S.shellyNoDir, S.shellyFailDir, sub          , silently, verbosely, escaping, print_stdout, print_stderr, print_commands          , tracing, errExit          , log_stdout_with, log_stderr_with -         -- * Running external commands.+         -- * Running external commands          , run, run_, runFoldLines, S.cmd, S.FoldCallback          , (-|-), lastStderr, setStdin, lastExitCode          , command, command_, command1, command1_@@ -50,7 +50,7 @@          , S.StdHandle(..), S.StdStream(..)  -         -- * Modifying and querying environment.+         -- * Modifying and querying environment          , setenv, get_env, get_env_text, get_env_all, appendToPath, prependToPath           -- * Environment directory@@ -60,14 +60,14 @@          , echo, echo_n, echo_err, echo_n_err, inspect, inspect_err          , tag, trace, S.show_command -         -- * Querying filesystem.+         -- * Querying filesystem          , ls, lsT, test_e, test_f, test_d, test_s, test_px, which           -- * Filename helpers          , absPath, (S.</>), (S.<.>), canonic, canonicalize, relPath, relativeTo          , S.hasExt -         -- * Manipulating filesystem.+         -- * Manipulating filesystem          , mv, rm, rm_f, rm_rf, cp, cp_r, mkdir, mkdir_p, mkdirTree           -- * reading/writing Files@@ -96,26 +96,23 @@          , followSymlink          ) where -import qualified Shelly as S-import Shelly.Base (Sh(..), ShIO, Text, (>=>), FilePath)+import qualified Shelly      as S import qualified Shelly.Base as S-import Control.Monad ( liftM )-import Prelude hiding ( FilePath )+import Shelly.Base     ( Sh(..), ShIO, Text, (>=>) )++import Control.Monad   ( liftM ) import Data.ByteString ( ByteString )-import Data.Monoid-import System.IO ( Handle )-import Data.Tree ( Tree )-import qualified System.FilePath as FP+import Data.Tree       ( Tree )+import System.IO       ( Handle )  import Control.Exception.Lifted import Control.Exception.Enclosed import Control.Monad.IO.Class import Control.Monad.Trans.Control import Control.Monad.Trans.Identity-import Control.Monad.Trans.List import Control.Monad.Trans.Maybe import Control.Monad.Trans.Cont-import Control.Monad.Trans.Error+import Control.Monad.Trans.Except import Control.Monad.Trans.Reader import Control.Monad.Trans.State import qualified Control.Monad.Trans.State.Strict as Strict@@ -132,40 +129,46 @@  instance MonadSh m => MonadSh (IdentityT m) where     liftSh = IdentityT . liftSh-instance MonadSh m => MonadSh (ListT m) where-    liftSh m = ListT $ do-        a <- liftSh m-        return [a]+ instance MonadSh m => MonadSh (MaybeT m) where     liftSh = MaybeT . liftM Just . liftSh+ instance MonadSh m => MonadSh (ContT r m) where     liftSh m = ContT (liftSh m >>=)-instance (Error e, MonadSh m) => MonadSh (ErrorT e m) where-    liftSh m = ErrorT $ do++instance (MonadSh m) => MonadSh (ExceptT e m) where+    liftSh m = ExceptT $ do         a <- liftSh m         return (Right a)+ instance MonadSh m => MonadSh (ReaderT r m) where     liftSh = ReaderT . const . liftSh+ instance MonadSh m => MonadSh (StateT s m) where     liftSh m = StateT $ \s -> do         a <- liftSh m         return (a, s)+ instance MonadSh m => MonadSh (Strict.StateT s m) where     liftSh m = Strict.StateT $ \s -> do         a <- liftSh m         return (a, s)+ instance (Monoid w, MonadSh m) => MonadSh (WriterT w m) where     liftSh m = WriterT $ do         a <- liftSh m         return (a, mempty :: w)+ instance (Monoid w, MonadSh m) => MonadSh (Strict.WriterT w m) where     liftSh m = Strict.WriterT $ do         a <- liftSh m         return (a, mempty :: w)+ instance (Monoid w, MonadSh m) => MonadSh (RWS.RWST r w s m) where     liftSh m = RWS.RWST $ \_ s -> do         a <- liftSh m         return (a, s, mempty :: w)+ instance (Monoid w, MonadSh m) => MonadSh (Strict.RWST r w s m) where     liftSh m = Strict.RWST $ \_ s -> do         a <- liftSh m@@ -181,7 +184,7 @@     cmdAll = (liftSh .) . S.run_  class Monad m => MonadShControl m where-    data ShM m a :: *+    data ShM m a     liftShWith :: ((forall x. m x -> Sh (ShM m x)) -> Sh a) -> m a     restoreSh :: ShM m a -> m a @@ -192,15 +195,6 @@      {-# INLINE liftShWith #-}      {-# INLINE restoreSh #-} -instance MonadShControl m => MonadShControl (ListT m) where-    newtype ShM (ListT m) a = ListTShM (ShM m [a])-    liftShWith f =-        ListT $ liftM return $ liftShWith $ \runInSh -> f $ \k ->-            liftM ListTShM $ runInSh $ runListT k-    restoreSh (ListTShM m) = ListT . restoreSh $ m-    {-# INLINE liftShWith #-}-    {-# INLINE restoreSh #-}- instance MonadShControl m => MonadShControl (MaybeT m) where     newtype ShM (MaybeT m) a = MaybeTShM (ShM m (Maybe a))     liftShWith f =@@ -240,13 +234,12 @@     {-# INLINE liftShWith #-}     {-# INLINE restoreSh #-} -instance (MonadShControl m, Error e)-         => MonadShControl (ErrorT e m) where-    newtype ShM (ErrorT e m) a = ErrorTShM (ShM m (Either e a))+instance MonadShControl m => MonadShControl (ExceptT e m) where+    newtype ShM (ExceptT e m) a = ExceptTShM (ShM m (Either e a))     liftShWith f =-        ErrorT $ liftM return $ liftShWith $ \runInSh -> f $ \k ->-            liftM ErrorTShM $ runInSh $ runErrorT k-    restoreSh (ErrorTShM m) = ErrorT . restoreSh $ m+        ExceptT $ liftM return $ liftShWith $ \runInSh -> f $ \k ->+            liftM ExceptTShM $ runInSh $ runExceptT k+    restoreSh (ExceptTShM m) = ExceptT . restoreSh $ m     {-# INLINE liftShWith #-}     {-# INLINE restoreSh #-} @@ -375,11 +368,11 @@ put :: MonadSh m => S.State -> m () put = liftSh . S.put -catch_sh :: (Exception e) => Sh a -> (e -> Sh a) -> Sh a+catch_sh :: Exception e => Sh a -> (e -> Sh a) -> Sh a catch_sh = Control.Exception.Lifted.catch {-# DEPRECATED catch_sh "use Control.Exception.Lifted.catch instead" #-} -handle_sh :: (Exception e) => (e -> Sh a) -> Sh a -> Sh a+handle_sh :: Exception e => (e -> Sh a) -> Sh a -> Sh a handle_sh = handle {-# DEPRECATED handle_sh "use Control.Exception.Lifted.handle instead" #-} @@ -573,7 +566,7 @@ canonic = liftSh . canonic  -- | Obtain a (reasonably) canonic file path to a filesystem object. Based on--- "canonicalizePath" in system-fileio.+-- "canonicalizePath". canonicalize :: MonadSh m => FilePath -> m FilePath canonicalize = liftSh . S.canonicalize 
src/Shelly/Pipe.hs view
@@ -1,14 +1,15 @@-{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, +{-# LANGUAGE FlexibleInstances, TypeSynonymInstances,              TypeFamilies, ExistentialQuantification #-}--- | This module is a wrapper for the module "Shelly". --- The only difference is a main type 'Sh'. In this module ++-- | This module is a wrapper for the module "Shelly".+-- The only difference is a main type 'Sh'. In this module -- 'Sh' contains a list of results. Actual definition of the type 'Sh' is: -- -- > import qualified Shelly as S -- > -- > newtype Sh a = Sh { unSh :: S.Sh [a] } ----- This definition can simplify some filesystem commands. +-- This definition can simplify some filesystem commands. -- A monad bind operator becomes a pipe operator and we can write -- -- > findExt ext = findWhen (pure . hasExt ext)@@ -17,13 +18,9 @@ -- > main = shs $ do -- >     mkdir "new" -- >     findExt "hs"  "." >>= flip cp "new"--- >     findExt "cpp" "." >>= rm_f +-- >     findExt "cpp" "." >>= rm_f -- >     liftIO $ putStrLn "done" ----- Monad methods "return" and ">>=" behave like methods for--- @ListT Shelly.Sh@, but ">>" forgets the number of --- the empty effects. So the last line prints @\"done\"@ only once. --- -- Documentation in this module mostly just reference documentation from -- the main "Shelly" module. --@@ -33,20 +30,21 @@ -- > import Shelly -- > import Data.Text as T -- > default (T.Text)+ module Shelly.Pipe        (-         -- * Entering Sh.+         -- * Entering Sh          Sh, shs, shelly, shellyFailDir, shsFailDir, sub, silently, verbosely, escaping, print_stdout, print_commands, tracing, errExit, log_stdout_with, log_stderr_with          -- * List functions          , roll, unroll, liftSh-         -- * Running external commands.+         -- * Running external commands          , FoldCallback          , run, run_, runFoldLines, cmd          , (-|-), lastStderr, setStdin, lastExitCode          , command, command_, command1, command1_          , sshPairs, sshPairs_ -         -- * Modifying and querying environment.+         -- * Modifying and querying environment          , setenv, get_env, get_env_text, get_env_def, appendToPath, prependToPath           -- * Environment directory@@ -56,14 +54,14 @@          , echo, echo_n, echo_err, echo_n_err, inspect, inspect_err          , tag, trace, show_command -         -- * Querying filesystem.+         -- * Querying filesystem          , ls, lsT, test_e, test_f, test_d, test_s, which           -- * Filename helpers          , absPath, (</>), (<.>), canonic, canonicalize, relPath, relativeTo          , hasExt -         -- * Manipulating filesystem.+         -- * Manipulating filesystem          , mv, rm, rm_f, rm_rf, cp, cp_r, mkdir, mkdir_p, mkdirTree           -- * reading/writing Files@@ -73,14 +71,14 @@          , exit, errorExit, quietExit, terror           -- * Exceptions-         , catchany, catch_sh, finally_sh +         , catchany, catch_sh, finally_sh          , ShellyHandler(..), catches_sh          , catchany_sh           -- * convert between Text and FilePath          , toTextIgnore, toTextWarn, S.fromText -         -- * Utilities.+         -- * Utilities          , (<$>), whenM, unlessM, time           -- * Re-exported for your convenience@@ -89,54 +87,50 @@          -- * internal functions for writing extensions          , get, put -         -- * find functions +         -- * find functions          , find, findWhen, findFold          , findDirFilter, findDirFilterWhen, findFoldDirFilter          , followSymlink          ) where -import Prelude hiding (FilePath)--import Control.Applicative-import Control.Monad-import Control.Monad.Trans-import Control.Exception hiding (handle)--import System.FilePath(FilePath)- import qualified Shelly as S -import Shelly(-      (</>), (<.>), hasExt+import Shelly+    ( (</>), (<.>), hasExt     , whenM, unlessM, toTextIgnore     , catchany-    , FoldCallback)--import Data.Maybe(fromMaybe)-import Shelly.Base(State)-import Data.ByteString (ByteString)+    , FoldCallback+    )+import Shelly.Base (State) -import Data.Tree(Tree)+import Control.Applicative+import Control.Monad+import Control.Monad.Trans+import Control.Exception +import Data.Maybe      ( fromMaybe )+import Data.ByteString ( ByteString )+import Data.Tree       ( Tree ) import Data.Text as T hiding (concat, all, find, cons) - -- | This type is a simple wrapper for a type @Shelly.Sh@.--- 'Sh' contains a list of results. +-- 'Sh' contains a list of results.+ newtype Sh a = Sh { unSh :: S.Sh [a] }  instance Functor Sh where-    fmap f = Sh . fmap (fmap f) . unSh    --instance Monad Sh where-    return  = Sh . return . return -    a >>= f = Sh $ fmap concat $ mapM (unSh . f) =<< unSh a-    a >> b  = Sh $ unSh a >> unSh b+    fmap f = Sh . fmap (fmap f) . unSh  instance Applicative Sh where-    pure = return+    pure  = Sh . pure . pure     (<*>) = ap+    a *> b  = Sh $ unSh a *> unSh b +instance Monad Sh where+    return  = pure+    a >>= f = Sh $ fmap concat $ mapM (unSh . f) =<< unSh a+    (>>)    = (*>)+ instance Alternative Sh where     empty = mzero     (<|>) = mplus@@ -154,29 +148,29 @@ sh0 :: S.Sh a -> Sh a sh0 = Sh . fmap return -sh1 :: (a -> S.Sh b) -> (a -> Sh b) +sh1 :: (a -> S.Sh b) -> (a -> Sh b) sh1 f = \a -> sh0 (f a) -sh2 :: (a1 -> a2 -> S.Sh b) -> (a1 -> a2 -> Sh b) +sh2 :: (a1 -> a2 -> S.Sh b) -> (a1 -> a2 -> Sh b) sh2 f = \a b -> sh0 (f a b) -sh3 :: (a1 -> a2 -> a3 -> S.Sh b) -> (a1 -> a2 -> a3 -> Sh b) +sh3 :: (a1 -> a2 -> a3 -> S.Sh b) -> (a1 -> a2 -> a3 -> Sh b) sh3 f = \a b c -> sh0 (f a b c) -sh4 :: (a1 -> a2 -> a3 -> a4 -> S.Sh b) -> (a1 -> a2 -> a3 -> a4 -> Sh b) +sh4 :: (a1 -> a2 -> a3 -> a4 -> S.Sh b) -> (a1 -> a2 -> a3 -> a4 -> Sh b) sh4 f = \a b c d -> sh0 (f a b c d)  sh0s :: S.Sh [a] -> Sh a sh0s = Sh -sh1s :: (a -> S.Sh [b]) -> (a -> Sh b) +sh1s :: (a -> S.Sh [b]) -> (a -> Sh b) sh1s f = \a -> sh0s (f a)  {-  Just in case ...-sh2s :: (a1 -> a2 -> S.Sh [b]) -> (a1 -> a2 -> Sh b) +sh2s :: (a1 -> a2 -> S.Sh [b]) -> (a1 -> a2 -> Sh b) sh2s f = \a b -> sh0s (f a b) -sh3s :: (a1 -> a2 -> a3 -> S.Sh [b]) -> (a1 -> a2 -> a3 -> Sh b) +sh3s :: (a1 -> a2 -> a3 -> S.Sh [b]) -> (a1 -> a2 -> a3 -> Sh b) sh3s f = \a b c -> sh0s (f a b c) -} @@ -188,19 +182,19 @@     where f' = \x y -> f (return x) (return y)  mapM2 :: Monad m => (a -> b -> m c)-> [a] -> [b] -> m [c]-mapM2 f as bs = sequence $ liftA2 f as bs +mapM2 f as bs = sequence $ liftA2 f as bs  -----------------------------------------------------------  -- | Unpack list of results. unroll :: Sh a -> Sh [a]-unroll = Sh . fmap return . unSh +unroll = Sh . fmap return . unSh  -- | Pack list of results. It performs @concat@ inside 'Sh'. roll :: Sh [a] -> Sh a roll = Sh . fmap concat . unSh --- | Transform result as list. It can be useful for filtering. +-- | Transform result as list. It can be useful for filtering. liftSh :: ([a] -> [b]) -> Sh a -> Sh b liftSh f = Sh . fmap f . unSh @@ -211,7 +205,7 @@ shelly :: MonadIO m => Sh a -> m [a] shelly = S.shelly . unSh --- | Performs 'shelly' and then an empty action @return ()@. +-- | Performs 'shelly' and then an empty action @return ()@. shs :: MonadIO m => Sh () -> m () shs x = shelly x >> return () @@ -289,7 +283,7 @@  -- | see 'S.setStdin' setStdin :: Text -> Sh ()-setStdin = sh1 S.setStdin +setStdin = sh1 S.setStdin  -- | see 'S.lastExitCode' lastExitCode :: Sh Int@@ -358,7 +352,7 @@ pwd = sh0 S.pwd  -------------------------------------------------------------------- Printing +-- Printing  -- | Echo text to standard (error, when using _err variants) output. The _n -- variants do not print a final newline.@@ -528,15 +522,15 @@ -- | see 'S.findDirFilter' findDirFilter :: (FilePath -> Sh Bool) -> FilePath -> Sh FilePath findDirFilter p a = Sh $ S.findDirFilter (fmap and . unSh . p) a-    + -- | see 'S.findDirFilterWhen' findDirFilterWhen :: (FilePath -> Sh Bool) -- ^ directory filter                   -> (FilePath -> Sh Bool) -- ^ file filter                   -> FilePath -- ^ directory                   -> Sh FilePath-findDirFilterWhen dirPred filePred a = -    Sh $ S.findDirFilterWhen  -            (fmap and . unSh . dirPred) +findDirFilterWhen dirPred filePred a =+    Sh $ S.findDirFilterWhen+            (fmap and . unSh . dirPred)             (fmap and . unSh . filePred)             a @@ -547,9 +541,9 @@     where p'    = fmap and . unSh . p           nil'  = return nil           cons' as dir = unSh $ roll $ mapM (flip cons dir) as-           + -------------------------------------------------------------- exiting the program +-- exiting the program  -- | see 'S.exit' exit :: Int -> Sh ()@@ -597,14 +591,14 @@           convert (ShellyHandler f) = S.ShellyHandler (unSh . f)  --------------------------------------------------------------- convert between Text and FilePath +-- convert between Text and FilePath  -- | see 'S.toTextWarn' toTextWarn :: FilePath -> Sh Text toTextWarn = sh1 S.toTextWarn  ---------------------------------------------------------------- internal functions for writing extension +-- internal functions for writing extension  get :: Sh State get = sh0 S.get
src/Shelly/Unix.hs view
@@ -1,6 +1,6 @@ {-# LANGUAGE OverloadedStrings #-} --- | commands that only work on Unix+-- | Commands that only work on Unix. module Shelly.Unix   ( kill   ) where
test/examples/drain.hs view
@@ -1,5 +1,5 @@ {-# Language OverloadedStrings, ExtendedDefaultRules #-}-import Prelude hiding (FilePath)+ import Shelly import Control.Monad (void) import Data.Text (Text)
test/src/CopySpec.hs view
@@ -3,18 +3,13 @@  import TestInit -#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706-import Prelude hiding ( FilePath, catch)-#else-import Prelude hiding ( FilePath)-#endif import Control.Monad (forM_) import System.IO.Error import Help  copySpec :: Spec copySpec = do-  let b = "b" +  let b = "b"   let c = "c"   describe "cp file" $ do     it "cp to same dir" $
test/src/EnvSpec.hs view
@@ -2,11 +2,6 @@ module EnvSpec ( envSpec ) where  import TestInit-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706-import Prelude hiding ( FilePath, catch)-#else-import Prelude hiding ( FilePath)-#endif import Data.Maybe  envSpec :: Spec@@ -32,7 +27,7 @@         setenv "SHELLY" "test"         get_env_text "SHELLY"       assert $ res == "test"- +   describe "get_env \"PATH\" (OS compatibility test)" $ do     it "get_env" $ do       res <- shelly $ get_env "PATH"
test/src/FindSpec.hs view
@@ -2,10 +2,10 @@  import TestInit import Data.List (sort)+import Data.Text (replace, pack, unpack) import System.Directory (createDirectoryIfMissing) import System.PosixCompat.Files (createSymbolicLink, fileExist) import qualified System.FilePath as SF-import Shelly  createSymlinkForTest :: IO () createSymlinkForTest = do@@ -20,6 +20,11 @@     rootDir = "test" SF.</> "data"     symDir = rootDir SF.</> "dir" +toWindowsStyleIfNecessary :: String -> String+toWindowsStyleIfNecessary s+  | isWindows = unpack . replace "/" "\\" . pack $ s+  | otherwise = s+ findSpec :: Spec findSpec = do   describe "relativeTo" $ do@@ -44,7 +49,7 @@   describe "relative listing" $ do     it "lists relative files" $ do       res <- shelly $ cd "test/src" >> ls "."-      sort res @?= ["./CopySpec.hs", "./EnvSpec.hs", "./FailureSpec.hs",+      sort res @?= map toWindowsStyleIfNecessary ["./CopySpec.hs", "./EnvSpec.hs", "./FailureSpec.hs",                     "./FindSpec.hs", "./Help.hs", "./LiftedSpec.hs", "./LogWithSpec.hs", "./MoveSpec.hs",                     "./ReadFileSpec.hs", "./RmSpec.hs", "./RunSpec.hs", "./SshSpec.hs",                     "./TestInit.hs", "./TestMain.hs",@@ -52,7 +57,7 @@      it "lists relative files in folder" $ do       res <- shelly $ cd "test" >> ls "src"-      sort res @?= ["src/CopySpec.hs", "src/EnvSpec.hs", "src/FailureSpec.hs",+      sort res @?=  map toWindowsStyleIfNecessary ["src/CopySpec.hs", "src/EnvSpec.hs", "src/FailureSpec.hs",                     "src/FindSpec.hs", "src/Help.hs", "src/LiftedSpec.hs", "src/LogWithSpec.hs", "src/MoveSpec.hs",                     "src/ReadFileSpec.hs", "src/RmSpec.hs", "src/RunSpec.hs", "src/SshSpec.hs",                     "src/TestInit.hs", "src/TestMain.hs",@@ -60,7 +65,7 @@      it "finds relative files" $ do       res <- shelly $ cd "test/src" >> find "."-      sort res @?= ["./CopySpec.hs", "./EnvSpec.hs", "./FailureSpec.hs",+      sort res @?= map toWindowsStyleIfNecessary ["./CopySpec.hs", "./EnvSpec.hs", "./FailureSpec.hs",                     "./FindSpec.hs", "./Help.hs", "./LiftedSpec.hs", "./LogWithSpec.hs", "./MoveSpec.hs",                     "./ReadFileSpec.hs", "./RmSpec.hs", "./RunSpec.hs", "./SshSpec.hs",                     "./TestInit.hs", "./TestMain.hs",@@ -77,8 +82,15 @@       res @?= []      it "lists relative files" $ do-      res <- shelly $ find "test/src"-      sort res @?= ["test/src/CopySpec.hs", "test/src/EnvSpec.hs", "test/src/FailureSpec.hs",+      res <- shelly $ verbosely $ find "test/src"+      if isWindows+        then sort res @?= ["test/src\\CopySpec.hs", "test/src\\EnvSpec.hs", "test/src\\FailureSpec.hs",+                    "test/src\\FindSpec.hs", "test/src\\Help.hs", "test/src\\LiftedSpec.hs",+                    "test/src\\LogWithSpec.hs", "test/src\\MoveSpec.hs", "test/src\\ReadFileSpec.hs",+                    "test/src\\RmSpec.hs", "test/src\\RunSpec.hs", "test/src\\SshSpec.hs",+                    "test/src\\TestInit.hs", "test/src\\TestMain.hs", "test/src\\WhichSpec.hs", "test/src\\WriteSpec.hs",+                    "test/src\\sleep.hs"]+        else sort res @?= ["test/src/CopySpec.hs", "test/src/EnvSpec.hs", "test/src/FailureSpec.hs",                     "test/src/FindSpec.hs", "test/src/Help.hs", "test/src/LiftedSpec.hs",                     "test/src/LogWithSpec.hs", "test/src/MoveSpec.hs", "test/src/ReadFileSpec.hs",                     "test/src/RmSpec.hs", "test/src/RunSpec.hs", "test/src/SshSpec.hs",@@ -93,7 +105,7 @@                     "TestInit.hs", "TestMain.hs",                     "WhichSpec.hs", "WriteSpec.hs", "sleep.hs"] -    before createSymlinkForTest $ do+    unless isWindows $ before createSymlinkForTest $ do       it "follow symlinks" $          do res <-               shelly $@@ -121,4 +133,3 @@               , "symlinked_dir/hoge_file"               , "zshrc"               ]-
test/src/Help.hs view
@@ -4,11 +4,6 @@ ) where  import Shelly-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706-import Prelude hiding ( catch, FilePath )-#else-import Prelude hiding ( FilePath )-#endif import Test.HUnit import Control.Monad.Trans ( MonadIO ) 
test/src/LogWithSpec.hs view
@@ -2,7 +2,6 @@ module LogWithSpec ( logWithSpec ) where  import TestInit-import Prelude hiding (FilePath)  import Control.Concurrent (newEmptyMVar, takeMVar, putMVar) import Data.Text (Text)
test/src/MoveSpec.hs view
@@ -5,7 +5,7 @@  moveSpec :: Spec moveSpec = do-    let b = "b" +    let b = "b"     let c = "c"     describe "mv file" $ do       it "to same dir" $ do@@ -15,7 +15,7 @@             mv b c             readfile c         res @?= "testing"-    +       it "to other dir" $ do         res <- shelly $           within_dir "test/a" $ do@@ -24,7 +24,7 @@             mv b c             readfile "c/b"         res @?= "testing"-    +     describe "mv dir" $ do       it "to dir does not exist: create the to dir" $ do         res <- shelly $@@ -36,7 +36,7 @@             liftIO $ assert cIsDir             test_f "c/d"         assert res-    +       it "to dir exists: creates a nested directory, full to path given" $ do         res <- shelly $           within_dir "test/a" $ do@@ -50,7 +50,7 @@             liftIO $ assert bIsDir             test_f "c/b/d"         assert res-    +       it "to dir exists: creates a nested directory, partial to path given" $ do         res <- shelly $           within_dir "test/a" $ do@@ -64,7 +64,7 @@             liftIO $ assert bIsDir             test_f "c/b/d"         assert res-    +       {-       it "mv the same dir" $ do         shelly $ do
test/src/ReadFileSpec.hs view
@@ -3,11 +3,6 @@ module ReadFileSpec (readFileSpec) where  import TestInit-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706-import Prelude hiding ( FilePath, catch)-#else-import Prelude hiding ( FilePath)-#endif import qualified Data.ByteString as BS import qualified Data.Text as T @@ -16,8 +11,7 @@     it "readBinary" $ do       res <- shelly $ readBinary "test/data/zshrc"       assert (BS.length res > 0)- +     it "readfile" $ do       res <- shelly $ readfile "test/data/zshrc"       assert (T.length res > 0)- 
test/src/RmSpec.hs view
@@ -57,7 +57,7 @@     it "rm" $ do       res <- shelly $ do         writefile b "b"-        cmd "ln" "-s" (T.pack b) (T.pack l)+        _ <- cmd "ln" "-s" (T.pack b) (T.pack l)         rm l         test_f b       assert res@@ -66,7 +66,7 @@     it "rm_f" $ do       res <- shelly $ do         writefile b "b"-        cmd "ln" "-s" (T.pack b) (T.pack l)+        _ <- cmd "ln" "-s" (T.pack b) (T.pack l)         rm_f l         test_f b       assert res@@ -76,7 +76,7 @@       res <- shelly $ do         mkdir d         writefile (d</>b) "b"-        cmd "ln" "-s" (T.pack $ d</>b) (T.pack l)+        _ <- cmd "ln" "-s" (T.pack $ d</>b) (T.pack l)         rm_rf l         test_f (d</>b)       assert res
test/src/RunSpec.hs view
@@ -18,12 +18,16 @@      it "without escaping" $ do       res <- shelly $ escaping False $ run "echo" [ "*" ]-      assert $ "README.md" `elem` T.words res+      if isWindows+        then res @?= "*\n"+        else assert $ "README.md" `elem` T.words res      it "with binary handle mode" $ do       res <- shelly $ onCommandHandles (initOutputHandles (flip hSetBinaryMode True))                     $ run "cat" [ "test/data/nonascii.txt" ]-      res @?= "Selbstverst\228ndlich \252berraschend\n"+      if isWindows+        then res @?= "Selbstverst\228ndlich \252berraschend\r\n"+        else res @?= "Selbstverst\228ndlich \252berraschend\n"    -- Bash-related commands   describe "bash" $ do@@ -38,7 +42,9 @@     it "with binary handle mode" $ do       res <- shelly $ onCommandHandles (initOutputHandles (flip hSetBinaryMode True))                     $ bash "cat" [ "test/data/nonascii.txt" ]-      res @?= "Selbstverst\228ndlich \252berraschend\n"+      if isWindows+        then res @?= "Selbstverst\228ndlich \252berraschend\r\n"+        else res @?= "Selbstverst\228ndlich \252berraschend\n"      {- This throws spurious errors on some systems     it "can detect failing commands in pipes" $ do@@ -51,8 +57,13 @@      it "preserve pipe behaviour" $ do       (eCode, res) <- shelly $ escaping False $ errExit False $ do-        res <- bash "echo" [ "'foo'", "|", "echo", "'bar'" ]+        res <-+          if isWindows+            then bash "echo" [ "foo", "|", "echo", "bar" ]+            else bash "echo" [ "'foo'", "|", "echo", "'bar'" ]         eCode <- lastExitCode         return (eCode, res)-      res @?= "bar\n"+      if isWindows+        then res @?= "bar'\n"+        else res @?= "bar\n"       eCode @?= 0
test/src/TestInit.hs view
@@ -1,4 +1,4 @@-module TestInit (module Export) where+module TestInit (module Export, isWindows) where  import Test.HUnit as Export hiding (path) import Test.Hspec as Export@@ -8,3 +8,6 @@ import Shelly as Export #endif import Test.Hspec.Contrib.HUnit ()+import System.Info(os)+isWindows :: Bool+isWindows = os == "mingw32"
test/src/WhichSpec.hs view
@@ -11,7 +11,7 @@     it "recognizes cabal as a path executable" $ do       res <- shelly $ test_px "find"       True @?= res- +     it "cannot find missing exe" $ do       Nothing <- shelly $ which "alskjdf;ashlva;ousnva;nj"       assert True
test/src/WriteSpec.hs view
@@ -1,7 +1,6 @@ module WriteSpec ( writeSpec ) where  import TestInit-import Prelude hiding (FilePath)  import Data.Text (Text) default (Text)