-
Notifications
You must be signed in to change notification settings - Fork 88
/
Shelly.hs
1505 lines (1281 loc) · 55.3 KB
/
Shelly.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# 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.
-- However, it also tries to use modern libraries and techniques to keep things efficient.
--
-- The functionality provided by
-- this module is (unlike standard Haskell filesystem functionality)
-- thread-safe: each Sh maintains its own environment and its own working
-- directory.
--
-- Recommended usage includes putting the following at the top of your program,
-- otherwise you will likely need either type annotations or type conversions
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- > {-# LANGUAGE ExtendedDefaultRules #-}
-- > {-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- > import Shelly
-- > import qualified Data.Text as T
-- > default (T.Text)
module Shelly
(
-- * Entering Sh
Sh, ShIO, shelly, shellyNoDir, shellyFailDir, asyncSh, sub
, silently, verbosely, escaping, print_stdout, print_stderr, print_commands, print_commands_with
, onCommandHandles
, tracing, errExit
, log_stdout_with, log_stderr_with
-- * Running external commands
, run, run_, runFoldLines, cmd, FoldCallback
, bash, bash_, bashPipeFail
, (-|-), lastStderr, setStdin, lastExitCode
, command, command_, command1, command1_
, sshPairs,sshPairsPar, sshPairs_,sshPairsPar_, sshPairsWithOptions
, sshCommandText, SshMode(..)
, ShellCmd(..), CmdArg (..)
-- * Running commands Using handles
, runHandle, runHandles, transferLinesAndCombine, transferFoldHandleLines
, StdHandle(..), StdStream(..)
-- * Handle manipulation
, HandleInitializer, StdInit(..), initOutputHandles, initAllHandles
-- * Modifying and querying environment
, setenv, get_env, get_env_text, getenv, get_env_def, get_env_all, get_environment, appendToPath, prependToPath
-- * Environment directory
, cd, chdir, chdir_p, pwd
-- * Printing
, echo, echo_n, echo_err, echo_n_err, echoWith, inspect, inspect_err
, tag, trace, show_command
-- * 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
, mv, rm, rm_f, rm_rf, cp, cp_r, mkdir, mkdir_p, mkdirTree
-- * reading/writing Files
, readfile, readBinary, writefile, writeBinary, appendfile, touchfile, withTmpDir
-- * exiting the program
, exit, errorExit, quietExit, terror
-- * Exceptions
, bracket_sh, catchany, catch_sh, handle_sh, handleany_sh, finally_sh, ShellyHandler(..), catches_sh, catchany_sh
, ReThrownException(..)
, RunFailed(..)
-- * convert between Text and FilePath
, toTextIgnore, toTextWarn, fromText
-- * Utility Functions
, whenM, unlessM, time, sleep
-- * Re-exported for your convenience
, liftIO, when, unless, FilePath, (<$>)
-- * internal functions for writing extensions
, get, put
-- * find functions
, find, findWhen, findFold, findDirFilter, findDirFilterWhen, findFoldDirFilter
, followSymlink
) where
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, liftM2 )
import Control.Monad.Trans ( MonadIO )
import Control.Monad.Reader (ask)
import Data.ByteString ( ByteString )
import Data.Char ( isAlphaNum, isDigit, isSpace, isPrint )
#if defined(mingw32_HOST_OS)
import Data.Char ( toLower )
#endif
import Data.Foldable ( toList )
import Data.IORef
import Data.Maybe
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup ( (<>) )
#endif
import Data.Sequence ( Seq, (|>) )
import Data.Time.Clock ( getCurrentTime, diffUTCTime )
import Data.Tree ( Tree(..) )
import Data.Typeable
import qualified Data.ByteString as BS
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.Directory
( setPermissions, getPermissions, Permissions(..), getTemporaryDirectory, pathIsSymbolicLink
, copyFile, removeFile, doesFileExist, doesDirectoryExist
, renameFile, renameDirectory, removeDirectoryRecursive, createDirectoryIfMissing
, getCurrentDirectory
)
import System.Environment
import System.Exit
import System.FilePath hiding ((</>), (<.>))
import qualified System.FilePath as FP
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(..)
)
-- | Argument converter for the variadic argument version of 'run' called 'cmd'.
-- Useful for a type signature of a function that uses 'cmd'.
class CmdArg a where
-- | @since 1.12.0
toTextArgs :: a -> [Text]
instance CmdArg Text where
toTextArgs = (: [])
instance CmdArg String where
toTextArgs = (: []) . T.pack
instance {-# OVERLAPPABLE #-} CmdArg a => CmdArg [a] where
toTextArgs = concatMap toTextArgs
-- | For the variadic function 'cmd'.
--
-- Partially applied variadic functions require type signatures.
class ShellCmd t where
cmdAll :: FilePath -> [Text] -> t
-- This is the only candidate for `_ <- cmd path x y z` so marking it incoherent will return it and
-- terminate the search immediately. This also removes the warning for do { cmd path x y z ; .. }
-- as GHC will infer `Sh ()` instead of `Sh Text` as before.
instance {-# INCOHERENT #-} s ~ () => ShellCmd (Sh s) where
cmdAll = run_
instance ShellCmd (Sh Text) where
cmdAll = run
instance (CmdArg arg, ShellCmd result) => ShellCmd (arg -> result) where
cmdAll fp acc x = cmdAll fp (acc ++ toTextArgs x)
-- | 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'.
--
-- Convenient usage of 'cmd' requires the following:
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- > {-# LANGUAGE ExtendedDefaultRules #-}
-- > {-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- > import Shelly
-- > import qualified Data.Text as T
-- > default (T.Text)
--
cmd :: (ShellCmd result) => FilePath -> result
cmd fp = cmdAll fp []
-- | Convert 'Text' to a 'FilePath'.
fromText :: Text -> FilePath
fromText = T.unpack
-- | Helper to convert a Text to a FilePath. Used by '(</>)' and '(<.>)'
class ToFilePath a where
toFilePath :: a -> FilePath
instance ToFilePath FilePath where toFilePath = id
instance ToFilePath Text where toFilePath = T.unpack
-- | 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'.
(<.>) :: (ToFilePath filepath) => filepath -> Text -> FilePath
x <.> y = toFilePath x FP.<.> T.unpack y
toTextWarn :: FilePath -> Sh Text
toTextWarn efile = do
when (not $ isValid efile) $ encodeError (T.pack $ makeValid efile)
return (T.pack $ makeValid efile)
where
encodeError f = echo ("non-unicode file name: " <> f)
-- | Transfer from one handle to another
-- For example, send contents of a process output to stdout.
-- Does not close the write handle.
--
-- Also, return the complete contents being streamed line by line.
transferLinesAndCombine :: Handle -> (Text -> IO ()) -> IO Text
transferLinesAndCombine readHandle putWrite =
transferFoldHandleLines mempty (|>) readHandle putWrite >>=
return . lineSeqToText
lineSeqToText :: Seq Text -> Text
-- extra append puts a newline at the end
lineSeqToText = T.intercalate "\n" . toList . flip (|>) ""
type FoldCallback a = (a -> Text -> a)
-- | Transfer from one handle to another
-- For example, send contents of a process output to stdout.
-- Does not close the write handle.
--
-- 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
go acc = do
mLine <- filterIOErrors $ TIO.hGetLine readHandle
case mLine of
Nothing -> return acc
Just line -> putWrite line >> go (foldLine acc line)
filterIOErrors :: IO a -> IO (Maybe a)
filterIOErrors action = catchIOError
(fmap Just action)
(\e -> if isEOFError e || isIllegalOperation e -- handle was closed
then return Nothing
else ioError e)
foldHandleLines :: a -> FoldCallback a -> Handle -> IO a
foldHandleLines start foldLine readHandle = go start
where
go acc = do
mLine <- filterIOErrors $ TIO.hGetLine readHandle
case mLine of
Nothing -> return acc
Just line -> go $ foldLine acc line
-- | Same as 'trace', but for use in combinator style: @action `tag` message@.
tag :: Sh a -> Text -> Sh a
tag action msg = do
trace msg
action
put :: State -> Sh ()
put newState = do
stateVar <- ask
liftIO (writeIORef stateVar newState)
runCommandNoEscape :: [StdHandle] -> State -> FilePath -> [Text] -> Sh (Handle, Handle, Handle, ProcessHandle)
runCommandNoEscape handles st exe args = liftIO $ shellyProcess handles st $
ShellCommand $ T.unpack $ T.intercalate " " (toTextIgnore exe : args)
runCommand :: [StdHandle] -> State -> FilePath -> [Text] -> Sh (Handle, Handle, Handle, ProcessHandle)
runCommand handles st exe args = findExe exe >>= \fullExe ->
liftIO $ shellyProcess handles st $
RawCommand fullExe (map T.unpack args)
where
findExe :: FilePath -> Sh FilePath
findExe
#if defined(mingw32_HOST_OS)
fp
#else
_fp
#endif
= do
mExe <- whichEith exe
case mExe of
Right execFp -> return execFp
-- windows looks in extra places besides the PATH, so just give
-- up even if the behavior is not properly specified anymore
--
-- 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)
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
(createdInH, createdOutH, createdErrorH, pHandle) <- createProcess CreateProcess {
cmdspec = cmdSpec
, cwd = Just $ sDirectory st
, env = Just $ sEnvironment st
, std_in = createUnless mInH
, std_out = createUnless mOutH
, std_err = createUnless mErrorH
, close_fds = False
, create_group = False
, delegate_ctlc = False
, detach_console = False
, create_new_console = False
, new_session = False
, child_group = Nothing
, child_user = Nothing
#if MIN_VERSION_process(1,5,0)
, use_process_jobs = False
#endif
}
return ( just $ createdInH <|> toHandle mInH
, just $ createdOutH <|> toHandle mOutH
, just $ createdErrorH <|> toHandle mErrorH
, pHandle
)
where
just :: Maybe a -> a
just Nothing = error "error in shelly creating process"
just (Just j) = j
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
createUnless (Just stream) = stream
mInH = getStream mIn reusedHandles
mOutH = getStream mOut reusedHandles
mErrorH = getStream mError reusedHandles
getStream :: (StdHandle -> Maybe StdStream) -> [StdHandle] -> Maybe StdStream
getStream _ [] = Nothing
getStream mHandle (h:hs) = mHandle h <|> getStream mHandle hs
mIn, mOut, mError :: (StdHandle -> Maybe StdStream)
mIn (InHandle h) = Just h
mIn _ = Nothing
mOut (OutHandle h) = Just h
mOut _ = Nothing
mError (ErrorHandle h) = Just h
mError _ = Nothing
{-
-- | use for commands requiring usage of sudo. see 'run_sudo'.
-- Use this pattern for priveledge separation
newtype Sudo a = Sudo { sudo :: Sh a }
-- | require that the caller explicitly state 'sudo'
run_sudo :: Text -> [Text] -> Sudo Text
run_sudo cmd args = Sudo $ run "/usr/bin/sudo" (cmd:args)
-}
-- | Same as a normal 'catch' but specialized for the Sh monad.
catch_sh :: (Exception e) => Sh a -> (e -> Sh a) -> Sh a
catch_sh action handler = do
ref <- ask
liftIO $ catch (runSh action ref) (\e -> runSh (handler e) ref)
-- | Same as a normal 'handle' but specialized for the Sh monad.
handle_sh :: (Exception e) => (e -> Sh a) -> Sh a -> Sh a
handle_sh handler action = do
ref <- ask
liftIO $ handle (\e -> runSh (handler e) ref) (runSh action ref)
-- | Same as a normal 'finally' but specialized for the 'Sh' monad.
finally_sh :: Sh a -> Sh b -> Sh a
finally_sh action handler = do
ref <- ask
liftIO $ finally (runSh action ref) (runSh handler ref)
bracket_sh :: Sh a -> (a -> Sh b) -> (a -> Sh c) -> Sh c
bracket_sh acquire release main = do
ref <- ask
liftIO $ bracket (runSh acquire ref)
(\resource -> runSh (release resource) ref)
(\resource -> runSh (main resource) ref)
-- | You need to wrap exception handlers with this when using 'catches_sh'.
data ShellyHandler a = forall e . Exception e => ShellyHandler (e -> Sh a)
-- | Same as a normal 'catches', but specialized for the 'Sh' monad.
catches_sh :: Sh a -> [ShellyHandler a] -> Sh a
catches_sh action handlers = do
ref <- ask
let runner a = runSh a ref
liftIO $ catches (runner action) $ map (toHandler runner) handlers
where
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.
catchany_sh :: Sh a -> (SomeException -> Sh a) -> Sh a
catchany_sh = catch_sh
-- | 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
-- track of its own working directory and builds absolute paths internally
-- instead of passing down relative paths.
cd :: FilePath -> Sh ()
cd = traceCanonicPath ("cd " <>) >=> cd'
where
cd' dir = do
unlessM (test_d dir) $ errorExit $ "not a directory: " <> tdir
modify $ \st -> st { sDirectory = dir, sPathExecutables = Nothing }
where
tdir = toTextIgnore dir
-- | '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_p :: FilePath -> Sh a -> Sh a
chdir_p d action = mkdir_p d >> chdir d action
pack :: String -> FilePath
pack = id
-- | Move a file. The second path could be a directory, in which case the
-- original file is moved into that directory.
-- wraps directory 'System.Directory.renameFile', which may not work across FS boundaries
mv :: FilePath -> FilePath -> Sh ()
mv from' to' = do
trace $ "mv " <> toTextIgnore from' <> " " <> toTextIgnore to'
from <- absPath from'
from_dir <- test_d from
to <- absPath to'
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
then liftIO $ renameFile from to_loc
`catchany` (\e -> throwIO $
ReThrownException e (extraMsg to_loc from)
)
else liftIO $ renameDirectory from to_loc
`catchany` (\e -> throwIO $
ReThrownException e (extraMsg to_loc from)
)
where
extraMsg :: String -> String -> String
extraMsg t f = "during copy from: " ++ f ++ " to: " ++ t
-- | Get back @[Text]@ instead of @[FilePath]@.
lsT :: FilePath -> Sh [Text]
lsT = ls >=> mapM toTextWarn
-- | 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 :: 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.
errorExit :: Text -> Sh a
errorExit msg = echo msg >> exit 1
-- | 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'.
terror :: Text -> Sh a
terror = fail . T.unpack
-- | Create a new directory (fails if the directory exists).
mkdir :: FilePath -> Sh ()
mkdir = traceAbsPath ("mkdir " <>) >=>
liftIO . createDirectoryIfMissing False
-- | Create a new directory, including parents (succeeds if the directory
-- already exists).
mkdir_p :: FilePath -> Sh ()
mkdir_p = traceAbsPath ("mkdir -p " <>) >=>
liftIO . createDirectoryIfMissing True
-- | Create a new directory tree. You can describe a bunch of directories as
-- a tree and this function will create all subdirectories. An example:
--
-- > exec = mkTree $
-- > "package" # [
-- > "src" # [
-- > "Data" # leaves ["Tree", "List", "Set", "Map"]
-- > ],
-- > "test" # leaves ["QuickCheck", "HUnit"],
-- > "dist/doc/html" # []
-- > ]
-- > where (#) = Node
-- > leaves = map (# [])
--
mkdirTree :: Tree FilePath -> Sh ()
mkdirTree = mk . unrollPath
where mk :: Tree FilePath -> Sh ()
mk (Node a ts) = do
b <- test_d a
unless b $ mkdir a
chdir a $ mapM_ mkdirTree ts
unrollPath :: Tree FilePath -> Tree FilePath
unrollPath (Node v ts) = unrollRoot v $ map unrollPath ts
where unrollRoot x = foldr1 phi $ map Node $ splitDirectories x
phi a b = a . return . b
isExecutable :: FilePath -> IO Bool
isExecutable f = (executable `fmap` getPermissions f) `catch` (\(_ :: IOError) -> return False)
-- | Get a full path to an executable by looking at the @PATH@ environement
-- variable. Windows normally looks in additional places besides the
-- @PATH@: this does not duplicate that behavior.
which :: FilePath -> Sh (Maybe FilePath)
which fp = either (const Nothing) Just <$> whichEith fp
-- | Get a full path to an executable by looking at the @PATH@ environement
-- variable. Windows normally looks in additional places besides the
-- @PATH@: this does not duplicate that behavior.
whichEith :: FilePath -> Sh (Either String FilePath)
whichEith originalFp = whichFull
#if defined(mingw32_HOST_OS)
$ case takeExtension originalFp of
"" -> originalFp <.> "exe"
_ -> originalFp
#else
originalFp
#endif
where
whichFull fp = do
(trace . mappend "which " . toTextIgnore) fp >> whichUntraced
where
whichUntraced | isAbsolute fp = checkFile
| startsWithDot splitOnDirs = checkFile
| otherwise = lookupPath >>= leftPathError
splitOnDirs = splitDirectories fp
-- 'startsWithDot' receives as input the result of 'splitDirectories',
-- which will include the dot (\".\") as its first element only if this
-- is a path of the form \"./foo/bar/baz.sh\". Check for example:
--
-- > import System.FilePath as FP
-- > FP.splitDirectories "./test/data/hello.sh"
-- [".","test","data","hello.sh"]
-- > FP.splitDirectories ".hello.sh"
-- [".hello.sh"]
-- > FP.splitDirectories ".test/hello.sh"
-- [".test","hello.sh"]
-- > FP.splitDirectories ".foo"
-- [".foo"]
--
-- Note that earlier versions of Shelly used
-- \"system-filepath\" which also has a 'splitDirectories'
-- function, but it returns \"./\" as its first argument,
-- so we pattern match on both for backward-compatibility.
startsWithDot (".":_) = True
startsWithDot _ = False
checkFile :: Sh (Either String FilePath)
checkFile = do
exists <- liftIO $ doesFileExist fp
return $ if exists then Right fp else
Left $ "did not find file: " <> fp
leftPathError :: Maybe FilePath -> Sh (Either String FilePath)
leftPathError Nothing = Left <$> pathLookupError
leftPathError (Just x) = return $ Right x
pathLookupError :: Sh String
pathLookupError = do
pATH <- get_env_text "PATH"
return $
"shelly did not find " `mappend` fp `mappend`
" in the PATH: " `mappend` T.unpack pATH
lookupPath :: Sh (Maybe FilePath)
lookupPath = (pathDirs >>=) $ findMapM $ \dir -> do
let fullFp = dir </> fp
res <- liftIO $ isExecutable fullFp
return $ if res then Just fullFp else Nothing
pathDirs = mapM absPath =<< ((map T.unpack . filter (not . T.null) . T.split (== searchPathSeparator)) `fmap` get_env_text "PATH")
-- | A monadic findMap, taken from MissingM package
findMapM :: Monad m => (a -> m (Maybe b)) -> [a] -> m (Maybe b)
findMapM _ [] = return Nothing
findMapM f (x:xs) = do
mb <- f x
if (isJust mb)
then return mb
else findMapM f xs
-- | A monadic-conditional version of the 'unless' guard.
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM c a = c >>= \res -> unless res a
-- | Does a path point to an existing filesystem object?
test_e :: FilePath -> Sh Bool
test_e = absPath >=> \f ->
liftIO $ do
file <- doesFileExist f
if file then return True else doesDirectoryExist f
-- | Does a path point to an existing file?
test_f :: FilePath -> Sh Bool
test_f = absPath >=> liftIO . doesFileExist
-- | Test that a file is in the PATH and also executable
test_px :: FilePath -> Sh Bool
test_px exe = do
mFull <- which exe
case mFull of
Nothing -> return False
Just full -> liftIO $ isExecutable full
-- | A swiss army cannon for removing things. Actually this goes farther than a
-- normal rm -rf, as it will circumvent permission problems for the files we
-- own. Use carefully.
-- Uses 'removeDirectoryRecursive'
rm_rf :: FilePath -> Sh ()
rm_rf infp = do
f <- traceAbsPath ("rm -rf " <>) infp
isDir <- (test_d f)
if not isDir then whenM (test_f f) $ rm_f f
else
(liftIO_ $ removeDirectoryRecursive f) `catch_sh` (\(e :: IOError) ->
when (isPermissionError e) $ do
find f >>= mapM_ (\file -> liftIO_ $ fixPermissions file `catchany` \_ -> return ())
liftIO $ removeDirectoryRecursive f
)
where fixPermissions file =
do permissions <- liftIO $ getPermissions file
let deletable = permissions { readable = True, writable = True, executable = True }
liftIO $ setPermissions file deletable
-- | Remove a file. Does not fail if the file does not exist.
-- Does fail if the file is not a file.
rm_f :: FilePath -> Sh ()
rm_f = traceAbsPath ("rm -f " <>) >=> \f ->
whenM (test_e f) $ liftIO $ removeFile f
-- | Remove a file.
-- Does fail if the file does not exist (use 'rm_f' instead) or is not a file.
rm :: FilePath -> Sh ()
rm = traceAbsPath ("rm " <>) >=>
-- TODO: better error message for removeFile (give takeFileName)
liftIO . removeFile
-- | Set an environment variable. The environment is maintained in Sh
-- internally, and is passed to any external commands to be executed.
setenv :: Text -> Text -> Sh ()
setenv k v = if k == path_env then setPath v else setenvRaw k v
setenvRaw :: Text -> Text -> Sh ()
setenvRaw k v = modify $ \x -> x { sEnvironment = wibble $ sEnvironment x }
where
normK = normalizeEnvVarNameText k
(kStr, vStr) = (T.unpack normK, T.unpack v)
wibble environment = (kStr, vStr) : filter ((/=kStr) . fst) environment
setPath :: Text -> Sh ()
setPath newPath = do
modify $ \x -> x{ sPathExecutables = Nothing }
setenvRaw path_env newPath
path_env :: Text
path_env = normalizeEnvVarNameText "PATH"
-- | 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.
prependToPath :: FilePath -> Sh ()
prependToPath = traceAbsPath ("prependToPath: " <>) >=> \filepath -> do
tp <- toTextWarn filepath
pe <- get_env_text path_env
setPath $ tp <> T.singleton searchPathSeparator <> pe
get_environment :: Sh [(String, String)]
get_environment = gets sEnvironment
{-# DEPRECATED get_environment "use get_env_all" #-}
-- | 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.
normalizeEnvVarNameText = T.toLower
#else
-- On other systems, keep the variable names as-is.
normalizeEnvVarNameText = id
#endif
-- | Fetch the current value of an environment variable.
-- If non-existant or empty text, will be 'Nothing'.
get_env :: Text -> Sh (Maybe Text)
get_env k = do
mval <- return
. fmap T.pack
. lookup (T.unpack normK)
=<< gets sEnvironment
return $ case mval of
Nothing -> Nothing
Just val -> if (not $ T.null val) then Just val else Nothing
where
normK = normalizeEnvVarNameText k
getenv :: Text -> Sh Text
getenv k = get_env_def k ""
{-# DEPRECATED getenv "use get_env or get_env_text" #-}
-- | Fetch the current value of an environment variable. Both empty and
-- non-existent variables give empty string as a result.
get_env_text :: Text -> Sh Text
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.
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).
initOutputHandles :: HandleInitializer -> StdInit
initOutputHandles f = StdInit (const $ return ()) f f
-- | Apply a single initializer to all three standard process handles (stdin, stdout and stderr).
initAllHandles :: HandleInitializer -> StdInit
initAllHandles f = StdInit f f f
-- | When running an external command, apply the given initializers to
-- the specified handles for that command.
-- This can for example be used to change the encoding of the
-- handles or set them into binary mode.
onCommandHandles :: StdInit -> Sh a -> Sh a
onCommandHandles initHandles a =
sub $ modify (\x -> x { sInitCommandHandles = initHandles }) >> a
-- | Create a sub-Sh in which external command outputs are not echoed and
-- commands are not printed.
-- See 'sub'.
silently :: Sh a -> Sh a
silently a = sub $ modify (\x -> x
{ sPrintStdout = False
, sPrintStderr = False
, sPrintCommands = False
}) >> a
-- | Create a sub-Sh in which external command outputs are echoed and
-- Executed commands are printed
-- See 'sub'.
verbosely :: Sh a -> Sh a
verbosely a = sub $ modify (\x -> x
{ sPrintStdout = True
, sPrintStderr = True
, sPrintCommands = True
}) >> a
-- | Create a sub-Sh in which stdout is sent to the user-defined
-- logger. When running with 'silently' the given log will not be
-- called for any output. Likewise the log will also not be called for
-- output from 'run_' and 'bash_' commands.
log_stdout_with :: (Text -> IO ()) -> Sh a -> Sh a
log_stdout_with logger a = sub $ modify (\s -> s { sPutStdout = logger })
>> a
-- | Create a sub-Sh in which stderr is sent to the user-defined
-- logger. When running with 'silently' the given log will not be
-- called for any output. However, unlike 'log_stdout_with' the log
-- will be called for output from 'run_' and 'bash_' commands.
log_stderr_with :: (Text -> IO ()) -> Sh a -> Sh a
log_stderr_with logger a = sub $ modify (\s -> s { sPutStderr = logger })
>> a
-- | Create a sub-Sh with stdout printing on or off
-- Defaults to True.
print_stdout :: Bool -> Sh a -> Sh a
print_stdout shouldPrint a =
sub $ modify (\x -> x { sPrintStdout = shouldPrint }) >> a
-- | Create a sub-Sh with stderr printing on or off
-- Defaults to True.
print_stderr :: Bool -> Sh a -> Sh a
print_stderr shouldPrint a =
sub $ modify (\x -> x { sPrintStderr = shouldPrint }) >> a
-- | Create a sub-Sh with command echoing on or off
-- Defaults to False, set to True by 'verbosely'
print_commands :: Bool -> Sh a -> Sh a
print_commands shouldPrint a = sub $ modify (\st -> st { sPrintCommands = shouldPrint }) >> a
-- | Create a sub-Sh in which commands are sent to the user-defined function.
--
-- @since 1.12.1
print_commands_with :: (Text -> IO ()) -> Sh a -> Sh a
print_commands_with fn a = sub $ modify (\st -> st { sPrintCommandsFn = fn }) >> a
-- | Enter a sub-Sh that inherits the environment
-- The original state will be restored when the sub-Sh completes.
-- Exceptions are propagated normally.
sub :: Sh a -> Sh a
sub a = do
oldState <- get
modify $ \st -> st { sTrace = T.empty }
a `finally_sh` restoreState oldState
where
restoreState oldState = do
newState <- get
put oldState {
-- avoid losing the log
sTrace = sTrace oldState <> sTrace newState
-- latest command execution: not make sense to restore these to old settings
, sCode = sCode newState
, sStderr = sStderr newState
-- it is questionable what the behavior of stdin should be
, sStdin = sStdin newState
}
-- | Create a sub-Sh where commands are not traced
-- 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 }
action
-- | Create a sub-Sh with shell character escaping on or off.
-- Defaults to @True@.
--
-- Setting to @False@ allows for shell wildcard such as * to be expanded by the shell along with any other special shell characters.
-- As a side-effect, setting to @False@ causes changes to @PATH@ to be ignored:
-- see the 'run' documentation.
escaping :: Bool -> Sh a -> Sh a
escaping shouldEscape action = sub $ do
modify $ \st -> st { sCommandEscaping = shouldEscape }
action
-- | named after bash -e errexit. Defaults to @True@.
-- When @True@, throw an exception on a non-zero exit code.
-- When @False@, ignore a non-zero exit code.
-- Not recommended to set to @False@ unless you are specifically checking the error code with 'lastExitCode'.
errExit :: Bool -> Sh a -> Sh a
errExit shouldExit action = sub $ do
modify $ \st -> st { sErrExit = shouldExit }
action
-- | 'find'-command follows symbolic links. Defaults to @False@.
-- When @True@, follow symbolic links.
-- When @False@, never follow symbolic links.
followSymlink :: Bool -> Sh a -> Sh a
followSymlink enableFollowSymlink action = sub $ do
modify $ \st -> st { sFollowSymlink = enableFollowSymlink }
action
defReadOnlyState :: ReadOnlyState
defReadOnlyState = ReadOnlyState { rosFailToDir = False }
-- | Deprecated now, just use 'shelly', whose default has been changed.
-- Using this entry point does not create a @.shelly@ directory in the case
-- of failure. Instead it logs directly into the standard error stream (@stderr@).
shellyNoDir :: MonadIO m => Sh a -> m a
shellyNoDir = shelly' ReadOnlyState { rosFailToDir = False }
{-# DEPRECATED shellyNoDir "Just use shelly. The default settings have changed" #-}
-- | Using this entry point creates a @.shelly@ directory in the case
-- of failure where errors are recorded.
shellyFailDir :: MonadIO m => Sh a -> m a
shellyFailDir = shelly' ReadOnlyState { rosFailToDir = True }
getNormalizedEnvironment :: IO [(String, String)]
getNormalizedEnvironment =
#if defined(mingw32_HOST_OS)
-- On Windows, normalize all environment variable names (to lowercase)
-- to account for case insensitivity.
fmap (\(a, b) -> (map toLower a, b)) <$> getEnvironment
#else
-- On other systems, keep the environment as-is.
getEnvironment
#endif
-- | Enter a Sh from (Monad)IO. The environment and working directories are
-- inherited from the current process-wide values. Any subsequent changes in
-- processwide working directory or environment are not reflected in the
-- running Sh.
shelly :: MonadIO m => Sh a -> m a
shelly = shelly' defReadOnlyState
shelly' :: MonadIO m => ReadOnlyState -> Sh a -> m a
shelly' ros action = do
environment <- liftIO getNormalizedEnvironment
dir <- liftIO getCurrentDirectory
let def = State { sCode = 0
, sStdin = Nothing
, sStderr = T.empty
, sPutStdout = TIO.hPutStrLn stdout
, sPutStderr = TIO.hPutStrLn stderr
, sPrintStdout = True
, sPrintStderr = True
, sPrintCommands = False
, sPrintCommandsFn = TIO.hPutStrLn stdout
, sInitCommandHandles = initAllHandles (const $ return ())
, sCommandEscaping = True
, sEnvironment = environment
, sTracing = True
, sTrace = T.empty
, sDirectory = dir
, sPathExecutables = Nothing
, sErrExit = True
, sReadOnly = ros
, sFollowSymlink = False
}
stref <- liftIO $ newIORef def
let caught =
action `catches_sh` [
ShellyHandler (\ex ->
case ex of
ExitSuccess -> liftIO $ throwIO ex
ExitFailure _ -> throwExplainedException ex
)
, ShellyHandler (\ex -> case ex of
QuietExit n -> liftIO $ throwIO $ ExitFailure n)
, ShellyHandler (\(ex::SomeException) -> throwExplainedException ex)
]
liftIO $ runSh caught stref
where
throwExplainedException :: Exception exception => exception -> Sh a
throwExplainedException ex = get >>= errorMsg >>= liftIO . throwIO . ReThrownException ex
errorMsg st =
if not (rosFailToDir $ sReadOnly st) then ranCommands else do
d <- pwd
sf <- shellyFile
let logFile = d</>shelly_dir</>sf
(writefile logFile trc >> return ("log of commands saved to: " <> logFile))
`catchany_sh` (\_ -> ranCommands)