shake 0.13.4 → 0.14
raw patch · 245 files changed
+10601/−20249 lines, 245 filesdep +extradep +js-flotdep +js-jquerydep ~unordered-containers
Dependencies added: extra, js-flot, js-jquery
Dependency ranges changed: unordered-containers
Files
- CHANGES.txt +17/−0
- Development/Make/All.hs +0/−131
- Development/Make/Env.hs +0/−40
- Development/Make/Parse.hs +0/−72
- Development/Make/Rules.hs +0/−62
- Development/Make/Type.hs +0/−57
- Development/Ninja/All.hs +0/−278
- Development/Ninja/Env.hs +0/−39
- Development/Ninja/Lexer.hs +0/−219
- Development/Ninja/Parse.hs +0/−78
- Development/Ninja/Type.hs +0/−67
- Development/Shake.hs +0/−161
- Development/Shake/Args.hs +0/−341
- Development/Shake/ByteString.hs +0/−75
- Development/Shake/Classes.hs +0/−11
- Development/Shake/Command.hs +0/−429
- Development/Shake/Config.hs +0/−88
- Development/Shake/Core.hs +0/−832
- Development/Shake/Database.hs +0/−531
- Development/Shake/Demo.hs +0/−135
- Development/Shake/Derived.hs +0/−139
- Development/Shake/Errors.hs +0/−132
- Development/Shake/FileInfo.hs +0/−138
- Development/Shake/FilePath.hs +0/−121
- Development/Shake/FilePattern.hs +0/−175
- Development/Shake/Monad.hs +0/−121
- Development/Shake/Pool.hs +0/−165
- Development/Shake/Profile.hs +0/−90
- Development/Shake/Progress.hs +0/−348
- Development/Shake/Resource.hs +0/−162
- Development/Shake/Rule.hs +0/−26
- Development/Shake/Rules/Directory.hs +0/−277
- Development/Shake/Rules/File.hs +0/−258
- Development/Shake/Rules/Files.hs +0/−145
- Development/Shake/Rules/Oracle.hs +0/−118
- Development/Shake/Rules/OrderOnly.hs +0/−55
- Development/Shake/Rules/Rerun.hs +0/−37
- Development/Shake/Shake.hs +0/−29
- Development/Shake/Special.hs +0/−20
- Development/Shake/Storage.hs +0/−255
- Development/Shake/Types.hs +0/−223
- Development/Shake/Util.hs +0/−60
- Development/Shake/Value.hs +0/−138
- General/Base.hs +0/−312
- General/Bilist.hs +0/−33
- General/Binary.hs +0/−63
- General/Cleanup.hs +0/−35
- General/Concurrent.hs +0/−106
- General/Intern.hs +0/−48
- General/String.hs +0/−65
- General/Template.hs +0/−30
- General/Timing.hs +0/−52
- Main.hs +0/−4
- Paths.hs +0/−22
- README.md +2/−0
- Start.hs +0/−49
- Test.hs +0/−131
- Test/Assume.hs +0/−45
- Test/Basic.hs +0/−132
- Test/Benchmark.hs +0/−21
- Test/C.hs +0/−28
- Test/C/constants.c +0/−7
- Test/C/constants.h +0/−1
- Test/C/main.c +0/−8
- Test/Cache.hs +0/−39
- Test/Command.hs +0/−60
- Test/Config.hs +0/−57
- Test/Digest.hs +0/−78
- Test/Directory.hs +0/−109
- Test/Docs.hs +0/−266
- Test/Errors.hs +0/−120
- Test/FilePath.hs +0/−96
- Test/FilePattern.hs +0/−61
- Test/Files.hs +0/−39
- Test/Journal.hs +0/−44
- Test/Lint.hs +0/−119
- Test/Live.hs +0/−29
- Test/MakeTutor/Makefile +0/−17
- Test/MakeTutor/hellofunc.c +0/−9
- Test/MakeTutor/hellomake.c +0/−8
- Test/MakeTutor/hellomake.h +0/−5
- Test/Makefile.hs +0/−24
- Test/Manual.hs +0/−24
- Test/Monad.hs +0/−89
- Test/Ninja.hs +0/−87
- Test/Ninja/compdb.ninja +0/−45
- Test/Ninja/compdb.output +0/−17
- Test/Ninja/lint.ninja +0/−13
- Test/Ninja/nocreate.ninja +0/−5
- Test/Ninja/test1.ninja +0/−5
- Test/Ninja/test2.ninja +0/−8
- Test/Ninja/test3-inc.ninja +0/−3
- Test/Ninja/test3-sub.ninja +0/−6
- Test/Ninja/test3-unix.ninja +0/−3
- Test/Ninja/test3-win.ninja +0/−3
- Test/Ninja/test3.ninja +0/−21
- Test/Ninja/test4.ninja +0/−9
- Test/Ninja/test5.ninja +0/−5
- Test/Ninja/test6-inc.ninja +0/−1
- Test/Ninja/test6-sub.ninja +0/−1
- Test/Ninja/test6.ninja +0/−3
- Test/Oracle.hs +0/−76
- Test/OrderOnly.hs +0/−41
- Test/Pool.hs +0/−68
- Test/Progress.hs +0/−63
- Test/Progress/self-clean-j2.prog +0/−62
- Test/Progress/self-rebuild-j2.prog +0/−56
- Test/Progress/self-zero-j2.prog +0/−57
- Test/Random.hs +0/−138
- Test/Resources.hs +0/−33
- Test/Self.hs +0/−86
- Test/Tar.hs +0/−13
- Test/Tar/list.txt +0/−3
- Test/Throttle.hs +0/−29
- Test/Type.hs +0/−211
- Test/Unicode.hs +0/−61
- Test/Util.hs +0/−20
- Test/Verbosity.hs +0/−39
- docs/Manual.md +29/−23
- docs/Why.md +1/−1
- docs/manual/Build.hs +2/−2
- html/jquery.flot.js +0/−28
- html/jquery.flot.stack.js +0/−36
- html/jquery.js +0/−2
- html/profile.html +3/−3
- html/progress.html +3/−3
- js-src/flot-0.8.0.zip binary
- js-src/jquery-1.8.3.js +0/−9472
- shake.cabal +40/−25
- src/Development/Make/All.hs +130/−0
- src/Development/Make/Env.hs +40/−0
- src/Development/Make/Parse.hs +72/−0
- src/Development/Make/Rules.hs +62/−0
- src/Development/Make/Type.hs +57/−0
- src/Development/Ninja/All.hs +279/−0
- src/Development/Ninja/Env.hs +39/−0
- src/Development/Ninja/Lexer.hs +219/−0
- src/Development/Ninja/Parse.hs +78/−0
- src/Development/Ninja/Type.hs +67/−0
- src/Development/Shake.hs +199/−0
- src/Development/Shake/Args.hs +342/−0
- src/Development/Shake/ByteString.hs +75/−0
- src/Development/Shake/Classes.hs +11/−0
- src/Development/Shake/Command.hs +469/−0
- src/Development/Shake/Config.hs +107/−0
- src/Development/Shake/Core.hs +833/−0
- src/Development/Shake/Database.hs +533/−0
- src/Development/Shake/Demo.hs +134/−0
- src/Development/Shake/Derived.hs +157/−0
- src/Development/Shake/Errors.hs +132/−0
- src/Development/Shake/FileInfo.hs +141/−0
- src/Development/Shake/FilePath.hs +95/−0
- src/Development/Shake/FilePattern.hs +174/−0
- src/Development/Shake/Monad.hs +122/−0
- src/Development/Shake/Pool.hs +164/−0
- src/Development/Shake/Profile.hs +91/−0
- src/Development/Shake/Progress.hs +353/−0
- src/Development/Shake/Resource.hs +162/−0
- src/Development/Shake/Rule.hs +26/−0
- src/Development/Shake/Rules/Directory.hs +280/−0
- src/Development/Shake/Rules/File.hs +256/−0
- src/Development/Shake/Rules/Files.hs +136/−0
- src/Development/Shake/Rules/Oracle.hs +118/−0
- src/Development/Shake/Rules/OrderOnly.hs +56/−0
- src/Development/Shake/Rules/Rerun.hs +37/−0
- src/Development/Shake/Shake.hs +29/−0
- src/Development/Shake/Special.hs +20/−0
- src/Development/Shake/Storage.hs +245/−0
- src/Development/Shake/Types.hs +223/−0
- src/Development/Shake/Util.hs +60/−0
- src/Development/Shake/Value.hs +138/−0
- src/General/Bilist.hs +34/−0
- src/General/Binary.hs +63/−0
- src/General/Cleanup.hs +38/−0
- src/General/Concurrent.hs +32/−0
- src/General/Extra.hs +75/−0
- src/General/Intern.hs +48/−0
- src/General/Prelude.hs +11/−0
- src/General/String.hs +65/−0
- src/General/Template.hs +46/−0
- src/General/Timing.hs +53/−0
- src/Paths.hs +22/−0
- src/Run.hs +49/−0
- src/Test.hs +130/−0
- src/Test/Assume.hs +45/−0
- src/Test/Basic.hs +132/−0
- src/Test/Benchmark.hs +21/−0
- src/Test/C.hs +28/−0
- src/Test/C/constants.c +7/−0
- src/Test/C/constants.h +1/−0
- src/Test/C/main.c +8/−0
- src/Test/Cache.hs +39/−0
- src/Test/Command.hs +79/−0
- src/Test/Config.hs +61/−0
- src/Test/Digest.hs +78/−0
- src/Test/Directory.hs +110/−0
- src/Test/Docs.hs +272/−0
- src/Test/Errors.hs +144/−0
- src/Test/FilePath.hs +86/−0
- src/Test/FilePattern.hs +65/−0
- src/Test/Files.hs +39/−0
- src/Test/Journal.hs +44/−0
- src/Test/Lint.hs +119/−0
- src/Test/Live.hs +28/−0
- src/Test/MakeTutor/Makefile +17/−0
- src/Test/MakeTutor/hellofunc.c +9/−0
- src/Test/MakeTutor/hellomake.c +8/−0
- src/Test/MakeTutor/hellomake.h +5/−0
- src/Test/Makefile.hs +24/−0
- src/Test/Manual.hs +24/−0
- src/Test/Monad.hs +89/−0
- src/Test/Ninja.hs +87/−0
- src/Test/Ninja/compdb.ninja +45/−0
- src/Test/Ninja/compdb.output +17/−0
- src/Test/Ninja/lint.ninja +13/−0
- src/Test/Ninja/nocreate.ninja +5/−0
- src/Test/Ninja/test1.ninja +5/−0
- src/Test/Ninja/test2.ninja +8/−0
- src/Test/Ninja/test3-inc.ninja +3/−0
- src/Test/Ninja/test3-sub.ninja +6/−0
- src/Test/Ninja/test3-unix.ninja +3/−0
- src/Test/Ninja/test3-win.ninja +3/−0
- src/Test/Ninja/test3.ninja +21/−0
- src/Test/Ninja/test4.ninja +9/−0
- src/Test/Ninja/test5.ninja +5/−0
- src/Test/Ninja/test6-inc.ninja +1/−0
- src/Test/Ninja/test6-sub.ninja +1/−0
- src/Test/Ninja/test6.ninja +3/−0
- src/Test/Oracle.hs +76/−0
- src/Test/OrderOnly.hs +41/−0
- src/Test/Pool.hs +68/−0
- src/Test/Progress.hs +63/−0
- src/Test/Progress/self-clean-j2.prog +62/−0
- src/Test/Progress/self-rebuild-j2.prog +56/−0
- src/Test/Progress/self-zero-j2.prog +57/−0
- src/Test/Random.hs +141/−0
- src/Test/Resources.hs +33/−0
- src/Test/Self.hs +87/−0
- src/Test/Tar.hs +13/−0
- src/Test/Tar/list.txt +3/−0
- src/Test/Throttle.hs +30/−0
- src/Test/Type.hs +211/−0
- src/Test/Unicode.hs +60/−0
- src/Test/Util.hs +20/−0
- src/Test/Verbosity.hs +39/−0
CHANGES.txt view
@@ -1,5 +1,22 @@ Changelog for Shake +0.14+ Make FilePattern on Windows cope with all path separators+ Rename normalise to normaliseEx+ Expose native System.FilePath in Development.Shake.FilePath+ #193, eliminate the custom version of </>+ #193, make need/orderOnly call normalise on their arguments+ #177, use the $PATH variable to resolve cmd+ #182, use js-jquery and js-flot+ #195, add getConfigKeys+ #194, replace *> with %> as the operator for rules+ #188, improve the docs on FilePattern+ #187, removeFiles on a missing directory should do nothing+ #166, add withTempFile and withTempDir in the Action monad+ Ensure Ninja response files are always deleted+ Fix incorrect units when showing profile to the console+ Require the extra library+ #178, make --help show the current executable name 0.13.4 #171, fix the --demo mode on Linux 0.13.3
− Development/Make/All.hs
@@ -1,131 +0,0 @@-{-# LANGUAGE RecordWildCards, PatternGuards #-} - -module Development.Make.All(runMakefile) where - -import System.Environment -import Development.Shake hiding (addEnv) -import Development.Shake.FilePath -import Development.Make.Parse -import Development.Make.Env -import Development.Make.Rules -import Development.Make.Type -import qualified System.Directory as IO -import General.Base -import Data.List -import Data.Maybe -import Control.Arrow -import Control.Monad -import System.Process -import System.Exit -import Control.Monad.Trans.State.Strict - - -runMakefile :: FilePath -> [String] -> IO (Rules ()) -runMakefile file args = do - env <- defaultEnv - mk <- parse file - rs <- eval env mk - return $ do - defaultRuleFile_ - case filter (not . isPrefixOf "." . target) rs of - Ruler x _ _ : _ | null args, '%' `notElem` x -> want_ [x] - _ -> return () - mapM_ (want_ . return) args - convert rs - - -data Ruler = Ruler - {target :: String - ,prereq :: (Env, Expr) -- Env is the Env at this point - ,cmds :: (Env, [Command]) -- Env is the Env at the end - } - - -eval :: Env -> Makefile -> IO [Ruler] -eval env (Makefile xs) = do - (rs, env) <- runStateT (fmap concat $ mapM f xs) env - return [r{cmds=(env,snd $ cmds r)} | r <- rs] - where - f :: Stmt -> StateT Env IO [Ruler] - f Assign{..} = do - e <- get - e <- liftIO $ addEnv name assign expr e - put e - return [] - - f Rule{..} = do - e <- get - target <- liftIO $ fmap words $ askEnv e targets - return $ map (\t -> Ruler t (e, prerequisites) (undefined, commands)) target - - -convert :: [Ruler] -> Rules () -convert rs = match ??> run - where - match s = any (isJust . check s) rs - check s r = makePattern (target r) s - - run target = do - let phony = has False ".PHONY" target - let silent = has True ".SILENT" target - (deps, cmds) <- fmap (first concat . second concat . unzip) $ forM rs $ \r -> - case check target r of - Nothing -> return ([], []) - Just op -> do - let (preEnv,preExp) = prereq r - env <- liftIO $ addEnv "@" Equals (Lit target) preEnv - pre <- liftIO $ askEnv env preExp - vp <- liftIO $ fmap splitSearchPath $ askEnv env $ Var "VPATH" - pre <- mapM (vpath vp) $ words $ op pre - return (pre, [cmds r]) - mapM_ (need_ . return) deps - forM_ cmds $ \(env,cmd) -> do - env <- liftIO $ addEnv "@" Equals (Lit target) env - env <- liftIO $ addEnv "^" Equals (Lit $ unwords deps) env - env <- liftIO $ addEnv "<" Equals (Lit $ head $ deps ++ [""]) env - forM_ cmd $ \c -> - case c of - Expr c -> (if silent then quietly else id) $ - execCommand =<< liftIO (askEnv env c) - return $ if phony then Phony else NotPhony - - has auto name target = - or [(null ws && auto) || target `elem` ws | Ruler t (_,Lit s) _ <- rs, t == name, let ws = words s] - - -execCommand :: String -> Action () -execCommand x = do - res <- if "@" `isPrefixOf` x then sys $ drop 1 x - else putNormal x >> sys x - when (res /= ExitSuccess) $ - error $ "System command failed: " ++ x - where sys = quietly . traced (unwords $ take 1 $ words x) . system - - -makePattern :: String -> FilePath -> Maybe (String -> String) -makePattern pat v = case break (== '%') pat of - (pre,'%':post) -> if pre `isPrefixOf` v && post `isSuffixOf` v && rest >= 0 - then Just $ concatMap (\x -> if x == '%' then subs else [x]) - else Nothing - where rest = length v - (length pre + length post) - subs = take rest $ drop (length pre) v - otherwise -> if pat == v then Just id else Nothing - - -vpath :: [FilePath] -> FilePath -> Action FilePath -vpath [] y = return y -vpath (x:xs) y = do - b <- doesFileExist $ x </> y - if b then return $ x </> y else vpath xs y - - -defaultEnv :: IO Env -defaultEnv = do - exePath <- getExePath - env <- getEnvironment - cur <- IO.getCurrentDirectory - return $ newEnv $ - ("EXE",if null exe then "" else "." ++ exe) : - ("MAKE",normalise exePath) : - ("CURDIR",normalise cur) : - env
− Development/Make/Env.hs
@@ -1,40 +0,0 @@-{-# LANGUAGE PatternGuards #-}---- | The IO in this module is only to evaluate an envrionment variable,--- the 'Env' itself it passed around purely.-module Development.Make.Env(Env, newEnv, addEnv, askEnv) where--import Development.Make.Type-import Data.Maybe-import qualified Data.HashMap.Strict as Map---newtype Env = Env (Map.HashMap String (Assign,Expr))--newEnv :: [(String,String)] -> Env-newEnv xs = Env $ Map.fromList [(a,(Equals,Lit b)) | (a,b) <- xs]---addEnv :: String -> Assign -> Expr -> Env -> IO Env-addEnv name ass val env@(Env e) = case ass of- QuestionEquals -> if isJust $ Map.lookup name e then return env else addEnv name Equals val env- Equals -> return $ Env $ Map.insert name (Equals,val) e- ColonEquals -> do l <- askEnv env val; return $ Env $ Map.insert name (ColonEquals,Lit l) e- PlusEquals -> case Map.lookup name e of- Just (Equals,x) -> return $ Env $ Map.insert name (Equals,Concat [x,Lit " ",val]) e- Just (ColonEquals,x) -> do l <- askEnv env val; return $ Env $ Map.insert name (ColonEquals,Concat [x,Lit " ",Lit l]) e- _ -> addEnv name Equals val env---askEnv :: Env -> Expr -> IO String-askEnv (Env e) x = do- res <- f [] x- case simplifyExpr res of- Lit x -> return x- x -> error $ "Internal error in askEnv, " ++ show x- where- f seen (Var x) | x `elem` seen = error $ "Recursion in variables, " ++ show seen- | Just (_,y) <- Map.lookup x e = f (x:seen) y- | otherwise = return $ Lit ""- f seen x = descendExprM (f seen) x-
− Development/Make/Parse.hs
@@ -1,72 +0,0 @@-{-# LANGUAGE PatternGuards #-} - -module Development.Make.Parse(parse) where - -import Development.Make.Type -import Data.Char -import Data.List -import Data.Maybe - - -trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse - - -parse :: FilePath -> IO Makefile -parse file = do - src <- if file == "-" then getContents else readFile file - return $ parseMakefile src - - -parseMakefile :: String -> Makefile -parseMakefile xs = Makefile $ rejoin $ concatMap parse $ map comments $ continuations $ lines xs - where - continuations (x:y:xs) | "\\" `isSuffixOf` x = continuations $ (init x ++ dropWhile isSpace y):xs - continuations (x:xs) = x : continuations xs - continuations [] = [] - - comments = takeWhile (/= '#') - - parse x | all isSpace x = [] - | all isSpace $ take 1 x = [Right $ parseCommand $ trim x] - | (a,b) <- break (== ';') x = Left (parseStmt a) : [Right $ parseCommand $ trim $ drop 1 b | b /= ""] - - rejoin (Left r@Rule{}:Right e:xs) = rejoin $ Left r{commands = commands r ++ [e]} : xs - rejoin (Right e:xs) = error $ "Command must be under a rule: " ++ show e - rejoin (Left r:xs) = r : rejoin xs - rejoin [] = [] - - -parseStmt :: String -> Stmt -parseStmt x - | (a,'=':b) <- break (== '=') x, ':' `notElem` a = - if "+" `isSuffixOf` a then Assign (trim $ init a) PlusEquals (parseExpr $ trim b) - else if "?" `isSuffixOf` a then Assign (trim $ init a) QuestionEquals (parseExpr $ trim b) - else Assign (trim a) Equals (parseExpr $ trim b) - | (a,':':b) <- break (== ':') x = case b of - '=':b -> Assign (trim a) ColonEquals (parseExpr $ trim b) - ':':'=':b -> Assign (trim a) ColonEquals (parseExpr $ trim b) - _ -> Rule (parseExpr $ trim a) (parseExpr $ trim $ fromMaybe b $ stripPrefix ":" b) [] - | otherwise = error $ "Invalid statement: " ++ x - - -parseExpr :: String -> Expr -parseExpr x = simplifyExpr $ Concat $ f x - where - f ('$':'$':x) = Lit "$" : f x - f ('$':'(':xs) = case break (== ')') xs of - (var,')':rest) -> parseVar var : f rest - _ -> error $ "Couldn't find trailing `)' after " ++ xs - f ('$':'{':xs) = case break (== '}') xs of - (var,'}':rest) -> parseVar var : f rest - _ -> error $ "Couldn't find trailing `}' after " ++ xs - f ('$':x:xs) = Var [x] : f xs - f (x:xs) = Lit [x] : f xs - f [] = [] - - -parseVar :: String -> Expr -parseVar x = Var x - - -parseCommand :: String -> Command -parseCommand = Expr . parseExpr
− Development/Make/Rules.hs
@@ -1,62 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable #-}---- | These are the additional rule types required by Makefile-module Development.Make.Rules(- need_, want_,- defaultRuleFile_,- (??>), Phony(..)- ) where--import Control.Monad.IO.Class-import System.Directory--import Development.Shake.Core-import General.String-import Development.Shake.Classes-import Development.Shake.FilePath-import Development.Shake.FileInfo--infix 1 ??>-------------------------------------------------------------------------- FILE_ RULES--- These are like file rules, but a rule may not bother creating the result--- Which matches the (insane) semantics of make--- If a file is not produced, it will rebuild forever--newtype File_Q = File_Q BSU- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show File_Q where show (File_Q x) = unpackU x--newtype File_A = File_A (Maybe ModTime)- deriving (Typeable,Eq,Hashable,Binary,Show,NFData)--instance Rule File_Q File_A where- storedValue _ (File_Q x) = fmap (fmap (File_A . Just . fst)) $ getFileInfo x---defaultRuleFile_ :: Rules ()-defaultRuleFile_ = priority 0 $ rule $ \(File_Q x) -> Just $ liftIO $ do- res <- getFileInfo x- case res of- Nothing -> error $ "Error, file does not exist and no rule available:\n " ++ unpackU x- Just (mt,_) -> return $ File_A $ Just mt---need_ :: [FilePath] -> Action ()-need_ xs = (apply $ map (File_Q . packU) xs :: Action [File_A]) >> return ()--want_ :: [FilePath] -> Rules ()-want_ = action . need_--data Phony = Phony | NotPhony deriving Eq--(??>) :: (FilePath -> Bool) -> (FilePath -> Action Phony) -> Rules ()-(??>) test act = rule $ \(File_Q x_) -> let x = unpackU x_ in- if not $ test x then Nothing else Just $ do- liftIO $ createDirectoryIfMissing True $ takeDirectory x- res <- act x- liftIO $ fmap (File_A . fmap fst) $ if res == Phony- then return Nothing- else getFileInfo x_
− Development/Make/Type.hs
@@ -1,57 +0,0 @@- -module Development.Make.Type where - -import Control.Monad - - -data Makefile = Makefile [Stmt] deriving Show - -data Stmt - = Rule - {targets :: Expr - ,prerequisites :: Expr - ,commands :: [Command] - } - | Assign - {name :: String - ,assign :: Assign - ,expr :: Expr - } - deriving Show - -data Assign = Equals | ColonEquals | PlusEquals | QuestionEquals deriving Show - -data Expr = Apply String [Expr] - | Concat [Expr] - | Var String - | Lit String - deriving Show - -data Command = Expr Expr | String := Expr deriving Show - -descendExpr :: (Expr -> Expr) -> Expr -> Expr -descendExpr f (Apply a b) = Apply a $ map f b -descendExpr f (Concat xs) = Concat $ map f xs -descendExpr f x = x - -descendExprM :: Monad m => (Expr -> m Expr) -> Expr -> m Expr -descendExprM f (Apply a b) = Apply a `liftM` mapM f b -descendExprM f (Concat xs) = Concat `liftM` mapM f xs -descendExprM f x = return x - -transformExpr :: (Expr -> Expr) -> Expr -> Expr -transformExpr f = f . descendExpr (transformExpr f) - -simplifyExpr :: Expr -> Expr -simplifyExpr = transformExpr f - where - f (Concat xs) = case g xs of - [] -> Lit "" - [x] -> x - xs -> Concat xs - f x = x - - g (Concat x:xs) = g $ x ++ xs - g (Lit x:Lit y:xs) = g $ Lit (x ++ y) : xs - g (x:xs) = x : g xs - g [] = []
− Development/Ninja/All.hs
@@ -1,278 +0,0 @@-{-# LANGUAGE RecordWildCards, ScopedTypeVariables, ViewPatterns #-} - -module Development.Ninja.All(runNinja) where - -import Development.Ninja.Env -import Development.Ninja.Type -import Development.Ninja.Parse -import Development.Shake hiding (addEnv) -import Development.Shake.ByteString -import Development.Shake.Errors -import Development.Shake.Rules.File -import Development.Shake.Rules.OrderOnly -import General.Base -import General.Timing -import qualified Data.ByteString as BS8 -import qualified Data.ByteString.Char8 as BS - -import System.Directory -import qualified Data.HashMap.Strict as Map -import qualified Data.HashSet as Set -import Control.Arrow -import Control.Monad -import Data.Maybe -import Data.Char - - -runNinja :: FilePath -> [String] -> Maybe String -> IO (Maybe (Rules ())) -runNinja file args (Just "compdb") = do - dir <- getCurrentDirectory - Ninja{..} <- parse file =<< newEnv - rules <- return $ Map.fromList [r | r <- rules, BS.unpack (fst r) `elem` args] - -- the build items are generated in reverse order, hence the reverse - let xs = [(a,b,file,rule) | (a,b@Build{..}) <- reverse $ multiples ++ map (first return) singles - , Just rule <- [Map.lookup ruleName rules], file:_ <- [depsNormal]] - xs <- forM xs $ \(out,Build{..},file,Rule{..}) -> do - -- the order of adding new environment variables matters - env <- scopeEnv env - addEnv env (BS.pack "out") (BS.unwords $ map quote out) - addEnv env (BS.pack "in") (BS.unwords $ map quote depsNormal) - addEnv env (BS.pack "in_newline") (BS.unlines depsNormal) - addBinds env buildBind - addBinds env ruleBind - commandline <- fmap BS.unpack $ askVar env $ BS.pack "command" - return $ CompDb dir commandline $ BS.unpack $ head depsNormal - putStr $ printCompDb xs - return Nothing - -runNinja file args (Just x) = error $ "Unknown tool argument, expected 'compdb', got " ++ x - -runNinja file args tool = do - addTiming "Ninja parse" - ninja@Ninja{..} <- parse file =<< newEnv - return $ Just $ do - needDeps <- return $ needDeps ninja -- partial application - phonys <- return $ Map.fromList phonys - singles <- return $ Map.fromList $ map (first filepathNormalise) singles - multiples <- return $ Map.fromList [(x,(xs,b)) | (xs,b) <- map (first $ map filepathNormalise) multiples, x <- xs] - rules <- return $ Map.fromList rules - pools <- fmap Map.fromList $ forM ((BS.pack "console",1):pools) $ \(name,depth) -> - fmap ((,) name) $ newResource (BS.unpack name) depth - - action $ needBS $ map filepathNormalise $ concatMap (resolvePhony phonys) $ - if not $ null args then map BS.pack args - else if not $ null defaults then defaults - else Map.keys singles ++ Map.keys multiples - - (\x -> fmap (map BS.unpack . fst) $ Map.lookup (BS.pack x) multiples) &?> \out -> let out2 = map BS.pack out in - build needDeps phonys rules pools out2 $ snd $ multiples Map.! head out2 - - (flip Map.member singles . BS.pack) ?> \out -> let out2 = BS.pack out in - build needDeps phonys rules pools [out2] $ singles Map.! out2 - - -resolvePhony :: Map.HashMap Str [Str] -> Str -> [Str] -resolvePhony mp = f $ Left 100 - where - f (Left 0) x = f (Right []) x - f (Right xs) x | x `elem` xs = error $ "Recursive phony involving " ++ BS.unpack x - f a x = case Map.lookup x mp of - Nothing -> [x] - Just xs -> concatMap (f $ either (Left . subtract 1) (Right . (x:)) a) xs - - -quote :: Str -> Str -quote x | BS.any isSpace x = let q = BS.singleton '\"' in BS.concat [q,x,q] - | otherwise = x - - -build :: (Build -> [Str] -> Action ()) -> Map.HashMap Str [Str] -> Map.HashMap Str Rule -> Map.HashMap Str Resource -> [Str] -> Build -> Action () -build needDeps phonys rules pools out build@Build{..} = do - needBS $ map filepathNormalise $ concatMap (resolvePhony phonys) $ depsNormal ++ depsImplicit - orderOnlyBS $ map filepathNormalise $ concatMap (resolvePhony phonys) depsOrderOnly - case Map.lookup ruleName rules of - Nothing -> error $ "Ninja rule named " ++ BS.unpack ruleName ++ " is missing, required to build " ++ BS.unpack (BS.unwords out) - Just Rule{..} -> do - env <- liftIO $ scopeEnv env - liftIO $ do - -- the order of adding new environment variables matters - addEnv env (BS.pack "out") (BS.unwords $ map quote out) - addEnv env (BS.pack "in") (BS.unwords $ map quote depsNormal) - addEnv env (BS.pack "in_newline") (BS.unlines depsNormal) - addBinds env buildBind - addBinds env ruleBind - - applyRspfile env $ do - commandline <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "command" - depfile <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "depfile" - deps <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "deps" - description <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "description" - pool <- liftIO $ askVar env $ BS.pack "pool" - - let withPool act = case Map.lookup pool pools of - _ | BS.null pool -> act - Nothing -> error $ "Ninja pool named " ++ BS.unpack pool ++ " not found, required to build " ++ BS.unpack (BS.unwords out) - Just r -> withResource r 1 act - - when (description /= "") $ putNormal description - let (cmdOpts, cmdProg, cmdArgs) = toCommand commandline - if deps == "msvc" then do - Stdout stdout <- withPool $ command cmdOpts cmdProg cmdArgs - prefix <- liftIO $ fmap (fromMaybe $ BS.pack "Note: including file: ") $ - askEnv env $ BS.pack "msvc_deps_prefix" - needDeps build $ map filepathNormalise $ parseShowIncludes prefix $ BS.pack stdout - else - withPool $ command_ cmdOpts cmdProg cmdArgs - when (depfile /= "") $ do - when (deps /= "gcc") $ need [depfile] - depsrc <- liftIO $ BS.readFile depfile - needDeps build $ concatMap snd $ parseMakefile depsrc - -- correct as per the Ninja spec, but breaks --skip-commands - -- when (deps == "gcc") $ liftIO $ removeFile depfile - - -needDeps :: Ninja -> Build -> [Str] -> Action () -needDeps Ninja{..} = \build xs -> do -- eta reduced so 'builds' is shared - opts <- getShakeOptions - if isNothing $ shakeLint opts then needBS xs else do - neededBS xs - -- now try and statically validate needed will never fail - -- first find which dependencies are generated files - xs <- return $ filter (`Map.member` builds) xs - -- now try and find them as dependencies - let bad = xs `difference` allDependencies build - case bad of - [] -> return () - x:_ -> errorStructured - "Lint checking error - file in deps is generated and not a pre-dependency" - [("File", Just $ BS.unpack x)] - "" - where - builds :: Map.HashMap FileStr Build - builds = Map.fromList $ singles ++ [(x,y) | (xs,y) <- multiples, x <- xs] - - -- do list difference, assuming a small initial set, most of which occurs early in the list - difference :: [Str] -> [Str] -> [Str] - difference [] ys = [] - difference xs ys = f (Set.fromList xs) ys - where - f xs [] = Set.toList xs - f xs (y:ys) | y `Set.member` xs = if Set.null xs2 then [] else f xs2 ys - where xs2 = Set.delete y xs - f xs (y:ys) = f xs ys - - -- find all dependencies of a rule, no duplicates, with all dependencies of this rule listed first - allDependencies :: Build -> [FileStr] - allDependencies rule = f Set.empty [] [rule] - where - f seen [] [] = [] - f seen [] (x:xs) = f seen (map filepathNormalise $ depsNormal x ++ depsImplicit x ++ depsOrderOnly x) xs - f seen (x:xs) rest | x `Set.member` seen = f seen xs rest - | otherwise = x : f (Set.insert x seen) xs (maybeToList (Map.lookup x builds) ++ rest) - - -applyRspfile :: Env Str Str -> Action a -> Action a -applyRspfile env act = do - rspfile <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "rspfile" - rspfile_content <- liftIO $ askVar env $ BS.pack "rspfile_content" - if rspfile == "" then - act - else do - liftIO $ BS.writeFile rspfile rspfile_content - res <- act - liftIO $ removeFile rspfile - return res - - -parseShowIncludes :: Str -> Str -> [FileStr] -parseShowIncludes prefix out = - [y | x <- BS.lines out, prefix `BS.isPrefixOf` x - , let y = BS.dropWhile isSpace $ BS.drop (BS.length prefix) x - , not $ isSystemInclude y] - --- Dodgy, but ported over from the original Ninja -isSystemInclude :: FileStr -> Bool -isSystemInclude x = bsProgFiles `BS.isInfixOf` tx || bsVisStudio `BS.isInfixOf` tx - where tx = BS8.map (\c -> if c >= 97 then c - 32 else c) x - -- optimised toUpper that only cares about letters and spaces - -bsProgFiles = BS.pack "PROGRAM FILES" -bsVisStudio = BS.pack "MICROSOFT VISUAL STUDIO" - - -data CompDb = CompDb - {cdbDirectory :: String - ,cdbCommand :: String - ,cdbFile :: String - } - deriving Show - -printCompDb :: [CompDb] -> String -printCompDb xs = unlines $ ["["] ++ concat (zipWith f [1..] xs) ++ ["]"] - where - n = length xs - f i CompDb{..} = - [" {" - ," \"directory\": " ++ g cdbDirectory ++ "," - ," \"command\": " ++ g cdbCommand ++ "," - ," \"file\": " ++ g cdbFile - ," }" ++ (if i == n then "" else ",")] - g = show - - -toCommand :: String -> ([CmdOption], String, [String]) -toCommand s - -- On POSIX, Ninja does a /bin/sh -c, and so does Haskell in Shell mode (easy). - | not isWindows = ([Shell], s, []) - -- On Windows, Ninja passes the string directly to CreateProcess, - -- but Haskell applies some escaping first. - -- We try and get back as close to the original as we can, but it's very hacky - | length s < 8000 = - -- Using the "cmd" program adds overhead (I measure 7ms), and a limit of 8191 characters, - -- but is the most robust, requiring no additional escaping. - ([Shell], s, []) - | (cmd,s) <- word1 s, map toUpper cmd `elem` ["CMD","CMD.EXE"], ("/c",s) <- word1 s = - -- Given "cmd.exe /c <something>" we translate to Shell, which adds cmd.exe - -- (looked up on the current path) and /c to the front. CMake uses this rule a lot. - -- Adding quotes around pieces are /c goes very wrong. - ([Shell], s, []) - | otherwise = - -- It's a long command line which doesn't call "cmd /c". We reverse the escaping - -- Haskell applies, but each argument will still gain quotes around it. - let xs = splitArgs s in ([], head $ xs ++ [""], drop 1 xs) - - -data State - = Gap -- ^ Current in the gap between words - | Word -- ^ Currently inside a space-separated argument - | Quot -- ^ Currently inside a quote-surrounded argument - --- | The process package contains a translate function, reproduced below. The aim is that after command line --- parsing we should get out mostly the same answer. -splitArgs :: String -> [String] -splitArgs = f Gap - where - f Gap (x:xs) | isSpace x = f Gap xs - f Gap ('\"':xs) = f Quot xs - f Gap [] = [] - f Gap xs = f Word xs - f Word (x:xs) | isSpace x = [] : f Gap xs - f Quot ('\"':xs) = [] : f Gap xs - f s ('\\':xs) | (length -> a, b) <- span (== '\\') xs = case b of - '\"':xs | even a -> add (replicate (a `div` 2) '\\' ++ "\"") $ f s xs - | otherwise -> add (replicate ((a+1) `div` 2) '\\') $ f s ('\"':xs) - xs -> add (replicate (a+1) '\\') $ f s xs - f s (x:xs) = add [x] $ f s xs - f s [] = [] : [] - - add a (b:c) = (a++b):c - add a [] = a:[] - -{- -translate (cmd,args) = unwords $ f cmd : map f args - where - f x = '"' : snd (foldr escape (True,"\"") xs) - escape '"' (_, str) = (True, '\\' : '"' : str) - escape '\\' (True, str) = (True, '\\' : '\\' : str) - escape c (_, str) = (False, c : str) --}
− Development/Ninja/Env.hs
@@ -1,39 +0,0 @@-{-# LANGUAGE PatternGuards #-}---- | A Ninja style environment, basically a linked-list of mutable hash tables.-module Development.Ninja.Env(- Env, newEnv, scopeEnv, addEnv, askEnv, fromEnv- ) where--import qualified Data.HashMap.Strict as Map-import Data.Hashable-import Data.IORef---data Env k v = Env (IORef (Map.HashMap k v)) (Maybe (Env k v))--instance Show (Env k v) where show _ = "Env"---newEnv :: IO (Env k v)-newEnv = do ref <- newIORef Map.empty; return $ Env ref Nothing---scopeEnv :: Env k v -> IO (Env k v)-scopeEnv e = do ref <- newIORef Map.empty; return $ Env ref $ Just e---addEnv :: (Eq k, Hashable k) => Env k v -> k -> v -> IO ()-addEnv (Env ref _) k v = modifyIORef ref $ Map.insert k v---askEnv :: (Eq k, Hashable k) => Env k v -> k -> IO (Maybe v)-askEnv (Env ref e) k = do- mp <- readIORef ref- case Map.lookup k mp of- Just v -> return $ Just v- Nothing | Just e <- e -> askEnv e k- _ -> return Nothing--fromEnv :: Env k v -> IO (Map.HashMap k v)-fromEnv (Env ref _) = readIORef ref
− Development/Ninja/Lexer.hs
@@ -1,219 +0,0 @@-{-# LANGUAGE PatternGuards #-}-{-# OPTIONS_GHC -O2 #-}--- {-# OPTIONS_GHC -ddump-simpl #-}---- | Lexing is a slow point, the code below is optimised-module Development.Ninja.Lexer(Lexeme(..), lexer, lexerFile) where--import Control.Arrow-import qualified Data.ByteString.Char8 as BS-import qualified Data.ByteString.Unsafe as BS-import Development.Ninja.Type-import qualified Data.ByteString.Internal as Internal-import Foreign-import GHC.Exts-------------------------------------------------------------------------- LIBRARY BITS--newtype Str0 = Str0 Str -- null terminated--type S = Ptr Word8--chr :: S -> Char-chr x = Internal.w2c $ Internal.inlinePerformIO $ peek x--inc :: S -> S-inc x = x `plusPtr` 1--{-# INLINE dropWhile0 #-}-dropWhile0 :: (Char -> Bool) -> Str0 -> Str0-dropWhile0 f x = snd $ span0 f x--{-# INLINE span0 #-}-span0 :: (Char -> Bool) -> Str0 -> (Str, Str0)-span0 f x = break0 (not . f) x--{-# INLINE break0 #-}-break0 :: (Char -> Bool) -> Str0 -> (Str, Str0)-break0 f (Str0 bs) = (BS.unsafeTake i bs, Str0 $ BS.unsafeDrop i bs)- where- i = Internal.inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> do- let start = castPtr ptr :: S- let end = go start- return $! Ptr end `minusPtr` start-- go s@(Ptr a) | c == '\0' || f c = a- | otherwise = go (inc s)- where c = chr s--{-# INLINE break00 #-}--- The predicate must return true for '\0'-break00 :: (Char -> Bool) -> Str0 -> (Str, Str0)-break00 f (Str0 bs) = (BS.unsafeTake i bs, Str0 $ BS.unsafeDrop i bs)- where- i = Internal.inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> do- let start = castPtr ptr :: S- let end = go start- return $! Ptr end `minusPtr` start-- go s@(Ptr a) | f c = a- | otherwise = go (inc s)- where c = chr s--head0 :: Str0 -> Char-head0 (Str0 x) = Internal.w2c $ BS.unsafeHead x--tail0 :: Str0 -> Str0-tail0 (Str0 x) = Str0 $ BS.unsafeTail x--list0 :: Str0 -> (Char, Str0)-list0 x = (head0 x, tail0 x)--take0 :: Int -> Str0 -> Str-take0 i (Str0 x) = BS.takeWhile (/= '\0') $ BS.take i x--------------------------------------------------------------------------- ACTUAL LEXER---- Lex each line separately, rather than each lexeme-data Lexeme- = LexBind Str Expr -- [indent]foo = bar- | LexBuild [Expr] Str [Expr] -- build foo: bar | baz || qux (| and || are represented as Expr)- | LexInclude Expr -- include file- | LexSubninja Expr -- include file- | LexRule Str -- rule name- | LexPool Str -- pool name- | LexDefault [Expr] -- default foo bar- | LexDefine Str Expr -- foo = bar- deriving Show--isVar, isVarDot :: Char -> Bool-isVar x = x == '-' || x == '_' || (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= '0' && x <= '9')-isVarDot x = x == '.' || isVar x--endsDollar :: Str -> Bool-endsDollar x = BS.isSuffixOf (BS.singleton '$') x--dropN :: Str0 -> Str0-dropN x = if head0 x == '\n' then tail0 x else x--dropSpace :: Str0 -> Str0-dropSpace x = dropWhile0 (== ' ') x---lexerFile :: Maybe FilePath -> IO [Lexeme]-lexerFile file = fmap lexer $ maybe BS.getContents BS.readFile file--lexer :: Str -> [Lexeme]-lexer x = lexerLoop $ Str0 $ x `BS.append` BS.pack "\n\n\0"--lexerLoop :: Str0 -> [Lexeme]-lexerLoop c_x | (c,x) <- list0 c_x = case c of- '\r' -> lexerLoop x- '\n' -> lexerLoop x- ' ' -> lexBind $ dropSpace x- '#' -> lexerLoop $ dropWhile0 (/= '\n') x- 'b' | Just x <- strip "uild " x -> lexBuild $ dropSpace x- 'r' | Just x <- strip "ule " x -> lexRule $ dropSpace x- 'd' | Just x <- strip "efault " x -> lexDefault $ dropSpace x- 'p' | Just x <- strip "ool " x -> lexPool $ dropSpace x- 'i' | Just x <- strip "nclude " x -> lexInclude $ dropSpace x- 's' | Just x <- strip "ubninja " x -> lexSubninja $ dropSpace x- '\0' -> []- _ -> lexDefine c_x- where- strip str (Str0 x) = if b `BS.isPrefixOf` x then Just $ Str0 $ BS.drop (BS.length b) x else Nothing- where b = BS.pack str--lexBind c_x | (c,x) <- list0 c_x = case c of- '\r' -> lexerLoop x- '\n' -> lexerLoop x- '#' -> lexerLoop $ dropWhile0 (/= '\n') x- '\0' -> []- _ -> lexxBind LexBind c_x--lexBuild x- | (outputs,x) <- lexxExprs True x- , (rule,x) <- span0 isVar $ dropSpace x- , (deps,x) <- lexxExprs False $ dropSpace x- = LexBuild outputs rule deps : lexerLoop x--lexDefault x- | (files,x) <- lexxExprs False x- = LexDefault files : lexerLoop x--lexRule x = lexxName LexRule x-lexPool x = lexxName LexPool x-lexInclude x = lexxFile LexInclude x-lexSubninja x = lexxFile LexSubninja x-lexDefine x = lexxBind LexDefine x--lexxBind ctor x- | (var,x) <- span0 isVarDot x- , ('=',x) <- list0 $ dropSpace x- , (exp,x) <- lexxExpr False False $ dropSpace x- = ctor var exp : lexerLoop x-lexxBind _ x = error $ show ("parse failed when parsing binding", take0 100 x)--lexxFile ctor x- | (exp,rest) <- lexxExpr False False $ dropSpace x- = ctor exp : lexerLoop rest--lexxName ctor x- | (name,rest) <- splitLineCont x- = ctor name : lexerLoop rest---lexxExprs :: Bool -> Str0 -> ([Expr], Str0)-lexxExprs stopColon x = case lexxExpr stopColon True x of- (a,c_x) | c <- head0 c_x, x <- tail0 c_x -> case c of- ' ' -> first (a:) $ lexxExprs stopColon $ dropSpace x- ':' | stopColon -> ([a], x)- _ | stopColon -> error "expected a colon"- '\r' -> a $: dropN x- '\n' -> a $: x- '\0' -> a $: c_x- where- Exprs [] $: x = ([], x)- a $: x = ([a], x)---{-# NOINLINE lexxExpr #-}-lexxExpr :: Bool -> Bool -> Str0 -> (Expr, Str0) -- snd will start with one of " :\n\r" or be empty-lexxExpr stopColon stopSpace = first exprs . f- where- exprs [x] = x- exprs xs = Exprs xs-- special = case (stopColon, stopSpace) of- (True , True ) -> \x -> x <= ':' && (x == ':' || x == ' ' || x == '$' || x == '\r' || x == '\n' || x == '\0')- (True , False) -> \x -> x <= ':' && (x == ':' || x == '$' || x == '\r' || x == '\n' || x == '\0')- (False, True ) -> \x -> x <= '$' && ( x == ' ' || x == '$' || x == '\r' || x == '\n' || x == '\0')- (False, False) -> \x -> x <= '$' && ( x == '$' || x == '\r' || x == '\n' || x == '\0')- f x = case break00 special x of (a,x) -> if BS.null a then g x else Lit a $: g x-- x $: (xs,y) = (x:xs,y)-- g x | head0 x /= '$' = ([], x)- g x | c_x <- tail0 x, (c,x) <- list0 c_x = case c of- '$' -> Lit (BS.singleton '$') $: f x- ' ' -> Lit (BS.singleton ' ') $: f x- ':' -> Lit (BS.singleton ':') $: f x- '\n' -> f $ dropSpace x- '\r' -> f $ dropSpace $ dropN x- '{' | (name,x) <- span0 isVarDot x, not $ BS.null name, ('}',x) <- list0 x -> Var name $: f x- _ | (name,x) <- span0 isVar c_x, not $ BS.null name -> Var name $: f x- _ -> error $ "Unexpect $ followed by unexpected stuff"---splitLineCont :: Str0 -> (Str, Str0)-splitLineCont x = first BS.concat $ f x- where- f x = if not $ endsDollar a then ([a], b) else let (c,d) = f $ dropSpace b in (BS.init a : c, d)- where (a,b) = splitLineCR x--splitLineCR :: Str0 -> (Str, Str0)-splitLineCR x = if BS.singleton '\r' `BS.isSuffixOf` a then (BS.init a, dropN b) else (a, dropN b)- where (a,b) = break0 (== '\n') x
− Development/Ninja/Parse.hs
@@ -1,78 +0,0 @@-{-# LANGUAGE RecordWildCards #-} - -module Development.Ninja.Parse(parse) where - -import qualified Data.ByteString.Char8 as BS -import Development.Ninja.Env -import Development.Ninja.Type -import Development.Ninja.Lexer -import Control.Monad - - -parse :: FilePath -> Env Str Str -> IO Ninja -parse file env = parseFile file env newNinja - - -parseFile :: FilePath -> Env Str Str -> Ninja -> IO Ninja -parseFile file env ninja = do - lexes <- lexerFile $ if file == "-" then Nothing else Just file - foldM (applyStmt env) ninja $ withBinds lexes - -withBinds :: [Lexeme] -> [(Lexeme, [(Str,Expr)])] -withBinds [] = [] -withBinds (x:xs) = (x,a) : withBinds b - where - (a,b) = f xs - f (LexBind a b : rest) = let (as,bs) = f rest in ((a,b):as, bs) - f xs = ([], xs) - - -applyStmt :: Env Str Str -> Ninja -> (Lexeme, [(Str,Expr)]) -> IO Ninja -applyStmt env ninja@Ninja{..} (key, binds) = case key of - LexBuild outputs rule deps -> do - outputs <- mapM (askExpr env) outputs - deps <- mapM (askExpr env) deps - let (normal,implicit,orderOnly) = splitDeps deps - let build = Build rule env normal implicit orderOnly binds - return $ - if rule == BS.pack "phony" then ninja{phonys = [(x, normal) | x <- outputs] ++ phonys} - else if length outputs == 1 then ninja{singles = (head outputs, build) : singles} - else ninja{multiples = (outputs, build) : multiples} - LexRule name -> - return ninja{rules = (name, Rule binds) : rules} - LexDefault xs -> do - xs <- mapM (askExpr env) xs - return ninja{defaults = xs ++ defaults} - LexPool name -> do - depth <- getDepth env binds - return ninja{pools = (name, depth) : pools} - LexInclude expr -> do - file <- askExpr env expr - parseFile (BS.unpack file) env ninja - LexSubninja expr -> do - file <- askExpr env expr - e <- scopeEnv env - parseFile (BS.unpack file) e ninja - LexDefine a b -> do - addBind env a b - return ninja - LexBind a b -> - error $ "Unexpected binding defining " ++ BS.unpack a - - -splitDeps :: [Str] -> ([Str], [Str], [Str]) -splitDeps (x:xs) | x == BS.pack "|" = ([],a++b,c) - | x == BS.pack "||" = ([],b,a++c) - | otherwise = (x:a,b,c) - where (a,b,c) = splitDeps xs -splitDeps [] = ([], [], []) - - -getDepth :: Env Str Str -> [(Str, Expr)] -> IO Int -getDepth env xs = case lookup (BS.pack "depth") xs of - Nothing -> return 1 - Just x -> do - x <- askExpr env x - case BS.readInt x of - Just (i, n) | BS.null n -> return i - _ -> error $ "Could not parse depth field in pool, got: " ++ BS.unpack x
− Development/Ninja/Type.hs
@@ -1,67 +0,0 @@---- | The IO in this module is only to evaluate an envrionment variable,--- the 'Env' itself it passed around purely.-module Development.Ninja.Type(- Str, FileStr,- Expr(..), Env, newEnv, askVar, askExpr, addEnv, addBind, addBinds,- Ninja(..), newNinja, Build(..), Rule(..),- ) where--import Development.Ninja.Env-import qualified Data.ByteString.Char8 as BS-import Data.Maybe---type Str = BS.ByteString-type FileStr = Str--------------------------------------------------------------------------- EXPRESSIONS AND BINDINGS--data Expr = Exprs [Expr] | Lit Str | Var Str deriving (Show,Eq)--askExpr :: Env Str Str -> Expr -> IO Str-askExpr e = f- where f (Exprs xs) = fmap BS.concat $ mapM f xs- f (Lit x) = return x- f (Var x) = askVar e x--askVar :: Env Str Str -> Str -> IO Str-askVar e x = fmap (fromMaybe BS.empty) $ askEnv e x--addBind :: Env Str Str -> Str -> Expr -> IO ()-addBind e k v = addEnv e k =<< askExpr e v--addBinds :: Env Str Str -> [(Str, Expr)] -> IO ()-addBinds e = mapM_ (uncurry $ addBind e)--------------------------------------------------------------------------- STRUCTURE--data Ninja = Ninja- {rules :: [(Str,Rule)]- ,singles :: [(FileStr,Build)]- ,multiples :: [([FileStr], Build)]- ,phonys :: ([(Str, [FileStr])])- ,defaults :: [FileStr]- ,pools :: [(Str, Int)]- }- deriving Show--newNinja :: Ninja-newNinja = Ninja [] [] [] [] [] []--data Build = Build- {ruleName :: Str- ,env :: Env Str Str- ,depsNormal :: [FileStr]- ,depsImplicit :: [FileStr]- ,depsOrderOnly :: [FileStr]- ,buildBind :: [(Str,Expr)]- } deriving Show--data Rule = Rule- {ruleBind :: [(Str,Expr)]- } deriving Show
− Development/Shake.hs
@@ -1,161 +0,0 @@---- | This module is used for defining Shake build systems. As a simple example of a Shake build system,--- let us build the file @result.tar@ from the files listed by @result.txt@:------ @---import "Development.Shake"---import "Development.Shake.FilePath"------main = 'shakeArgs' 'shakeOptions' $ do--- 'want' [\"result.tar\"]--- \"*.tar\" '*>' \\out -> do--- contents \<- 'readFileLines' $ out 'Development.Shake.FilePath.-<.>' \"txt\"--- 'need' contents--- 'cmd' \"tar -cf\" [out] contents--- @------ We start by importing the modules defining both Shake and routines for manipulating 'FilePath' values.--- We define @main@ to call 'shake' with the default 'shakeOptions'. As the second argument to--- 'shake', we provide a set of rules. There are two common forms of rules, 'want' to specify target files,--- and '*>' to define a rule which builds a 'FilePattern'. We use 'want' to require that after the build--- completes the file @result.tar@ should be ready.------ The @*.tar@ rule describes how to build files with the extension @.tar@, including @result.tar@.--- We 'readFileLines' on @result.txt@, after changing the @.tar@ extension to @.txt@. We read each line--- into the variable @contents@ -- being a list of the files that should go into @result.tar@. Next, we--- depend ('need') all the files in @contents@. If any of these files change, the rule will be repeated.--- Finally we call the @tar@ program. If either @result.txt@ changes, or any of the files listed by @result.txt@--- change, then @result.tar@ will be rebuilt.------ To find out more:------ * The user manual contains a longer example and background information on how to use Shake--- <https://github.com/ndmitchell/shake/blob/master/docs/Manual.md#readme>.------ * The home page has links to additional information <https://github.com/ndmitchell/shake#readme>, including--- a mailing list.------ * The theory behind Shake is described in an ICFP 2012 paper, /Shake Before Building -- Replacing Make with Haskell/--- <http://community.haskell.org/~ndm/downloads/paper-shake_before_building-10_sep_2012.pdf>. The associated talk--- forms a short overview of Shake <http://www.youtube.com/watch?v=xYCPpXVlqFM>.------ /== WRITING A BUILD SYSTEM ==============================/------ When writing a Shake build system, start by defining what you 'want', then write rules--- with '*>' to produce the results. Before calling 'cmd' you should ensure that any files the command--- requires are demanded with calls to 'need'. We offer the following advice to Shake users:------ * If @ghc --make@ or @cabal@ is capable of building your project, use that instead. Custom build systems are--- necessary for many complex projects, but many projects are not complex.------ * The 'shakeArgs' function automatically handles command line arguments. To define non-file targets use 'phony'.------ * Put all result files in a distinguished directory, for example @_make@. You can implement a @clean@--- command by removing that directory, using @'removeFilesAfter' \"_make\" [\"\/\/\*\"]@.------ * To obtain parallel builds set 'shakeThreads' to a number greater than 1.------ * Lots of compilers produce @.o@ files. To avoid overlapping rules, use @.c.o@ for C compilers,--- @.hs.o@ for Haskell compilers etc.------ * Do not be afraid to mix Shake rules, system commands and other Haskell libraries -- use each for what--- it does best.------ * The more accurate the dependencies are, the better. Use additional rules like 'doesFileExist' and--- 'getDirectoryFiles' to track information other than just the contents of files. For information in the environment--- that you suspect will change regularly (perhaps @ghc@ version number), either write the information to--- a file with 'alwaysRerun' and 'writeFileChanged', or use 'addOracle'.------ /== GHC BUILD FLAGS ==============================/------ For large build systems the choice of GHC flags can have a significant impact. We recommend:------ > ghc --make MyBuildSystem -rtsopts -with-rtsopts=-I0------ * @-rtsopts@: Allow the setting of further GHC options at runtime.------ * @-I0@: Disable idle garbage collection. In a build system regularly running many system--- commands the program appears \"idle\" very often, triggering regular unnecessary garbage collection, stealing--- resources from the program doing actual work.------ * Omit @-threaded@: In GHC 7.6 and earlier bug 7646 <http://ghc.haskell.org/trac/ghc/ticket/7646>--- can cause a race condition in build systems that write files then read them. Omitting @-threaded@ will--- still allow your 'cmd' actions to run in parallel, so most build systems will still run in parallel.------ * If you do compile with @-threaded@, pass the options @-qg -qb@ to @-with-rtsopts@--- to disable parallel garbage collection. Parallel garbage collection in Shake--- programs typically goes slower than sequential garbage collection, while occupying many cores that--- could be used for running system commands.------ /Acknowledgements/: Thanks to Austin Seipp for properly integrating the profiling code.-module Development.Shake(- -- * Core- shake,- shakeOptions,- Rules, action, withoutActions, alternatives, priority,- Action, traced,- liftIO, actionOnException, actionFinally,- ShakeException(..),- -- * Configuration- ShakeOptions(..), Assume(..), Lint(..), Change(..), getShakeOptions,- -- ** Command line- shakeArgs, shakeArgsWith, shakeOptDescrs,- -- ** Progress reporting- Progress(..), progressSimple, progressDisplay, progressTitlebar, progressProgram,- -- ** Verbosity- Verbosity(..), getVerbosity, putLoud, putNormal, putQuiet, withVerbosity, quietly,- -- * Running commands- command, command_, cmd,- Stdout(..), Stderr(..), Exit(..),- CmdResult, CmdOption(..),- addPath, addEnv,- -- * Utility functions- copyFile', copyFileChanged,- readFile', readFileLines,- writeFile', writeFileLines, writeFileChanged,- removeFiles, removeFilesAfter,- -- * File rules- need, want, (*>), (|*>), (?>), phony, (~>),- (&*>), (&?>),- orderOnly,- FilePattern, (?==),- needed, trackRead, trackWrite, trackAllow,- -- * Directory rules- doesFileExist, doesDirectoryExist, getDirectoryContents, getDirectoryFiles, getDirectoryDirs,- -- * Environment rules- getEnv, getEnvWithDefault,- -- * Oracle rules- addOracle, askOracle, askOracleWith,- -- * Special rules- alwaysRerun,- -- * Resources- Resource, newResource, newResourceIO, withResource, withResources,- newThrottle, newThrottleIO,- unsafeExtraThread,- -- * Cache- newCache, newCacheIO,- -- * Deprecated- (**>), (*>>), (?>>),- system', systemCwd, systemOutput- ) where---- I would love to use module export in the above export list, but alas Haddock--- then shows all the things that are hidden in the docs, which is terrible.--import Control.Monad.IO.Class-import Development.Shake.Types-import Development.Shake.Core hiding (trackAllow)-import Development.Shake.Derived-import Development.Shake.Errors-import Development.Shake.Progress-import Development.Shake.Args-import Development.Shake.Shake--import Development.Shake.Command-import Development.Shake.Rules.Directory-import Development.Shake.Rules.File-import Development.Shake.FilePattern-import Development.Shake.Rules.Files-import Development.Shake.Rules.Oracle-import Development.Shake.Rules.OrderOnly-import Development.Shake.Rules.Rerun
− Development/Shake/Args.hs
@@ -1,341 +0,0 @@---- | Command line parsing flags.-module Development.Shake.Args(shakeOptDescrs, shakeArgs, shakeArgsWith) where--import Paths_shake-import Development.Shake.Types-import Development.Shake.Core-import Development.Shake.Demo-import Development.Shake.Rules.File-import Development.Shake.FilePath-import Development.Shake.Progress-import Development.Shake.Shake-import General.Base-import General.Timing--import Control.Arrow-import Control.Concurrent-import Control.Exception-import Control.Monad-import Data.Char-import Data.Either-import Data.List-import Data.Maybe-import Data.Time-import Data.Version(showVersion)-import System.Console.GetOpt-import System.Directory-import System.Environment-import System.Exit----- | Run a build system using command line arguments for configuration.--- The available flags are those from 'shakeOptDescrs', along with a few additional--- @make@ compatible flags that are not represented in 'ShakeOptions', such as @--print-directory@.--- If there are no file arguments then the 'Rules' are used directly, otherwise the file arguments--- are 'want'ed (after calling 'withoutActions'). As an example:------ @--- main = 'shakeArgs' 'shakeOptions'{'shakeFiles' = \"_make/\", 'shakeProgress' = 'progressSimple'} $ do--- 'phony' \"clean\" $ 'Development.Shake.removeFilesAfter' \"_make\" [\"\/\/*\"]--- 'want' [\"_make\/neil.txt\",\"_make\/emily.txt\"]--- \"_make\/*.txt\" '*>' \\out ->--- ... build action here ...--- @------ This build system will default to building @neil.txt@ and @emily.txt@, while showing progress messages,--- and putting the Shake files in locations such as @_make\/.database@. Some example command line flags:------ * @main --no-progress@ will turn off progress messages.------ * @main -j6@ will build on 6 threads.------ * @main --help@ will display a list of supported flags.------ * @main clean@ will not build anything, but will remove the @_make@ directory, including the--- any 'shakeFiles'.------ * @main _make/henry.txt@ will not build @neil.txt@ or @emily.txt@, but will instead build @henry.txt@.-shakeArgs :: ShakeOptions -> Rules () -> IO ()-shakeArgs opts rules = shakeArgsWith opts [] f- where f _ files = return $ Just $ if null files then rules else want (map normalise files) >> withoutActions rules----- | A version of 'shakeArgs' with more flexible handling of command line arguments.--- The caller of 'shakeArgsWith' can add additional flags (the second argument) and chose how to convert--- the flags/arguments into rules (the third argument). Given:------ @--- 'shakeArgsWith' opts flags (\\flagValues argValues -> result)--- @------ * @opts@ is the initial 'ShakeOptions' value, which may have some fields overriden by command line flags.--- This argument is usually 'shakeOptions', perhaps with a few fields overriden.------ * @flags@ is a list of flag descriptions, which either produce a 'String' containing an error--- message (typically for flags with invalid arguments, .e.g. @'Left' \"could not parse as int\"@), or a value--- that is passed as @flagValues@. If you have no custom flags, pass @[]@.------ * @flagValues@ is a list of custom flags that the user supplied. If @flags == []@ then this list will--- be @[]@.------ * @argValues@ is a list of non-flag arguments, which are often treated as files and passed to 'want'.------ * @result@ should produce a 'Nothing' to indicate that no building needs to take place, or a 'Just'--- providing the rules that should be used.------ As an example of a build system that can use either @gcc@ or @distcc@ for compiling:------ @---import System.Console.GetOpt------data Flags = DistCC deriving Eq---flags = [Option \"\" [\"distcc\"] (NoArg $ Right DistCC) \"Run distributed.\"]------main = 'shakeArgsWith' 'shakeOptions' flags $ \\flags targets -> return $ Just $ do--- if null targets then 'want' [\"result.exe\"] else 'want' targets--- let compiler = if DistCC \`elem\` flags then \"distcc\" else \"gcc\"--- \"*.o\" '*>' \\out -> do--- 'need' ...--- 'cmd' compiler ...--- ...--- @------ Now you can pass @--distcc@ to use the @distcc@ compiler.-shakeArgsWith :: ShakeOptions -> [OptDescr (Either String a)] -> ([a] -> [String] -> IO (Maybe (Rules ()))) -> IO ()-shakeArgsWith baseOpts userOptions rules = do- addTiming "shakeArgsWith"- args <- getArgs- let (flags,files,errs) = getOpt Permute opts args- (flagsError,flag1) = partitionEithers flags- (self,user) = partitionEithers flag1- (flagsExtra,flagsShake) = first concat $ unzip self- assumeNew = [x | AssumeNew x <- flagsExtra]- assumeOld = [x | AssumeOld x <- flagsExtra]- progressReplays = [x | ProgressReplay x <- flagsExtra]- progressRecords = [x | ProgressRecord x <- flagsExtra]- changeDirectory = listToMaybe [x | ChangeDirectory x <- flagsExtra]- printDirectory = last $ False : [x | PrintDirectory x <- flagsExtra]- shakeOpts = foldl' (flip ($)) baseOpts flagsShake-- -- error if you pass some clean and some dirty with specific flags- errs <- return $ errs ++ flagsError ++ ["cannot mix " ++ a ++ " and " ++ b | a:b:_ <-- [["`--assume-new'" | assumeNew/=[] ] ++ ["`--assume-old'" | assumeOld/=[] ] ++ ["explicit targets" | files/=[]]]]-- when (errs /= []) $ do- putStr $ unlines $ map ("shake: " ++) $ filter (not . null) $ lines $ unlines errs- showHelp- exitFailure-- if Help `elem` flagsExtra then do- showHelp- else if Version `elem` flagsExtra then- putStrLn $ "Shake build system, version " ++ showVersion version- else if NumericVersion `elem` flagsExtra then- putStrLn $ showVersion version- else if Demo `elem` flagsExtra then- demo $ shakeStaunch shakeOpts- else if not $ null progressReplays then do- dat <- forM progressReplays $ \file -> do- src <- readFile file- return (file, map read $ lines src)- forM_ (if null $ shakeReport shakeOpts then ["-"] else shakeReport shakeOpts) $ \file -> do- putStrLn $ "Writing report to " ++ file- writeProgressReport file dat- else do- when (Sleep `elem` flagsExtra) $ threadDelay 1000000- start <- getCurrentTime- curdir <- getCurrentDirectory- let redir = case changeDirectory of- Nothing -> id- -- get the "html" directory so it caches with the current directory- -- required only for debug code- Just d -> bracket_ (getDataFileName "html" >> setCurrentDirectory d) (setCurrentDirectory curdir)- shakeOpts <- if null progressRecords then return shakeOpts else do- t <- offsetTime- return shakeOpts{shakeProgress = \p -> do- bracket- (forkIO $ shakeProgress shakeOpts p)- killThread- $ const $ progressDisplay 1 (const $ return ()) $ do- p <- p- t <- t- forM_ progressRecords $ \file -> do- appendFile file $ show (t,p) ++ "\n"- return p- }- (ran,res) <- redir $ do- when printDirectory $ putStrLn $ "shake: In directory `" ++ curdir ++ "'"- rules <- rules user files- case rules of- Nothing -> return (False,Right ())- Just rules -> do- res <- try $ shake shakeOpts $- if NoBuild `elem` flagsExtra then withoutActions rules else rules- return (True, res)-- if not ran || shakeVerbosity shakeOpts < Normal || NoTime `elem` flagsExtra then- either throwIO return res- else- let esc code = if Color `elem` flagsExtra then escape code else id- in case res of- Left err ->- if Exception `elem` flagsExtra then- throw err- else do- putStrLn $ esc "31" $ show (err :: SomeException)- exitFailure- Right () -> do- stop <- getCurrentTime- let tot = diffUTCTime stop start- (mins,secs) = divMod (ceiling tot) (60 :: Int)- time = show mins ++ ":" ++ ['0' | secs < 10] ++ show secs- putStrLn $ esc "32" $ "Build completed in " ++ time ++ "m"- where- opts = map (wrap Left . snd) shakeOptsEx ++ map (wrap Right) userOptions- showHelp = putStr $ unlines $ "Usage: shake [options] [target] ..." : "Options:" : showOptDescr opts-- wrap :: (a -> b) -> OptDescr (Either String a) -> OptDescr (Either String b)- wrap f = fmapOptDescr (either Left (Right . f))---showOptDescr :: [OptDescr a] -> [String]-showOptDescr xs = concat- [ if nargs <= 26 then [" " ++ args ++ replicate (28 - nargs) ' ' ++ desc]- else [" " ++ args, replicate 30 ' ' ++ desc]- | Option s l arg desc <- xs- , let args = intercalate ", " $ map (short arg) s ++ map (long arg) l- , let nargs = length args]- where short NoArg{} x = "-" ++ [x]- short (ReqArg _ b) x = "-" ++ [x] ++ " " ++ b- short (OptArg _ b) x = "-" ++ [x] ++ "[=" ++ b ++ "]"- long NoArg{} x = "--" ++ x- long (ReqArg _ b) x = "--" ++ x ++ "=" ++ b- long (OptArg _ b) x = "--" ++ x ++ "[=" ++ b ++ "]"---fmapOptDescr :: (a -> b) -> OptDescr a -> OptDescr b-fmapOptDescr f (Option a b c d) = Option a b (g c) d- where g (NoArg a) = NoArg $ f a- g (ReqArg a b) = ReqArg (f . a) b- g (OptArg a b) = OptArg (f . a) b----- | A list of command line options that can be used to modify 'ShakeOptions'. Each option returns--- either an error message (invalid argument to the flag) or a function that changes some fields--- in 'ShakeOptions'. The command line flags are @make@ compatible where possbile, but additional--- flags have been added for the extra options Shake supports.-shakeOptDescrs :: [OptDescr (Either String (ShakeOptions -> ShakeOptions))]-shakeOptDescrs = [fmapOptDescr (either Left (Right . snd)) o | (True, o) <- shakeOptsEx]--data Extra = ChangeDirectory FilePath- | Version- | NumericVersion- | AssumeNew FilePath- | AssumeOld FilePath- | PrintDirectory Bool- | Color- | Help- | Sleep- | NoTime- | Exception- | NoBuild- | ProgressRecord FilePath- | ProgressReplay FilePath- | Demo- deriving Eq---unescape :: String -> String-unescape ('\ESC':'[':xs) = unescape $ drop 1 $ dropWhile (not . isAlpha) xs-unescape (x:xs) = x : unescape xs-unescape [] = []--escape :: String -> String -> String-escape code x = "\ESC[" ++ code ++ "m" ++ x ++ "\ESC[0m"----- | True if it has a potential effect on ShakeOptions-shakeOptsEx :: [(Bool, OptDescr (Either String ([Extra], ShakeOptions -> ShakeOptions)))]-shakeOptsEx =- [yes $ Option "a" ["abbrev"] (pairArg "abbrev" "FULL=SHORT" $ \a s -> s{shakeAbbreviations=shakeAbbreviations s ++ [a]}) "Use abbreviation in status messages."- ,yes $ Option "B" ["always-make"] (noArg $ \s -> s{shakeAssume=Just AssumeDirty}) "Unconditionally make all targets."- ,no $ Option "" ["no-build"] (NoArg $ Right ([NoBuild], id)) "Don't build anything."- ,no $ Option "C" ["directory"] (ReqArg (\x -> Right ([ChangeDirectory x],id)) "DIRECTORY") "Change to DIRECTORY before doing anything."- ,yes $ Option "" ["color","colour"] (NoArg $ Right ([Color], \s -> s{shakeOutput=outputColor (shakeOutput s)})) "Colorize the output."- ,yes $ Option "d" ["debug"] (OptArg (\x -> Right ([], \s -> s{shakeVerbosity=Diagnostic, shakeOutput=outputDebug (shakeOutput s) x})) "FILE") "Print lots of debugging information."- ,no $ Option "" ["demo"] (NoArg $ Right ([Demo], id)) "Run in demo mode."- ,yes $ Option "" ["digest"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeDigest})) "Files change when digest changes."- ,yes $ Option "" ["digest-and"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeModtimeAndDigest})) "Files change when modtime and digest change."- ,yes $ Option "" ["digest-and-input"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeModtimeAndDigestInput})) "Files change on modtime (and digest for inputs)."- ,yes $ Option "" ["digest-or"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeModtimeOrDigest})) "Files change when modtime or digest change."- ,no $ Option "" ["exception"] (NoArg $ Right ([Exception], id)) "Throw exceptions directly."- ,yes $ Option "" ["flush"] (intArg 1 "flush" "N" (\i s -> s{shakeFlush=Just i})) "Flush metadata every N seconds."- ,yes $ Option "" ["never-flush"] (noArg $ \s -> s{shakeFlush=Nothing}) "Never explicitly flush metadata."- ,no $ Option "h" ["help"] (NoArg $ Right ([Help],id)) "Print this message and exit."- ,yes $ Option "j" ["jobs"] (optIntArg 0 "jobs" "N" $ \i s -> s{shakeThreads=fromMaybe 0 i}) "Allow N jobs/threads at once [default CPUs]."- ,yes $ Option "k" ["keep-going"] (noArg $ \s -> s{shakeStaunch=True}) "Keep going when some targets can't be made."- ,yes $ Option "l" ["lint"] (noArg $ \s -> s{shakeLint=Just LintBasic}) "Perform limited validation after the run."- ,yes $ Option "" ["lint-tracker"] (noArg $ \s -> s{shakeLint=Just LintTracker}) "Use tracker.exe to do validation."- ,yes $ Option "" ["no-lint"] (noArg $ \s -> s{shakeLint=Nothing}) "Turn off --lint."- ,yes $ Option "" ["live"] (OptArg (\x -> Right ([], \s -> s{shakeLiveFiles=shakeLiveFiles s ++ [fromMaybe "live.txt" x]})) "FILE") "List the files that are live [to live.txt]."- ,yes $ Option "m" ["metadata"] (reqArg "PREFIX" $ \x s -> s{shakeFiles=x}) "Prefix for storing metadata files."- ,no $ Option "" ["numeric-version"] (NoArg $ Right ([NumericVersion],id)) "Print just the version number and exit."- ,no $ Option "o" ["old-file","assume-old"] (ReqArg (\x -> Right ([AssumeOld x],id)) "FILE") "Consider FILE to be very old and don't remake it."- ,yes $ Option "" ["old-all"] (noArg $ \s -> s{shakeAssume=Just AssumeClean}) "Don't remake any files."- ,yes $ Option "" ["assume-skip"] (noArg $ \s -> s{shakeAssume=Just AssumeSkip}) "Don't remake any files this run."- ,yes $ Option "" ["skip-commands"] (noArg $ \s -> s{shakeRunCommands=False}) "Try and avoid running external programs."- ,yes $ Option "r" ["report","profile"] (OptArg (\x -> Right ([], \s -> s{shakeReport=shakeReport s ++ [fromMaybe "report.html" x]})) "FILE") "Write out profiling information [to report.html]."- ,yes $ Option "" ["no-reports"] (noArg $ \s -> s{shakeReport=[]}) "Turn off --report."- ,yes $ Option "" ["rule-version"] (reqArg "VERSION" $ \x s -> s{shakeVersion=x}) "Version of the build rules."- ,yes $ Option "s" ["silent"] (noArg $ \s -> s{shakeVerbosity=Silent}) "Don't print anything."- ,no $ Option "" ["sleep"] (NoArg $ Right ([Sleep],id)) "Sleep for a second before building."- ,yes $ Option "S" ["no-keep-going","stop"] (noArg $ \s -> s{shakeStaunch=False}) "Turns off -k."- ,yes $ Option "" ["storage"] (noArg $ \s -> s{shakeStorageLog=True}) "Write a storage log."- ,yes $ Option "p" ["progress"] (progress $ optIntArg 1 "progress" "N" $ \i s -> s{shakeProgress=prog $ fromMaybe 5 i}) "Show progress messages [every N secs, default 5]."- ,yes $ Option "" ["no-progress"] (noArg $ \s -> s{shakeProgress=const $ return ()}) "Don't show progress messages."- ,yes $ Option "q" ["quiet"] (noArg $ \s -> s{shakeVerbosity=move (shakeVerbosity s) pred}) "Don't print much."- ,no $ Option "" ["no-time"] (NoArg $ Right ([NoTime],id)) "Don't print build time."- ,yes $ Option "" ["timings"] (noArg $ \s -> s{shakeTimings=True}) "Print phase timings."- ,yes $ Option "" ["touch"] (noArg $ \s -> s{shakeAssume=Just AssumeClean}) "Assume targets are clean."- ,yes $ Option "V" ["verbose","trace"] (noArg $ \s -> s{shakeVerbosity=move (shakeVerbosity s) succ}) "Print tracing information."- ,no $ Option "v" ["version"] (NoArg $ Right ([Version],id)) "Print the version number and exit."- ,no $ Option "w" ["print-directory"] (NoArg $ Right ([PrintDirectory True],id)) "Print the current directory."- ,no $ Option "" ["no-print-directory"] (NoArg $ Right ([PrintDirectory False],id)) "Turn off -w, even if it was turned on implicitly."- ,no $ Option "W" ["what-if","new-file","assume-new"] (ReqArg (\x -> Right ([AssumeNew x],id)) "FILE") "Consider FILE to be infinitely new."- ]- where- yes = (,) True- no = (,) False-- move :: Verbosity -> (Int -> Int) -> Verbosity- move x by = toEnum $ min (fromEnum mx) $ max (fromEnum mn) $ by $ fromEnum x- where (mn,mx) = (asTypeOf minBound x, asTypeOf maxBound x)-- noArg f = NoArg $ Right ([], f)- reqArg a f = ReqArg (\x -> Right ([], f x)) a- intArg mn flag a f = flip ReqArg a $ \x -> case reads x of- [(i,"")] | i >= mn -> Right ([],f i)- _ -> Left $ "the `--" ++ flag ++ "' option requires a number, " ++ show mn ++ " or above"- optIntArg mn flag a f = flip OptArg a $ maybe (Right ([], f Nothing)) $ \x -> case reads x of- [(i,"")] | i >= mn -> Right ([],f $ Just i)- _ -> Left $ "the `--" ++ flag ++ "' option requires a number, " ++ show mn ++ " or above"- pairArg flag a f = flip ReqArg a $ \x -> case break (== '=') x of- (a,'=':b) -> Right ([],f (a,b))- _ -> Left $ "the `--" ++ flag ++ "' option requires an = in the argument"-- progress (OptArg func msg) = flip OptArg msg $ \x -> case break (== '=') `fmap` x of- Just ("record",file) -> Right ([ProgressRecord $ if null file then "progress.txt" else tail file], id)- Just ("replay",file) -> Right ([ProgressReplay $ if null file then "progress.txt" else tail file], id)- _ -> func x-- outputDebug output Nothing = output- outputDebug output (Just file) = \v msg -> do- when (v /= Diagnostic) $ output v msg- appendFile file $ unescape msg-- outputColor output v msg = output v $ escape "34" msg-- prog i p = do- program <- progressProgram- progressDisplay i (\s -> progressTitlebar s >> program s) p
− Development/Shake/ByteString.hs
@@ -1,75 +0,0 @@--module Development.Shake.ByteString(parseMakefile, filepathNormalise, linesCR) where--import qualified Data.ByteString.Char8 as BS-import qualified System.FilePath as Native-import General.Base-import Data.Char-import Data.List---endsSlash :: BS.ByteString -> Bool-endsSlash = BS.isSuffixOf (BS.singleton '\\')--wordsMakefile :: BS.ByteString -> [BS.ByteString]-wordsMakefile = f . BS.splitWith isSpace- where- f (x:xs) | BS.null x = f xs- f (x:y:xs) | endsSlash x = BS.concat [BS.init x, BS.singleton ' ', y] : f xs- f (x:xs) = x : f xs- f [] = []--parseMakefile :: BS.ByteString -> [(BS.ByteString, [BS.ByteString])]-parseMakefile = concatMap f . join . linesCR- where- join xs = case span endsSlash xs of- ([], []) -> []- (xs, []) -> [BS.unwords $ map BS.init xs]- ([], y:ys) -> y : join ys- (xs, y:ys) -> BS.unwords (map BS.init xs ++ [y]) : join ys-- f x = [(a, wordsMakefile $ BS.drop 1 b) | a <- wordsMakefile a]- where (a,b) = BS.break (== ':') $ BS.takeWhile (/= '#') x----- | This is a hot-spot, so optimised-linesCR :: BS.ByteString -> [BS.ByteString]-linesCR x = case BS.split '\n' x of- x:xs | Just ('\r',x) <- unsnoc x -> x : map (\x -> case unsnoc x of Just ('\r',x) -> x; _ -> x) xs- xs -> xs- where- -- the ByteString unsnoc was introduced in a newer version- unsnoc x | BS.null x = Nothing- | otherwise = Just (BS.last x, BS.init x)---filepathNormalise :: BS.ByteString -> BS.ByteString-filepathNormalise xs- | isWindows, Just (a,xs) <- BS.uncons xs, sep a, Just (b,_) <- BS.uncons xs, sep b = '/' `BS.cons` f xs- | otherwise = f xs- where- sep = Native.isPathSeparator- f o = deslash o $ BS.concat $ (slash:) $ intersperse slash $ reverse $ (BS.empty:) $ g 0 $ reverse $ split $ o-- deslash o x- | x == slash = case (pre,pos) of- (True,True) -> slash- (True,False) -> BS.pack "/."- (False,True) -> BS.pack "./"- (False,False) -> dot- | otherwise = (if pre then id else BS.tail) $ (if pos then id else BS.init) x- where pre = not (BS.null o) && sep (BS.head o)- pos = not (BS.null o) && sep (BS.last o)-- g i [] = replicate i dotDot- g i (x:xs) | BS.null x = g i xs- g i (x:xs) | x == dotDot = g (i+1) xs- g i (x:xs) | x == dot = g i xs- g 0 (x:xs) = x : g 0 xs- g i (x:xs) = g (i-1) xs-- split xs = BS.splitWith sep xs--dotDot = BS.pack ".."-dot = BS.singleton '.'-slash = BS.singleton '/'
− Development/Shake/Classes.hs
@@ -1,11 +0,0 @@---- | This module reexports the six necessary type classes that every 'Rule' type must support.--- You can use this module to define new rules without depending on the @binary@, @deepseq@ and @hashable@ packages.-module Development.Shake.Classes(- Show(..), Typeable(..), Eq(..), Hashable(..), Binary(..), NFData(..)- ) where--import Data.Hashable-import Data.Typeable-import Data.Binary-import Control.DeepSeq
− Development/Shake/Command.hs
@@ -1,429 +0,0 @@-{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, TypeOperators #-}---- | This module provides functions for calling command line programs, primarily--- 'command' and 'cmd'. As a simple example:------ @--- 'command' [] \"gcc\" [\"-c\",myfile]--- @------ The functions from this module are now available directly from "Development.Shake".--- You should only need to import this module if you are using the 'cmd' function in the 'IO' monad.-module Development.Shake.Command(- command, command_, cmd, CmdArguments,- Stdout(..), Stderr(..), Exit(..),- CmdResult, CmdOption(..),- addPath, addEnv,- ) where--import Control.Arrow-import Control.Concurrent-import Control.DeepSeq-import Control.Exception as C-import Control.Monad-import Control.Monad.IO.Class-import Data.Char-import Data.Either-import Data.List-import Data.Maybe-import Foreign.C.Error-import System.Directory-import System.Environment-import System.Exit-import System.IO-import System.Process--import Development.Shake.Core-import Development.Shake.FilePath-import Development.Shake.Types-import Development.Shake.Rules.File-import General.Base--import GHC.IO.Exception (IOErrorType(..), IOException(..))--------------------------------------------------------------------------- ACTUAL EXECUTION---- | Options passed to 'command' or 'cmd' to control how processes are executed.-data CmdOption- = Cwd FilePath -- ^ Change the current directory in the spawned process. By default uses this processes current directory.- | Env [(String,String)] -- ^ Change the environment variables in the spawned process. By default uses this processes environment.- -- Use 'addPath' to modify the @$PATH@ variable, or 'addEnv' to modify other variables.- | Stdin String -- ^ Given as the @stdin@ of the spawned process. By default the @stdin@ is inherited.- | Shell -- ^ Pass the command to the shell without escaping - any arguments will be joined with spaces. By default arguments are escaped properly.- | BinaryPipes -- ^ Treat the @stdin@\/@stdout@\/@stderr@ messages as binary. By default streams use text encoding.- | Traced String -- ^ Name to use with 'traced', or @\"\"@ for no tracing. By default traces using the name of the executable.- | WithStderr Bool -- ^ Should I include the @stderr@ in the exception if the command fails? Defaults to 'True'.- | EchoStdout Bool -- ^ Should I echo the @stdout@? Defaults to 'True' unless a 'Stdout' result is required.- | EchoStderr Bool -- ^ Should I echo the @stderr@? Defaults to 'True' unless a 'Stderr' result is required.- deriving (Eq,Ord,Show)----- | Produce a 'CmdOption' of value 'Env' that is the current environment, plus a--- prefix and suffix to the @$PATH@ environment variable. For example:------ @--- opt <- 'addPath' [\"\/usr\/special\"] []--- 'cmd' opt \"userbinary --version\"--- @------ Would prepend @\/usr\/special@ to the current @$PATH@, and the command would pick--- @\/usr\/special\/userbinary@, if it exists. To add other variables see 'addEnv'.-addPath :: MonadIO m => [String] -> [String] -> m CmdOption-addPath pre post = do- args <- liftIO getEnvironment- let (path,other) = partition ((== "PATH") . (if isWindows then map toUpper else id) . fst) args- return $ Env $- [("PATH",intercalate [searchPathSeparator] $ pre ++ post) | null path] ++- [(a,intercalate [searchPathSeparator] $ pre ++ [b | b /= ""] ++ post) | (a,b) <- path] ++- other---- | Produce a 'CmdOption' of value 'Env' that is the current environment, plus the argument--- environment variables. For example:------ @--- opt <- 'addEnv' [(\"CFLAGS\",\"-O2\")]--- 'cmd' opt \"gcc -c main.c\"--- @------ Would add the environment variable @$CFLAGS@ with value @-O2@. If the variable @$CFLAGS@--- was already defined it would be overwritten. If you wish to modify @$PATH@ see 'addPath'.-addEnv :: MonadIO m => [(String, String)] -> m CmdOption-addEnv extra = do- args <- liftIO getEnvironment- return $ Env $ extra ++ filter (\(a,b) -> a `notElem` map fst extra) args---data Result- = ResultStdout String- | ResultStderr String- | ResultCode ExitCode- deriving Eq---commandExplicit :: String -> [CmdOption] -> [Result] -> String -> [String] -> Action [Result]-commandExplicit funcName copts results exe args = do- opts <- getShakeOptions- verb <- getVerbosity-- let skipper act = if null results && not (shakeRunCommands opts) then return [] else act-- let verboser act = do- let cwd = listToMaybe $ reverse [x | Cwd x <- copts]- putLoud $ maybe "" (\x -> "cd " ++ x ++ "; ") cwd ++ saneCommandForUser exe args- (if verb >= Loud then quietly else id) act-- let tracer = case reverse [x | Traced x <- copts] of- "":_ -> liftIO- msg:_ -> traced msg- [] -> traced (takeFileName exe)-- let tracker act = case shakeLint opts of- Just LintTracker -> do- dir <- liftIO $ getTemporaryDirectory- (file, handle) <- liftIO $ openTempFile dir "shake.lint"- liftIO $ hClose handle- dir <- return $ file <.> "dir"- liftIO $ createDirectory dir- let cleanup = removeDirectoryRecursive dir >> removeFile file- flip actionFinally cleanup $ do- res <- act "tracker" $ "/if":dir:"/c":exe:args- (read,write) <- liftIO $ trackerFiles dir- trackRead read- trackWrite write- return res- _ -> act exe args-- skipper $ tracker $ \exe args -> verboser $ tracer $ commandExplicitIO funcName copts results exe args----- | Given a directory (as passed to tracker /if) report on which files were used for reading/writing-trackerFiles :: FilePath -> IO ([FilePath], [FilePath])-trackerFiles dir = do- curdir <- getCurrentDirectory- let pre = map toUpper curdir ++ "\\"- files <- getDirectoryContents dir- let f typ = do- files <- forM [x | x <- files, takeExtension x == ".tlog", takeExtension (dropExtension $ dropExtension x) == '.':typ] $ \file -> do- xs <- readFileUCS2 $ dir </> file- return $ filter (not . isPrefixOf "." . takeFileName) . mapMaybe (stripPrefix pre) $ lines xs- fmap nub $ mapMaybeM correctCase $ nub $ concat files- liftM2 (,) (f "read") (f "write")---correctCase :: FilePath -> IO (Maybe FilePath)-correctCase x = f "" x- where- f pre "" = return $ Just pre- f pre x = do- let (a,b) = (takeDirectory1 x, dropDirectory1 x)- dir <- getDirectoryContents pre- case find ((==) a . map toUpper) dir of- Nothing -> return Nothing -- if it can't be found it probably doesn't exist, so assume a file that wasn't really read- Just v -> f (pre +/+ v) b-- a +/+ b = if null a then b else a ++ "/" ++ b---commandExplicitIO :: String -> [CmdOption] -> [Result] -> String -> [String] -> IO [Result]-commandExplicitIO funcName opts results exe args =--- BEGIN COPIED--- Originally from readProcessWithExitCode with as few changes as possible- mask $ \restore -> do- ans <- try $ createProcess cp- (inh, outh, errh, pid) <- case ans of- Right a -> return a- Left err -> do- error $ msgPrefix ++ show (err :: SomeException)-- let close = maybe (return ()) hClose- flip onException- (do close inh; close outh; close errh- terminateProcess pid; waitForProcess pid) $ restore $ do-- -- set pipes to binary if appropriate- when (BinaryPipes `elem` opts) $ do- let bin = maybe (return ()) (`hSetBinaryMode` True)- bin inh; bin outh; bin errh-- -- fork off a thread to start consuming stdout- (out,waitOut,waitOutEcho) <- case outh of- Nothing -> return ("", return (), return ())- Just outh -> do- out <- hGetContents outh- waitOut <- forkWait $ C.evaluate $ rnf out- waitOutEcho <- if stdoutEcho- then forkWait (hPutStr stdout out)- else return (return ())- return (out,waitOut,waitOutEcho)-- -- fork off a thread to start consuming stderr- (err,waitErr,waitErrEcho) <- case errh of- Nothing -> return ("", return (), return ())- Just errh -> do- err <- hGetContents errh- waitErr <- forkWait $ C.evaluate $ rnf err- waitErrEcho <- if stderrEcho- then forkWait (hPutStr stderr err)- else return (return ())- return (err,waitErr,waitErrEcho)-- -- now write and flush any input- let writeInput = do- case inh of- Nothing -> return ()- Just inh -> do- hPutStr inh input- hFlush inh- hClose inh-- C.catch writeInput $ \e -> case e of- IOError { ioe_type = ResourceVanished- , ioe_errno = Just ioe }- | Errno ioe == ePIPE -> return ()- _ -> throwIO e-- -- wait on the output- waitOut- waitErr-- waitOutEcho- waitErrEcho-- close outh- close errh-- -- wait on the process- ex <- waitForProcess pid--- END COPIED-- when (ResultCode ExitSuccess `notElem` results && ex /= ExitSuccess) $ do- error $ msgPrefix ++- "Exit code: " ++ show (case ex of ExitFailure i -> i; _ -> 0) ++ "\n" ++- (if not stderrThrow then "Stderr not captured because ErrorsWithoutStderr was used"- else if null err then "Stderr was empty"- else "Stderr:\n" ++ unlines (dropWhile null $ lines err))-- return $ flip map results $ \x -> case x of- ResultStdout _ -> ResultStdout out- ResultStderr _ -> ResultStderr err- ResultCode _ -> ResultCode ex- where- msgPrefix =- "Development.Shake." ++ funcName ++ ", system command failed\n" ++- "Command: " ++ saneCommandForUser exe args ++ "\n" ++- (case cwd cp of Nothing -> ""; Just v -> "Current directory: " ++ v ++ "\n")-- input = last $ "" : [x | Stdin x <- opts]-- -- what should I do with these handles- binary = BinaryPipes `elem` opts- stdoutEcho = last $ (ResultStdout "" `notElem` results) : [b | EchoStdout b <- opts]- stdoutCapture = ResultStdout "" `elem` results- stderrEcho = last $ (ResultStderr "" `notElem` results) : [b | EchoStderr b <- opts]- stderrThrow = last $ True : [b | WithStderr b <- opts]- stderrCapture = ResultStderr "" `elem` results || (stderrThrow && ResultCode ExitSuccess `notElem` results)-- cp0 = (if Shell `elem` opts then shell $ unwords $ exe:args else proc exe args)- {std_out = if binary || stdoutCapture || not stdoutEcho then CreatePipe else Inherit- ,std_err = if binary || stderrCapture || not stderrEcho then CreatePipe else Inherit- ,std_in = if null input then Inherit else CreatePipe- }- cp = foldl applyOpt cp0{std_out = CreatePipe, std_err = CreatePipe} opts- applyOpt :: CreateProcess -> CmdOption -> CreateProcess- applyOpt o (Cwd x) = o{cwd = if x == "" then Nothing else Just x}- applyOpt o (Env x) = o{env = Just x}- applyOpt o _ = o----- Copied from System.Process-forkWait :: IO a -> IO (IO a)-forkWait a = do- res <- newEmptyMVar- _ <- mask $ \restore -> forkIO $ try (restore a) >>= putMVar res- return (takeMVar res >>= either (\ex -> throwIO (ex :: SomeException)) return)----- Like System.Process, but tweaked to show less escaping,--- Relies on relatively detailed internals of showCommandForUser.-saneCommandForUser :: FilePath -> [String] -> String-saneCommandForUser cmd args = unwords $ map f $ cmd:args- where- f x = if take (length y - 2) (drop 1 y) == x then x else y- where y = showCommandForUser x []--------------------------------------------------------------------------- FIXED ARGUMENT WRAPPER---- | Collect the @stdout@ of the process.--- If you are collecting the @stdout@, it will not be echoed to the terminal, unless you include 'EchoStdout'.-newtype Stdout = Stdout {fromStdout :: String}---- | Collect the @stderr@ of the process.--- If you are collecting the @stderr@, it will not be echoed to the terminal, unless you include 'EchoStderr'.-newtype Stderr = Stderr {fromStderr :: String}---- | Collect the 'ExitCode' of the process.--- If you do not collect the exit code, any 'ExitFailure' will cause an exception.-newtype Exit = Exit {fromExit :: ExitCode}---- | A class for specifying what results you want to collect from a process.--- Values are formed of 'Stdout', 'Stderr', 'Exit' and tuples of those.-class CmdResult a where- -- Return a list of results (with the right type but dummy data)- -- and a function to transform a populated set of results into a value- cmdResult :: ([Result], [Result] -> a)--instance CmdResult Exit where- cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> Exit x)--instance CmdResult ExitCode where- cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> x)--instance CmdResult Stdout where- cmdResult = ([ResultStdout ""], \[ResultStdout x] -> Stdout x)--instance CmdResult Stderr where- cmdResult = ([ResultStderr ""], \[ResultStderr x] -> Stderr x)--instance CmdResult () where- cmdResult = ([], \[] -> ())--instance (CmdResult x1, CmdResult x2) => CmdResult (x1,x2) where- cmdResult = (a1++a2, \rs -> let (r1,r2) = splitAt (length a1) rs in (b1 r1, b2 r2))- where (a1,b1) = cmdResult- (a2,b2) = cmdResult--cmdResultWith f = second (f .) cmdResult--instance (CmdResult x1, CmdResult x2, CmdResult x3) => CmdResult (x1,x2,x3) where- cmdResult = cmdResultWith $ \(a,(b,c)) -> (a,b,c)----- | Execute a system command. Before running 'command' make sure you 'Development.Shake.need' any files--- that are used by the command.------ This function takes a list of options (often just @[]@, see 'CmdOption' for the available--- options), the name of the executable (either a full name, or a program on the @$PATH@) and--- a list of arguments. The result is often @()@, but can be a tuple containg any of 'Stdout',--- 'Stderr' and 'Exit'. Some examples:------ @--- 'command_' [] \"gcc\" [\"-c\",\"myfile.c\"] -- compile a file, throwing an exception on failure--- 'Exit' c <- 'command' [] \"gcc\" [\"-c\",myfile] -- run a command, recording the exit code--- ('Exit' c, 'Stderr' err) <- 'command' [] \"gcc\" [\"-c\",\"myfile.c\"] -- run a command, recording the exit code and error output--- 'Stdout' out <- 'command' [] \"gcc\" [\"-MM\",\"myfile.c\"] -- run a command, recording the output--- 'command_' ['Cwd' \"generated\"] \"gcc\" [\"-c\",myfile] -- run a command in a directory--- @------ Unless you retrieve the 'ExitCode' using 'Exit', any 'ExitFailure' will throw an error, including--- the 'Stderr' in the exception message. If you capture the 'Stdout' or 'Stderr', that stream will not be echoed to the console,--- unless you use the option 'EchoStdout' or 'EchoStderr'.------ If you use 'command' inside a @do@ block and do not use the result, you may get a compile-time error about being--- unable to deduce 'CmdResult'. To avoid this error, use 'command_'.-command :: CmdResult r => [CmdOption] -> String -> [String] -> Action r-command opts x xs = fmap b $ commandExplicit "command" opts a x xs- where (a,b) = cmdResult---- | A version of 'command' where you do not require any results, used to avoid errors about being unable--- to deduce 'CmdResult'.-command_ :: [CmdOption] -> String -> [String] -> Action ()-command_ opts x xs = void $ commandExplicit "command_" opts [] x xs--------------------------------------------------------------------------- VARIABLE ARGUMENT WRAPPER--type a :-> t = a----- | Execute a system command. Before running 'cmd' make sure you 'Development.Shake.need' any files--- that are used by the command.------ * @String@ arguments are treated as whitespace separated arguments.------ * @[String]@ arguments are treated as literal arguments.------ * 'CmdOption' arguments are used as options.------ To take the examples from 'command':------ @--- () <- 'cmd' \"gcc -c myfile.c\" -- compile a file, throwing an exception on failure--- 'Exit' c <- 'cmd' \"gcc -c\" [myfile] -- run a command, recording the exit code--- ('Exit' c, 'Stderr' err) <- 'cmd' \"gcc -c myfile.c\" -- run a command, recording the exit code and error output--- 'Stdout' out <- 'cmd' \"gcc -MM myfile.c\" -- run a command, recording the output--- 'cmd' ('Cwd' \"generated\") \"gcc -c\" [myfile] :: 'Action' () -- run a command in a directory--- @------ When passing file arguments we use @[myfile]@ so that if the @myfile@ variable contains spaces they are properly escaped.------ If you use 'cmd' inside a @do@ block and do not use the result, you may get a compile-time error about being--- unable to deduce 'CmdResult'. To avoid this error, bind the result to @()@, or include a type signature.------ The 'cmd' command can also be run in the 'IO' monad, but then 'Traced' is ignored and command lines are not echoed.-cmd :: CmdArguments args => args :-> Action r-cmd = cmdArguments []--class CmdArguments t where cmdArguments :: [Either CmdOption String] -> t-instance (Arg a, CmdArguments r) => CmdArguments (a -> r) where- cmdArguments xs x = cmdArguments $ xs ++ arg x-instance CmdResult r => CmdArguments (Action r) where- cmdArguments x = case partitionEithers x of- (opts, x:xs) -> let (a,b) = cmdResult in fmap b $ commandExplicit "cmd" opts a x xs- _ -> error "Error, no executable or arguments given to Development.Shake.cmd"-instance CmdResult r => CmdArguments (IO r) where- cmdArguments x = case partitionEithers x of- (opts, x:xs) -> let (a,b) = cmdResult in fmap b $ commandExplicitIO "cmd" opts a x xs- _ -> error "Error, no executable or arguments given to Development.Shake.cmd"--class Arg a where arg :: a -> [Either CmdOption String]-instance Arg String where arg = map Right . words-instance Arg [String] where arg = map Right-instance Arg (Maybe String) where arg = map Right . maybe [] words-instance Arg CmdOption where arg = return . Left-instance Arg [CmdOption] where arg = map Left-instance Arg (Maybe CmdOption) where arg = map Left . maybeToList
− Development/Shake/Config.hs
@@ -1,88 +0,0 @@-{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}---- | A module for parsing and using config files in a Shake build system. Config files--- consist of variable bindings, for example:------ > # This is my Config file--- > HEADERS_DIR = /path/to/dir--- > CFLAGS = -g -I${HEADERS_DIR}--- > CFLAGS = $CFLAGS -O2--- > include extra/file.cfg------ This defines the variable @HEADERS_DIR@ (equal to @\/path\/to\/dir@), and--- @CFLAGS@ (equal to @-g -I\/path\/to\/dir -O2@), and also includes the configuration--- statements in the file @extra/file.cfg@. The full lexical syntax for configuration--- files is defined here: <http://martine.github.io/ninja/manual.html#_lexical_syntax>.------ To use the configuration file either use 'readConfigFile' to parse the configuration file--- and use the values directly, or 'usingConfigFile' and 'getConfig' to track the configuration--- values, so they become build dependencies.-module Development.Shake.Config(- readConfigFile, readConfigFileWithEnv,- usingConfigFile, usingConfig,- getConfig- ) where--import Development.Shake-import Development.Shake.Classes-import qualified Development.Ninja.Parse as Ninja-import qualified Development.Ninja.Env as Ninja-import qualified Data.HashMap.Strict as Map-import qualified Data.ByteString.UTF8 as UTF8-import Control.Applicative-import Control.Arrow----- | Read a config file, returning a list of the variables and their bindings.--- Config files use the Ninja lexical syntax:--- <http://martine.github.io/ninja/manual.html#_lexical_syntax>-readConfigFile :: FilePath -> IO (Map.HashMap String String)-readConfigFile = readConfigFileWithEnv []----- | Read a config file with an initial environment, returning a list of the variables and their bindings.--- Config files use the Ninja lexical syntax:--- <http://martine.github.io/ninja/manual.html#_lexical_syntax>-readConfigFileWithEnv :: [(String, String)] -> FilePath -> IO (Map.HashMap String String)-readConfigFileWithEnv vars file = do- env <- Ninja.newEnv- mapM_ (uncurry (Ninja.addEnv env) . (UTF8.fromString *** UTF8.fromString)) vars- Ninja.parse file env- mp <- Ninja.fromEnv env- return $ Map.fromList $ map (UTF8.toString *** UTF8.toString) $ Map.toList mp---newtype Config = Config String deriving (Show,Typeable,Eq,Hashable,Binary,NFData)----- | Specify the file to use with 'getConfig'.-usingConfigFile :: FilePath -> Rules ()-usingConfigFile file = do- mp <- newCache $ \() -> liftIO $ readConfigFile file- addOracle $ \(Config x) -> Map.lookup x <$> mp ()- return ()----- | Specify the values to use with 'getConfig', generally prefer--- 'usingConfigFile' unless you also need access to the values--- of variables outside 'Action'.-usingConfig :: Map.HashMap String String -> Rules ()-usingConfig mp = do- addOracle $ \(Config x) -> return $ Map.lookup x mp- return ()----- | Obtain the value of a configuration variable, returns 'Nothing' to indicate the variable--- has no binding. Any build system using 'getConfig' /must/ call either 'usingConfigFile'--- or 'usingConfig'. The 'getConfig' function will introduce a dependency on the configuration--- variable (but not the whole configuration file), and if the configuration variable changes, the rule will be rerun.--- As an example:------ @--- 'usingConfigFile' \"myconfiguration.cfg\"--- \"*.o\" '*>' \\out -> do--- cflags <- 'getConfig' \"CFLAGS\"--- 'cmd' \"gcc\" [out '-<.>' \"c\"] (fromMaybe \"\" cflags)--- @-getConfig :: String -> Action (Maybe String)-getConfig = askOracle . Config
− Development/Shake/Core.hs
@@ -1,832 +0,0 @@-{-# LANGUAGE RecordWildCards, GeneralizedNewtypeDeriving, ScopedTypeVariables, PatternGuards #-}-{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-}--{-# LANGUAGE CPP #-}-#if __GLASGOW_HASKELL__ >= 704-{-# LANGUAGE ConstraintKinds #-}-#endif--module Development.Shake.Core(- run,-#if __GLASGOW_HASKELL__ >= 704- ShakeValue,-#endif- Rule(..), Rules, rule, action, withoutActions, alternatives, priority,- Action, actionOnException, actionFinally, apply, apply1, traced, getShakeOptions,- trackUse, trackChange, trackAllow,- getVerbosity, putLoud, putNormal, putQuiet, withVerbosity, quietly,- Resource, newResource, newResourceIO, withResource, withResources, newThrottle, newThrottleIO,- newCache, newCacheIO,- unsafeExtraThread,- -- Internal stuff- rulesIO, runAfter- ) where--import Control.Exception as E-import Control.Applicative-import Control.Arrow-import Control.Concurrent-import Control.Monad-import Control.Monad.IO.Class-import Control.Monad.Trans.Writer.Strict-import Data.Typeable-import Data.Function-import Data.List-import qualified Data.HashMap.Strict as Map-import Data.Maybe-import Data.Monoid-import Data.IORef-import System.Directory-import System.IO--import Development.Shake.Classes-import Development.Shake.Pool-import Development.Shake.Database-import Development.Shake.Monad-import Development.Shake.Resource-import Development.Shake.Value-import Development.Shake.Profile-import Development.Shake.Types-import Development.Shake.Errors-import Development.Shake.Special-import General.Timing-import General.Base-import General.Concurrent-import General.Cleanup-import General.String--------------------------------------------------------------------------- RULES--#if __GLASGOW_HASKELL__ >= 704--- | Define an alias for the six type classes required for things involved in Shake 'Development.Shake.Rule's.--- This alias is only available in GHC 7.4 and above, and requires the @ConstraintKinds@ extension.------ To define your own values meeting the necessary constraints it is convenient to use the extensions--- @GeneralizedNewtypeDeriving@ and @DeriveDataTypeable@ to write:------ > newtype MyType = MyType (String, Bool) deriving (Show,Typeable,Eq,Hashable,Binary,NFData)-type ShakeValue a = (Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a)-#endif----- | Define a pair of types that can be used by Shake rules.--- To import all the type classes required see "Development.Shake.Classes".-class (-#if __GLASGOW_HASKELL__ >= 704- ShakeValue key, ShakeValue value-#else- Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key,- Show value, Typeable value, Eq value, Hashable value, Binary value, NFData value-#endif- ) => Rule key value where-- -- | /[Required]/ Retrieve the @value@ associated with a @key@, if available.- --- -- As an example for filenames/timestamps, if the file exists you should return 'Just'- -- the timestamp, but otherwise return 'Nothing'. For rules whose values are not- -- stored externally, 'storedValue' should return 'Nothing'.- storedValue :: ShakeOptions -> key -> IO (Maybe value)-- -- | /[Optional]/ Equality check, with a notion of how expensive the check was.- equalValue :: ShakeOptions -> key -> value -> value -> EqualCost- equalValue _ _ v1 v2 = if v1 == v2 then EqualCheap else NotEqual---data ARule m = forall key value . Rule key value => ARule (key -> Maybe (m value))--ruleKey :: Rule key value => (key -> Maybe (m value)) -> key-ruleKey = err "ruleKey"--ruleValue :: Rule key value => (key -> Maybe (m value)) -> value-ruleValue = err "ruleValue"----- | Define a set of rules. Rules can be created with calls to functions such as 'Development.Shake.*>' or 'action'. Rules are combined--- with either the 'Monoid' instance, or (more commonly) the 'Monad' instance and @do@ notation. To define your own--- custom types of rule, see "Development.Shake.Rule".-newtype Rules a = Rules (WriterT (SRules Action) IO a) -- All IO must be associative/commutative (e.g. creating IORef/MVars)- deriving (Monad, Functor, Applicative)--rulesIO :: IO a -> Rules a-rulesIO = Rules . liftIO--newRules :: SRules Action -> Rules ()-newRules = Rules . tell--modifyRules :: (SRules Action -> SRules Action) -> Rules () -> Rules ()-modifyRules f (Rules r) = Rules $ censor f r--getRules :: Rules () -> IO (SRules Action)-getRules (Rules r) = execWriterT r---data SRules m = SRules- {actions :: [m ()]- ,rules :: Map.HashMap TypeRep{-k-} (TypeRep{-k-},TypeRep{-v-},[(Double,ARule m)]) -- higher fst is higher priority- }--instance Monoid (SRules m) where- mempty = SRules [] (Map.fromList [])- mappend (SRules x1 x2) (SRules y1 y2) = SRules (x1++y1) (Map.unionWith f x2 y2)- where f (k, v1, xs) (_, v2, ys)- | v1 == v2 = (k, v1, xs ++ ys)- | otherwise = errorIncompatibleRules k v1 v2--instance Monoid a => Monoid (Rules a) where- mempty = return mempty- mappend = liftA2 mappend----- | Add a rule to build a key, returning an appropriate 'Action'. All rules at a given priority--- must be disjoint. Rules have priority 1 by default, but can be modified with 'priority'.-rule :: Rule key value => (key -> Maybe (Action value)) -> Rules ()-rule r = newRules mempty{rules = Map.singleton k (k, v, [(1,ARule r)])}- where k = typeOf $ ruleKey r; v = typeOf $ ruleValue r----- | Change the priority of a given set of rules, where higher priorities take precedence.--- All matching rules at a given priority must be disjoint, or an error is raised.--- All builtin Shake rules have priority between 0 and 1.--- Excessive use of 'priority' is discouraged. As an example:------ @--- 'priority' 4 $ \"hello.*\" *> \\out -> 'writeFile'' out \"hello.*\"--- 'priority' 8 $ \"*.txt\" *> \\out -> 'writeFile'' out \"*.txt\"--- @------ In this example @hello.txt@ will match the second rule, instead of raising an error about ambiguity.-priority :: Double -> Rules () -> Rules ()-priority i = modifyRules $ \s -> s{rules = Map.map (\(a,b,cs) -> (a,b,map (first $ const i) cs)) $ rules s}----- | Change the matching behaviour of rules so rules do not have to be disjoint, but are instead matched--- in order. Only recommended for small blocks containing a handful of rules.------ @--- 'alternatives' $ do--- \"hello.*\" *> \\out -> 'writeFile'' out \"hello.*\"--- \"*.txt\" *> \\out -> 'writeFile'' out \"*.txt\"--- @------ In this example @hello.txt@ will match the first rule, instead of raising an error about ambiguity.-alternatives :: Rules () -> Rules ()-alternatives = modifyRules $ \r -> r{rules = Map.map f $ rules r}- where- f (k, v, []) = (k, v, [])- f (k, v, xs) = let (is,rs) = unzip xs in (k, v, [(maximum is, foldl1' g rs)])-- g (ARule a) (ARule b) = ARule $ \x -> a x `mplus` b2 x- where b2 = fmap (fmap (fromJust . cast)) . b . fromJust . cast----- | Run an action, usually used for specifying top-level requirements.------ @--- main = 'Development.Shake.shake' 'shakeOptions' $ do--- 'action' $ do--- b <- 'Development.Shake.doesFileExist' \"file.src\"--- when b $ 'Development.Shake.need' [\"file.out\"]--- @------ This 'action' builds @file.out@, but only if @file.src@ exists. The 'action'--- will be run in every build execution (unless 'withoutActions' is used), so only cheap--- operations should be performed. All arguments to 'action' may be run in parallel, in any order.------ For the standard requirement of only 'Development.Shake.need'ing a fixed list of files in the 'action',--- see 'Development.Shake.want'.-action :: Action a -> Rules ()-action a = newRules mempty{actions=[void a]}----- | Remove all actions specified in a set of rules, usually used for implementing--- command line specification of what to build.-withoutActions :: Rules () -> Rules ()-withoutActions = modifyRules $ \x -> x{actions=[]}---registerWitnesses :: SRules m -> IO ()-registerWitnesses SRules{..} =- forM_ (Map.elems rules) $ \(_, _, (_,ARule r):_) -> do- registerWitness $ ruleKey r- registerWitness $ ruleValue r---data RuleInfo m = RuleInfo- {stored :: Key -> IO (Maybe Value)- ,equal :: Key -> Value -> Value -> EqualCost- ,execute :: Key -> m Value- ,resultType :: TypeRep- }--createRuleinfo :: ShakeOptions -> SRules Action -> Map.HashMap TypeRep (RuleInfo Action)-createRuleinfo opt SRules{..} = flip Map.map rules $ \(_,tv,rs) -> RuleInfo (stored rs) (equal rs) (execute rs) tv- where- stored ((_,ARule r):_) = fmap (fmap newValue) . f r . fromKey- where f :: Rule key value => (key -> Maybe (m value)) -> (key -> IO (Maybe value))- f _ = storedValue opt-- equal ((_,ARule r):_) = \k v1 v2 -> f r (fromKey k) (fromValue v1) (fromValue v2)- where f :: Rule key value => (key -> Maybe (m value)) -> key -> value -> value -> EqualCost- f _ = equalValue opt-- execute rs = \k -> case filter (not . null) $ map (mapMaybe ($ k)) rs2 of- [r]:_ -> r- rs -> errorMultipleRulesMatch (typeKey k) (show k) (length rs)- where rs2 = sets [(i, \k -> fmap (fmap newValue) $ r (fromKey k)) | (i,ARule r) <- rs] -- sets :: Ord a => [(a, b)] -> [[b]] -- highest to lowest- sets = map (map snd) . reverse . groupBy ((==) `on` fst) . sortBy (compare `on` fst)--runStored :: Map.HashMap TypeRep (RuleInfo m) -> Key -> IO (Maybe Value)-runStored mp k = case Map.lookup (typeKey k) mp of- Nothing -> return Nothing- Just RuleInfo{..} -> stored k--runEqual :: Map.HashMap TypeRep (RuleInfo m) -> Key -> Value -> Value -> EqualCost-runEqual mp k v1 v2 = case Map.lookup (typeKey k) mp of- Nothing -> NotEqual- Just RuleInfo{..} -> equal k v1 v2--runExecute :: Map.HashMap TypeRep (RuleInfo m) -> Key -> m Value-runExecute mp k = let tk = typeKey k in case Map.lookup tk mp of- Nothing -> errorNoRuleToBuildType tk (Just $ show k) Nothing -- Not sure if this is even possible, but best be safe- Just RuleInfo{..} -> execute k--------------------------------------------------------------------------- MAKE---- global constants of Action-data Global = Global- {globalDatabase :: Database- ,globalPool :: Pool- ,globalCleanup :: Cleanup- ,globalTimestamp :: IO Time- ,globalRules :: Map.HashMap TypeRep (RuleInfo Action)- ,globalOutput :: Verbosity -> String -> IO ()- ,globalOptions :: ShakeOptions- ,globalDiagnostic :: String -> IO ()- ,globalLint :: String -> IO ()- ,globalAfter :: IORef [IO ()]- ,globalTrackAbsent :: IORef [(Key, Key)] -- in rule fst, snd must be absent- }----- local variables of Action-data Local = Local- -- constants- {localStack :: Stack- -- stack scoped local variables- ,localVerbosity :: Verbosity- ,localBlockApply :: Maybe String -- reason to block apply, or Nothing to allow- -- mutable local variables- ,localDepends :: [Depends] -- built up in reverse- ,localDiscount :: !Duration- ,localTraces :: [Trace] -- in reverse- ,localTrackAllows :: [Key -> Bool]- ,localTrackUsed :: [Key]- }---- | The 'Action' monad, use 'liftIO' to raise 'IO' actions into it, and 'Development.Shake.need' to execute files.--- Action values are used by 'rule' and 'action'. The 'Action' monad tracks the dependencies of a 'Rule'.-newtype Action a = Action {fromAction :: RAW Global Local a}- deriving (Functor, Applicative, Monad, MonadIO)---actionBoom :: Bool -> Action a -> IO b -> Action a-actionBoom runOnSuccess act clean = do- cleanup <- Action $ getsRO globalCleanup- clean <- liftIO $ addCleanup cleanup $ void clean- res <- Action $ catchRAW (fromAction act) $ \(e :: SomeException) -> liftIO (clean True) >> throwRAW e- liftIO $ clean runOnSuccess- return res---- | If an exception is raised by the 'Action', perform some 'IO'.-actionOnException :: Action a -> IO b -> Action a-actionOnException = actionBoom False---- | After an 'Action', perform some 'IO', even if there is an exception.-actionFinally :: Action a -> IO b -> Action a-actionFinally = actionBoom True----- | Internal main function (not exported publicly)-run :: ShakeOptions -> Rules () -> IO ()-run opts@ShakeOptions{..} rs = (if shakeLineBuffering then lineBuffering else id) $ do- start <- offsetTime- rs <- getRules rs- registerWitnesses rs-- outputLocked <- do- lock <- newLock- return $ \v msg -> withLock lock $ shakeOutput v msg-- let diagnostic = if shakeVerbosity >= Diagnostic then outputLocked Diagnostic . ("% "++) else const $ return ()- let output v = outputLocked v . abbreviate shakeAbbreviations-- except <- newIORef (Nothing :: Maybe (String, SomeException))- let staunch act | not shakeStaunch = void act- | otherwise = do- res <- try act- case res of- Left err -> do- let named = maybe "" (abbreviate shakeAbbreviations . shakeExceptionTarget) . fromException- atomicModifyIORef except $ \v -> (Just $ fromMaybe (named err, err) v, ())- let msg = show err ++ "Continuing due to staunch mode, this error will be repeated later"- when (shakeVerbosity >= Quiet) $ output Quiet msg- Right _ -> return ()-- lint <- if isNothing shakeLint then return $ const $ return () else do- dir <- getCurrentDirectory- return $ \msg -> do- now <- getCurrentDirectory- when (dir /= now) $ errorStructured- "Lint checking error - current directory has changed"- [("When", Just msg)- ,("Wanted",Just dir)- ,("Got",Just now)]- ""-- progressAbort <- newIORef $ return ()- after <- newIORef []- absent <- newIORef []- shakeThreads <- if shakeThreads == 0 then getProcessorCount else return shakeThreads- withCleanup $ \cleanup -> do- _ <- addCleanup cleanup $ do- join $ readIORef progressAbort- when shakeTimings printTimings- resetTimings -- so we don't leak memory- withCapabilities shakeThreads $ do- withDatabase opts diagnostic $ \database -> do- wait <- newBarrier- tid <- forkIO $ flip finally (signalBarrier wait ()) $- shakeProgress $ do- failure <- fmap (fmap fst) $ readIORef except- stats <- progress database- return stats{isFailure=failure}- writeIORef progressAbort $ do- forkIO $ sleep 1 >> signalBarrier wait ()- killThread tid- waitBarrier wait-- let ruleinfo = createRuleinfo opts rs- addTiming "Running rules"- runPool (shakeThreads == 1) shakeThreads $ \pool -> do- let s0 = Global database pool cleanup start ruleinfo output opts diagnostic lint after absent- let s1 = Local emptyStack shakeVerbosity Nothing [] 0 [] [] []- forM_ (actions rs) $ \act -> do- addPool pool $ runAction s0 s1 act $ \x -> staunch $ either throwIO return x-- when (isJust shakeLint) $ do- addTiming "Lint checking"- absent <- readIORef absent- checkValid database (runStored ruleinfo) (runEqual ruleinfo) absent- when (shakeVerbosity >= Loud) $ output Loud "Lint checking succeeded"- when (shakeReport /= []) $ do- addTiming "Profile report"- report <- toReport database- forM_ shakeReport $ \file -> do- when (shakeVerbosity >= Normal) $- output Normal $ "Writing report to " ++ file- writeProfile file report- when (shakeLiveFiles /= []) $ do- addTiming "Listing live"- live <- listLive database- let liveFiles = [show k | k <- live, specialIsFileKey $ typeKey k]- forM_ shakeLiveFiles $ \file -> do- when (shakeVerbosity >= Normal) $- output Normal $ "Writing live list to " ++ file- (if file == "-" then putStr else writeFile file) $ unlines liveFiles- maybe (return ()) (throwIO . snd) =<< readIORef except- sequence_ . reverse =<< readIORef after---lineBuffering :: IO a -> IO a-lineBuffering = withBufferMode stdout LineBuffering . withBufferMode stderr LineBuffering---abbreviate :: [(String,String)] -> String -> String-abbreviate [] = id-abbreviate abbrev = f- where- -- order so longer appreviations are preferred- ordAbbrev = sortBy (flip (compare `on` length . fst)) abbrev-- f [] = []- f x | (to,rest):_ <- [(to,rest) | (from,to) <- ordAbbrev, Just rest <- [stripPrefix from x]] = to ++ f rest- f (x:xs) = x : f xs---wrapStack :: IO [String] -> IO a -> IO a-wrapStack stk act = E.catch act $ \(SomeException e) -> case cast e of- Just s@ShakeException{} -> throwIO s- Nothing -> do- stk <- stk- if null stk then throwIO e- else throwIO $ ShakeException (last stk) stk $ SomeException e---runAction :: Global -> Local -> Action a -> Capture (Either SomeException a)-runAction g l (Action x) k = runRAW g l x k---runAfter :: IO () -> Action ()-runAfter op = do- Global{..} <- Action getRO- liftIO $ atomicModifyIORef globalAfter $ \ops -> (op:ops, ())----- | Execute a rule, returning the associated values. If possible, the rules will be run in parallel.--- This function requires that appropriate rules have been added with 'rule'.--- All @key@ values passed to 'apply' become dependencies of the 'Action'.-apply :: Rule key value => [key] -> Action [value]-apply = f -- Don't short-circuit [] as we still want error messages- where- -- We don't want the forall in the Haddock docs- f :: forall key value . Rule key value => [key] -> Action [value]- f ks = do- let tk = typeOf (err "apply key" :: key)- tv = typeOf (err "apply type" :: value)- Global{..} <- Action getRO- block <- Action $ getsRW localBlockApply- whenJust block $ errorNoApply tk (fmap show $ listToMaybe ks)- case Map.lookup tk globalRules of- Nothing -> errorNoRuleToBuildType tk (fmap show $ listToMaybe ks) (Just tv)- Just RuleInfo{resultType=tv2} | tv /= tv2 -> errorRuleTypeMismatch tk (fmap show $ listToMaybe ks) tv2 tv- _ -> fmap (map fromValue) $ applyKeyValue $ map newKey ks---applyKeyValue :: [Key] -> Action [Value]-applyKeyValue [] = return []-applyKeyValue ks = do- global@Global{..} <- Action getRO- let exec stack k continue = do- let s = Local {localVerbosity=shakeVerbosity globalOptions, localDepends=[], localStack=stack, localBlockApply=Nothing- ,localDiscount=0, localTraces=[], localTrackAllows=[], localTrackUsed=[]}- let top = showTopStack stack- time <- offsetTime- runAction global s (do- liftIO $ evaluate $ rnf k- liftIO $ globalLint $ "before building " ++ top- putWhen Chatty $ "# " ++ show k- res <- runExecute globalRules k- when (shakeLint globalOptions == Just LintTracker)- trackCheckUsed- Action $ fmap ((,) res) getRW) $ \x -> case x of- Left e -> (continue =<<) $ try $ wrapStack (showStack globalDatabase stack) $ throwIO e- Right (res, Local{..}) -> do- dur <- time- globalLint $ "after building " ++ top- let ans = (res, reverse localDepends, dur - localDiscount, reverse localTraces)- evaluate $ rnf ans- continue $ Right ans- stack <- Action $ getsRW localStack- (dur, dep, vs) <- Action $ captureRAW $ build globalPool globalDatabase (Ops (runStored globalRules) (runEqual globalRules) exec) stack ks- Action $ modifyRW $ \s -> s{localDiscount=localDiscount s + dur, localDepends=dep : localDepends s}- return vs----- | Apply a single rule, equivalent to calling 'apply' with a singleton list. Where possible,--- use 'apply' to allow parallelism.-apply1 :: Rule key value => key -> Action value-apply1 = fmap head . apply . return----- | Get the initial 'ShakeOptions', these will not change during the build process.-getShakeOptions :: Action ShakeOptions-getShakeOptions = Action $ getsRO globalOptions----- | Write an action to the trace list, along with the start/end time of running the IO action.--- The 'Development.Shake.cmd' and 'Development.Shake.command' functions automatically call 'traced'.--- The trace list is used for profile reports (see 'shakeReport').-traced :: String -> IO a -> Action a-traced msg act = do- Global{..} <- Action getRO- stack <- Action $ getsRW localStack- start <- liftIO globalTimestamp- putNormal $ "# " ++ msg ++ " (for " ++ showTopStack stack ++ ")"- res <- liftIO act- stop <- liftIO globalTimestamp- Action $ modifyRW $ \s -> s{localTraces = Trace (pack msg) (doubleToFloat start) (doubleToFloat stop) : localTraces s}- return res---putWhen :: Verbosity -> String -> Action ()-putWhen v msg = do- Global{..} <- Action getRO- verb <- getVerbosity- when (verb >= v) $- liftIO $ globalOutput v msg----- | Write a message to the output when the verbosity ('shakeVerbosity') is appropriate.--- The output will not be interleaved with any other Shake messages--- (other than those generated by system commands).-putLoud, putNormal, putQuiet :: String -> Action ()-putLoud = putWhen Loud-putNormal = putWhen Normal-putQuiet = putWhen Quiet----- | Get the current verbosity level, originally set by 'shakeVerbosity'. If you--- want to output information to the console, you are recommended to use--- 'putLoud' \/ 'putNormal' \/ 'putQuiet', which ensures multiple messages are--- not interleaved. The verbosity can be modified locally by 'withVerbosity'.-getVerbosity :: Action Verbosity-getVerbosity = Action $ getsRW localVerbosity----- | Run an action with a particular verbosity level.--- Will not update the 'shakeVerbosity' returned by 'getShakeOptions' and will--- not have any impact on 'Diagnostic' tracing.-withVerbosity :: Verbosity -> Action a -> Action a-withVerbosity new = Action . unmodifyRW f . fromAction- where f s0 = (s0{localVerbosity=new}, \s -> s{localVerbosity=localVerbosity s0})----- | Run an action with 'Quiet' verbosity, in particular messages produced by 'traced'--- (including from 'Development.Shake.cmd' or 'Development.Shake.command') will not be printed to the screen.--- Will not update the 'shakeVerbosity' returned by 'getShakeOptions' and will--- not turn off any 'Diagnostic' tracing.-quietly :: Action a -> Action a-quietly = withVerbosity Quiet--------------------------------------------------------------------------- TRACKING---- | Track that a key has been used by the action preceeding it.-trackUse ::-#if __GLASGOW_HASKELL__ >= 704- ShakeValue key-#else- (Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key)-#endif- => key -> Action ()--- One of the following must be true:--- 1) you are the one building this key (e.g. key == topStack)--- 2) you have already been used by apply, and are on the dependency list--- 3) someone explicitly gave you permission with trackAllow--- 4) at the end of the rule, a) you are now on the dependency list, and b) this key itself has no dependencies (is source file)-trackUse key = do- let k = newKey key- Global{..} <- Action getRO- l@Local{..} <- Action getRW- deps <- liftIO $ concatMapM (listDepends globalDatabase) localDepends- let top = topStack localStack- if top == Just k then- return () -- condition 1- else if k `elem` deps then- return () -- condition 2- else if any ($ k) localTrackAllows then- return () -- condition 3- else- Action $ putRW l{localTrackUsed = k : localTrackUsed} -- condition 4---trackCheckUsed :: Action ()-trackCheckUsed = do- Global{..} <- Action getRO- Local{..} <- Action getRW- liftIO $ do- deps <- concatMapM (listDepends globalDatabase) localDepends-- -- check 3a- bad <- return $ localTrackUsed \\ deps- unless (null bad) $ do- let n = length bad- errorStructured- ("Link checking error - " ++ (if n == 1 then "value was" else show n ++ " values were") ++ " used but not depended upon")- [("Used", Just $ show x) | x <- bad]- ""-- -- check 3b- bad <- flip filterM localTrackUsed $ \k -> fmap (not . null) $ lookupDependencies globalDatabase k- unless (null bad) $ do- let n = length bad- errorStructured- ("Link checking error - " ++ (if n == 1 then "value was" else show n ++ " values were") ++ " depended upon after being used")- [("Used", Just $ show x) | x <- bad]- ""----- | Track that a key has been changed by the action preceeding it.-trackChange ::-#if __GLASGOW_HASKELL__ >= 704- ShakeValue key-#else- (Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key)-#endif- => key -> Action ()--- One of the following must be true:--- 1) you are the one building this key (e.g. key == topStack)--- 2) someone explicitly gave you permission with trackAllow--- 3) this file is never known to the build system, at the end it is not in the database-trackChange key = do- let k = newKey key- Global{..} <- Action getRO- Local{..} <- Action getRW- liftIO $ do- let top = topStack localStack- if top == Just k then- return () -- condition 1- else if any ($ k) localTrackAllows then- return () -- condition 2- else- -- condition 3- atomicModifyIORef globalTrackAbsent $ \ks -> ((fromMaybe k top, k):ks, ())----- | Allow any matching key to violate the tracking rules.-trackAllow ::-#if __GLASGOW_HASKELL__ >= 704- ShakeValue key-#else- (Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key)-#endif- => (key -> Bool) -> Action ()-trackAllow test = Action $ modifyRW $ \s -> s{localTrackAllows = f : localTrackAllows s}- where- -- We don't want the forall in the Haddock docs- arrow1Type :: forall a b . Typeable a => (a -> b) -> TypeRep- arrow1Type _ = typeOf (err "trackAllow" :: a)-- ty = arrow1Type test- f k = typeKey k == ty && test (fromKey k)--------------------------------------------------------------------------- RESOURCES---- | Create a finite resource, given a name (for error messages) and a quantity of the resource that exists.--- Shake will ensure that actions using the same finite resource do not execute in parallel.--- As an example, only one set of calls to the Excel API can occur at one time, therefore--- Excel is a finite resource of quantity 1. You can write:------ @--- 'Development.Shake.shake' 'Development.Shake.shakeOptions'{'Development.Shake.shakeThreads'=2} $ do--- 'Development.Shake.want' [\"a.xls\",\"b.xls\"]--- excel <- 'Development.Shake.newResource' \"Excel\" 1--- \"*.xls\" 'Development.Shake.*>' \\out ->--- 'Development.Shake.withResource' excel 1 $--- 'Development.Shake.cmd' \"excel\" out ...--- @------ Now the two calls to @excel@ will not happen in parallel.------ As another example, calls to compilers are usually CPU bound but calls to linkers are usually--- disk bound. Running 8 linkers will often cause an 8 CPU system to grid to a halt. We can limit--- ourselves to 4 linkers with:------ @--- disk <- 'Development.Shake.newResource' \"Disk\" 4--- 'Development.Shake.want' [show i 'Development.Shake.FilePath.<.>' \"exe\" | i <- [1..100]]--- \"*.exe\" 'Development.Shake.*>' \\out ->--- 'Development.Shake.withResource' disk 1 $--- 'Development.Shake.cmd' \"ld -o\" [out] ...--- \"*.o\" 'Development.Shake.*>' \\out ->--- 'Development.Shake.cmd' \"cl -o\" [out] ...--- @-newResource :: String -> Int -> Rules Resource-newResource name mx = rulesIO $ newResourceIO name mx----- | Create a throttled resource, given a name (for error messages) and a number of resources (the 'Int') that can be--- used per time period (the 'Double' in seconds). Shake will ensure that actions using the same throttled resource--- do not exceed the limits. As an example, let us assume that making more than 1 request every 5 seconds to--- Google results in our client being blacklisted, we can write:------ @--- google <- 'Development.Shake.newThrottle' \"Google\" 1 5--- \"*.url\" 'Development.Shake.*>' \\out -> do--- 'Development.Shake.withResource' google 1 $--- 'Development.Shake.cmd' \"wget\" [\"http:\/\/google.com?q=\" ++ 'Development.Shake.FilePath.takeBaseName' out] \"-O\" [out]--- @------ Now we will wait at least 5 seconds after querying Google before performing another query. If Google change the rules to--- allow 12 requests per minute we can instead use @'Development.Shake.newThrottle' \"Google\" 12 60@, which would allow--- greater parallelisation, and avoid throttling entirely if only a small number of requests are necessary.------ In the original example we never make a fresh request until 5 seconds after the previous request has /completed/. If we instead--- want to throttle requests since the previous request /started/ we can write:------ @--- google <- 'Development.Shake.newThrottle' \"Google\" 1 5--- \"*.url\" 'Development.Shake.*>' \\out -> do--- 'Development.Shake.withResource' google 1 $ return ()--- 'Development.Shake.cmd' \"wget\" [\"http:\/\/google.com?q=\" ++ 'Development.Shake.FilePath.takeBaseName' out] \"-O\" [out]--- @------ However, the rule may not continue running immediately after 'Development.Shake.withResource' completes, so while--- we will never exceed an average of 1 request every 5 seconds, we may end up running an unbounded number of--- requests simultaneously. If this limitation causes a problem in practice it can be fixed.-newThrottle :: String -> Int -> Double -> Rules Resource-newThrottle name count period = rulesIO $ newThrottleIO name count period---blockApply :: String -> Action a -> Action a-blockApply msg = Action . unmodifyRW f . fromAction- where f s0 = (s0{localBlockApply=Just msg}, \s -> s{localBlockApply=localBlockApply s0})----- | Run an action which uses part of a finite resource. For more details see 'Resource'.--- You cannot depend on a rule (e.g. 'need') while a resource is held.-withResource :: Resource -> Int -> Action a -> Action a-withResource r i act = do- Global{..} <- Action getRO- liftIO $ globalDiagnostic $ show r ++ " waiting to acquire " ++ show i- Action $ captureRAW $ \continue -> acquireResource r globalPool i $ do- globalDiagnostic $ show r ++ " acquired " ++ show i- continue $ Right ()- res <- Action $ tryRAW $ fromAction $ blockApply ("Within withResource using " ++ show r) act- liftIO $ releaseResource r globalPool i- liftIO $ globalDiagnostic $ show r ++ " released " ++ show i- Action $ either throwRAW return res----- | Run an action which uses part of several finite resources. Acquires the resources in a stable--- order, to prevent deadlock. If all rules requiring more than one resource acquire those--- resources with a single call to 'withResources', resources will not deadlock.-withResources :: [(Resource, Int)] -> Action a -> Action a-withResources res act- | (r,i):_ <- filter ((< 0) . snd) res = error $ "You cannot acquire a negative quantity of " ++ show r ++ ", requested " ++ show i- | otherwise = f $ groupBy ((==) `on` fst) $ sortBy (compare `on` fst) res- where- f [] = act- f (r:rs) = withResource (fst $ head r) (sum $ map snd r) $ f rs----- | A version of 'newCache' that runs in IO, and can be called before calling 'Development.Shake.shake'.--- Most people should use 'newCache' instead.-newCacheIO :: (Eq k, Hashable k) => (k -> Action v) -> IO (k -> Action v)-newCacheIO act = do- var {- :: Var (Map k (Fence (Either SomeException ([Depends],v)))) -} <- newVar Map.empty- return $ \key -> do- join $ liftIO $ modifyVar var $ \mp -> case Map.lookup key mp of- Just bar -> return $ (,) mp $ do- res <- liftIO $ testFence bar- res <- case res of- Just res -> return res- Nothing -> do- pool <- Action $ getsRO globalPool- Action $ captureRAW $ \k -> waitFence bar $ \v ->- addPool pool $ k $ Right v- case res of- Left err -> Action $ throwRAW err- Right (deps,v) -> do- Action $ modifyRW $ \s -> s{localDepends = deps ++ localDepends s}- return v- Nothing -> do- bar <- newFence- return $ (,) (Map.insert key bar mp) $ do- pre <- Action $ getsRW localDepends- res <- Action $ tryRAW $ fromAction $ act key- case res of- Left err -> do- liftIO $ signalFence bar $ Left (err :: SomeException)- Action $ throwRAW err- Right v -> do- post <- Action $ getsRW localDepends- let deps = take (length post - length pre) post- liftIO $ signalFence bar $ Right (deps, v)- return v---- | Given an action on a key, produce a cached version that will execute the action at most once per key.--- Using the cached result will still result include any dependencies that the action requires.--- Each call to 'newCache' creates a separate cache that is independent of all other calls to 'newCache'.------ This function is useful when creating files that store intermediate values,--- to avoid the overhead of repeatedly reading from disk, particularly if the file requires expensive parsing.--- As an example:------ @--- digits \<- 'newCache' $ \\file -> do--- src \<- readFile\' file--- return $ length $ filter isDigit src--- \"*.digits\" 'Development.Shake.*>' \\x -> do--- v1 \<- digits ('dropExtension' x)--- v2 \<- digits ('dropExtension' x)--- 'Development.Shake.writeFile'' x $ show (v1,v2)--- @------ To create the result @MyFile.txt.digits@ the file @MyFile.txt@ will be read and counted, but only at most--- once per execution.-newCache :: (Eq k, Hashable k) => (k -> Action v) -> Rules (k -> Action v)-newCache = rulesIO . newCacheIO----- | Run an action without counting to the thread limit, typically used for actions that execute--- on remote machines using barely any local CPU resources. Unsafe as it allows the 'shakeThreads' limit to be exceeded.--- You cannot depend on a rule (e.g. 'need') while the extra thread is executing.--- If the rule blocks (e.g. calls 'withResource') then the extra thread may be used by some other action.--- Only really suitable for calling 'cmd'/'command'.-unsafeExtraThread :: Action a -> Action a-unsafeExtraThread act = Action $ do- global@Global{..} <- getRO- stop <- liftIO $ increasePool globalPool- res <- tryRAW $ fromAction $ blockApply "Within unsafeExtraThread" act- liftIO stop- captureRAW $ \continue -> (if isLeft_ res then addPoolPriority else addPool) globalPool $ continue res
− Development/Shake/Database.hs
@@ -1,531 +0,0 @@-{-# LANGUAGE RecordWildCards, ScopedTypeVariables, PatternGuards, ViewPatterns #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}--module Development.Shake.Database(- Trace(..),- Database, withDatabase,- listDepends, lookupDependencies,- Ops(..), build, Depends,- progress,- Stack, emptyStack, topStack, showStack, showTopStack,- toReport, checkValid, listLive- ) where--import Development.Shake.Classes-import General.Binary-import Development.Shake.Pool-import Development.Shake.Value-import Development.Shake.Errors-import Development.Shake.Storage-import Development.Shake.Types-import Development.Shake.Special-import Development.Shake.Profile-import Development.Shake.Monad-import General.Base-import General.Concurrent-import General.String-import General.Intern as Intern--import Control.Applicative-import Control.Exception-import Control.Monad-import qualified Data.HashSet as Set-import qualified Data.HashMap.Strict as Map-import Data.IORef-import Data.Maybe-import Data.List-import Data.Monoid--type Map = Map.HashMap--------------------------------------------------------------------------- UTILITY TYPES--newtype Step = Step Word32 deriving (Eq,Ord,Show,Binary,NFData,Hashable,Typeable)--incStep (Step i) = Step $ i + 1--------------------------------------------------------------------------- CALL STACK--data Stack = Stack (Maybe Key) [Id] !(Set.HashSet Id)--showStack :: Database -> Stack -> IO [String]-showStack Database{..} (Stack _ xs _) = do- status <- withLock lock $ readIORef status- return $ reverse $ map (maybe "<unknown>" (show . fst) . flip Map.lookup status) xs--addStack :: Id -> Key -> Stack -> Stack-addStack x key (Stack _ xs set) = Stack (Just key) (x:xs) (Set.insert x set)--showTopStack :: Stack -> String-showTopStack = maybe "<unknown>" show . topStack--topStack :: Stack -> Maybe Key-topStack (Stack key _ _) = key--checkStack :: [Id] -> Stack -> Maybe Id-checkStack new (Stack _ old set)- | bad:_ <- filter (`Set.member` set) new = Just bad- | otherwise = Nothing--emptyStack :: Stack-emptyStack = Stack Nothing [] Set.empty--------------------------------------------------------------------------- CENTRAL TYPES--data Trace = Trace BS Float Float -- (message, start, end)- deriving Show--instance NFData Trace where- rnf (Trace a b c) = rnf a `seq` rnf b `seq` rnf c---- | Invariant: The database does not have any cycles where a Key depends on itself-data Database = Database- {lock :: Lock- ,intern :: IORef (Intern Key)- ,status :: IORef (Map Id (Key, Status))- ,step :: Step- ,journal :: Id -> (Key, Status {- Loaded or Missing -}) -> IO ()- ,diagnostic :: String -> IO () -- logging function- ,assume :: Maybe Assume- }--data Status- = Ready Result -- I have a value- | Error SomeException -- I have been run and raised an error- | Loaded Result -- Loaded from the database- | Waiting Pending (Maybe Result) -- Currently checking if I am valid or building- | Missing -- I am only here because I got into the Intern table- deriving Show--data Result = Result- {result :: Value -- the result associated with the Key- ,built :: {-# UNPACK #-} !Step -- when it was actually run- ,changed :: {-# UNPACK #-} !Step -- the step for deciding if it's valid- ,depends :: [[Id]] -- dependencies- ,execution :: {-# UNPACK #-} !Float -- how long it took when it was last run (seconds)- ,traces :: [Trace] -- a trace of the expensive operations (start/end in seconds since beginning of run)- } deriving Show---newtype Pending = Pending (IORef (IO ()))- -- you must run this action when you finish, while holding DB lock- -- after you have set the result to Error or Ready--instance Show Pending where show _ = "Pending"---statusType Ready{} = "Ready"-statusType Error{} = "Error"-statusType Loaded{} = "Loaded"-statusType Waiting{} = "Waiting"-statusType Missing{} = "Missing"--isError Error{} = True; isError _ = False-isWaiting Waiting{} = True; isWaiting _ = False-isReady Ready{} = True; isReady _ = False----- All the waiting operations are only valid when isWaiting-type Waiting = Status--afterWaiting :: Waiting -> IO () -> IO ()-afterWaiting (Waiting (Pending p) _) act = modifyIORef'' p (>> act)--newWaiting :: Maybe Result -> IO Waiting-newWaiting r = do ref <- newIORef $ return (); return $ Waiting (Pending ref) r--runWaiting :: Waiting -> IO ()-runWaiting (Waiting (Pending p) _) = join $ readIORef p---- Wait for a set of actions to complete--- If the action returns True, the function will not be called again--- If the first argument is True, the thing is ended-waitFor :: [(a, Waiting)] -> (Bool -> a -> IO Bool) -> IO ()-waitFor ws@(_:_) act = do- todo <- newIORef $ length ws- forM_ ws $ \(k,w) -> afterWaiting w $ do- t <- readIORef todo- when (t /= 0) $ do- b <- act (t == 1) k- writeIORef'' todo $ if b then 0 else t - 1---getResult :: Status -> Maybe Result-getResult (Ready r) = Just r-getResult (Loaded r) = Just r-getResult (Waiting _ r) = r-getResult _ = Nothing--------------------------------------------------------------------------- OPERATIONS--newtype Depends = Depends {fromDepends :: [Id]}- deriving (NFData)---data Ops = Ops- {stored :: Key -> IO (Maybe Value)- -- ^ Given a Key, find the value stored on disk- ,equal :: Key -> Value -> Value -> EqualCost- -- ^ Given both Values, see if they are equal and how expensive that check was- ,execute :: Stack -> Key -> Capture (Either SomeException (Value, [Depends], Duration, [Trace]))- -- ^ Given a stack and a key, either raise an exception or successfully build it- }----- | Return either an exception (crash), or (how much time you spent waiting, the value)-build :: Pool -> Database -> Ops -> Stack -> [Key] -> Capture (Either SomeException (Duration,Depends,[Value]))-build pool Database{..} Ops{..} stack ks continue = do- join $ withLock lock $ do- is <- forM ks $ \k -> do- is <- readIORef intern- case Intern.lookup k is of- Just i -> return i- Nothing -> do- (is, i) <- return $ Intern.add k is- writeIORef'' intern is- modifyIORef'' status $ Map.insert i (k,Missing)- return i-- whenJust (checkStack is stack) $ \bad -> do- status <- readIORef status- uncurry errorRuleRecursion $ case Map.lookup bad status of- Nothing -> (Nothing, Nothing)- Just (k,_) -> (Just $ typeKey k, Just $ show k)-- vs <- mapM (reduce stack) is- let errs = [e | Error e <- vs]- if all isReady vs then- return $ continue $ Right (0, Depends is, [result r | Ready r <- vs])- else if not $ null errs then- return $ continue $ Left $ head errs- else do- time <- offsetTime- let done x = do- case x of- Left e -> addPoolPriority pool $ continue $ Left e- Right v -> addPool pool $ do dur <- time; continue $ Right (dur, Depends is, v)- return True- waitFor (filter (isWaiting . snd) $ zip is vs) $ \finish i -> do- s <- readIORef status- case Map.lookup i s of- Just (_, Error e) -> done $ Left e -- on error make sure we immediately kick off our parent- Just (_, Ready{}) | finish -> done $ Right [result r | i <- is, let Ready r = snd $ fromJust $ Map.lookup i s]- | otherwise -> return False- return $ return ()- where- (#=) :: Id -> (Key, Status) -> IO Status- i #= (k,v) = do- s <- readIORef status- writeIORef'' status $ Map.insert i (k,v) s- diagnostic $ maybe "Missing" (statusType . snd) (Map.lookup i s) ++ " -> " ++ statusType v ++ ", " ++ maybe "<unknown>" (show . fst) (Map.lookup i s)- return v-- atom x = let s = show x in if ' ' `elem` s then "(" ++ s ++ ")" else s-- -- Rules for each eval* function- -- * Must NOT lock- -- * Must have an equal return to what is stored in the db at that point- -- * Must not return Loaded-- reduce :: Stack -> Id -> IO Status- reduce stack i = do- s <- readIORef status- case Map.lookup i s of- Nothing -> err $ "interned value missing from database, " ++ show i- Just (k, Missing) -> run stack i k Nothing- Just (k, Loaded r) -> do- let out b = diagnostic $ "valid " ++ show b ++ " for " ++ atom k ++ " " ++ atom (result r)- let continue r = out True >> check stack i k r (depends r)- let rebuild = out False >> run stack i k (Just r)- case assume of- Just AssumeDirty -> rebuild- Just AssumeSkip -> continue r- _ -> do- s <- stored k- case s of- Just s -> case equal k (result r) s of- NotEqual -> rebuild- EqualCheap -> continue r- EqualExpensive -> do- -- warning, have the db lock while appending (may harm performance)- r <- return r{result=s}- journal i (k, Loaded r)- i #= (k, Loaded r)- continue r- _ -> rebuild- Just (k, res) -> return res-- run :: Stack -> Id -> Key -> Maybe Result -> IO Waiting- run stack i k r = do- w <- newWaiting r- addPool pool $ do- let reply res = do- ans <- withLock lock $ do- ans <- i #= (k, res)- runWaiting w- return ans- case ans of- Ready r -> do- diagnostic $ "result " ++ atom k ++ " = " ++ atom (result r)- journal i (k, Loaded r) -- leave the DB lock before appending- Error _ -> do- diagnostic $ "result " ++ atom k ++ " = error"- journal i (k, Missing)- _ -> return ()- let norm = execute (addStack i k stack) k $ \res ->- reply $ case res of- Left err -> Error err- Right (v,deps,(doubleToFloat -> execution),traces) ->- let c | Just r <- r, result r == v = changed r- | otherwise = step- in Ready Result{result=v,changed=c,built=step,depends=map fromDepends deps,..}-- case r of- Just r | assume == Just AssumeClean -> do- v <- stored k- case v of- Just v -> reply $ Ready r{result=v}- Nothing -> norm- _ -> norm- i #= (k, w)-- check :: Stack -> Id -> Key -> Result -> [[Id]] -> IO Status- check stack i k r [] =- i #= (k, Ready r)- check stack i k r (ds:rest) = do- vs <- mapM (reduce (addStack i k stack)) ds- let ws = filter (isWaiting . snd) $ zip ds vs- if any isError vs || any (> built r) [changed | Ready Result{..} <- vs] then- run stack i k $ Just r- else if null ws then- check stack i k r rest- else do- self <- newWaiting $ Just r- waitFor ws $ \finish d -> do- s <- readIORef status- let buildIt = do- b <- run stack i k $ Just r- afterWaiting b $ runWaiting self- return True- case Map.lookup d s of- Just (_, Error{}) -> buildIt- Just (_, Ready r2)- | changed r2 > built r -> buildIt- | finish -> do- res <- check stack i k r rest- if not $ isWaiting res- then runWaiting self- else afterWaiting res $ runWaiting self- return True- | otherwise -> return False- i #= (k, self)--------------------------------------------------------------------------- PROGRESS--progress :: Database -> IO Progress-progress Database{..} = do- s <- readIORef status- return $ foldl' f mempty $ map snd $ Map.elems s- where- g = floatToDouble-- f s (Ready Result{..}) = if step == built- then s{countBuilt = countBuilt s + 1, timeBuilt = timeBuilt s + g execution}- else s{countSkipped = countSkipped s + 1, timeSkipped = timeSkipped s + g execution}- f s (Loaded Result{..}) = s{countUnknown = countUnknown s + 1, timeUnknown = timeUnknown s + g execution}- f s (Waiting _ r) =- let (d,c) = timeTodo s- t | Just Result{..} <- r = let d2 = d + g execution in d2 `seq` (d2,c)- | otherwise = let c2 = c + 1 in c2 `seq` (d,c2)- in s{countTodo = countTodo s + 1, timeTodo = t}- f s _ = s--------------------------------------------------------------------------- QUERY DATABASE---- | Given a map of representing a dependency order (with a show for error messages), find an ordering for the items such--- that no item points to an item before itself.--- Raise an error if you end up with a cycle.-dependencyOrder :: (Eq a, Hashable a) => (a -> String) -> Map a [a] -> [a]--- Algorithm:--- Divide everyone up into those who have no dependencies [Id]--- And those who depend on a particular Id, Dep :-> Maybe [(Key,[Dep])]--- Where d :-> Just (k, ds), k depends on firstly d, then remaining on ds--- For each with no dependencies, add to list, then take its dep hole and--- promote them either to Nothing (if ds == []) or into a new slot.--- k :-> Nothing means the key has already been freed-dependencyOrder shw status = f (map fst noDeps) $ Map.map Just $ Map.fromListWith (++) [(d, [(k,ds)]) | (k,d:ds) <- hasDeps]- where- (noDeps, hasDeps) = partition (null . snd) $ Map.toList status-- f [] mp | null bad = []- | otherwise = error $ unlines $- "Internal invariant broken, database seems to be cyclic" :- map (" " ++) bad ++- ["... plus " ++ show (length badOverflow) ++ " more ..." | not $ null badOverflow]- where (bad,badOverflow) = splitAt 10 $ [shw i | (i, Just _) <- Map.toList mp]-- f (x:xs) mp = x : f (now++xs) later- where Just free = Map.lookupDefault (Just []) x mp- (now,later) = foldl' g ([], Map.insert x Nothing mp) free-- g (free, mp) (k, []) = (k:free, mp)- g (free, mp) (k, d:ds) = case Map.lookupDefault (Just []) d mp of- Nothing -> g (free, mp) (k, ds)- Just todo -> (free, Map.insert d (Just $ (k,ds) : todo) mp)----- | Eliminate all errors from the database, pretending they don't exist-resultsOnly :: Map Id (Key, Status) -> Map Id (Key, Result)-resultsOnly mp = Map.map (\(k, v) -> (k, let Just r = getResult v in r{depends = map (filter (isJust . flip Map.lookup keep)) $ depends r})) keep- where keep = Map.filter (isJust . getResult . snd) mp--removeStep :: Map Id (Key, Result) -> Map Id (Key, Result)-removeStep = Map.filter (\(k,_) -> k /= stepKey)--toReport :: Database -> IO [ProfileEntry]-toReport Database{..} = do- status <- fmap (removeStep . resultsOnly) $ readIORef status- let order = let shw i = maybe "<unknown>" (show . fst) $ Map.lookup i status- in dependencyOrder shw $ Map.map (concat . depends . snd) status- ids = Map.fromList $ zip order [0..]-- steps = let xs = Set.toList $ Set.fromList $ concat [[changed, built] | (_,Result{..}) <- Map.elems status]- in Map.fromList $ zip (sortBy (flip compare) xs) [0..]-- f (k, Result{..}) = ProfileEntry- {prfName = show k- ,prfBuilt = fromStep built- ,prfChanged = fromStep changed- ,prfDepends = mapMaybe (`Map.lookup` ids) (concat depends)- ,prfExecution = floatToDouble execution- ,prfTraces = map fromTrace traces- }- where fromStep i = fromJust $ Map.lookup i steps- fromTrace (Trace a b c) = ProfileTrace (unpack a) (floatToDouble b) (floatToDouble c)- return [maybe (err "toReport") f $ Map.lookup i status | i <- order]---checkValid :: Database -> (Key -> IO (Maybe Value)) -> (Key -> Value -> Value -> EqualCost) -> [(Key, Key)] -> IO ()-checkValid Database{..} stored equal missing = do- status <- readIORef status- intern <- readIORef intern- diagnostic "Starting validity/lint checking"-- -- Do not use a forM here as you use too much stack space- bad <- (\f -> foldM f [] (Map.toList status)) $ \seen (i,v) -> case v of- (key, Ready Result{..}) -> do- now <- stored key- let good = maybe False ((==) EqualCheap . equal key result) now- diagnostic $ "Checking if " ++ show key ++ " is " ++ show result ++ ", " ++ if good then "passed" else "FAILED"- return $ [(key, result, now) | not good && not (specialAlwaysRebuilds result)] ++ seen- _ -> return seen- unless (null bad) $ do- let n = length bad- errorStructured- ("Lint checking error - " ++ (if n == 1 then "value has" else show n ++ " values have") ++ " changed since being depended upon")- (intercalate [("",Just "")] [ [("Key", Just $ show key),("Old", Just $ show result),("New", Just $ maybe "<missing>" show now)]- | (key, result, now) <- bad])- ""-- bad <- return [(parent,key) | (parent, key) <- missing, isJust $ Intern.lookup key intern]- unless (null bad) $ do- let n = length bad- errorStructured- ("Link checking error - " ++ (if n == 1 then "value" else show n ++ " values") ++ " did not have " ++ (if n == 1 then "its" else "their") ++ " creation tracked")- (intercalate [("",Just "")] [ [("Rule", Just $ show parent), ("Created", Just $ show key)] | (parent,key) <- bad])- ""-- diagnostic "Validity/lint check passed"---listLive :: Database -> IO [Key]-listLive Database{..} = do- diagnostic "Listing live keys"- status <- readIORef status- return [k | (k, Ready{}) <- Map.elems status]---listDepends :: Database -> Depends -> IO [Key]-listDepends Database{..} (Depends xs) =- withLock lock $ do- status <- readIORef status- return $ map (fst . fromJust . flip Map.lookup status) xs--lookupDependencies :: Database -> Key -> IO [Key]-lookupDependencies Database{..} k = do- withLock lock $ do- intern <- readIORef intern- status <- readIORef status- let Just i = Intern.lookup k intern- let Just (_, Ready r) = Map.lookup i status- return $ map (fst . fromJust . flip Map.lookup status) $ concat $ depends r--------------------------------------------------------------------------- STORAGE---- To simplify journaling etc we smuggle the Step in the database, with a special StepKey-newtype StepKey = StepKey ()- deriving (Show,Eq,Typeable,Hashable,Binary,NFData)--stepKey :: Key-stepKey = newKey $ StepKey ()--toStepResult :: Step -> Result-toStepResult i = Result (newValue i) i i [] 0 []--fromStepResult :: Result -> Step-fromStepResult = fromValue . result---withDatabase :: ShakeOptions -> (String -> IO ()) -> (Database -> IO a) -> IO a-withDatabase opts diagnostic act = do- registerWitness $ StepKey ()- registerWitness $ Step 0- witness <- currentWitness- withStorage opts diagnostic witness $ \mp2 journal -> do- let mp1 = Intern.fromList [(k, i) | (i, (k,_)) <- Map.toList mp2]-- (mp1, stepId) <- case Intern.lookup stepKey mp1 of- Just stepId -> return (mp1, stepId)- Nothing -> do- (mp1, stepId) <- return $ Intern.add stepKey mp1- return (mp1, stepId)-- intern <- newIORef mp1- status <- newIORef mp2- let step = case Map.lookup stepId mp2 of- Just (_, Loaded r) -> incStep $ fromStepResult r- _ -> Step 1- journal stepId (stepKey, Loaded $ toStepResult step)- lock <- newLock- act Database{assume=shakeAssume opts,..}---instance BinaryWith Witness Result where- putWith ws (Result x1 x2 x3 x4 x5 x6) = putWith ws x1 >> put x2 >> put x3 >> put (BinList $ map BinList x4) >> put (BinFloat x5) >> put (BinList x6)- getWith ws = (\x1 x2 x3 (BinList x4) (BinFloat x5) (BinList x6) -> Result x1 x2 x3 (map fromBinList x4) x5 x6) <$>- getWith ws <*> get <*> get <*> get <*> get <*> get--instance Binary Trace where- put (Trace a b c) = put a >> put (BinFloat b) >> put (BinFloat c)- get = (\a (BinFloat b) (BinFloat c) -> Trace a b c) <$> get <*> get <*> get--instance BinaryWith Witness Status where- putWith ctx Missing = putWord8 0- putWith ctx (Loaded x) = putWord8 1 >> putWith ctx x- putWith ctx x = err $ "putWith, Cannot write Status with constructor " ++ statusType x- getWith ctx = do i <- getWord8; if i == 0 then return Missing else fmap Loaded $ getWith ctx
− Development/Shake/Demo.hs
@@ -1,135 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}---- | Demo tutorial, accessed with --demo-module Development.Shake.Demo(demo) where--import Paths_shake-import Development.Shake.Command-import General.Base--import Control.Exception as E-import Control.Monad-import Data.Char-import Data.List-import Data.Maybe-import Data.Version(showVersion)-import System.Directory-import System.Exit-import System.FilePath-import Development.Shake.FilePath(exe)-import System.IO---demo :: Bool -> IO ()-demo auto = do- hSetBuffering stdout NoBuffering- putStrLn $ "% Welcome to the Shake v" ++ showVersion version ++ " demo mode!"- putStr $ "% Detecting machine configuration... "-- -- CONFIGURE-- manual <- getDataFileName "docs/manual"- hasManual <- wrap $ doesDirectoryExist manual- ghc <- findExecutable "ghc"- gcc <- do- v <- findExecutable "gcc"- case v of- Nothing | isWindows, Just ghc <- ghc -> do- let dir = takeDirectory (takeDirectory ghc) </> "bin/mingw/gcc.exe"- b <- wrap $ doesFileExist dir- return $ if b then Just dir else Nothing- _ -> return v- shakeLib <- wrap $ fmap (not . null . words . fromStdout) (cmd "ghc-pkg list --simple-output shake")- ninja <- findExecutable "ninja"- putStrLn "done\n"-- let path = if isWindows then "%PATH%" else "$PATH"- require (isJust ghc) $ "% You don't have 'ghc' on your " ++ path ++ ", which is required to run the demo."- require (isJust gcc) $ "% You don't have 'gcc' on your " ++ path ++ ", which is required to run the demo."- require shakeLib "% You don't have the 'shake' library installed with GHC, which is required to run the demo."- require hasManual "% You don't have the Shake data files installed, which are required to run the demo."-- empty <- fmap (null . filter (not . all (== '.'))) $ getDirectoryContents "."- dir <- if empty then getCurrentDirectory else do- home <- getHomeDirectory- dir <- getDirectoryContents home- return $ home </> head (map ("shake-demo" ++) ("":map show [2..]) \\ dir)-- putStrLn $ "% The Shake demo uses an empty directory, OK to use:"- putStrLn $ "% " ++ dir- b <- yesNo auto- require b "% Please create an empty directory to run the demo from, then run 'shake --demo' again."-- putStr "% Copying files... "- createDirectoryIfMissing True dir- forM_ ["Build.hs","main.c","constants.c","constants.h","build" <.> if isWindows then "bat" else "sh"] $ \file ->- copyFile (manual </> file) (dir </> file)- when (not isWindows) $ do- p <- getPermissions $ dir </> "build.sh"- setPermissions (dir </> "build.sh") p{executable=True}- putStrLn "done"-- let pause = do- putStr "% Press ENTER to continue: "- if auto then putLine "" else getLine- let execute x = do- putStrLn $ "% RUNNING: " ++ x- cmd (Cwd dir) Shell x :: IO ()- let build = if isWindows then "build" else "./build.sh"-- putStrLn "\n% [1/5] Building an example project with Shake."- pause- putStrLn $ "% RUNNING: cd " ++ dir- execute build-- putStrLn "\n% [2/5] Running the produced example."- pause- execute $ "_build" </> "run" <.> exe-- putStrLn "\n% [3/5] Rebuilding an example project with Shake (nothing should change)."- pause- execute build-- putStrLn "\n% [4/5] Cleaning the build."- pause- execute $ build ++ " clean"-- putStrLn "\n% [5/5] Rebuilding with 2 threads and profiling."- pause- execute $ build ++ " -j2 --report --report=-"- putStrLn "\n% See the profiling summary above, or look at the HTML profile report in"- putStrLn $ "% " ++ dir </> "report.html"-- putStrLn "\n% Demo complete - all the examples can be run from:"- putStrLn $ "% " ++ dir- putStrLn "% For more info see http://www.shakebuild.com/"- when (isJust ninja) $ do- putStrLn "\n% PS. Shake can also execute Ninja build files"- putStrLn "% For more info see http://www.shakebuild.com/ninja"------ | Require the user to press @y@ before continuing.-yesNo :: Bool -> IO Bool-yesNo auto = do- putStr $ "% [Y/N] (then ENTER): "- x <- if auto then putLine "y" else fmap (map toLower) getLine- if "y" `isPrefixOf` x then- return True- else if "n" `isPrefixOf` x then- return False- else- yesNo auto--putLine :: String -> IO String-putLine x = putStrLn x >> return x----- | Replace exceptions with 'False'.-wrap :: IO Bool -> IO Bool-wrap act = act `E.catch` \(_ :: SomeException) -> return False----- | Require a condition to be true, or exit with a message.-require :: Bool -> String -> IO ()-require b msg = unless b $ putStrLn msg >> exitFailure
− Development/Shake/Derived.hs
@@ -1,139 +0,0 @@--module Development.Shake.Derived(- system', systemCwd, systemOutput,- copyFile', copyFileChanged,- readFile', readFileLines,- writeFile', writeFileLines, writeFileChanged- ) where--import Control.Monad-import Control.Monad.IO.Class-import System.Process-import System.Directory-import System.Exit-import System.IO--import Development.Shake.Core-import Development.Shake.Rules.File-import Development.Shake.FilePath-import Development.Shake.Types-import General.Base-import qualified Data.ByteString as BS---checkExitCode :: String -> ExitCode -> Action ()-checkExitCode cmd ExitSuccess = return ()-checkExitCode cmd (ExitFailure i) = error $ "System command failed (code " ++ show i ++ "):\n" ++ cmd--{-# DEPRECATED system' "Use 'command' or 'cmd'" #-}-{-# DEPRECATED systemCwd "Use 'command' or 'cmd' with 'Cwd'" #-}-{-# DEPRECATED systemOutput "Use 'command' or 'cmd' with 'Stdout' or 'Stderr'" #-}---- | /Deprecated:/ Please use 'command' or 'cmd' instead.--- This function will be removed in a future version.------ Execute a system command. This function will raise an error if the exit code is non-zero.--- Before running 'system'' make sure you 'need' any required files.-system' :: FilePath -> [String] -> Action ()-system' path args = do- let path2 = toNative path- let cmd = unwords $ path2 : args- v <- getVerbosity- putLoud cmd- res <- (if v >= Loud then quietly else id) $ traced (takeBaseName path) $ rawSystem path2 args- checkExitCode cmd res----- | /Deprecated:/ Please use 'command' or 'cmd' instead, with 'Cwd'.--- This function will be removed in a future version.------ Execute a system command with a specified current working directory (first argument).--- This function will raise an error if the exit code is non-zero.--- Before running 'systemCwd' make sure you 'need' any required files.------ @--- 'systemCwd' \"\/usr\/MyDirectory\" \"pwd\" []--- @-systemCwd :: FilePath -> FilePath -> [String] -> Action ()-systemCwd cwd path args = do- let path2 = toNative path- let cmd = unwords $ path2 : args- putLoud cmd- res <- traced (takeBaseName path) $ do- -- FIXME: Should I be using the non-exported System.Process.syncProcess?- -- That installs/removes signal handlers.- hdl <- runProcess path2 args (Just cwd) Nothing Nothing Nothing Nothing- waitForProcess hdl- checkExitCode cmd res----- | /Deprecated:/ Please use 'command' or 'cmd' instead, with 'Stdout' or 'Stderr'.--- This function will be removed in a future version.------ Execute a system command, returning @(stdout,stderr)@.--- This function will raise an error if the exit code is non-zero.--- Before running 'systemOutput' make sure you 'need' any required files.-systemOutput :: FilePath -> [String] -> Action (String, String)-systemOutput path args = do- let path2 = toNative path- let cmd = unwords $ path2 : args- putLoud cmd- (res,stdout,stderr) <- traced (takeBaseName path) $ readProcessWithExitCode path2 args ""- checkExitCode cmd res- return (stdout, stderr)----- | @copyFile' old new@ copies the existing file from @old@ to @new@.--- The @old@ file will be tracked as a dependency.-copyFile' :: FilePath -> FilePath -> Action ()-copyFile' old new = do- need [old]- putLoud $ "Copying from " ++ old ++ " to " ++ new- liftIO $ copyFile old new----- | @copyFile' old new@ copies the existing file from @old@ to @new@, if the contents have changed.--- The @old@ file will be tracked as a dependency.-copyFileChanged :: FilePath -> FilePath -> Action ()-copyFileChanged old new = do- need [old]- eq <- liftIO $ doesFileExist new &&^ do- withBinaryFile old ReadMode $ \h1 -> withBinaryFile new ReadMode $ \h2 ->- liftM2 (==) (hFileSize h1) (hFileSize h2) &&^- liftM2 (==) (BS.hGetContents h1) (BS.hGetContents h2)- when (not eq) $ do- putLoud $ "Copying from " ++ old ++ " to " ++ new- -- copyFile does a lot of clever stuff with permissions etc, so make sure we just reuse it- liftIO $ copyFile old new----- | Read a file, after calling 'need'. The argument file will be tracked as a dependency.-readFile' :: FilePath -> Action String-readFile' x = need [x] >> liftIO (readFile x)---- | Write a file, lifted to the 'Action' monad.-writeFile' :: FilePath -> String -> Action ()-writeFile' name x = liftIO $ writeFile name x----- | A version of 'readFile'' which also splits the result into lines.--- The argument file will be tracked as a dependency.-readFileLines :: FilePath -> Action [String]-readFileLines = fmap lines . readFile'---- | A version of 'writeFile'' which writes out a list of lines.-writeFileLines :: FilePath -> [String] -> Action ()-writeFileLines name = writeFile' name . unlines----- | Write a file, but only if the contents would change.-writeFileChanged :: FilePath -> String -> Action ()-writeFileChanged name x = liftIO $ do- b <- doesFileExist name- if not b then writeFile name x else do- -- Cannot use ByteString here, since it has different line handling- -- semantics on Windows- b <- withFile name ReadMode $ \h -> do- src <- hGetContents h- return $! src /= x- when b $ writeFile name x
− Development/Shake/Errors.hs
@@ -1,132 +0,0 @@-{-# LANGUAGE DeriveDataTypeable, PatternGuards, RecordWildCards #-}---- | Errors seen by the user-module Development.Shake.Errors(- ShakeException(..),- errorStructured, err,- errorNoRuleToBuildType, errorRuleTypeMismatch, errorIncompatibleRules,- errorMultipleRulesMatch, errorRuleRecursion, errorNoApply,- ) where--import Control.Arrow-import Control.Exception-import Data.Typeable-import Data.List---err :: String -> a-err msg = error $ "Development.Shake: Internal error, please report to Neil Mitchell (" ++ msg ++ ")"--alternatives = let (*) = (,) in- ["_rule_" * "oracle"- ,"_Rule_" * "Oracle"- ,"_key_" * "question"- ,"_Key_" * "Question"- ,"_result_" * "answer"- ,"_Result_" * "Answer"- ,"_rule/defaultRule_" * "addOracle"- ,"_apply_" * "askOracle"]---errorStructured :: String -> [(String, Maybe String)] -> String -> a-errorStructured msg args hint = error $ unlines $- [msg ++ ":"] ++- [" " ++ a ++ [':' | a /= ""] ++ replicate (as - length a + 2) ' ' ++ b | (a,b) <- args2] ++- [hint | hint /= ""]- where- as = maximum $ 0 : map (length . fst) args2- args2 = [(a,b) | (a,Just b) <- args]----structured :: Bool -> String -> [(String, Maybe String)] -> String -> a-structured alt msg args hint = errorStructured (f msg) (map (first f) args) (f hint)- where- f = filter (/= '_') . (if alt then g else id)- g xs | (a,b):_ <- filter (\(a,b) -> a `isPrefixOf` xs) alternatives = b ++ g (drop (length a) xs)- g (x:xs) = x : g xs- g [] = []---errorNoRuleToBuildType :: TypeRep -> Maybe String -> Maybe TypeRep -> a-errorNoRuleToBuildType tk k tv = structured (specialIsOracleKey tk)- "Build system error - no _rule_ matches the _key_ type"- [("_Key_ type", Just $ show tk)- ,("_Key_ value", k)- ,("_Result_ type", fmap show tv)]- "Either you are missing a call to _rule/defaultRule_, or your call to _apply_ has the wrong _key_ type"--errorRuleTypeMismatch :: TypeRep -> Maybe String -> TypeRep -> TypeRep -> a-errorRuleTypeMismatch tk k tvReal tvWant = structured (specialIsOracleKey tk)- "Build system error - _rule_ used at the wrong _result_ type"- [("_Key_ type", Just $ show tk)- ,("_Key_ value", k)- ,("_Rule_ _result_ type", Just $ show tvReal)- ,("Requested _result_ type", Just $ show tvWant)]- "Either the function passed to _rule/defaultRule_ has the wrong _result_ type, or the result of _apply_ is used at the wrong type"--errorIncompatibleRules :: TypeRep -> TypeRep -> TypeRep -> a-errorIncompatibleRules tk tv1 tv2 = if specialIsOracleKey tk then errorDuplicateOracle tk Nothing [tv1,tv2] else errorStructured- "Build system error - rule has multiple result types"- [("Key type", Just $ show tk)- ,("First result type", Just $ show tv1)- ,("Second result type", Just $ show tv2)]- "A function passed to rule/defaultRule has the wrong result type"--errorMultipleRulesMatch :: TypeRep -> String -> Int -> a-errorMultipleRulesMatch tk k count- | specialIsOracleKey tk = if count == 0 then err $ "no oracle match for " ++ show tk else errorDuplicateOracle tk (Just k) []- | otherwise = errorStructured- ("Build system error - key matches " ++ (if count == 0 then "no" else "multiple") ++ " rules")- [("Key type",Just $ show tk)- ,("Key value",Just k)- ,("Rules matched",Just $ show count)]- (if count == 0 then "Either add a rule that produces the above key, or stop requiring the above key"- else "Modify your rules/defaultRules so only one can produce the above key")--errorRuleRecursion :: Maybe TypeRep -> Maybe String -> a-errorRuleRecursion tk k = errorStructured -- may involve both rules and oracle, so report as a rule- "Build system error - recursion detected"- [("Key type",fmap show tk)- ,("Key value",k)]- "Rules may not be recursive"--errorDuplicateOracle :: TypeRep -> Maybe String -> [TypeRep] -> a-errorDuplicateOracle tk k tvs = errorStructured- "Build system error - duplicate oracles for the same question type"- ([("Question type",Just $ show tk)- ,("Question value",k)] ++- [("Answer type " ++ show i, Just $ show tv) | (i,tv) <- zip [1..] tvs])- "Only one call to addOracle is allowed per question type"--errorNoApply :: TypeRep -> Maybe String -> String -> a-errorNoApply tk k msg = structured (specialIsOracleKey tk)- "Build system error - cannot currently call _apply_"- [("Reason", Just msg)- ,("_Key_ type", Just $ show tk)- ,("_Key_ value", k)]- "Move the _apply_ call earlier/later"----- Should be in Special, but then we get an import cycle-specialIsOracleKey :: TypeRep -> Bool-specialIsOracleKey t = con == "OracleQ"- where con = show $ fst $ splitTyConApp t----- | Error representing all expected exceptions thrown by Shake.--- Problems when executing rules will be raising using this exception type.-data ShakeException = ShakeException- {shakeExceptionTarget :: String -- ^ The target that was being built when the exception occured.- ,shakeExceptionStack :: [String] -- ^ The stack of targets, where the 'shakeExceptionTarget' is last.- ,shakeExceptionInner :: SomeException -- ^ The underlying exception that was raised.- }- deriving Typeable--instance Exception ShakeException--instance Show ShakeException where- show ShakeException{..} = unlines $- "Error when running Shake build system:" :- map ("* " ++) shakeExceptionStack ++- [show shakeExceptionInner]
− Development/Shake/FileInfo.hs
@@ -1,138 +0,0 @@-{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, CPP, ForeignFunctionInterface #-}--module Development.Shake.FileInfo(- FileInfo, fileInfoEq, fileInfoNeq, fileInfoVal,- FileSize, ModTime, FileHash,- getFileHash, getFileInfo- ) where--import Control.Exception-import Development.Shake.Classes-import General.String-import qualified Data.ByteString.Lazy as LBS-import Data.Char-import Data.Word-import Numeric-import System.IO--#if defined(PORTABLE)-import System.IO.Error-import System.Directory-import Data.Time-import System.Time--#elif defined(mingw32_HOST_OS)-import qualified Data.ByteString.Char8 as BS-import Foreign-import Foreign.C.Types-import Foreign.C.String--#else-import System.IO.Error-import Control.Exception-import System.Posix.Files.ByteString-#endif---- A piece of file information, where 0 = Eq to everything, 1 = Eq to nothing, 2+ = normal values-newtype FileInfo a = FileInfo Word32- deriving (Typeable,Hashable,Binary,NFData)--instance Show (FileInfo a) where- show (FileInfo x)- | x == 0 = "EQ"- | x == 1 = "NEQ"- | x == 2 = "VAL"- | otherwise = "0x" ++ map toUpper (showHex (x-2) "")--instance Eq (FileInfo a) where- FileInfo a == FileInfo b- | a == 0 || b == 0 = True- | a == 1 || b == 1 = False- | otherwise = a == b--fileInfoEq, fileInfoNeq, fileInfoVal :: FileInfo a-fileInfoEq = FileInfo 0-fileInfoNeq = FileInfo 1-fileInfoVal = FileInfo 2--fileInfo :: Word32 -> FileInfo a-fileInfo a = FileInfo $ if a > maxBound - 3 then a else a + 3--data FileInfoHash; type FileHash = FileInfo FileInfoHash-data FileInfoMod ; type ModTime = FileInfo FileInfoMod-data FileInfoSize; type FileSize = FileInfo FileInfoSize---getFileHash :: BSU -> IO FileHash-getFileHash x = withFile (unpackU x) ReadMode $ \h -> do- s <- LBS.hGetContents h- let res = fileInfo $ fromIntegral $ hash s- evaluate res- return res---getFileInfo :: BSU -> IO (Maybe (ModTime, FileSize))--#if defined(PORTABLE)--- Portable fallback-getFileInfo x = handleJust (\e -> if isDoesNotExistError e then Just () else Nothing) (const $ return Nothing) $ do- let file = unpackU x- time <- getModificationTime file- size <- withFile file ReadMode hFileSize- return $ Just (fileInfo $ extractFileTime time, fileInfo $ fromIntegral size)---- deal with difference in return type of getModificationTime between directory versions-class ExtractFileTime a where extractFileTime :: a -> Word32-instance ExtractFileTime ClockTime where extractFileTime (TOD t _) = fromIntegral t-instance ExtractFileTime UTCTime where extractFileTime = floor . fromRational . toRational . utctDayTime---#elif defined(mingw32_HOST_OS)--- Directly against the Win32 API, twice as fast as the portable version-getFileInfo x = BS.useAsCString (unpackU_ x) $ \file ->- alloca_WIN32_FILE_ATTRIBUTE_DATA $ \fad -> do- res <- c_getFileAttributesExA file 0 fad- let peek = do mt <- peekLastWriteTimeLow fad; sz <- peekFileSizeLow fad; return $ Just (fileInfo mt, fileInfo sz)- if res then- peek- else if requireU x then withCWString (unpackU x) $ \file -> do- res <- c_getFileAttributesExW file 0 fad- if res then peek else return Nothing- else- return Nothing--foreign import stdcall unsafe "Windows.h GetFileAttributesExA" c_getFileAttributesExA :: Ptr CChar -> Int32 -> Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Bool-foreign import stdcall unsafe "Windows.h GetFileAttributesExW" c_getFileAttributesExW :: Ptr CWchar -> Int32 -> Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Bool--data WIN32_FILE_ATTRIBUTE_DATA--alloca_WIN32_FILE_ATTRIBUTE_DATA :: (Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO a) -> IO a-alloca_WIN32_FILE_ATTRIBUTE_DATA act = allocaBytes size_WIN32_FILE_ATTRIBUTE_DATA act- where size_WIN32_FILE_ATTRIBUTE_DATA = 36--peekLastWriteTimeLow :: Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Word32-peekLastWriteTimeLow p = peekByteOff p index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime- where index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime = 20--peekFileSizeLow :: Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Word32-peekFileSizeLow p = peekByteOff p index_WIN32_FILE_ATTRIBUTE_DATA_nFileSizeLow- where index_WIN32_FILE_ATTRIBUTE_DATA_nFileSizeLow = 32---#else--- Unix version-getFileInfo x = handleJust (\e -> if isDoesNotExistError e then Just () else Nothing) (const $ return Nothing) $ do- s <- getFileStatus $ unpackU_ x- return $ Just (fileInfo $ extractFileTime s, fileInfo $ fromIntegral $ fileSize s)--extractFileTime :: FileStatus -> Word32-#ifndef MIN_VERSION_unix-#define MIN_VERSION_unix(a,b,c) 0-#endif-#if MIN_VERSION_unix(2,6,0)-extractFileTime x = ceiling $ modificationTimeHiRes x * 1e4 -- precision of 0.1ms-#else-extractFileTime x = fromIntegral $ fromEnum $ modificationTime x-#endif--#endif
− Development/Shake/FilePath.hs
@@ -1,121 +0,0 @@---- | A module for 'FilePath' operations, to be used instead of "System.FilePath"--- when writing build systems. In build systems, when using the file name--- as a key for indexing rules, it is important that two different strings do--- not refer to the same on-disk file. We therefore follow the conventions:------ * Always use @\/@ as the directory separator, even on Windows.------ * When combining 'FilePath' values with '</>' we squash any @\/.\/@ components.-module Development.Shake.FilePath(- module System.FilePath.Posix, -- apart from what I override and search path stuff- module System.FilePath, -- only search-path stuff- dropDirectory1, takeDirectory1, normalise,- (-<.>),- toNative, toStandard, (</>), combine,- exe- ) where--import System.FilePath.Posix hiding- (normalise, (</>), combine- ,searchPathSeparator, isSearchPathSeparator, splitSearchPath, getSearchPath)-import System.FilePath(searchPathSeparator, isSearchPathSeparator, splitSearchPath, getSearchPath)-import General.Base-import qualified System.FilePath as Native--infixr 5 </>-infixr 7 -<.>----- | Drop the first directory from a 'FilePath'. Should only be used on--- relative paths.------ > dropDirectory1 "aaa/bbb" == "bbb"--- > dropDirectory1 "aaa/" == ""--- > dropDirectory1 "aaa" == ""--- > dropDirectory1 "" == ""-dropDirectory1 :: FilePath -> FilePath-dropDirectory1 = drop 1 . dropWhile (not . Native.isPathSeparator)----- | Take the first component of a 'FilePath'. Should only be used on--- relative paths.------ > takeDirectory1 "aaa/bbb" == "aaa"--- > takeDirectory1 "aaa/" == "aaa"--- > takeDirectory1 "aaa" == "aaa"-takeDirectory1 :: FilePath -> FilePath-takeDirectory1 = takeWhile (not . Native.isPathSeparator)----- | Normalise a 'FilePath', trying to do:------ * All 'pathSeparators' become @\/@------ * @foo\/bar\/..\/baz@ becomes @foo\/baz@------ * @foo\/.\/bar@ becomes @foo\/bar@------ * @foo\/\/bar@ becomes @foo\/bar@------ This function is not based on the normalise function from the filepath library, as that function--- is quite broken.-normalise :: FilePath -> FilePath-normalise xs | a:b:xs <- xs, isWindows && sep a && sep b = '/' : f ('/':xs) -- account for UNC paths being double //- | otherwise = f xs- where- sep = Native.isPathSeparator- f o = deslash o $ (++"/") $ concatMap ('/':) $ reverse $ g 0 $ reverse $ split o-- deslash o x- | x == "/" = case (pre,pos) of- (True,True) -> "/"- (True,False) -> "/."- (False,True) -> "./"- (False,False) -> "."- | otherwise = (if pre then id else tail) $ (if pos then id else init) x- where pre = sep $ head $ o ++ " "- pos = sep $ last $ " " ++ o-- g i [] = replicate i ".."- g i ("..":xs) = g (i+1) xs- g i (".":xs) = g i xs- g 0 (x:xs) = x : g 0 xs- g i (x:xs) = g (i-1) xs-- split xs = if null ys then [] else a : split b- where (a,b) = break sep $ ys- ys = dropWhile sep xs----- | Convert to native path separators, namely @\\@ on Windows. -toNative :: FilePath -> FilePath-toNative = map (\x -> if Native.isPathSeparator x then Native.pathSeparator else x)---- | Convert all path separators to @/@, even on Windows.-toStandard :: FilePath -> FilePath-toStandard | Native.pathSeparators == [pathSeparator] = id- | otherwise = map (\x -> if Native.isPathSeparator x then pathSeparator else x)----- | Combine two file paths, an alias for 'combine'.-(</>) :: FilePath -> FilePath -> FilePath-(</>) = combine---- | Remove the current extension and add another, an alias for 'replaceExtension'.-(-<.>) :: FilePath -> String -> FilePath-(-<.>) = replaceExtension---- | Combine two file paths. Any redundant @.\/@ or @..\/@ components in the--- resulting path are eliminated - the result will always have 'normalise' applied.------ > combine "aaa/bbb" "ccc" == "aaa/bbb/ccc"--- > combine "aaa/bbb" "./ccc" == "aaa/bbb/ccc"--- > combine "aaa/bbb" "../ccc" == "aaa/ccc"-combine :: FilePath -> FilePath -> FilePath-combine x y = normalise $ Native.combine (toNative x) (toNative y)----- | The extension of executables, @\"exe\"@ on Windows and @\"\"@ otherwise.-exe :: String-exe = if isWindows then "exe" else ""
− Development/Shake/FilePattern.hs
@@ -1,175 +0,0 @@-{-# LANGUAGE PatternGuards #-}--module Development.Shake.FilePattern(- FilePattern, (?==),- compatible, simple, extract, substitute,- directories, directories1- ) where--import System.FilePath(pathSeparators)-import Data.List-import Control.Arrow-import General.Base--------------------------------------------------------------------------- BASIC FILE PATTERN MATCHING---- | A type synonym for file patterns, containing @\/\/@ and @*@. For the syntax--- and semantics of 'FilePattern' see '?=='.-type FilePattern = String---data Lexeme = Star | SlashSlash | Char Char deriving (Show, Eq)--isChar (Char _) = True; isChar _ = False-isDull (Char x) = x /= '/'; isDull _ = False-fromChar (Char x) = x---data Regex = Lit [Char] | Not [Char] | Any- | Start | End- | Bracket Regex- | Or Regex Regex | Concat Regex Regex- | Repeat Regex | Empty- deriving Show--type SString = (Bool, String) -- fst is True if at the start of the string---lexer :: FilePattern -> [Lexeme]-lexer ('*':xs) = Star : lexer xs-lexer ('/':'/':xs) = SlashSlash : lexer xs-lexer (x:xs) = Char x : lexer xs-lexer [] = []---pattern :: [Lexeme] -> Regex-pattern = Concat Start . foldr Concat End . map f- where- f Star = Bracket $ Repeat $ Not pathSeparators- f SlashSlash = let s = Start `Or` End `Or` Lit pathSeparators in Bracket $- Or (s `Concat` Repeat Any `Concat` s) (Lit pathSeparators)- f (Char x) = Lit $ if x == '/' then pathSeparators else [x]----- | Return is (brackets, matched, rest)-match :: Regex -> SString -> [([String], String, SString)]-match (Lit l) (_, x:xs) | x `elem` l = [([], [x], (False, xs))]-match (Not l) (_, x:xs) | x `notElem` l = [([], [x], (False, xs))]-match Any (_, x:xs) = [([], [x], (False, xs))]-match Start (True, xs) = [([], [], (True, xs))]-match End (s, []) = [([], [], (s, []))]-match (Bracket r) xs = [(a ++ [b], b, c) | (a,b,c) <- match r xs]-match (Or r1 r2) xs = match r1 xs ++ match r2 xs-match (Concat r1 r2) xs = [(a1++a2,b1++b2,c2) | (a1,b1,c1) <- match r1 xs, (a2,b2,c2) <- match r2 c1]-match (Repeat r) xs = match (Empty `Or` Concat r (Repeat r)) xs-match Empty xs = [([], "", xs)]-match _ _ = []------- | Match a 'FilePattern' against a 'FilePath', There are only two special forms:------ * @*@ matches an entire path component, excluding any separators.------ * @\/\/@ matches an arbitrary number of path components.------ Some examples that match:------ @--- \"\/\/*.c\" '?==' \"foo\/bar\/baz.c\"--- \"*.c\" '?==' \"baz.c\"--- \"\/\/*.c\" '?==' \"baz.c\"--- \"test.c\" '?==' \"test.c\"--- @------ Examples that /don't/ match:------ @--- \"*.c\" '?==' \"foo\/bar.c\"--- \"*\/*.c\" '?==' \"foo\/bar\/baz.c\"--- @------ An example that only matches on Windows:------ @--- \"foo\/bar\" '?==' \"foo\\\\bar\"--- @------ Patterns with constructs such as @foo\/..\/bar@ will never match--- normalised 'FilePath' values, so are unlikely to be correct.-(?==) :: FilePattern -> FilePath -> Bool-(?==) "//*" = const True-(?==) p = \x -> not $ null $ match pat (True, x)- where pat = pattern $ lexer p-------------------------------------------------------------------------- DIRECTORY PATTERNS---- | Given a pattern, return the directory that requires searching,--- with 'True' if it requires a recursive search. Must be conservative.--- Examples:------ > directories1 "*.xml" == ("",False)--- > directories1 "//*.xml" == ("",True)--- > directories1 "foo//*.xml" == ("foo",True)--- > directories1 "foo/bar/*.xml" == ("foo/bar",False)--- > directories1 "*/bar/*.xml" == ("",True)-directories1 :: FilePattern -> (FilePath, Bool)-directories1 = first (intercalate "/") . f . lexer- where- f xs | (a@(_:_),b:bs) <- span isDull xs, b `elem` [Char '/',SlashSlash] =- if b == SlashSlash then ([map fromChar a],True) else first (map fromChar a:) $ f bs- | all (\x -> isDull x || x == Star) xs = ([],False)- | otherwise = ([], True)----- | Given a set of patterns, produce a set of directories that require searching,--- with 'True' if it requires a recursive search. Must be conservative. Examples:------ > directories ["*.xml","//*.c"] == [("",True)]--- > directories ["bar/*.xml","baz//*.c"] == [("bar",False),("baz",True)]--- > directories ["bar/*.xml","baz//*.c"] == [("bar",False),("baz",True)]-directories :: [FilePattern] -> [(FilePath,Bool)]-directories ps = foldl f xs xs- where- xs = fastNub $ map directories1 ps-- -- Eliminate anything which is a strict subset- f xs (x,True) = filter (\y -> not $ (x,False) == y || (x ++ "/") `isPrefixOf` fst y) xs- f xs _ = xs--------------------------------------------------------------------------- MULTIPATTERN COMPATIBLE SUBSTITUTIONS---- | Is the pattern free from any * and //.-simple :: FilePattern -> Bool-simple = all isChar . lexer----- | Do they have the same * and // counts in the same order-compatible :: [FilePattern] -> Bool-compatible [] = True-compatible (x:xs) = all ((==) (f x) . f) xs- where f = filter (not . isChar) . lexer----- | Extract the items that match the wildcards. The pair must match with '?=='.-extract :: FilePattern -> FilePath -> [String]-extract p x = ms- where (ms,_,_):_ = match (pattern $ lexer p) (True,x)----- | Given the result of 'extract', substitute it back in to a 'compatible' pattern.------ > p '?==' x ==> substitute (extract p x) p == x-substitute :: [String] -> FilePattern -> FilePath-substitute ms p = f ms (lexer p)- where- f ms (Char p:ps) = p : f ms ps- f (m:ms) (_:ps) = m ++ f ms ps- f [] [] = []- f _ _ = error $ "Substitution failed into pattern " ++ show p ++ " with " ++ show (length ms) ++ " matches, namely " ++ show ms
− Development/Shake/Monad.hs
@@ -1,121 +0,0 @@-{-# LANGUAGE GeneralizedNewtypeDeriving #-}--module Development.Shake.Monad(- RAW, Capture, runRAW,- getRO, getRW, getsRO, getsRW, putRW, modifyRW,- withRO, withRW,- catchRAW, tryRAW, throwRAW,- unmodifyRW, captureRAW,- ) where--import Control.Applicative-import Control.Exception as E-import Control.Monad.IO.Class-import Control.Monad.Trans.Cont-import Control.Monad.Trans.Reader-import Data.IORef---data S ro rw = S- {handler :: IORef (SomeException -> IO ())- ,ro :: ro- ,rww :: IORef rw -- Read/Write Writeable var (rww)- }--newtype RAW ro rw a = RAW {fromRAW :: ReaderT (S ro rw) (ContT () IO) a}- deriving (Functor, Applicative, Monad, MonadIO)--type Capture a = (a -> IO ()) -> IO ()----- | Run and then call a continuation.-runRAW :: ro -> rw -> RAW ro rw a -> Capture (Either SomeException a)-runRAW ro rw m k = do- rww <- newIORef rw- handler <- newIORef $ k . Left- fromRAW m `runReaderT` S handler ro rww `runContT` (k . Right)- `E.catch` \e -> ($ e) =<< readIORef handler--------------------------------------------------------------------------- STANDARD--getRO :: RAW ro rw ro-getRO = RAW $ asks ro--getRW :: RAW ro rw rw-getRW = RAW $ liftIO . readIORef =<< asks rww--getsRO :: (ro -> a) -> RAW ro rw a-getsRO f = fmap f getRO--getsRW :: (rw -> a) -> RAW ro rw a-getsRW f = fmap f getRW---- | Strict version-putRW :: rw -> RAW ro rw ()-putRW rw = rw `seq` RAW $ liftIO . flip writeIORef rw =<< asks rww--withRAW :: (S ro rw -> S ro2 rw2) -> RAW ro2 rw2 a -> RAW ro rw a-withRAW f m = RAW $ withReaderT f $ fromRAW m--modifyRW :: (rw -> rw) -> RAW ro rw ()-modifyRW f = do x <- getRW; putRW $ f x--withRO :: (ro -> ro2) -> RAW ro2 rw a -> RAW ro rw a-withRO f = withRAW $ \s -> s{ro=f $ ro s}--withRW :: (rw -> rw2) -> RAW ro rw2 a -> RAW ro rw a-withRW f m = do- rw <- getRW- rww <- liftIO $ newIORef $ f rw- withRAW (\s -> s{rww=rww}) m--------------------------------------------------------------------------- EXCEPTIONS--catchRAW :: RAW ro rw a -> (SomeException -> RAW ro rw a) -> RAW ro rw a-catchRAW m hdl = RAW $ ReaderT $ \s -> ContT $ \k -> do- old <- readIORef $ handler s- writeIORef (handler s) $ \e -> do- writeIORef (handler s) old- fromRAW (hdl e) `runReaderT` s `runContT` k `E.catch`- \e -> ($ e) =<< readIORef (handler s)- fromRAW m `runReaderT` s `runContT` \v -> do- writeIORef (handler s) old- k v---tryRAW :: RAW ro rw a -> RAW ro rw (Either SomeException a)-tryRAW m = catchRAW (fmap Right m) (return . Left)--throwRAW :: Exception e => e -> RAW ro rw a-throwRAW = liftIO . throwIO--------------------------------------------------------------------------- WEIRD STUFF---- | Apply a modification, run an action, then undo the changes after.-unmodifyRW :: (rw -> (rw, rw -> rw)) -> RAW ro rw a -> RAW ro rw a-unmodifyRW f m = do- (s2,undo) <- fmap f getRW- putRW s2- res <- m- modifyRW undo- return res----- | Capture a continuation. The continuation should be called at most once.--- Calling the same continuation, multiple times, in parallel, results in incorrect behaviour.-captureRAW :: Capture (Either SomeException a) -> RAW ro rw a-captureRAW f = RAW $ ReaderT $ \s -> ContT $ \k -> do- old <- readIORef (handler s)- writeIORef (handler s) throwIO- f $ \x -> case x of- Left e -> old e- Right v -> do- writeIORef (handler s) old- k v `E.catch` \e -> ($ e) =<< readIORef (handler s)- writeIORef (handler s) throwIO
− Development/Shake/Pool.hs
@@ -1,165 +0,0 @@---- | Thread pool implementation.-module Development.Shake.Pool(- Pool, runPool,- addPool, addPoolPriority,- increasePool- ) where--import Control.Concurrent-import Control.Exception-import Control.Monad-import General.Concurrent-import General.Timing-import qualified Data.HashSet as Set-import System.IO.Unsafe-import System.Random--------------------------------------------------------------------------- UNFAIR/RANDOM QUEUE---- Monad for non-deterministic (but otherwise pure) computations-type NonDet a = IO a--nonDet :: NonDet [Bool]-nonDet = do bs <- unsafeInterleaveIO nonDet- b <- randomIO- return $ b:bs---- Left = deterministic list, Right = non-deterministic tree-data Queue a = Queue [a] (Either [a] (Maybe (Tree a)))--newQueue :: Bool -> Queue a-newQueue deterministic = Queue [] $ if deterministic then Left [] else Right Nothing--enqueuePriority :: a -> Queue a -> Queue a-enqueuePriority x (Queue p t) = Queue (x:p) t--enqueue :: a -> Queue a -> NonDet (Queue a)-enqueue x (Queue p (Left xs)) = return $ Queue p $ Left $ x:xs-enqueue x (Queue p (Right Nothing)) = return $ Queue p $ Right $ Just $ Leaf x-enqueue x (Queue p (Right (Just t))) = do bs <- nonDet; return $ Queue p $ Right $ Just $ insertTree bs x t--dequeue :: Queue a -> Maybe (NonDet (a, Queue a))-dequeue (Queue (p:ps) t) = Just $ return (p, Queue ps t)-dequeue (Queue [] (Left (x:xs))) = Just $ return (x, Queue [] $ Left xs)-dequeue (Queue [] (Left [])) = Nothing-dequeue (Queue [] (Right (Just t))) = Just $ do bs <- nonDet; (x,t) <- return $ removeTree bs t; return (x, Queue [] $ Right t)-dequeue (Queue [] (Right Nothing)) = Nothing--------------------------------------------------------------------------- TREE---- Note that for a Random tree, since everything is Random, Branch x y =~= Branch y x-data Tree a = Leaf a | Branch (Tree a) (Tree a)--insertTree :: [Bool] -> a -> Tree a -> Tree a-insertTree _ x (Leaf y) = Branch (Leaf x) (Leaf y)-insertTree (b:bs) x (Branch y z) = if b then f y z else f z y- where f y z = Branch y (insertTree bs x z)--removeTree :: [Bool] -> Tree a -> (a, Maybe (Tree a))-removeTree _ (Leaf x) = (x, Nothing)-removeTree (b:bs) (Branch y z) = if b then f y z else f z y- where- f y z = case removeTree bs z of- (x, Nothing) -> (x, Just y)- (x, Just z) -> (x, Just $ Branch y z)-------------------------------------------------------------------------- THREAD POOL--{--Must keep a list of active threads, so can raise exceptions in a timely manner-If any worker throws an exception, must signal to all the other workers--}--data Pool = Pool- !(Var (Maybe S)) -- Current state, 'Nothing' to say we are aborting- !(Barrier (Either SomeException S)) -- Barrier to signal that we are--data S = S- {threads :: !(Set.HashSet ThreadId) -- IMPORTANT: Must be strict or we leak thread stacks- ,threadsLimit :: {-# UNPACK #-} !Int -- user supplied thread limit, Set.size threads <= threadsLimit- ,threadsMax :: {-# UNPACK #-} !Int -- high water mark of Set.size threads (accounting only)- ,threadsSum :: {-# UNPACK #-} !Int -- number of threads we have been through (accounting only)- ,todo :: !(Queue (IO ())) -- operations waiting a thread- }---emptyS :: Int -> Bool -> S-emptyS n deterministic = S Set.empty n 0 0 $ newQueue deterministic----- | Given a pool, and a function that breaks the S invariants, restore them--- They are only allowed to touch threadsLimit or todo-step :: Pool -> (S -> NonDet S) -> IO ()-step pool@(Pool var done) op = do- let onVar act = modifyVar_ var $ maybe (return Nothing) act- onVar $ \s -> do- s <- op s- res <- maybe (return Nothing) (fmap Just) $ dequeue $ todo s- case res of- Just (now, todo2) | Set.size (threads s) < threadsLimit s -> do- -- spawn a new worker- t <- forkIO $ do- t <- myThreadId- res <- try now- case res of- Left e -> onVar $ \s -> do- mapM_ killThread $ Set.toList $ Set.delete t $ threads s- signalBarrier done $ Left e- return Nothing- Right _ -> step pool $ \s -> return s{threads = Set.delete t $ threads s}- let threads2 = Set.insert t $ threads s- return $ Just s{todo = todo2, threads = threads2- ,threadsSum = threadsSum s + 1, threadsMax = threadsMax s `max` Set.size threads2}- Nothing | Set.null $ threads s -> do- signalBarrier done $ Right s- return Nothing- _ -> return $ Just s----- | Add a new task to the pool, may be cancelled by sending it an exception-addPool :: Pool -> IO a -> IO ()-addPool pool act = step pool $ \s -> do- todo <- enqueue (void act) (todo s)- return s{todo = todo}---- | Add a new task to the pool, may be cancelled by sending it an exception.--- Takes priority over everything else.-addPoolPriority :: Pool -> IO a -> IO ()-addPoolPriority pool act = step pool $ \s -> do- todo <- return $ enqueuePriority (void act) (todo s)- return s{todo = todo}----- | Temporarily increase the pool by 1 thread. Call the cleanup action to restore the value.--- After calling cleanup you should requeue onto a new thread.-increasePool :: Pool -> IO (IO ())-increasePool pool = do- step pool $ \s -> return s{threadsLimit = threadsLimit s + 1}- return $ step pool $ \s -> return s{threadsLimit = threadsLimit s - 1}----- | Run all the tasks in the pool on the given number of works.--- If any thread throws an exception, the exception will be reraised.-runPool :: Bool -> Int -> (Pool -> IO ()) -> IO () -- run all tasks in the pool-runPool deterministic n act = do- s <- newVar $ Just $ emptyS n deterministic- let cleanup = modifyVar_ s $ \s -> do- -- if someone kills our thread, make sure we kill our child threads- case s of- Just s -> mapM_ killThread $ Set.toList $ threads s- Nothing -> return ()- return Nothing- flip onException cleanup $ do- res <- newBarrier- let pool = Pool s res- addPool pool $ act pool- res <- waitBarrier res- case res of- Left e -> throw e- Right s -> addTiming $ "Pool finished (" ++ show (threadsSum s) ++ " threads, " ++ show (threadsMax s) ++ " max)"
− Development/Shake/Profile.hs
@@ -1,90 +0,0 @@-{-# LANGUAGE PatternGuards, RecordWildCards #-}--module Development.Shake.Profile(ProfileEntry(..), ProfileTrace(..), writeProfile) where--import General.Base-import General.Template-import Control.Arrow-import Data.Function-import Data.List-import Data.Version-import System.FilePath-import Paths_shake-import qualified Data.ByteString.Lazy.Char8 as LBS---data ProfileEntry = ProfileEntry- {prfName :: String, prfBuilt :: Int, prfChanged :: Int, prfDepends :: [Int], prfExecution :: Double, prfTraces :: [ProfileTrace]}-data ProfileTrace = ProfileTrace- {prfCommand :: String, prfStart :: Double, prfStop :: Double}-prfTime ProfileTrace{..} = prfStop - prfStart----- | Generates an report given some build system profiling data.-writeProfile :: FilePath -> [ProfileEntry] -> IO ()-writeProfile out xs- | takeExtension out == ".js" = writeFile out $ "var shake = \n" ++ generateJSON xs- | takeExtension out == ".json" = writeFile out $ generateJSON xs- | takeExtension out == ".trace" = writeFile out $ generateTrace xs- | out == "-" = putStr $ unlines $ generateSummary xs- | otherwise = LBS.writeFile out =<< generateHTML xs---generateSummary :: [ProfileEntry] -> [String]-generateSummary xs =- ["* This database has tracked " ++ show (maximum (0 : map prfChanged xs) + 1) ++ " runs."- ,let f = show . length in "* There are " ++ f xs ++ " rules (" ++ f ls ++ " rebuilt in the last run)."- ,let f = show . sum . map (length . prfTraces) in "* Building required " ++ f xs ++ " traced commands (" ++ f ls ++ " in the last run)."- ,"* The total (unparallelised) time is " ++ showTime (sum $ map prfExecution xs) ++- " of which " ++ showTime (sum $ map prfTime $ concatMap prfTraces xs) ++ " is traced commands."- ,let f xs = if null xs then "0s" else (\(a,b) -> showTime a ++ " (" ++ b ++ ")") $ maximumBy (compare `on` fst) xs in- "* The longest rule takes " ++ f (map (prfExecution &&& prfName) xs) ++- ", and the longest traced command takes " ++ f (map (prfTime &&& prfCommand) $ concatMap prfTraces xs) ++ "."- ,let sumLast = sum $ map prfTime $ concatMap prfTraces ls- maxStop = maximum $ 0 : map prfStop (concatMap prfTraces ls) in- "* Last run gave an average parallelism of " ++ showDP 2 (if maxStop == 0 then 0 else sumLast / maxStop) ++- " times over " ++ showTime(maxStop) ++ "."- ]- where ls = filter ((==) 0 . prfBuilt) xs---generateHTML :: [ProfileEntry] -> IO LBS.ByteString-generateHTML xs = do- htmlDir <- getDataFileName "html"- report <- LBS.readFile $ htmlDir </> "profile.html"- let f name | name == "profile-data.js" = return $ LBS.pack $ "var shake =\n" ++ generateJSON xs- | name == "version.js" = return $ LBS.pack $ "var version = " ++ show (showVersion version)- | otherwise = LBS.readFile $ htmlDir </> name- runTemplate f report---generateTrace :: [ProfileEntry] -> String-generateTrace xs = jsonListLines $- showEntries 0 [y{prfCommand=prfName x} | x <- xs, y <- prfTraces x] ++- showEntries 1 (concatMap prfTraces xs)- where- showEntries pid xs = map (showEntry pid) $ snd $ mapAccumL alloc [] $ sortBy (compare `on` prfStart) xs- alloc as r | (a1,an:a2) <- break (\a -> prfStop a <= prfStart r) as = (a1++r:a2, (length a1,r))- | otherwise = (as++[r], (length as,r))- showEntry pid (tid, ProfileTrace{..}) = jsonObject- [("args","{}"), ("ph",show "X"), ("cat",show "target")- ,("name",show prfCommand), ("tid",show tid), ("pid",show pid)- ,("ts",show $ 1000000*prfStart), ("dur",show $ 1000000*(prfStop-prfStart))]---generateJSON :: [ProfileEntry] -> String-generateJSON = jsonListLines . map showEntry- where- showEntry ProfileEntry{..} = jsonObject $- [("name", show prfName)- ,("built", show prfBuilt)- ,("changed", show prfChanged)- ,("depends", show prfDepends)- ,("execution", show prfExecution)] ++- [("traces", jsonList $ map showTrace prfTraces) | not $ null prfTraces]- showTrace ProfileTrace{..} = jsonObject- [("command",show prfCommand), ("start",show prfStart), ("stop",show prfStop)]--jsonListLines xs = "[" ++ intercalate "\n," xs ++ "\n]"-jsonList xs = "[" ++ intercalate "," xs ++ "]"-jsonObject xs = "{" ++ intercalate ", " [show a ++ ":" ++ b | (a,b) <- xs] ++ "}"
− Development/Shake/Progress.hs
@@ -1,348 +0,0 @@-{-# LANGUAGE DeriveDataTypeable, RecordWildCards, CPP, ForeignFunctionInterface, ScopedTypeVariables #-}-{-# LANGUAGE ViewPatterns #-}---- | Progress tracking-module Development.Shake.Progress(- Progress(..),- progressSimple, progressDisplay, progressTitlebar, progressProgram,- ProgressEntry(..), progressReplay, writeProgressReport -- INTERNAL USE ONLY- ) where--import Control.Applicative-import Control.Arrow-import Control.Exception-import Control.Monad-import System.Environment-import System.Directory-import System.Process-import System.FilePath-import Data.Char-import Data.Data-import Data.IORef-import Data.List-import Data.Maybe-import Data.Monoid-import Data.Version-import qualified Data.ByteString.Char8 as BS-import qualified Data.ByteString.Lazy.Char8 as LBS-import General.Base-import General.Template-import System.IO.Unsafe-import Paths_shake--#ifdef mingw32_HOST_OS--import Foreign-import Foreign.C.Types--type LPCSTR = Ptr CChar--foreign import stdcall "Windows.h SetConsoleTitleA" c_setConsoleTitle :: LPCSTR -> IO Bool--#endif--------------------------------------------------------------------------- PROGRESS TYPES - exposed to the user---- | Information about the current state of the build, obtained by passing a callback function--- to 'Development.Shake.shakeProgress'. Typically a program will use 'progressDisplay' to poll this value and produce--- status messages, which is implemented using this data type.-data Progress = Progress- {isFailure :: !(Maybe String) -- ^ Starts out 'Nothing', becomes 'Just' a target name if a rule fails.- ,countSkipped :: {-# UNPACK #-} !Int -- ^ Number of rules which were required, but were already in a valid state.- ,countBuilt :: {-# UNPACK #-} !Int -- ^ Number of rules which were have been built in this run.- ,countUnknown :: {-# UNPACK #-} !Int -- ^ Number of rules which have been built previously, but are not yet known to be required.- ,countTodo :: {-# UNPACK #-} !Int -- ^ Number of rules which are currently required (ignoring dependencies that do not change), but not built.- ,timeSkipped :: {-# UNPACK #-} !Double -- ^ Time spent building 'countSkipped' rules in previous runs.- ,timeBuilt :: {-# UNPACK #-} !Double -- ^ Time spent building 'countBuilt' rules.- ,timeUnknown :: {-# UNPACK #-} !Double -- ^ Time spent building 'countUnknown' rules in previous runs.- ,timeTodo :: {-# UNPACK #-} !(Double,Int) -- ^ Time spent building 'countTodo' rules in previous runs, plus the number which have no known time (have never been built before).- }- deriving (Eq,Ord,Show,Read,Data,Typeable)--instance Monoid Progress where- mempty = Progress Nothing 0 0 0 0 0 0 0 (0,0)- mappend a b = Progress- {isFailure = isFailure a `mplus` isFailure b- ,countSkipped = countSkipped a + countSkipped b- ,countBuilt = countBuilt a + countBuilt b- ,countUnknown = countUnknown a + countUnknown b- ,countTodo = countTodo a + countTodo b- ,timeSkipped = timeSkipped a + timeSkipped b- ,timeBuilt = timeBuilt a + timeBuilt b- ,timeUnknown = timeUnknown a + timeUnknown b- ,timeTodo = let (a1,a2) = timeTodo a; (b1,b2) = timeTodo b- x1 = a1 + b1; x2 = a2 + b2- in x1 `seq` x2 `seq` (x1,x2)- }--------------------------------------------------------------------------- MEALY TYPE - for writing the progress functions--- See <http://hackage.haskell.org/package/machines-0.2.3.1/docs/Data-Machine-Mealy.html>---- | A machine that takes inputs and produces outputs-newtype Mealy i a = Mealy {runMealy :: i -> (a, Mealy i a)}--instance Functor (Mealy i) where- fmap f (Mealy m) = Mealy $ \i -> case m i of- (x, m) -> (f x, fmap f m)--instance Applicative (Mealy i) where- pure x = let r = Mealy (const (x, r)) in r- Mealy mf <*> Mealy mx = Mealy $ \i -> case mf i of- (f, mf) -> case mx i of- (x, mx) -> (f x, mf <*> mx)--echoMealy :: Mealy i i-echoMealy = Mealy $ \i -> (i, echoMealy)--scanMealy :: (a -> b -> a) -> a -> Mealy i b -> Mealy i a-scanMealy f z (Mealy m) = Mealy $ \i -> case m i of- (x, m) -> let z2 = f z x in (z2, scanMealy f z2 m)--------------------------------------------------------------------------- MEALY UTILITIES--oldMealy :: a -> Mealy i a -> Mealy i (a,a)-oldMealy old = scanMealy (\(_,old) new -> (old,new)) (old,old)--latch :: Mealy i (Bool, a) -> Mealy i a-latch s = fromJust <$> scanMealy f Nothing s- where f old (b,v) = Just $ if b then fromMaybe v old else v--iff :: Mealy i Bool -> Mealy i a -> Mealy i a -> Mealy i a-iff c t f = (\c t f -> if c then t else f) <$> c <*> t <*> f---- decay'd division, compute a/b, with a decay of f--- r' is the new result, r is the last result--- r ~= a / b--- r' = r*b + f*(a'-a)--- ---------------- b + f*(b'-b)--- when f == 1, r == r'------ both streams must only ever increase-decay :: Double -> Mealy i Double -> Mealy i Double -> Mealy i Double-decay f a b = scanMealy step 0 $ (,) <$> oldMealy 0 a <*> oldMealy 0 b- where step r ((a,a'),(b,b')) =((r*b) + f*(a'-a)) / (b + f*(b'-b))--------------------------------------------------------------------------- MESSAGE GENERATOR--formatMessage :: Double -> Double -> String-formatMessage secs perc =- (if isNaN secs || secs < 0 then "??s" else showMinSec $ ceiling secs) ++ " (" ++- (if isNaN perc || perc < 0 || perc > 100 then "??" else show $ floor perc) ++ "%)"--showMinSec :: Int -> String-showMinSec secs = (if m == 0 then "" else show m ++ "m" ++ ['0' | s < 10]) ++ show s ++ "s"- where (m,s) = divMod secs 60----- | return (number of seconds, percentage, explanation)-message :: Mealy (Double, Progress) (Double, Progress) -> Mealy (Double, Progress) (Double, Double, String)-message input = liftA3 (,,) time perc debug- where- progress = snd <$> input- secs = fst <$> input- debug = (\donePerSec ruleTime (todoKnown,todoUnknown) ->- "Progress: " ++- "((known=" ++ showDP 2 todoKnown ++ "s) + " ++- "(unknown=" ++ show todoUnknown ++ " * time=" ++ showDP 2 ruleTime ++ "s)) " ++- "(rate=" ++ showDP 2 donePerSec ++ "))")- <$> donePerSec <*> ruleTime <*> (timeTodo <$> progress)-- -- Number of seconds work completed in this build run- -- Ignores timeSkipped which would be more truthful, but it makes the % drop sharply- -- which isn't what users want- done = timeBuilt <$> progress-- -- Work done per second, don't divide by 0 and don't update if 'done' doesn't change- donePerSec = iff ((==) 0 <$> done) (pure 1) perSecStable- where perSecStable = latch $ liftA2 (,) (uncurry (==) <$> oldMealy 0 done) perSecRaw- perSecRaw = decay 1.2 done secs-- -- Predicted build time for a rule that has never been built before- -- The high decay means if a build goes in "phases" - lots of source files, then lots of compiling- -- we reach a reasonable number fairly quickly, without bouncing too much- ruleTime = liftA2 weightedAverage- (f (decay 10) timeBuilt countBuilt)- (f (liftA2 (/)) (fst . timeTodo) (\Progress{..} -> countTodo - snd timeTodo))- -- don't call decay on todo, since it goes up and down (as things get done)- where- weightedAverage (w1,x1) (w2,x2)- | w1 == 0 && w2 == 0 = 0- | otherwise = ((w1 *. x1) + (w2 *. x2)) / intToDouble (w1+w2)- where i *. d = if i == 0 then 0 else intToDouble i * d -- since d might be NaN-- f divide time count = let xs = count <$> progress in liftA2 (,) xs $ divide (time <$> progress) (intToDouble <$> xs)-- -- Number of seconds work remaining, ignoring multiple threads- todo = f <$> progress <*> ruleTime- where f Progress{..} ruleTime = fst timeTodo + (fromIntegral (snd timeTodo) * ruleTime)-- -- Display information- time = liftA2 (/) todo donePerSec- perc = iff ((==) 0 <$> done) (pure 0) $- liftA2' done todo $ \done todo -> 100 * done / (done + todo)--------------------------------------------------------------------------- EXPOSED FUNCTIONS---- | Given a sampling interval (in seconds) and a way to display the status message,--- produce a function suitable for using as 'Development.Shake.shakeProgress'.--- This function polls the progress information every /n/ seconds, produces a status--- message and displays it using the display function.------ Typical status messages will take the form of @1m25s (15%)@, indicating that the build--- is predicted to complete in 1 minute 25 seconds (85 seconds total), and 15% of the necessary build time has elapsed.--- This function uses past observations to predict future behaviour, and as such, is only--- guessing. The time is likely to go up as well as down, and will be less accurate from a--- clean build (as the system has fewer past observations).------ The current implementation is to predict the time remaining (based on 'timeTodo') and the--- work already done ('timeBuilt'). The percentage is then calculated as @remaining / (done + remaining)@,--- while time left is calculated by scaling @remaining@ by the observed work rate in this build,--- roughly @done / time_elapsed@.-progressDisplay :: Double -> (String -> IO ()) -> IO Progress -> IO ()-progressDisplay sample disp prog = do- disp "Starting..." -- no useful info at this stage- time <- offsetTime- catchJust (\x -> if x == ThreadKilled then Just () else Nothing) (loop time $ message echoMealy) (const $ disp "Finished")- where- loop :: IO Double -> Mealy (Double, Progress) (Double, Double, String) -> IO ()- loop time mealy = do- sleep sample- p <- prog- t <- time- ((secs,perc,debug), mealy) <- return $ runMealy mealy (t, p)- -- putStrLn debug- disp $ formatMessage secs perc ++ maybe "" (\err -> ", Failure! " ++ err) (isFailure p)- loop time mealy---data ProgressEntry = ProgressEntry- {idealSecs :: Double, idealPerc :: Double- ,actualSecs :: Double, actualPerc :: Double- }---- | Given a list of progress inputs, what would you have suggested (seconds, percentage)-progressReplay :: [(Double, Progress)] -> [ProgressEntry]-progressReplay [] = []-progressReplay ps = snd $ mapAccumL f (message echoMealy) ps- where- end = fst $ last ps- f a (time,p) = (a2, ProgressEntry (end - time) (time * 100 / end) secs perc)- where ((secs,perc,_),a2) = runMealy a (time,p)----- | Given a trace, display information about how well we did-writeProgressReport :: FilePath -> [(FilePath, [(Double, Progress)])] -> IO ()-writeProgressReport out (map (second progressReplay) -> xs)- | takeExtension out == ".js" = writeFile out $ "var shake = \n" ++ generateJSON xs- | takeExtension out == ".json" = writeFile out $ generateJSON xs- | out == "-" = putStr $ unlines $ generateSummary xs- | otherwise = LBS.writeFile out =<< generateHTML xs---generateSummary :: [(FilePath, [ProgressEntry])] -> [String]-generateSummary xs = flip concatMap xs $ \(file,xs) ->- ["# " ++ file, f xs "Seconds" idealSecs actualSecs, f xs "Percent" idealPerc actualPerc]- where- levels = [100,90,80,50]- f xs lbl ideal actual = lbl ++ ": " ++ intercalate ", "- [show l ++ "% within " ++ show (ceiling $ maximum $ 0 : take ((length xs * l) `div` 100) diff) | l <- levels]- where diff = sort [abs $ ideal x - actual x | x <- xs]---generateHTML :: [(FilePath, [ProgressEntry])] -> IO LBS.ByteString-generateHTML xs = do- htmlDir <- getDataFileName "html"- report <- LBS.readFile $ htmlDir </> "progress.html"- let f name | name == "progress-data.js" = return $ LBS.pack $ "var shake =\n" ++ generateJSON xs- | name == "version.js" = return $ LBS.pack $ "var version = " ++ show (showVersion version)- | otherwise = LBS.readFile $ htmlDir </> name- runTemplate f report--generateJSON :: [(FilePath, [ProgressEntry])] -> String-generateJSON = concat . jsonList . map ((++"}") . unlines . f)- where- f (file,ps) =- ("{\"name\":" ++ show (takeFileName file) ++ ", \"values\":") :- indent (jsonList $ map g ps)-- shw = showDP 1- g ProgressEntry{..} = jsonObject- [("idealSecs",shw idealSecs),("idealPerc",shw idealPerc)- ,("actualSecs",shw actualSecs),("actualPerc",shw actualPerc)]--indent = map (" "++)-jsonList xs = zipWith (:) ('[':repeat ',') xs ++ ["]"]-jsonObject xs = "{" ++ intercalate ", " [show a ++ ":" ++ b | (a,b) <- xs] ++ "}"---{-# NOINLINE xterm #-}-xterm :: Bool-xterm = System.IO.Unsafe.unsafePerformIO $- -- Terminal.app uses "xterm-256color" as its env variable- Control.Exception.catch (fmap ("xterm" `isPrefixOf`) $ getEnv "TERM") $- \(e :: SomeException) -> return False----- | Set the title of the current console window to the given text. If the--- environment variable @$TERM@ is set to @xterm@ this uses xterm escape sequences.--- On Windows, if not detected as an xterm, this function uses the @SetConsoleTitle@ API.-progressTitlebar :: String -> IO ()-progressTitlebar x- | xterm = BS.putStr $ BS.pack $ "\ESC]0;" ++ x ++ "\BEL"-#ifdef mingw32_HOST_OS- | otherwise = BS.useAsCString (BS.pack x) $ \x -> c_setConsoleTitle x >> return ()-#else- | otherwise = return ()-#endif----- | Call the program @shake-progress@ if it is on the @$PATH@. The program is called with--- the following arguments:------ * @--title=string@ - the string passed to @progressProgram@.------ * @--state=Normal@, or one of @NoProgress@, @Normal@, or @Error@ to indicate--- what state the progress bar should be in.------ * @--value=25@ - the percent of the build that has completed, if not in @NoProgress@ state.------ The program will not be called consecutively with the same @--state@ and @--value@ options.------ Windows 7 or higher users can get taskbar progress notifications by placing the following--- program in their @$PATH@: <https://github.com/ndmitchell/shake/releases>.-progressProgram :: IO (String -> IO ())-progressProgram = do- exe <- findExecutable "shake-progress"- case exe of- Nothing -> return $ const $ return ()- Just exe -> do- ref <- newIORef Nothing- return $ \msg -> do- let failure = " Failure! " `isInfixOf` msg- let perc = let (a,b) = break (== '%') msg- in if null b then "" else reverse $ takeWhile isDigit $ reverse a- let key = (failure, perc)- same <- atomicModifyIORef ref $ \old -> (Just key, old == Just key)- let state = if perc == "" then "NoProgress" else if failure then "Error" else "Normal"- rawSystem exe $ ["--title=" ++ msg, "--state=" ++ state] ++ ["--value=" ++ perc | perc /= ""]- return ()----- | A simple method for displaying progress messages, suitable for using as 'Development.Shake.shakeProgress'.--- This function writes the current progress to the titlebar every five seconds using 'progressTitlebar',--- and calls any @shake-progress@ program on the @$PATH@ using 'progressProgram'.-progressSimple :: IO Progress -> IO ()-progressSimple p = do- program <- progressProgram- progressDisplay 5 (\s -> progressTitlebar s >> program s) p
− Development/Shake/Resource.hs
@@ -1,162 +0,0 @@-{-# LANGUAGE RecordWildCards, ViewPatterns #-}--module Development.Shake.Resource(- Resource, newResourceIO, newThrottleIO, acquireResource, releaseResource- ) where--import General.Base-import General.Concurrent-import Data.Function-import Data.Monoid-import System.IO.Unsafe-import Control.Concurrent-import Control.Arrow-import Control.Monad-import General.Bilist-import Development.Shake.Pool---{-# NOINLINE resourceIds #-}-resourceIds :: Var Int-resourceIds = unsafePerformIO $ newVar 0--resourceId :: IO Int-resourceId = modifyVar resourceIds $ \i -> let j = i + 1 in j `seq` return (j, j)----- | A type representing an external resource which the build system should respect. There--- are two ways to create 'Resource's in Shake:------ * 'Development.Shake.newResource' creates a finite resource, stopping too many actions running--- simultaneously.------ * 'Development.Shake.newThrottle' creates a throttled resource, stopping too many actions running--- over a short time period.------ These resources are used with 'Development.Shake.withResource' when defining rules. Typically only--- system commands (such as 'Development.Shake.cmd') should be run inside 'Development.Shake.withResource',--- not commands such as 'Development.Shake.need'.------ Be careful that the actions run within 'Development.Shake.withResource' do not themselves require further--- resources, or you may get a \"thread blocked indefinitely in an MVar operation\" exception.--- If an action requires multiple resources, use 'Development.Shake.withResources' to avoid deadlock.-data Resource = Resource- {resourceOrd :: Int- -- ^ Key used for Eq/Ord operations. To make withResources work, we require newResourceIO < newThrottleIO- ,resourceShow :: String- -- ^ String used for Show- ,acquireResource :: Pool -> Int -> IO () -> IO ()- -- ^ Acquire the resource and call the function. Passes 'False' to indicate you have acquired with no blocking,- -- or 'True' to say there was waiting and you must not do significant computation on that thread.- ,releaseResource :: Pool -> Int -> IO ()- -- ^ You should only ever releaseResource that you obtained with acquireResource.- }--instance Show Resource where show = resourceShow-instance Eq Resource where (==) = (==) `on` resourceOrd-instance Ord Resource where compare = compare `on` resourceOrd--------------------------------------------------------------------------- FINITE RESOURCES--data Finite = Finite- {finiteAvailable :: !Int- -- ^ number of currently available resources- ,finiteWaiting :: Bilist (Int, IO ())- -- ^ queue of people with how much they want and the action when it is allocated to them- }---- | A version of 'Development.Shake.newResource' that runs in IO, and can be called before calling 'Development.Shake.shake'.--- Most people should use 'Development.Shake.newResource' instead.-newResourceIO :: String -> Int -> IO Resource-newResourceIO name mx = do- when (mx < 0) $- error $ "You cannot create a resource named " ++ name ++ " with a negative quantity, you used " ++ show mx- key <- resourceId- var <- newVar $ Finite mx mempty- return $ Resource (negate key) shw (acquire var) (release var)- where- shw = "Resource " ++ name-- acquire :: Var Finite -> Pool -> Int -> IO () -> IO ()- acquire var pool want continue- | want < 0 = error $ "You cannot acquire a negative quantity of " ++ shw ++ ", requested " ++ show want- | want > mx = error $ "You cannot acquire more than " ++ show mx ++ " of " ++ shw ++ ", requested " ++ show want- | otherwise = join $ modifyVar var $ \x@Finite{..} -> return $- if want <= finiteAvailable then- (x{finiteAvailable = finiteAvailable - want}, continue)- else- (x{finiteWaiting = finiteWaiting `snoc` (want, addPool pool continue)}, return ())-- release :: Var Finite -> Pool -> Int -> IO ()- release var _ i = join $ modifyVar var $ \x -> return $ f x{finiteAvailable = finiteAvailable x + i}- where- f (Finite i (uncons -> Just ((wi,wa),ws)))- | wi <= i = second (wa >>) $ f $ Finite (i-wi) ws- | otherwise = first (add (wi,wa)) $ f $ Finite i ws- f (Finite i _) = (Finite i mempty, return ())- add a s = s{finiteWaiting = a `cons` finiteWaiting s}--------------------------------------------------------------------------- THROTTLE RESOURCES----- call a function after a certain delay-waiter :: Duration -> IO () -> IO ()-waiter period act = void $ forkIO $ do- sleep period- act---- Make sure the pool cannot run try until after you have finished with it-blockPool :: Pool -> IO (IO ())-blockPool pool = do- bar <- newBarrier- addPool pool $ do- cancel <- increasePool pool- waitBarrier bar- cancel- return $ signalBarrier bar ()---data Throttle- -- | Some number of resources are available- = ThrottleAvailable !Int- -- | Some users are blocked (non-empty), plus an action to call once we go back to Available- | ThrottleWaiting (IO ()) (Bilist (Int, IO ()))----- | A version of 'Development.Shake.newThrottle' that runs in IO, and can be called before calling 'Development.Shake.shake'.--- Most people should use 'Development.Shake.newThrottle' instead.-newThrottleIO :: String -> Int -> Double -> IO Resource-newThrottleIO name count period = do- when (count < 0) $- error $ "You cannot create a throttle named " ++ name ++ " with a negative quantity, you used " ++ show count- key <- resourceId- var <- newVar $ ThrottleAvailable count- return $ Resource key shw (acquire var) (release var)- where- shw = "Throttle " ++ name-- acquire :: Var Throttle -> Pool -> Int -> IO () -> IO ()- acquire var pool want continue- | want < 0 = error $ "You cannot acquire a negative quantity of " ++ shw ++ ", requested " ++ show want- | want > count = error $ "You cannot acquire more than " ++ show count ++ " of " ++ shw ++ ", requested " ++ show want- | otherwise = join $ modifyVar var $ \x -> case x of- ThrottleAvailable i- | i >= want -> return (ThrottleAvailable $ i - want, continue)- | otherwise -> do- stop <- blockPool pool- return (ThrottleWaiting stop $ (want - i, addPool pool continue) `cons` mempty, return ())- ThrottleWaiting stop xs -> return (ThrottleWaiting stop $ xs `snoc` (want, addPool pool continue), return ())-- release :: Var Throttle -> Pool -> Int -> IO ()- release var pool n = waiter period $ join $ modifyVar var $ \x -> return $ case x of- ThrottleAvailable i -> (ThrottleAvailable $ i+n, return ())- ThrottleWaiting stop xs -> f stop n xs- where- f stop i (uncons -> Just ((wi,wa),ws))- | i >= wi = second (wa >>) $ f stop (i-wi) ws- | otherwise = (ThrottleWaiting stop $ (wi-i,wa) `cons` ws, return ())- f stop i _ = (ThrottleAvailable i, stop)
− Development/Shake/Rule.hs
@@ -1,26 +0,0 @@-{-# LANGUAGE CPP #-}---- | This module is used for defining new types of rules for Shake build systems.--- Most users will find the built-in set of rules sufficient.-module Development.Shake.Rule(-#if __GLASGOW_HASKELL__ >= 704- ShakeValue,-#endif- Rule(..), EqualCost(..), rule, apply, apply1,- trackUse, trackChange, trackAllow,- -- * Deprecated- defaultRule- ) where--import Development.Shake.Core-import Development.Shake.Types--{-# DEPRECATED defaultRule "Use 'rule' with 'priority' 0" #-}---- | A deprecated way of defining a low priority rule. Defined as:------ @--- defaultRule = 'priority' 0 . 'rule'--- @-defaultRule :: Rule key value => (key -> Maybe (Action value)) -> Rules ()-defaultRule = priority 0 . rule
− Development/Shake/Rules/Directory.hs
@@ -1,277 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, ScopedTypeVariables, DeriveDataTypeable, RecordWildCards, FlexibleContexts #-}---- | Both System.Directory and System.Environment wrappers-module Development.Shake.Rules.Directory(- doesFileExist, doesDirectoryExist,- getDirectoryContents, getDirectoryFiles, getDirectoryDirs,- getEnv, getEnvWithDefault,- removeFiles, removeFilesAfter,- defaultRuleDirectory- ) where--import Control.Applicative-import Control.Monad-import Control.Monad.IO.Class-import Data.Maybe-import Data.Binary-import Data.List-import qualified System.Directory as IO--import Development.Shake.Core-import Development.Shake.Classes-import Development.Shake.FilePath-import Development.Shake.FilePattern-import General.Base---newtype DoesFileExistQ = DoesFileExistQ FilePath- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show DoesFileExistQ where- show (DoesFileExistQ a) = "doesFileExist " ++ showQuote a--newtype DoesFileExistA = DoesFileExistA Bool- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show DoesFileExistA where- show (DoesFileExistA a) = show a---newtype DoesDirectoryExistQ = DoesDirectoryExistQ FilePath- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show DoesDirectoryExistQ where- show (DoesDirectoryExistQ a) = "doesDirectoryExist " ++ showQuote a--newtype DoesDirectoryExistA = DoesDirectoryExistA Bool- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show DoesDirectoryExistA where- show (DoesDirectoryExistA a) = show a---newtype GetEnvQ = GetEnvQ String- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show GetEnvQ where- show (GetEnvQ a) = "getEnv " ++ showQuote a--newtype GetEnvA = GetEnvA (Maybe String)- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show GetEnvA where- show (GetEnvA a) = maybe "<unset>" showQuote a---data GetDirectoryQ- = GetDir {dir :: FilePath}- | GetDirFiles {dir :: FilePath, pat :: [FilePattern]}- | GetDirDirs {dir :: FilePath}- deriving (Typeable,Eq)--newtype GetDirectoryA = GetDirectoryA [FilePath]- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show GetDirectoryQ where- show (GetDir x) = "getDirectoryContents " ++ showQuote x- show (GetDirFiles a b) = "getDirectoryFiles " ++ showQuote a ++ " [" ++ unwords (map showQuote b) ++ "]"- show (GetDirDirs x) = "getDirectoryDirs " ++ showQuote x--instance Show GetDirectoryA where- show (GetDirectoryA xs) = unwords $ map showQuote xs--instance NFData GetDirectoryQ where- rnf (GetDir a) = rnf a- rnf (GetDirFiles a b) = rnf a `seq` rnf b- rnf (GetDirDirs a) = rnf a--instance Hashable GetDirectoryQ where- hashWithSalt salt = hashWithSalt salt . f- where f (GetDir x) = (0 :: Int, x, [])- f (GetDirFiles x y) = (1, x, y)- f (GetDirDirs x) = (2, x, [])--instance Binary GetDirectoryQ where- get = do- i <- getWord8- case i of- 0 -> liftM GetDir get- 1 -> liftM2 GetDirFiles get get- 2 -> liftM GetDirDirs get-- put (GetDir x) = putWord8 0 >> put x- put (GetDirFiles x y) = putWord8 1 >> put x >> put y- put (GetDirDirs x) = putWord8 2 >> put x---instance Rule DoesFileExistQ DoesFileExistA where- storedValue _ (DoesFileExistQ x) = fmap (Just . DoesFileExistA) $ IO.doesFileExist x--instance Rule DoesDirectoryExistQ DoesDirectoryExistA where- storedValue _ (DoesDirectoryExistQ x) = fmap (Just . DoesDirectoryExistA) $ IO.doesDirectoryExist x--instance Rule GetEnvQ GetEnvA where- storedValue _ (GetEnvQ x) = fmap (Just . GetEnvA) $ getEnvMaybe x--instance Rule GetDirectoryQ GetDirectoryA where- storedValue _ x = fmap Just $ getDir x----- | This function is not actually exported, but Haddock is buggy. Please ignore.-defaultRuleDirectory :: Rules ()-defaultRuleDirectory = do- rule $ \(DoesFileExistQ x) -> Just $- liftIO $ fmap DoesFileExistA $ IO.doesFileExist x- rule $ \(DoesDirectoryExistQ x) -> Just $- liftIO $ fmap DoesDirectoryExistA $ IO.doesDirectoryExist x- rule $ \(x :: GetDirectoryQ) -> Just $- liftIO $ getDir x- rule $ \(GetEnvQ x) -> Just $- liftIO $ fmap GetEnvA $ getEnvMaybe x----- | Returns 'True' if the file exists. The existence of the file is tracked as a--- dependency, and if the file is created or deleted the rule will rerun in subsequent builds.------ You should not call 'doesFileExist' on files which can be created by the build system.-doesFileExist :: FilePath -> Action Bool-doesFileExist file = do- DoesFileExistA res <- apply1 $ DoesFileExistQ file- return res---- | Returns 'True' if the directory exists. The existence of the directory is tracked as a--- dependency, and if the directory is created or delete the rule will rerun in subsequent builds.------ You should not call 'doesDirectoryExist' on directories which can be created by the build system.-doesDirectoryExist :: FilePath -> Action Bool-doesDirectoryExist file = do- DoesDirectoryExistA res <- apply1 $ DoesDirectoryExistQ file- return res---- | Return 'Just' the value of the environment variable, or 'Nothing'--- if the variable is not set. The environment variable is tracked as a--- dependency, and if it changes the rule will rerun in subsequent builds.-getEnv :: String -> Action (Maybe String)-getEnv var = do- GetEnvA res <- apply1 $ GetEnvQ var- return res---- | Return the value of the environment variable, or the default value if it--- not set. Similar to 'getEnv'.-getEnvWithDefault :: String -> String -> Action String-getEnvWithDefault def var = fromMaybe def <$> getEnv var---- | Get the contents of a directory. The result will be sorted, and will not contain--- the entries @.@ or @..@ (unlike the standard Haskell version). The resulting paths will be relative--- to the first argument. The result is tracked as a--- dependency, and if it changes the rule will rerun in subsequent builds.------ It is usually simpler to call either 'getDirectoryFiles' or 'getDirectoryDirs'.-getDirectoryContents :: FilePath -> Action [FilePath]-getDirectoryContents x = getDirAction $ GetDir x---- | Get the files anywhere under a directory that match any of a set of patterns.--- For the interpretation of the patterns see '?=='. All results will be--- relative to the 'FilePath' argument. The result is tracked as a--- dependency, and if it changes the rule will rerun in subsequent builds.--- Some examples:------ > getDirectoryFiles "Config" ["//*.xml"]--- > -- All .xml files anywhere under the Config directory--- > -- If Config/foo/bar.xml exists it will return ["foo/bar.xml"]--- > getDirectoryFiles "Modules" ["*.hs","*.lhs"]--- > -- All .hs or .lhs in the Modules directory--- > -- If Modules/foo.hs and Modules/foo.lhs exist, it will return ["foo.hs","foo.lhs"]------ If you require a qualified file name it is often easier to use @\"\"@ as 'FilePath' argument,--- for example the following two expressions are equivalent:------ > fmap (map ("Config" </>)) (getDirectoryFiles "Config" ["//*.xml"])--- > getDirectoryFiles "" ["Config//*.xml"]-getDirectoryFiles :: FilePath -> [FilePattern] -> Action [FilePath]-getDirectoryFiles x f = getDirAction $ GetDirFiles x f---- | Get the directories in a directory, not including @.@ or @..@.--- All directories are relative to the argument directory. The result is tracked as a--- dependency, and if it changes the rule will rerun in subsequent builds.--------- > getDirectoryDirs "/Users"--- > -- Return all directories in the /Users directory--- > -- e.g. ["Emily","Henry","Neil"]-getDirectoryDirs :: FilePath -> Action [FilePath]-getDirectoryDirs x = getDirAction $ GetDirDirs x--getDirAction x = do GetDirectoryA y <- apply1 x; return y--contents :: FilePath -> IO [FilePath]--- getDirectoryContents "" is equivalent to getDirectoryContents "." on Windows,--- but raises an error on Linux. We smooth out the difference.-contents x = fmap (filter $ not . all (== '.')) $ IO.getDirectoryContents $ if x == "" then "." else x---answer :: [FilePath] -> GetDirectoryA-answer = GetDirectoryA . sort--getDir :: GetDirectoryQ -> IO GetDirectoryA-getDir GetDir{..} = fmap answer $ contents dir--getDir GetDirDirs{..} = fmap answer $ filterM f =<< contents dir- where f x = IO.doesDirectoryExist $ dir </> x--getDir GetDirFiles{..} = fmap answer $ concatMapM f $ directories pat- where- test = let ps = map (?==) pat in \x -> any ($ x) ps-- f (dir2,False) = do- xs <- fmap (map (dir2 </>)) $ contents $ dir </> dir2- flip filterM xs $ \x -> if not $ test x then return False else fmap not $ IO.doesDirectoryExist $ dir </> x-- f (dir2,True) = do- xs <- fmap (map (dir2 </>)) $ contents $ dir </> dir2- (dirs,files) <- partitionM (\x -> IO.doesDirectoryExist $ dir </> x) xs- rest <- concatMapM (\d -> f (d, True)) dirs- return $ filter test files ++ rest----- | Remove all files and directories that match any of the patterns within a directory.--- Some examples:------ @--- 'removeFiles' \"output\" [\"\/\/*\"]--- 'removeFiles' \".\" [\"\/\/*.hi\",\"\/\/*.o\"]--- @------ Any directories that become empty after deleting items from within them will themselves be deleted,--- up to (and including) the containing directory.--- This function is often useful when writing a @clean@ action for your build system,--- often as a 'phony' rule.-removeFiles :: FilePath -> [FilePattern] -> IO ()-removeFiles dir pat = void $ f ""- where- -- because it is generate and match anything like ../ will be ignored, since we never generate ..- -- therefore we can safely know we never escape the containing directory- test = let ps = map (?==) pat in \x -> any ($ x) ps-- -- dir </> dir2 is the part to operate on, return True if you deleted the directory- f :: FilePath -> IO Bool- f dir2 | test dir2 = do- IO.removeDirectoryRecursive $ dir </> dir2- return True- f dir2 = do- xs <- fmap (map (dir2 </>)) $ contents $ dir </> dir2- (dirs,files) <- partitionM (\x -> IO.doesDirectoryExist $ dir </> x) xs- noDirs <- fmap and $ mapM f dirs- let (del,keep) = partition test files- forM del $ \d -> IO.removeFile $ dir </> d- let die = noDirs && null keep && not (null xs)- when die $ IO.removeDirectory $ dir </> dir2- return die----- | Remove files, like 'removeFiles', but executed after the build completes successfully.--- Useful for implementing @clean@ actions that delete files Shake may have open for building.-removeFilesAfter :: FilePath -> [FilePattern] -> Action ()-removeFilesAfter a b = do- putLoud $ "Will remove " ++ unwords b ++ " from " ++ a- runAfter $ removeFiles a b
− Development/Shake/Rules/File.hs
@@ -1,258 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}--module Development.Shake.Rules.File(- need, needBS, needed, neededBS, want,- trackRead, trackWrite, trackAllow,- defaultRuleFile,- (*>), (|*>), (**>), (?>), phony, (~>),- -- * Internal only- FileQ(..), FileA- ) where--import Control.Applicative hiding ((*>))-import Control.Monad-import Control.Monad.IO.Class-import System.Directory-import qualified Data.ByteString.Char8 as BS-import qualified Data.HashSet as Set--import Development.Shake.Core hiding (trackAllow)-import qualified Development.Shake.Core as S-import General.String-import Development.Shake.Classes-import Development.Shake.FilePath(toStandard)-import Development.Shake.FilePattern-import Development.Shake.FileInfo-import Development.Shake.Types-import Development.Shake.Errors--import Data.Bits-import Data.List-import Data.Maybe-import System.FilePath(takeDirectory) -- important that this is the system local filepath, or wrong slashes go wrong-import System.IO.Unsafe(unsafeInterleaveIO)---infix 1 *>, ?>, |*>, **>, ~>---- | /Deprecated:/ Alias for '|*>'.-(**>) :: [FilePattern] -> (FilePath -> Action ()) -> Rules ()-(**>) = (|*>)---newtype FileQ = FileQ {fromFileQ :: BSU}- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show FileQ where show (FileQ x) = unpackU x--data FileA = FileA {-# UNPACK #-} !ModTime {-# UNPACK #-} !FileSize FileHash- deriving (Typeable,Eq)--instance Hashable FileA where- hashWithSalt salt (FileA a b c) = hashWithSalt salt a `xor` hashWithSalt salt b `xor` hashWithSalt salt c--instance NFData FileA where- rnf (FileA a b c) = rnf a `seq` rnf b `seq` rnf c--instance Binary FileA where- put (FileA a b c) = put a >> put b >> put c- get = liftA3 FileA get get get--instance Show FileA where- show (FileA m s h) = "File {mod=" ++ show m ++ ",size=" ++ show s ++ ",digest=" ++ show h ++ "}"--instance Rule FileQ FileA where- storedValue ShakeOptions{shakeChange=c} (FileQ x) = do- res <- getFileInfo x- case res of- Nothing -> return Nothing- Just (time,size) | c == ChangeModtime -> return $ Just $ FileA time size fileInfoVal- Just (time,size) -> do- hash <- unsafeInterleaveIO $ getFileHash x- return $ Just $ FileA (if c == ChangeDigest then fileInfoVal else time) size hash-- equalValue ShakeOptions{shakeChange=c} q (FileA x1 x2 x3) (FileA y1 y2 y3) = case c of- ChangeModtime -> bool $ x1 == y1- ChangeDigest -> bool $ x2 == y2 && x3 == y3- ChangeModtimeOrDigest -> bool $ x1 == y1 && x2 == y2 && x3 == y3- _ -> if x1 == y1 then EqualCheap- else if x2 == y2 && x3 == y3 then EqualExpensive- else NotEqual- where bool b = if b then EqualCheap else NotEqual--storedValueError :: ShakeOptions -> Bool -> String -> FileQ -> IO FileA-storedValueError opts input msg x = fromMaybe def <$> storedValue opts2 x- where def = if shakeCreationCheck opts || input then error err else FileA fileInfoNeq fileInfoNeq fileInfoNeq- err = msg ++ "\n " ++ unpackU (fromFileQ x)- opts2 = if not input && shakeChange opts == ChangeModtimeAndDigestInput then opts{shakeChange=ChangeModtime} else opts----- | This function is not actually exported, but Haddock is buggy. Please ignore.-defaultRuleFile :: Rules ()-defaultRuleFile = priority 0 $ rule $ \x -> Just $ do- opts <- getShakeOptions- liftIO $ storedValueError opts True "Error, file does not exist and no rule available:" x----- | Add a dependency on the file arguments, ensuring they are built before continuing.--- The file arguments may be built in parallel, in any order. This function is particularly--- necessary when calling 'Development.Shake.cmd' or 'Development.Shake.command'. As an example:------ @--- \"\/\/*.rot13\" '*>' \\out -> do--- let src = 'Development.Shake.FilePath.dropExtension' out--- 'need' [src]--- 'Development.Shake.cmd' \"rot13\" [src] \"-o\" [out]--- @------ Usually @need [foo,bar]@ is preferable to @need [foo] >> need [bar]@ as the former allows greater--- parallelism, while the latter requires @foo@ to finish building before starting to build @bar@.-need :: [FilePath] -> Action ()-need xs = (apply $ map (FileQ . packU) xs :: Action [FileA]) >> return ()--needBS :: [BS.ByteString] -> Action ()-needBS xs = (apply $ map (FileQ . packU_) xs :: Action [FileA]) >> return ()----- | Like 'need', but if 'shakeLint' is set, check that the file does not rebuild.--- Used for adding dependencies on files that have already been used in this rule.-needed :: [FilePath] -> Action ()-needed xs = do- opts <- getShakeOptions- if isNothing $ shakeLint opts then need xs else neededCheck $ map packU xs---neededBS :: [BS.ByteString] -> Action ()-neededBS xs = do- opts <- getShakeOptions- if isNothing $ shakeLint opts then needBS xs else neededCheck $ map packU_ xs---neededCheck :: [BSU] -> Action ()-neededCheck xs = do- opts <- getShakeOptions- pre <- liftIO $ mapM (storedValue opts . FileQ) xs- post <- apply $ map FileQ xs :: Action [FileA]- let bad = [ (x, if isJust a then "File change" else "File created")- | (x, a, b) <- zip3 xs pre post, Just b /= a]- case bad of- [] -> return ()- (file,msg):_ -> errorStructured- "Lint checking error - 'needed' file required rebuilding"- [("File", Just $ unpackU file)- ,("Error",Just msg)]- ""----- | Track that a file was read by the action preceeding it. If 'shakeLint' is activated--- then these files must be dependencies of this rule. Calls to 'trackRead' are--- automatically inserted in 'LintTracker' mode.-trackRead :: [FilePath] -> Action ()-trackRead = mapM_ (trackUse . FileQ . packU)---- | Track that a file was written by the action preceeding it. If 'shakeLint' is activated--- then these files must either be the target of this rule, or never referred to by the build system.--- Calls to 'trackWrite' are automatically inserted in 'LintTracker' mode.-trackWrite :: [FilePath] -> Action ()-trackWrite = mapM_ (trackChange . FileQ . packU)---- | Allow accessing a file in this rule, ignoring any 'trackRead'\/'trackWrite' calls matching--- the pattern.-trackAllow :: [FilePattern] -> Action ()-trackAllow ps = do- opts <- getShakeOptions- when (isJust $ shakeLint opts) $- S.trackAllow $ \(FileQ x) -> any (?== unpackU x) ps----- | Require that the argument files are built by the rules, used to specify the target.------ @--- main = 'Development.Shake.shake' 'shakeOptions' $ do--- 'want' [\"Main.exe\"]--- ...--- @------ This program will build @Main.exe@, given sufficient rules. All arguments to all 'want' calls--- may be built in parallel, in any order.------ This function is defined in terms of 'action' and 'need', use 'action' if you need more complex--- targets than 'want' allows.-want :: [FilePath] -> Rules ()-want = action . need---root :: String -> (FilePath -> Bool) -> (FilePath -> Action ()) -> Rules ()-root help test act = rule $ \(FileQ x_) -> let x = unpackU x_ in- if not $ test x then Nothing else Just $ do- liftIO $ createDirectoryIfMissing True $ takeDirectory x- act x- opts <- getShakeOptions- liftIO $ storedValueError opts False ("Error, rule " ++ help ++ " failed to build file:") $ FileQ x_----- | Declare a phony action -- an action that does not produce a file, and will be rerun--- in every execution that requires it. You can demand 'phony' rules using 'want' \/ 'need'.--- Phony actions are never executed more than once in a single build run.------ Phony actions are intended to define command-line abbreviations. If you 'need' a phony action--- in a rule then every execution where that rule is required will rerun both the rule and the phony--- action.-phony :: String -> Action () -> Rules ()-phony name act = rule $ \(FileQ x_) -> let x = unpackU x_ in- if name /= x then Nothing else Just $ do- act- return $ FileA fileInfoNeq fileInfoNeq fileInfoNeq---- | Infix operator alias for 'phony', for sake of consistency with normal--- rules.-(~>) :: String -> Action () -> Rules ()-(~>) = phony ----- | Define a rule to build files. If the first argument returns 'True' for a given file,--- the second argument will be used to build it. Usually '*>' is sufficient, but '?>' gives--- additional power. For any file used by the build system, only one rule should return 'True'.--- This function will create the directory for the result file, if necessary.------ @--- (all isUpper . 'Development.Shake.FilePath.takeBaseName') '?>' \\out -> do--- let src = 'Development.Shake.FilePath.replaceBaseName' out $ map toLower $ takeBaseName out--- 'Development.Shake.writeFile'' out . map toUpper =<< 'Development.Shake.readFile'' src--- @-(?>) :: (FilePath -> Bool) -> (FilePath -> Action ()) -> Rules ()-(?>) test act = priority 0.5 $ root "with ?>" test act----- | Define a set of patterns, and if any of them match, run the associated rule. Defined in terms of '*>'.--- Think of it as the OR (@||@) equivalent of '*>'.-(|*>) :: [FilePattern] -> (FilePath -> Action ()) -> Rules ()-(|*>) pats act = do- let (simp,other) = partition simple pats- case simp of- [] -> return ()- [p] -> root "with |*>" (\x -> toStandard x == p) act- ps -> let ps = Set.fromList pats in root "with |*>" (flip Set.member ps . toStandard) act- unless (null other) $- let ps = map (?==) other in priority 0.5 $ root "with |*>" (\x -> any ($ x) ps) act---- | Define a rule that matches a 'FilePattern', see '?==' for the pattern rules.--- Patterns with no wildcards have higher priority than those with wildcards, and no file--- required by the system may be matched by more than one pattern at the same priority--- (see 'priority' and 'alternatives' to modify this behaviour).--- This function will create the directory for the result file, if necessary.------ @--- \"*.asm.o\" '*>' \\out -> do--- let src = 'Development.Shake.FilePath.dropExtension' out--- 'need' [src]--- 'Development.Shake.cmd' \"as\" [src] \"-o\" [out]--- @------ To define a build system for multiple compiled languages, we recommend using @.asm.o@,--- @.cpp.o@, @.hs.o@, to indicate which language produces an object file.--- I.e., the file @foo.cpp@ produces object file @foo.cpp.o@.------ Note that matching is case-sensitive, even on Windows.-(*>) :: FilePattern -> (FilePath -> Action ()) -> Rules ()-(*>) test act = (if simple test then id else priority 0.5) $ root (show test) (test ?==) act
− Development/Shake/Rules/Files.hs
@@ -1,145 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}--module Development.Shake.Rules.Files(- (?>>), (*>>), (&?>), (&*>)- ) where--import Control.Monad-import Control.Monad.IO.Class-import Data.Maybe-import System.Directory--import Development.Shake.Core hiding (trackAllow)-import General.Base-import General.String-import Development.Shake.Classes-import Development.Shake.Rules.File-import Development.Shake.FilePattern-import Development.Shake.Types--import System.FilePath(takeDirectory) -- important that this is the system local filepath, or wrong slashes go wrong---infix 1 ?>>, *>>, &?>, &*>---- | /Deprecated:/ Alias for '&?>'.-(?>>) :: (FilePath -> Maybe [FilePath]) -> ([FilePath] -> Action ()) -> Rules ()-(?>>) = (&?>)---- | /Deprecated:/ Alias for '&*>'.-(*>>) :: [FilePattern] -> ([FilePath] -> Action ()) -> Rules ()-(*>>) = (&*>)----newtype FilesQ = FilesQ [FileQ]- deriving (Typeable,Eq,Hashable,Binary,NFData)----newtype FilesA = FilesA [FileA]- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show FilesA where show (FilesA xs) = unwords $ "Files" : map (drop 5 . show) xs--instance Show FilesQ where show (FilesQ xs) = unwords $ map (showQuote . show) xs---instance Rule FilesQ FilesA where- storedValue opts (FilesQ xs) = fmap (fmap FilesA . sequence) $ mapM (storedValue opts) xs- equalValue opts (FilesQ qs) (FilesA xs) (FilesA ys)- | let n = length qs in n /= length xs || n /= length ys = NotEqual- | otherwise = foldr and_ EqualCheap (zipWith3 (equalValue opts) qs xs ys)- where and_ NotEqual x = NotEqual- and_ EqualCheap x = x- and_ EqualExpensive x = if x == NotEqual then NotEqual else EqualExpensive----- | Define a rule for building multiple files at the same time.--- Think of it as the AND (@&&@) equivalent of '*>'.--- As an example, a single invocation of GHC produces both @.hi@ and @.o@ files:------ @--- [\"*.o\",\"*.hi\"] '&*>' \\[o,hi] -> do--- let hs = o 'Development.Shake.FilePath.-<.>' \"hs\"--- 'Development.Shake.need' ... -- all files the .hs import--- 'Development.Shake.cmd' \"ghc -c\" [hs]--- @------ However, in practice, it's usually easier to define rules with '*>' and make the @.hi@ depend--- on the @.o@. When defining rules that build multiple files, all the 'FilePattern' values must--- have the same sequence of @\/\/@ and @*@ wildcards in the same order.--- This function will create directories for the result files, if necessary.--- Think of it as the OR (@||@) equivalent of '*>'.-(&*>) :: [FilePattern] -> ([FilePath] -> Action ()) -> Rules ()-ps &*> act- | not $ compatible ps = error $- "All patterns to &*> must have the same number and position of // and * wildcards\n" ++- unwords ps- | otherwise = do- forM_ ps $ \p ->- p *> \file -> do- _ :: FilesA <- apply1 $ FilesQ $ map (FileQ . packU . substitute (extract p file)) ps- return ()- (if all simple ps then id else priority 0.5) $- rule $ \(FilesQ xs_) -> let xs = map (unpackU . fromFileQ) xs_ in- if not $ length xs == length ps && and (zipWith (?==) ps xs) then Nothing else Just $ do- liftIO $ mapM_ (createDirectoryIfMissing True) $ fastNub $ map takeDirectory xs- trackAllow xs- act xs- getFileTimes "&*>" xs_----- | Define a rule for building multiple files at the same time, a more powerful--- and more dangerous version of '&*>'. Think of it as the AND (@&&@) equivalent of '?>'.------ Given an application @test &?> ...@, @test@ should return @Just@ if the rule applies, and should--- return the list of files that will be produced. This list /must/ include the file passed as an argument and should--- obey the invariant:------ > forAll $ \x ys -> test x == Just ys ==> x `elem` ys && all ((== Just ys) . test) ys------ As an example of a function satisfying the invariaint:------ @---test x | 'Development.Shake.FilePath.takeExtension' x \`elem\` [\".hi\",\".o\"]--- = Just ['Development.Shake.FilePath.dropExtension' x 'Development.Shake.FilePath.<.>' \"hi\", 'Development.Shake.FilePath.dropExtension' x 'Development.Shake.FilePath.<.>' \"o\"]---test _ = Nothing--- @------ Regardless of whether @Foo.hi@ or @Foo.o@ is passed, the function always returns @[Foo.hi, Foo.o]@.-(&?>) :: (FilePath -> Maybe [FilePath]) -> ([FilePath] -> Action ()) -> Rules ()-(&?>) test act = priority 0.5 $ do- let checkedTest x = case test x of- Nothing -> Nothing- Just ys | x `elem` ys && all ((== Just ys) . test) ys -> Just ys- | otherwise -> error $ "Invariant broken in &?> when trying on " ++ x-- isJust . checkedTest ?> \x -> do- -- FIXME: Could optimise this test by calling rule directly and returning FileA Eq Eq Eq- -- But only saves noticable time on uncommon Change modes- _ :: FilesA <- apply1 $ FilesQ $ map (FileQ . packU) $ fromJust $ test x- return ()-- rule $ \(FilesQ xs_) -> let xs@(x:_) = map (unpackU . fromFileQ) xs_ in- case checkedTest x of- Just ys | ys == xs -> Just $ do- liftIO $ mapM_ (createDirectoryIfMissing True) $ fastNub $ map takeDirectory xs- act xs- getFileTimes "&?>" xs_- Just ys -> error $ "Error, &?> is incompatible with " ++ show xs ++ " vs " ++ show ys- Nothing -> Nothing---getFileTimes :: String -> [FileQ] -> Action FilesA-getFileTimes name xs = do- opts <- getShakeOptions- ys <- liftIO $ mapM (storedValue opts) xs- case sequence ys of- Just ys -> return $ FilesA ys- Nothing | not $ shakeCreationCheck opts -> return $ FilesA []- Nothing -> do- let missing = length $ filter isNothing ys- error $ "Error, " ++ name ++ " rule failed to build " ++ show missing ++- " file" ++ (if missing == 1 then "" else "s") ++ " (out of " ++ show (length xs) ++ ")" ++- concat ["\n " ++ unpackU x ++ if isNothing y then " - MISSING" else "" | (FileQ x,y) <- zip xs ys]
− Development/Shake/Rules/Oracle.hs
@@ -1,118 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}--- Allows the user to violate the functional dependency, but it has a runtime check so still safe-{-# LANGUAGE UndecidableInstances #-}--{-# LANGUAGE CPP #-}-#if __GLASGOW_HASKELL__ >= 704-{-# LANGUAGE ConstraintKinds #-}-#endif--module Development.Shake.Rules.Oracle(- addOracle, askOracle, askOracleWith- ) where--import Development.Shake.Core-import Development.Shake.Classes----- Use should type names, since the names appear in the Haddock, and are too long if they are in full-newtype OracleQ question = OracleQ question- deriving (Show,Typeable,Eq,Hashable,Binary,NFData)-newtype OracleA answer = OracleA answer- deriving (Show,Typeable,Eq,Hashable,Binary,NFData)--instance (-#if __GLASGOW_HASKELL__ >= 704- ShakeValue q, ShakeValue a-#else- Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,- Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a-#endif- ) => Rule (OracleQ q) (OracleA a) where- storedValue _ _ = return Nothing----- | Add extra information which rules can depend on.--- An oracle is a function from a question type @q@, to an answer type @a@.--- As an example, we can define an oracle allowing you to depend on the current version of GHC:------ @--- newtype GhcVersion = GhcVersion () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)--- rules = do--- 'addOracle' $ \\(GhcVersion _) -> fmap 'Development.Shake.fromStdout' $ 'Development.Shake.cmd' \"ghc --numeric-version\"--- ... rules ...--- @------ If a rule calls @'askOracle' (GhcVersion ())@, that rule will be rerun whenever the GHC version changes.--- Some notes:------ * We define @GhcVersion@ with a @newtype@ around @()@, allowing the use of @GeneralizedNewtypeDeriving@.--- All the necessary type classes are exported from "Development.Shake.Classes".------ * Each call to 'addOracle' must use a different type of question.------ * Actions passed to 'addOracle' will be run in every build they are required,--- but if their value does not change they will not invalidate any rules depending on them.--- To get a similar behaviour using data stored in files, see 'Development.Shake.alwaysRerun'.------ * If the value returned by 'askOracle' is ignored then 'askOracleWith' may help avoid ambiguous type messages.--- Alternatively, use the result of 'addOracle', which is 'askOracle' restricted to the correct type.------ As a more complex example, consider tracking Haskell package versions:------ @---newtype GhcPkgList = GhcPkgList () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)---newtype GhcPkgVersion = GhcPkgVersion String deriving (Show,Typeable,Eq,Hashable,Binary,NFData)------rules = do--- getPkgList \<- 'addOracle' $ \\GhcPkgList{} -> do--- Stdout out <- 'Development.Shake.cmd' \"ghc-pkg list --simple-output\"--- return [(reverse b, reverse a) | x <- words out, let (a,_:b) = break (== \'-\') $ reverse x]--- ----- getPkgVersion \<- 'addOracle' $ \\(GhcPkgVersion pkg) -> do--- pkgs <- getPkgList $ GhcPkgList ()--- return $ lookup pkg pkgs--- ----- \"myrule\" *> \\_ -> do--- getPkgVersion $ GhcPkgVersion \"shake\"--- ... rule using the shake version ...--- @------ Using these definitions, any rule depending on the version of @shake@--- should call @getPkgVersion $ GhcPkgVersion \"shake\"@ to rebuild when @shake@ is upgraded.-addOracle :: (-#if __GLASGOW_HASKELL__ >= 704- ShakeValue q, ShakeValue a-#else- Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,- Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a-#endif- ) => (q -> Action a) -> Rules (q -> Action a)-addOracle act = do- rule $ \(OracleQ q) -> Just $ fmap OracleA $ act q- return askOracle----- | Get information previously added with 'addOracle'. The question/answer types must match those provided--- to 'addOracle'.-askOracle :: (-#if __GLASGOW_HASKELL__ >= 704- ShakeValue q, ShakeValue a-#else- Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,- Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a-#endif- ) => q -> Action a-askOracle question = do OracleA answer <- apply1 $ OracleQ question; return answer---- | Get information previously added with 'addOracle'. The second argument is not used, but can--- be useful to fix the answer type, avoiding ambiguous type error messages.-askOracleWith :: (-#if __GLASGOW_HASKELL__ >= 704- ShakeValue q, ShakeValue a-#else- Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,- Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a-#endif- ) => q -> a -> Action a-askOracleWith question _ = askOracle question
− Development/Shake/Rules/OrderOnly.hs
@@ -1,55 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable #-}--module Development.Shake.Rules.OrderOnly(- defaultRuleOrderOnly, orderOnly, orderOnlyBS- ) where--import Development.Shake.Core-import General.String-import Development.Shake.Classes-import Development.Shake.Rules.File-import qualified Data.ByteString.Char8 as BS---newtype OrderOnlyQ = OrderOnlyQ BSU- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show OrderOnlyQ where show (OrderOnlyQ x) = unpackU x--newtype OrderOnlyA = OrderOnlyA ()- deriving (Typeable,Eq,Hashable,Binary,NFData)--instance Show OrderOnlyA where show (OrderOnlyA ()) = "OrderOnly"---instance Rule OrderOnlyQ OrderOnlyA where- storedValue _ (OrderOnlyQ _) = return $ Just $ OrderOnlyA ()---defaultRuleOrderOnly :: Rules ()-defaultRuleOrderOnly = rule $ \(OrderOnlyQ x) -> Just $ do- needBS [unpackU_ x]- return $ OrderOnlyA ()----- | Define order-only dependencies, these are dependencies that will always--- be built before continuing, but which aren't dependencies of this action.--- Mostly useful for defining generated dependencies you think might be real dependencies.--- If they turn out to be real dependencies, you should add an explicit dependency afterwards.------ @--- \"source.o\" *> \\out -> do--- 'orderOnly' [\"header.h\"]--- () <- 'cmd' \"gcc -c source.c -o source.o -MMD -MF source.m\"--- 'neededMakefileDependencies' \"source.m\"--- @------ If @header.h@ is included by @source.c@ then the call to 'needMakefileDependencies' will cause--- it to be added as a real dependency. If it isn't, then the rule won't rebuild if it changes,--- and you will have lost some opportunity for parallelism.-orderOnly :: [FilePath] -> Action ()-orderOnly xs = (apply $ map (OrderOnlyQ . packU) xs :: Action [OrderOnlyA]) >> return ()---orderOnlyBS :: [BS.ByteString] -> Action ()-orderOnlyBS xs = (apply $ map (OrderOnlyQ . packU_) xs :: Action [OrderOnlyA]) >> return ()
− Development/Shake/Rules/Rerun.hs
@@ -1,37 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}--module Development.Shake.Rules.Rerun(- defaultRuleRerun, alwaysRerun- ) where--import Development.Shake.Core-import Development.Shake.Classes---newtype AlwaysRerunQ = AlwaysRerunQ ()- deriving (Typeable,Eq,Hashable,Binary,NFData)-instance Show AlwaysRerunQ where show _ = "alwaysRerun"--newtype AlwaysRerunA = AlwaysRerunA ()- deriving (Typeable,Hashable,Binary,NFData)-instance Show AlwaysRerunA where show _ = "<none>"-instance Eq AlwaysRerunA where a == b = False--instance Rule AlwaysRerunQ AlwaysRerunA where- storedValue _ _ = return Nothing----- | Always rerun the associated action. Useful for defining rules that query--- the environment. For example:------ @--- \"ghcVersion.txt\" 'Development.Shake.*>' \\out -> do--- 'alwaysRerun'--- 'Development.Shake.Stdout' stdout <- 'Development.Shake.cmd' \"ghc --numeric-version\"--- 'Development.Shake.writeFileChanged' out stdout--- @-alwaysRerun :: Action ()-alwaysRerun = do AlwaysRerunA _ <- apply1 $ AlwaysRerunQ (); return ()--defaultRuleRerun :: Rules ()-defaultRuleRerun = rule $ \AlwaysRerunQ{} -> Just $ return $ AlwaysRerunA()
− Development/Shake/Shake.hs
@@ -1,29 +0,0 @@---- | The main entry point that calls all the default rules-module Development.Shake.Shake(shake) where--import Development.Shake.Types-import General.Timing-import Development.Shake.Core--import Development.Shake.Rules.Directory-import Development.Shake.Rules.File-import Development.Shake.Rules.OrderOnly-import Development.Shake.Rules.Rerun----- | Main entry point for running Shake build systems. For an example see the top of the module "Development.Shake".--- Use 'ShakeOptions' to specify how the system runs, and 'Rules' to specify what to build. The function will throw--- an exception if the build fails.------ To use command line flags to modify 'ShakeOptions' see 'Development.Shake.shakeArgs'.-shake :: ShakeOptions -> Rules () -> IO ()-shake opts r = do- addTiming "Function shake"- run opts $ do- r- defaultRuleFile- defaultRuleDirectory- defaultRuleOrderOnly- defaultRuleRerun- return ()
− Development/Shake/Special.hs
@@ -1,20 +0,0 @@---- | This module contains rule types that have special behaviour in some way.--- Everything in this module is a hack.-module Development.Shake.Special(- specialAlwaysRebuilds,- specialIsFileKey- ) where--import Development.Shake.Value-import Data.Typeable---specialAlwaysRebuilds :: Value -> Bool-specialAlwaysRebuilds v = con `elem` ["AlwaysRerunA","OracleA"] || (con == "FileA" && show v == "File {mod=NEQ,size=NEQ,digest=NEQ}")- where con = show $ fst $ splitTyConApp $ typeValue v---specialIsFileKey :: TypeRep -> Bool-specialIsFileKey t = con == "FileQ"- where con = show $ fst $ splitTyConApp t
− Development/Shake/Storage.hs
@@ -1,255 +0,0 @@-{-# LANGUAGE ScopedTypeVariables, PatternGuards, NamedFieldPuns, FlexibleInstances, MultiParamTypeClasses #-}-{--This module stores the meta-data so its very important its always accurate-We can't rely on getting any exceptions or termination at the end, so we'd better write out a journal-We store a series of records, and if they contain twice as many records as needed, we compress--}--module Development.Shake.Storage(- withStorage- ) where--import General.Binary-import General.Base-import General.Concurrent-import Development.Shake.Types-import General.Timing--import Control.Arrow-import Control.Exception as E-import Control.Monad-import Control.Concurrent-import Data.Binary.Get-import Data.Binary.Put-import Data.Time-import Data.Char-import Development.Shake.Classes-import qualified Data.HashMap.Strict as Map-import Data.List-import Numeric-import System.Directory-import System.Exit-import System.FilePath-import System.IO--import qualified Data.ByteString.Lazy.Char8 as LBS-import qualified Data.ByteString.Lazy as LBS8---type Map = Map.HashMap---- Increment every time the on-disk format/semantics change,--- @x@ is for the users version number-databaseVersion :: String -> String--- THINGS I WANT TO DO ON THE NEXT CHANGE--- * Change filepaths to store a 1 byte prefix saying 8bit ASCII or UTF8--- * Duration and Time should be stored as number of 1/10000th seconds Int32-databaseVersion x = "SHAKE-DATABASE-10-" ++ s ++ "\r\n"- where s = tail $ init $ show x -- call show, then take off the leading/trailing quotes- -- ensures we do not get \r or \n in the user portion---withStorage- :: (Show w, Show k, Show v, Eq w, Eq k, Hashable k- ,Binary w, BinaryWith w k, BinaryWith w v)- => ShakeOptions -- ^ Storage options- -> (String -> IO ()) -- ^ Logging function- -> w -- ^ Witness- -> (Map k v -> (k -> v -> IO ()) -> IO a) -- ^ Execute- -> IO a-withStorage ShakeOptions{shakeVerbosity,shakeOutput,shakeVersion,shakeFlush,shakeFiles,shakeStorageLog} diagnostic witness act = do- let dbfile = shakeFiles <.> "database"- bupfile = shakeFiles <.> "bup"- createDirectoryIfMissing True $ takeDirectory shakeFiles-- -- complete a partially failed compress- b <- doesFileExist bupfile- when b $ do- unexpected "Backup file exists, restoring over the previous file\n"- diagnostic $ "Backup file move to original"- E.catch (removeFile dbfile) (\(e :: SomeException) -> return ())- renameFile bupfile dbfile-- addTiming "Database read"- withBinaryFile dbfile ReadWriteMode $ \h -> do- n <- hFileSize h- diagnostic $ "Reading file of size " ++ show n- src <- LBS.hGet h $ fromInteger n-- if not $ ver `LBS.isPrefixOf` src then do- unless (LBS.null src) $ do- let limit x = let (a,b) = splitAt 200 x in a ++ (if null b then "" else "...")- let disp = map (\x -> if isPrint x && isAscii x then x else '?') . takeWhile (`notElem` "\r\n")- outputErr $ unlines- ["Error when reading Shake database - invalid version stamp detected:"- ," File: " ++ dbfile- ," Expected: " ++ disp (LBS.unpack ver)- ," Found: " ++ disp (limit $ LBS.unpack src)- ,"All rules will be rebuilt"]- continue h Map.empty- else- -- make sure you are not handling exceptions from inside- join $ handleJust (\e -> if asyncException e then Nothing else Just e) (\err -> do- msg <- showException err- outputErr $ unlines $- ("Error when reading Shake database " ++ dbfile) :- map (" "++) (lines msg) ++- ["All files will be rebuilt"]- when shakeStorageLog $ do- hSeek h AbsoluteSeek 0- i <- hFileSize h- bs <- LBS.hGet h $ fromInteger i- let cor = shakeFiles <.> "corrupt"- LBS.writeFile cor bs- unexpected $ "Backup of corrupted file stored at " ++ cor ++ ", " ++ show i ++ " bytes\n"- - -- exitFailure -- should never happen without external corruption- -- add back to check during random testing- return $ continue h Map.empty) $- case readChunks $ LBS.drop (LBS.length ver) src of- ([], slop) -> do- when (LBS.length slop > 0) $ unexpected $ "Last " ++ show slop ++ " bytes do not form a whole record\n"- diagnostic $ "Read 0 chunks, plus " ++ show slop ++ " slop"- return $ continue h Map.empty- (w:xs, slopRaw) -> do- let slop = fromIntegral $ LBS.length slopRaw- when (slop > 0) $ unexpected $ "Last " ++ show slop ++ " bytes do not form a whole record\n"- diagnostic $ "Read " ++ show (length xs + 1) ++ " chunks, plus " ++ show slop ++ " slop"- let ws = decode w- f mp (k, v) = Map.insert k v mp- ents = map (runGet $ getWith ws) xs- mp = foldl' f Map.empty ents-- when (shakeVerbosity == Diagnostic) $ do- let raw x = "[len " ++ show (LBS.length x) ++ "] " ++ concat- [['0' | length c == 1] ++ c | x <- LBS8.unpack x, let c = showHex x ""]- let pretty (Left x) = "FAILURE: " ++ show (x :: SomeException)- pretty (Right x) = x- diagnostic $ "Witnesses " ++ raw w- forM_ (zip3 [1..] xs ents) $ \(i,x,ent) -> do- x2 <- try $ evaluate $ let s = show ent in rnf s `seq` s- diagnostic $ "Chunk " ++ show i ++ " " ++ raw x ++ " " ++ pretty x2- diagnostic $ "Slop " ++ raw slopRaw-- diagnostic $ "Found " ++ show (Map.size mp) ++ " real entries"-- -- if mp is null, continue will reset it, so no need to clean up- if Map.null mp || (ws == witness && Map.size mp * 2 > length xs - 2) then do- -- make sure we reset to before the slop- when (not (Map.null mp) && slop /= 0) $ do- diagnostic $ "Dropping last " ++ show slop ++ " bytes of database (incomplete)"- now <- hFileSize h- hSetFileSize h $ now - slop- hSeek h AbsoluteSeek $ now - slop- hFlush h- diagnostic $ "Drop complete"- return $ continue h mp- else do- addTiming "Database compression"- unexpected "Compressing database\n"- diagnostic "Compressing database"- hClose h -- two hClose are fine- return $ do- renameFile dbfile bupfile- withBinaryFile dbfile ReadWriteMode $ \h -> do- reset h mp- removeFile bupfile- diagnostic "Compression complete"- continue h mp- where- unexpected x = when shakeStorageLog $ do- t <- getCurrentTime- appendFile (shakeFiles <.> "storage") $ "\n[" ++ show t ++ "]: " ++ x- outputErr x = do- when (shakeVerbosity >= Quiet) $ shakeOutput Quiet x- unexpected x-- ver = LBS.pack $ databaseVersion shakeVersion-- writeChunk h s = do- diagnostic $ "Writing chunk " ++ show (LBS.length s)- LBS.hPut h $ toChunk s-- reset h mp = do- diagnostic $ "Resetting database to " ++ show (Map.size mp) ++ " elements"- hSetFileSize h 0- hSeek h AbsoluteSeek 0- LBS.hPut h ver- writeChunk h $ encode witness- mapM_ (writeChunk h . runPut . putWith witness) $ Map.toList mp- hFlush h- diagnostic "Flush"-- -- continuation (since if we do a compress, h changes)- continue h mp = do- when (Map.null mp) $- reset h mp -- might as well, no data to lose, and need to ensure a good witness table- -- also lets us recover in the case of corruption- flushThread shakeFlush h $ \out -> do- addTiming "With database"- act mp $ \k v -> out $ toChunk $ runPut $ putWith witness (k, v)----- We avoid calling flush too often on SSD drives, as that can be slow--- Make sure all exceptions happen on the caller, so we don't have to move exceptions back--- Make sure we only write on one thread, otherwise async exceptions can cause partial writes-flushThread :: Maybe Double -> Handle -> ((LBS.ByteString -> IO ()) -> IO a) -> IO a-flushThread flush h act = do- chan <- newChan -- operations to perform on the file- kick <- newEmptyMVar -- kicked whenever something is written- died <- newBarrier -- has the writing thread finished-- flusher <- case flush of- Nothing -> return Nothing- Just flush -> fmap Just $ forkIO $ forever $ do- takeMVar kick- threadDelay $ ceiling $ flush * 1000000- tryTakeMVar kick- writeChan chan $ hFlush h >> return True-- root <- myThreadId- writer <- forkIO $ handle (\(e :: SomeException) -> signalBarrier died () >> throwTo root e) $- -- only one thread ever writes, ensuring only the final write can be torn- whileM $ join $ readChan chan-- (act $ \s -> do- evaluate $ LBS.length s -- ensure exceptions occur on this thread- writeChan chan $ LBS.hPut h s >> tryPutMVar kick () >> return True)- `finally` do- maybe (return ()) killThread flusher- writeChan chan $ signalBarrier died () >> return False- waitBarrier died----- Return the amount of junk at the end, along with all the chunk-readChunks :: LBS.ByteString -> ([LBS.ByteString], LBS.ByteString)-readChunks x- | Just (n, x) <- grab 4 x- , Just (y, x) <- grab (fromIntegral (decode n :: Word32)) x- = first (y :) $ readChunks x- | otherwise = ([], x)- where- grab i x | LBS.length a == i = Just (a, b)- | otherwise = Nothing- where (a,b) = LBS.splitAt i x---toChunk :: LBS.ByteString -> LBS.ByteString-toChunk x = n `LBS.append` x- where n = encode (fromIntegral $ LBS.length x :: Word32)----- Some exceptions may have an error message which is itself an exception,--- make sure you show them properly-showException :: SomeException -> IO String-showException err = do- let msg = show err- E.catch (evaluate $ rnf msg `seq` msg) (\(_ :: SomeException) -> return "Unknown exception (error while showing error message)")----- | Is the exception asyncronous, not a "coding error" that should be ignored-asyncException :: SomeException -> Bool-asyncException e- | Just (_ :: AsyncException) <- fromException e = True- | Just (_ :: ExitCode) <- fromException e = True- | otherwise = False
− Development/Shake/Types.hs
@@ -1,223 +0,0 @@-{-# LANGUAGE DeriveDataTypeable, PatternGuards #-}---- | Types exposed to the user-module Development.Shake.Types(- Progress(..), Verbosity(..), Assume(..), Lint(..), Change(..), EqualCost(..),- ShakeOptions(..), shakeOptions- ) where--import Data.Data-import Data.List-import Development.Shake.Progress-import qualified Data.ByteString.Char8 as BS----- | The current assumptions made by the build system, used by 'shakeAssume'. These options--- allow the end user to specify that any rules run are either to be treated as clean, or as--- dirty, regardless of what the build system thinks.------ These assumptions only operate on files reached by the current 'Development.Shake.action' commands. Any--- other files in the database are left unchanged.-data Assume- = AssumeDirty- -- ^ Assume that all rules reached are dirty and require rebuilding, equivalent to 'Development.Shake.storedValue' always- -- returning 'Nothing'. Useful to undo the results of 'AssumeClean', for benchmarking rebuild speed and- -- for rebuilding if untracked dependencies have changed. This assumption is safe, but may cause- -- more rebuilding than necessary.- | AssumeClean- -- ^ /This assumption is unsafe, and may lead to incorrect build results in this run, and in future runs/.- -- Assume and record that all rules reached are clean and do not require rebuilding, provided the rule- -- has a 'Development.Shake.storedValue' and has been built before. Useful if you have modified a file in some- -- inconsequential way, such as only the comments or whitespace, and wish to avoid a rebuild.- | AssumeSkip- -- ^ /This assumption is unsafe, and may lead to incorrect build results in this run/.- -- Assume that all rules reached are clean in this run. Only useful for benchmarking, to remove any overhead- -- from running 'Development.Shake.storedValue' operations.- deriving (Eq,Ord,Show,Data,Typeable,Bounded,Enum)----- | Which lint checks to perform, used by 'shakeLint'.-data Lint- = LintBasic- -- ^ The most basic form of linting. Checks that the current directory does not change and that results do not change after they- -- are first written. Any calls to 'needed' will assert that they do not cause a rule to be rebuilt.- | LintTracker- -- ^ Track which files are accessed by command line programs run by 'command' or 'cmd', using @tracker.exe@ as supplied- -- with the Microsoft .NET 4.5 SDK (Windows only). Also performs all checks from 'LintBasic'. Note that some programs are not- -- tracked properly, particularly cygwin programs (it seems).- deriving (Eq,Ord,Show,Data,Typeable,Bounded,Enum)----- | How should you determine if a file has changed, used by 'shakeChange'. The most common values are--- 'ChangeModtime' (very fast, @touch@ causes files to rebuild) and 'ChangeModtimeAndDigestInput'--- (a bit slower, @touch@ does not cause input files to rebuild).-data Change- = ChangeModtime- -- ^ Compare equality of modification timestamps, a file has changed if its last modified time changes.- -- A @touch@ will force a rebuild. This mode is fast and usually sufficiently accurate, so is the default.- | ChangeDigest- -- ^ Compare equality of file contents digests, a file has changed if its digest changes.- -- A @touch@ will not force a rebuild. Use this mode if modification times on your file system are unreliable.- | ChangeModtimeAndDigest- -- ^ A file is rebuilt if both its modification time and digest have changed. For efficiency reasons, the modification- -- time is checked first, and if that has changed, the digest is checked.- | ChangeModtimeAndDigestInput- -- ^ Use 'ChangeModtimeAndDigest' for input\/source files and 'ChangeModtime' for output files.- | ChangeModtimeOrDigest- -- ^ A file is rebuilt if either its modification time or its digest has changed. A @touch@ will force a rebuild,- -- but even if a files modification time is reset afterwards, changes will also cause a rebuild.- deriving (Eq,Ord,Show,Data,Typeable,Bounded,Enum)----- | Options to control the execution of Shake, usually specified by overriding fields in--- 'shakeOptions':------ @ 'shakeOptions'{'shakeThreads'=4, 'shakeReport'=[\"report.html\"]} @------ The 'Data' instance for this type reports the 'shakeProgress' and 'shakeOutput' fields as having the abstract type 'Function',--- because 'Data' cannot be defined for functions.-data ShakeOptions = ShakeOptions- {shakeFiles :: FilePath- -- ^ Defaults to @.shake@. The prefix of the filename used for storing Shake metadata files.- -- All metadata files will be named @'shakeFiles'./extension/@, for some @/extension/@.- -- If the 'shakeFiles' directory does not exist it will be created.- ,shakeThreads :: Int- -- ^ Defaults to @1@. Maximum number of rules to run in parallel, similar to @make --jobs=/N/@.- -- For many build systems, a number equal to or slightly less than the number of physical processors- -- works well.- ,shakeVersion :: String- -- ^ Defaults to @"1"@. The version number of your build rules.- -- Change the version number to force a complete rebuild, such as when making- -- significant changes to the rules that require a wipe. The version number should be- -- set in the source code, and not passed on the command line.- ,shakeVerbosity :: Verbosity- -- ^ Defaults to 'Normal'. What level of messages should be printed out.- ,shakeStaunch :: Bool- -- ^ Defaults to 'False'. Operate in staunch mode, where building continues even after errors,- -- similar to @make --keep-going@.- ,shakeReport :: [FilePath]- -- ^ Defaults to @[]@. Write a profiling report to a file, showing which rules rebuilt,- -- why, and how much time they took. Useful for improving the speed of your build systems.- -- If the file extension is @.json@ it will write JSON data; if @.js@ it will write Javascript;- -- if @.trace@ it will write trace events (load into @about:\/\/tracing@ in Chrome);- -- otherwise it will write HTML.- ,shakeLint :: Maybe Lint- -- ^ Defaults to 'Nothing'. Perform sanity checks during building, see 'Lint' for details.- ,shakeFlush :: Maybe Double- -- ^ Defaults to @'Just' 10@. How often to flush Shake metadata files in seconds, or 'Nothing' to never flush explicitly.- -- It is possible that on abnormal termination (not Haskell exceptions) any rules that completed in the last- -- 'shakeFlush' seconds will be lost.- ,shakeAssume :: Maybe Assume- -- ^ Defaults to 'Nothing'. Assume all build objects are clean/dirty, see 'Assume' for details.- -- Can be used to implement @make --touch@.- ,shakeAbbreviations :: [(String,String)]- -- ^ Defaults to @[]@. A list of substrings that should be abbreviated in status messages, and their corresponding abbreviation.- -- Commonly used to replace the long paths (e.g. @.make\/i586-linux-gcc\/output@) with an abbreviation (e.g. @$OUT@).- ,shakeStorageLog :: Bool- -- ^ Defaults to 'False'. Write a message to @'shakeFiles'.storage@ whenever a storage event happens which may impact- -- on the current stored progress. Examples include database version number changes, database compaction or corrupt files.- ,shakeLineBuffering :: Bool- -- ^ Defaults to 'True'. Change 'stdout' and 'stderr' to line buffering while running Shake.- ,shakeTimings :: Bool- -- ^ Defaults to 'False'. Print timing information for each stage at the end.- ,shakeRunCommands :: Bool- -- ^ Default to 'True'. Should you run command line actions, set to 'False' to skip actions whose output streams and exit code- -- are not used. Useful for profiling the non-command portion of the build system.- ,shakeChange :: Change- -- ^ Default to 'ChangeModtime'. How to check if a file has changed, see 'Change' for details.- ,shakeCreationCheck :: Bool- -- ^ Default to 'True'. After running a rule to create a file, is it an error if the file does not exist.- -- Provided for compatibility with @make@ and @ninja@ (which have ugly file creation semantics).- ,shakeLiveFiles :: [FilePath]- -- ^ Default to '[]'. After the build system completes, write a list of all files which were /live/ in that run,- -- i.e. those which Shake checked were valid or rebuilt. Produces best answers if nothing rebuilds.- ,shakeProgress :: IO Progress -> IO ()- -- ^ Defaults to no action. A function called when the build starts, allowing progress to be reported.- -- The function is called on a separate thread, and that thread is killed when the build completes.- -- For applications that want to display progress messages, 'progressSimple' is often sufficient, but more advanced- -- users should look at the 'Progress' data type.- ,shakeOutput :: Verbosity -> String -> IO ()- -- ^ Defaults to writing using 'putStrLn'. A function called to output messages from Shake, along with the 'Verbosity' at- -- which that message should be printed. This function will be called atomically from all other 'shakeOutput' functions.- -- The 'Verbosity' will always be greater than or higher than 'shakeVerbosity'.- }- deriving Typeable---- | The default set of 'ShakeOptions'.-shakeOptions :: ShakeOptions-shakeOptions = ShakeOptions- ".shake" 1 "1" Normal False [] Nothing (Just 10) Nothing [] False True False- True ChangeModtime True []- (const $ return ())- (const $ BS.putStrLn . BS.pack) -- try and output atomically using BS--fieldsShakeOptions =- ["shakeFiles", "shakeThreads", "shakeVersion", "shakeVerbosity", "shakeStaunch", "shakeReport"- ,"shakeLint", "shakeFlush", "shakeAssume", "shakeAbbreviations", "shakeStorageLog"- ,"shakeLineBuffering", "shakeTimings", "shakeRunCommands", "shakeChange", "shakeCreationCheck"- ,"shakeLiveFiles","shakeProgress", "shakeOutput"]-tyShakeOptions = mkDataType "Development.Shake.Types.ShakeOptions" [conShakeOptions]-conShakeOptions = mkConstr tyShakeOptions "ShakeOptions" fieldsShakeOptions Prefix-unhide x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 =- ShakeOptions x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 (fromFunction x18) (fromFunction x19)--instance Data ShakeOptions where- gfoldl k z (ShakeOptions x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19) =- z unhide `k` x1 `k` x2 `k` x3 `k` x4 `k` x5 `k` x6 `k` x7 `k` x8 `k` x9 `k` x10 `k` x11 `k`- x12 `k` x13 `k` x14 `k` x15 `k` x16 `k` x17 `k`- Function x18 `k` Function x19- gunfold k z c = k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ z unhide- toConstr ShakeOptions{} = conShakeOptions- dataTypeOf _ = tyShakeOptions--instance Show ShakeOptions where- show x = "ShakeOptions {" ++ intercalate ", " inner ++ "}"- where- inner = zipWith (\x y -> x ++ " = " ++ y) fieldsShakeOptions $ gmapQ f x-- f x | Just x <- cast x = show (x :: Int)- | Just x <- cast x = show (x :: FilePath)- | Just x <- cast x = show (x :: Verbosity)- | Just x <- cast x = show (x :: Change)- | Just x <- cast x = show (x :: Bool)- | Just x <- cast x = show (x :: [FilePath])- | Just x <- cast x = show (x :: Maybe Assume)- | Just x <- cast x = show (x :: Maybe Lint)- | Just x <- cast x = show (x :: Maybe Double)- | Just x <- cast x = show (x :: [(String,String)])- | Just x <- cast x = show (x :: Function (IO Progress -> IO ()))- | Just x <- cast x = show (x :: Function (Verbosity -> String -> IO ()))- | otherwise = error $ "Error while showing ShakeOptions, missing alternative for " ++ show (typeOf x)----- | Internal type, copied from Hide in Uniplate-newtype Function a = Function {fromFunction :: a}- deriving Typeable--instance Show (Function a) where show _ = "<function>"--instance Typeable a => Data (Function a) where- gfoldl k z x = z x- gunfold k z c = error "Development.Shake.Types.ShakeProgress: gunfold not implemented - data type has no constructors"- toConstr _ = error "Development.Shake.Types.ShakeProgress: toConstr not implemented - data type has no constructors"- dataTypeOf _ = tyFunction--tyFunction = mkDataType "Development.Shake.Types.Function" []----- | The verbosity data type, used by 'shakeVerbosity'.-data Verbosity- = Silent -- ^ Don't print any messages.- | Quiet -- ^ Only print essential messages, typically errors.- | Normal -- ^ Print errors and @# /command-name/ (for /file-name/)@ when running a 'Development.Shake.traced' command.- | Loud -- ^ Print errors and full command lines when running a 'Development.Shake.command' or 'Development.Shake.cmd' command.- | Chatty -- ^ Print errors, full command line and status messages when starting a rule.- | Diagnostic -- ^ Print messages for virtually everything (mostly for debugging).- deriving (Eq,Ord,Bounded,Enum,Show,Read,Typeable,Data)---- | An equality check and a cost.-data EqualCost- = EqualCheap -- ^ The equality check was cheap.- | EqualExpensive -- ^ The equality check was expensive, as the results are not trivially equal.- | NotEqual -- ^ The values are not equal.- deriving (Eq,Ord,Bounded,Enum,Show,Read,Typeable,Data)
− Development/Shake/Util.hs
@@ -1,60 +0,0 @@---- | A module for useful utility functions for Shake build systems.-module Development.Shake.Util(- parseMakefile, needMakefileDependencies, neededMakefileDependencies,- shakeArgsAccumulate- ) where--import Development.Shake-import Development.Shake.Rules.File-import qualified Data.ByteString.Char8 as BS-import qualified Development.Shake.ByteString as BS-import Control.Arrow-import Data.List-import System.Console.GetOpt----- | Given the text of a Makefile, extract the list of targets and dependencies. Assumes a--- small subset of Makefile syntax, mostly that generated by @gcc -MM@.------ > parseMakefile "a: b c\nd : e" == [("a",["b","c"]),("d",["e"])]-parseMakefile :: String -> [(FilePath, [FilePath])]-parseMakefile = map (BS.unpack *** map BS.unpack) . BS.parseMakefile . BS.pack----- | Depend on the dependencies listed in a Makefile. Does not depend on the Makefile itself.------ > needMakefileDependencies file = need . concatMap snd . parseMakefile =<< liftIO (readFile file)-needMakefileDependencies :: FilePath -> Action ()-needMakefileDependencies file = needBS . concatMap snd . BS.parseMakefile =<< liftIO (BS.readFile file)----- | Depend on the dependencies listed in a Makefile. Does not depend on the Makefile itself.--- Use this function to indicate that you have /already/ used the files in question.------ > neededMakefileDependencies file = needed . concatMap snd . parseMakefile =<< liftIO (readFile file)-neededMakefileDependencies :: FilePath -> Action ()-neededMakefileDependencies file = neededBS . concatMap snd . BS.parseMakefile =<< liftIO (BS.readFile file)----- | Like `shakeArgsWith`, but instead of accumulating a list of flags, apply functions to a default value.--- Usually used to populate a record structure. As an example of a build system that can use either @gcc@ or @distcc@ for compiling:------ @---import System.Console.GetOpt------data Flags = Flags {distCC :: Bool} deriving Eq---flags = [Option \"\" [\"distcc\"] (NoArg $ Right $ \\x -> x{distCC=True}) \"Run distributed.\"]------main = 'shakeArgsAccumulate' 'shakeOptions' flags (Flags False) $ \\flags targets -> return $ Just $ do--- if null targets then 'want' [\"result.exe\"] else 'want' targets--- let compiler = if distCC flags then \"distcc\" else \"gcc\"--- \"*.o\" '*>' \\out -> do--- 'need' ...--- 'cmd' compiler ...--- ...--- @------ Now you can pass @--distcc@ to use the @distcc@ compiler.-shakeArgsAccumulate :: ShakeOptions -> [OptDescr (Either String (a -> a))] -> a -> (a -> [String] -> IO (Maybe (Rules ()))) -> IO ()-shakeArgsAccumulate opts flags def f = shakeArgsWith opts flags $ \flags targets -> f (foldl' (flip ($)) def flags) targets
− Development/Shake/Value.hs
@@ -1,138 +0,0 @@-{-# LANGUAGE ExistentialQuantification, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}--{- |-This module implements the Key/Value types, to abstract over hetrogenous data types.--}-module Development.Shake.Value(- Value, newValue, fromValue, typeValue,- Key, newKey, fromKey, typeKey,- Witness, currentWitness, registerWitness- ) where--import General.Binary-import Development.Shake.Classes-import Development.Shake.Errors-import Data.Typeable--import Data.Bits-import Data.Function-import Data.IORef-import Data.List-import Data.Maybe-import qualified Data.HashMap.Strict as Map-import qualified Data.ByteString.Char8 as BS-import System.IO.Unsafe----- We deliberately avoid Typeable instances on Key/Value to stop them accidentally--- being used inside themselves-newtype Key = Key Value- deriving (Eq,Hashable,NFData,BinaryWith Witness)--data Value = forall a . (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => Value a---newKey :: (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => a -> Key-newKey = Key . newValue--newValue :: (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => a -> Value-newValue = Value--typeKey :: Key -> TypeRep-typeKey (Key v) = typeValue v--typeValue :: Value -> TypeRep-typeValue (Value x) = typeOf x--fromKey :: Typeable a => Key -> a-fromKey (Key v) = fromValue v--fromValue :: Typeable a => Value -> a-fromValue (Value x) = fromMaybe (err "fromValue, bad cast") $ cast x--instance Show Key where- show (Key a) = show a--instance Show Value where- show (Value a) = show a--instance NFData Value where- rnf (Value a) = rnf a--instance Hashable Value where- hashWithSalt salt (Value a) = hashWithSalt salt (typeOf a) `xor` hashWithSalt salt a--instance Eq Value where- Value a == Value b = maybe False (a ==) $ cast b- Value a /= Value b = maybe True (a /=) $ cast b--------------------------------------------------------------------------- BINARY INSTANCES--{-# NOINLINE witness #-}-witness :: IORef (Map.HashMap TypeRep Value)-witness = unsafePerformIO $ newIORef Map.empty--registerWitness :: (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => a -> IO ()-registerWitness x = atomicModifyIORef witness $ \mp -> (Map.insert (typeOf x) (Value $ err msg `asTypeOf` x) mp, ())- where msg = "registerWitness, type " ++ show (typeOf x)----- Produce a list in a predictable order from a Map TypeRep, which should be consistent regardless of the order--- elements were added and stable between program executions.--- Cannot rely on hash (not pure in hashable-1.2) or compare (not available before 7.2)-toStableList :: Map.HashMap TypeRep v -> [(TypeRep,v)]-toStableList = sortBy (compare `on` show . fst) . Map.toList---data Witness = Witness- {typeNames :: [String] -- the canonical data, the names of the types- ,witnessIn :: Map.HashMap Word16 Value -- for reading in, the find the values (some may be missing)- ,witnessOut :: Map.HashMap TypeRep Word16 -- for writing out, find the value- } deriving Show--instance Eq Witness where- -- Type names are produced by toStableList so should to remain consistent- -- regardless of the order of registerWitness calls.- a == b = typeNames a == typeNames b--currentWitness :: IO Witness-currentWitness = do- ws <- readIORef witness- let (ks,vs) = unzip $ toStableList ws- return $ Witness (map show ks) (Map.fromList $ zip [0..] vs) (Map.fromList $ zip ks [0..])---instance Binary Witness where- put (Witness ts _ _) = put $ BS.unlines $ map BS.pack ts- get = do- ts <- fmap (map BS.unpack . BS.lines) get- let ws = toStableList $ unsafePerformIO $ readIORefAfter ts witness- let (is,ks,vs) = unzip3 [(i,k,v) | (i,t) <- zip [0..] ts, (k,v):_ <- [filter ((==) t . show . fst) ws]]- return $ Witness ts (Map.fromList $ zip is vs) (Map.fromList $ zip ks is)- where- -- Read an IORef after examining a variable, used to avoid GHC over-optimisation- {-# NOINLINE readIORefAfter #-}- readIORefAfter :: a -> IORef b -> IO b- readIORefAfter v ref = v `seq` readIORef ref---instance BinaryWith Witness Value where- putWith ws (Value x) = do- let msg = "no witness for " ++ show (typeOf x)- put $ fromMaybe (error msg) $ Map.lookup (typeOf x) (witnessOut ws)- put x-- getWith ws = do- h <- get- case Map.lookup h $ witnessIn ws of- Nothing | h >= 0 && h < genericLength (typeNames ws) -> error $- "Failed to find a type " ++ (typeNames ws !! fromIntegral h) ++ " which is stored in the database.\n" ++- "The most likely cause is that your build tool has changed significantly."- Nothing -> error $- -- should not happen, unless proper data corruption- "Corruption when reading Value, got type " ++ show h ++ ", but should be in range 0.." ++ show (length (typeNames ws) - 1)- Just (Value t) -> do- x <- get- return $ Value $ x `asTypeOf` t
− General/Base.hs
@@ -1,312 +0,0 @@-{-# LANGUAGE BangPatterns, CPP, ScopedTypeVariables #-}--module General.Base(- Duration, duration, Time, diffTime, offsetTime, offsetTimeIncrease, sleep,- intToDouble, floatToDouble, doubleToFloat,- isWindows, getProcessorCount,- readFileStrict, readFileUCS2, getEnvMaybe, captureOutput, getExePath,- randomElem,- showDP, showTime,- modifyIORef'', writeIORef'',- isLeft_, isRight_,- swap,- whenJust, loopM, whileM, partitionM, concatMapM, mapMaybeM, liftA2', retry,- ifM, notM, (&&^), (||^),- fastNub, showQuote, word1,- withBufferMode, withCapabilities- ) where--import Control.Applicative-import Control.Arrow-import Control.Concurrent-import Control.Exception as E-import Control.Monad-import Data.Char-import Data.IORef-import Data.List-import Data.Maybe-import Data.Time-import qualified Data.HashSet as Set-import Numeric-import System.Directory-import System.Environment-import System.IO-import System.IO.Error-import System.IO.Unsafe-import System.Random-import GHC.IO.Handle(hDuplicate,hDuplicateTo)-import Development.Shake.Classes-import Foreign.C.Types--------------------------------------------------------------------------- Data.Time--type Time = Double -- how far you are through this run, in seconds--diffTime :: UTCTime -> UTCTime -> Duration-diffTime end start = fromRational $ toRational $ end `diffUTCTime` start---- | Call once at the start, then call repeatedly to get Time values out-offsetTime :: IO (IO Time)-offsetTime = do- start <- getCurrentTime- return $ do- end <- getCurrentTime- return $ diffTime end start---- | Like offsetTime, but results will never decrease (though they may stay the same)-offsetTimeIncrease :: IO (IO Time)-offsetTimeIncrease = do- t <- offsetTime- ref <- newIORef 0- return $ do- t <- t- atomicModifyIORef ref $ \o -> let m = max t o in m `seq` (m, m)---type Duration = Double -- duration in seconds--duration :: IO a -> IO (Duration, a)-duration act = do- time <- offsetTime- res <- act- time <- time- return (time, res)---sleep :: Duration -> IO ()-sleep x = threadDelay $ ceiling $ x * 1000000--------------------------------------------------------------------------- Numeric--intToDouble :: Int -> Double-intToDouble = fromInteger . toInteger--floatToDouble :: Float -> Double-floatToDouble = fromRational . toRational--doubleToFloat :: Double -> Float-doubleToFloat = fromRational . toRational--------------------------------------------------------------------------- Data.IORef---- Two 's because GHC 7.6 has a strict modifyIORef-modifyIORef'' :: IORef a -> (a -> a) -> IO ()-modifyIORef'' ref f = do- x <- readIORef ref- writeIORef'' ref $ f x--writeIORef'' :: IORef a -> a -> IO ()-writeIORef'' ref !x = writeIORef ref x--------------------------------------------------------------------------- Data.List---- | Like 'nub', but the results may be in any order.-fastNub :: (Eq a, Hashable a) => [a] -> [a]-fastNub = f Set.empty- where f seen [] = []- f seen (x:xs) | x `Set.member` seen = f seen xs- | otherwise = x : f (Set.insert x seen) xs---showQuote :: String -> String-showQuote xs | any isSpace xs = "\"" ++ concatMap (\x -> if x == '\"' then "\"\"" else [x]) xs ++ "\""- | otherwise = xs---word1 :: String -> (String, String)-word1 x = second (dropWhile isSpace) $ break isSpace $ dropWhile isSpace x--------------------------------------------------------------------------- Data.String--showDP :: RealFloat a => Int -> a -> String-showDP n x = a ++ (if n > 0 then "." else "") ++ b ++ replicate (n - length b) '0'- where (a,b) = second (drop 1) $ break (== '.') $ showFFloat (Just n) x ""--showTime :: Double -> String-showTime x | x >= 3600 = f (x / 60) "h" "m"- | x >= 60 = f x "m" "s"- | otherwise = showDP 2 x ++ "s"- where- f x m s = show ms ++ m ++ ['0' | ss < 10] ++ show ss ++ m- where (ms,ss) = round x `divMod` 60--------------------------------------------------------------------------- Data.Either--isLeft_, isRight_ :: Either a b -> Bool-isLeft_ Left{} = True; isLeft_ Right{} = False-isRight_ = not . isLeft_--------------------------------------------------------------------------- Data.Tuple--swap :: (a, b) -> (b, a)-swap (a, b) = (b, a)--------------------------------------------------------------------------- Control.Monad--whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()-whenJust (Just a) f = f a-whenJust Nothing f = return ()--loopM :: Monad m => (a -> m (Either a b)) -> a -> m b-loopM act x = do- res <- act x- case res of- Left x -> loopM act x- Right v -> return v--whileM :: Monad m => m Bool -> m ()-whileM act = do- b <- act- when b $ whileM act--concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]-concatMapM f xs = liftM concat $ mapM f xs--partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])-partitionM f [] = return ([], [])-partitionM f (x:xs) = do- t <- f x- (a,b) <- partitionM f xs- return $ if t then (x:a,b) else (a,x:b)--mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b]-mapMaybeM f xs = liftM catMaybes $ mapM f xs--liftA2' :: Applicative m => m a -> m b -> (a -> b -> c) -> m c-liftA2' a b f = liftA2 f a b--ifM :: Monad m => m Bool -> m a -> m a -> m a-ifM b t f = do b <- b; if b then t else f--notM :: Functor m => m Bool -> m Bool-notM = fmap not--(||^), (&&^) :: Monad m => m Bool -> m Bool -> m Bool-(||^) a b = do a <- a; if a then return True else b-(&&^) a b = do a <- a; if a then b else return False--retry :: Int -> IO a -> IO a-retry i x | i <= 0 = error "retry count must be 1 or more"-retry 1 x = x-retry i x = do- res <- E.try x- case res of- Left (e :: SomeException) -> do- putStrLn $ "Retrying after exception: " ++ show e- retry (i-1) x- Right v -> return v--------------------------------------------------------------------------- System.Info--isWindows :: Bool-#if defined(mingw32_HOST_OS)-isWindows = True-#else-isWindows = False-#endif----- Use the underlying GHC function-foreign import ccall getNumberOfProcessors :: IO CInt---{-# NOINLINE getProcessorCount #-}-getProcessorCount :: IO Int--- unsafePefromIO so we cache the result and only compute it once-getProcessorCount = let res = unsafePerformIO act in return res- where- act =- if rtsSupportsBoundThreads then- fromIntegral <$> getNumberOfProcessors- else- handle (\(_ :: SomeException) -> return 1) $ do- env <- getEnvMaybe "NUMBER_OF_PROCESSORS"- case env of- Just s | [(i,"")] <- reads s -> return i- _ -> do- src <- readFile "/proc/cpuinfo"- return $ length [() | x <- lines src, "processor" `isPrefixOf` x]--------------------------------------------------------------------------- System.IO--readFileStrict :: FilePath -> IO String-readFileStrict file = withFile file ReadMode $ \h -> do- src <- hGetContents h- evaluate $ length src- return src--readFileUCS2 :: FilePath -> IO String-readFileUCS2 name = openFile name ReadMode >>= \h -> do- hSetEncoding h utf16- hGetContents h--getEnvMaybe :: String -> IO (Maybe String)-getEnvMaybe x = catchJust (\x -> if isDoesNotExistError x then Just x else Nothing) (fmap Just $ getEnv x) (const $ return Nothing)--captureOutput :: IO () -> IO String-captureOutput act = do- tmp <- getTemporaryDirectory- (f,h) <- openTempFile tmp "hlint"- sto <- hDuplicate stdout- ste <- hDuplicate stderr- hDuplicateTo h stdout- hDuplicateTo h stderr- hClose h- act- hDuplicateTo sto stdout- hDuplicateTo ste stderr- res <- readFile f- evaluate $ length res- removeFile f- return res--withCapabilities :: Int -> IO a -> IO a-#if __GLASGOW_HASKELL__ >= 706-withCapabilities new act | rtsSupportsBoundThreads = do- old <- getNumCapabilities- if old == new then act else- bracket_ (setNumCapabilities new) (setNumCapabilities old) act-#endif-withCapabilities new act = act--withBufferMode :: Handle -> BufferMode -> IO a -> IO a-withBufferMode h b act = bracket (hGetBuffering h) (hSetBuffering h) $ const $ do- hSetBuffering h LineBuffering- act---getExePath :: IO FilePath-#if __GLASGOW_HASKELL__ >= 706-getExePath = getExecutablePath-#else-getExePath = getProgName-#endif--------------------------------------------------------------------------- System.Random--randomElem :: [a] -> IO a-randomElem xs = do- i <- randomRIO (0, length xs - 1)- return $ xs !! i
− General/Bilist.hs
@@ -1,33 +0,0 @@--module General.Bilist(- Bilist, cons, snoc, uncons, toList, isEmpty- ) where--import Data.Monoid---data Bilist a = Bilist [a] [a]--toList :: Bilist a -> [a]-toList (Bilist as bs) = as ++ reverse bs--isEmpty :: Bilist a -> Bool-isEmpty (Bilist as bs) = null as && null bs--instance Eq a => Eq (Bilist a) where- a == b = toList a == toList b--instance Monoid (Bilist a) where- mempty = Bilist [] []- mappend a b = Bilist (toList a ++ toList b) []--cons :: a -> Bilist a -> Bilist a-cons x (Bilist as bs) = Bilist (x:as) bs--snoc :: Bilist a -> a -> Bilist a-snoc (Bilist as bs) x = Bilist as (x:bs)--uncons :: Bilist a -> Maybe (a, Bilist a)-uncons (Bilist [] []) = Nothing-uncons (Bilist (a:as) bs) = Just (a, Bilist as bs)-uncons (Bilist [] bs) = uncons $ Bilist (reverse bs) []
− General/Binary.hs
@@ -1,63 +0,0 @@-{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}--module General.Binary(- BinaryWith(..), module Data.Binary,- BinList(..), BinFloat(..)- ) where--import Control.Applicative-import Control.Monad-import Data.Binary-import Data.List-import Foreign-import System.IO.Unsafe as U---class BinaryWith ctx a where- putWith :: ctx -> a -> Put- getWith :: ctx -> Get a--instance (BinaryWith ctx a, BinaryWith ctx b) => BinaryWith ctx (a,b) where- putWith ctx (a,b) = putWith ctx a >> putWith ctx b- getWith ctx = liftA2 (,) (getWith ctx) (getWith ctx)--instance BinaryWith ctx a => BinaryWith ctx [a] where- putWith ctx xs = put (length xs) >> mapM_ (putWith ctx) xs- getWith ctx = do n <- get; replicateM n $ getWith ctx--instance BinaryWith ctx a => BinaryWith ctx (Maybe a) where- putWith ctx Nothing = putWord8 0- putWith ctx (Just x) = putWord8 1 >> putWith ctx x- getWith ctx = do i <- getWord8; if i == 0 then return Nothing else fmap Just $ getWith ctx---newtype BinList a = BinList {fromBinList :: [a]}--instance Show a => Show (BinList a) where show = show . fromBinList--instance Binary a => Binary (BinList a) where- put (BinList xs) = case splitAt 254 xs of- (a, []) -> putWord8 (genericLength xs) >> mapM_ put xs- (a, b) -> putWord8 255 >> mapM_ put a >> put (BinList b)- get = do- x <- getWord8- case x of- 255 -> do xs <- replicateM 254 get; BinList ys <- get; return $ BinList $ xs ++ ys- n -> fmap BinList $ replicateM (fromInteger $ toInteger n) get---newtype BinFloat = BinFloat {fromBinFloat :: Float}--instance Show BinFloat where show = show . fromBinFloat--instance Binary BinFloat where- put (BinFloat x) = put (convert x :: Word32)- get = fmap (BinFloat . convert) (get :: Get Word32)----- Originally from data-binary-ieee754 package--convert :: (Storable a, Storable b) => a -> b-convert x = U.unsafePerformIO $ alloca $ \buf -> do- poke (castPtr buf) x- peek buf
− General/Cleanup.hs
@@ -1,35 +0,0 @@---- | Code for ensuring cleanup actions are run.-module General.Cleanup(- Cleanup, withCleanup, addCleanup- ) where--import Control.Exception as E-import Control.Monad-import qualified Data.HashMap.Strict as Map-import Data.IORef---data S = S {unique :: !Int, items :: Map.HashMap Int (IO ())}--newtype Cleanup = Cleanup (IORef S)----- | Run with some cleanup scope. Regardless of exceptions/threads, all 'addCleanup' actions--- will be run by the time it exits.-withCleanup :: (Cleanup -> IO a) -> IO a-withCleanup act = do- ref <- newIORef $ S 0 Map.empty- act (Cleanup ref) `finally` do- join $ atomicModifyIORef ref $ \s -> (s{items=Map.empty}, sequence_ $ Map.elems $ items s)----- | Add a cleanup action to a 'Cleanup' scope. If the return action is not run by the time--- 'withCleanup' terminates then it will be run then. The argument 'Bool' is 'True' to say--- run the action, 'False' to say ignore the action (and never run it).-addCleanup :: Cleanup -> IO () -> IO (Bool -> IO ())-addCleanup (Cleanup ref) act = atomicModifyIORef ref $ \s -> let i = unique s in- (,) (S (unique s + 1) (Map.insert i act $ items s)) $ \b -> do- join $ atomicModifyIORef ref $ \s -> case Map.lookup i $ items s of- Nothing -> (s, return ())- Just act -> (s{items = Map.delete i $ items s}, when b act)
− General/Concurrent.hs
@@ -1,106 +0,0 @@--module General.Concurrent(- Lock, newLock, withLock, withLockTry,- Var, newVar, readVar, modifyVar, modifyVar_, withVar,- Barrier, newBarrier, signalBarrier, waitBarrier, waitBarrierMaybe,- Fence, newFence, signalFence, waitFence, testFence,- ) where--import Control.Applicative-import Control.Concurrent-import Control.Exception-import Control.Monad-import Data.IORef-import General.Base--------------------------------------------------------------------------- LOCK---- | Like an MVar, but has no value-newtype Lock = Lock (MVar ())-instance Show Lock where show _ = "Lock"--newLock :: IO Lock-newLock = fmap Lock $ newMVar ()--withLock :: Lock -> IO a -> IO a-withLock (Lock x) = withMVar x . const--withLockTry :: Lock -> IO a -> IO (Maybe a)-withLockTry (Lock m) act =- mask $ \restore -> do- a <- tryTakeMVar m- case a of- Nothing -> return Nothing- Just _ -> restore (fmap Just act) `finally` putMVar m ()--------------------------------------------------------------------------- VAR---- | Like an MVar, but must always be full-newtype Var a = Var (MVar a)-instance Show (Var a) where show _ = "Var"--newVar :: a -> IO (Var a)-newVar = fmap Var . newMVar--readVar :: Var a -> IO a-readVar (Var x) = readMVar x--modifyVar :: Var a -> (a -> IO (a, b)) -> IO b-modifyVar (Var x) f = modifyMVar x f--modifyVar_ :: Var a -> (a -> IO a) -> IO ()-modifyVar_ (Var x) f = modifyMVar_ x f--withVar :: Var a -> (a -> IO b) -> IO b-withVar (Var x) f = withMVar x f--------------------------------------------------------------------------- BARRIER---- | Starts out empty, then is filled exactly once-newtype Barrier a = Barrier (MVar a)-instance Show (Barrier a) where show _ = "Barrier"--newBarrier :: IO (Barrier a)-newBarrier = fmap Barrier newEmptyMVar--signalBarrier :: Barrier a -> a -> IO ()-signalBarrier (Barrier x) = void . tryPutMVar x--waitBarrier :: Barrier a -> IO a-waitBarrier (Barrier x) = readMVar x--waitBarrierMaybe :: Barrier a -> IO (Maybe a)-waitBarrierMaybe (Barrier x) = do- res <- tryTakeMVar x- whenJust res $ void . tryPutMVar x- return res--------------------------------------------------------------------------- FENCE---- | Like a barrier, but based on callbacks-newtype Fence a = Fence (IORef (Either [a -> IO ()] a))-instance Show (Fence a) where show _ = "Fence"--newFence :: IO (Fence a)-newFence = Fence <$> newIORef (Left [])--signalFence :: Fence a -> a -> IO ()-signalFence (Fence ref) v = join $ atomicModifyIORef ref $ \x -> case x of- Left queue -> (Right v, mapM_ ($ v) $ reverse queue)- Right v -> error "Shake internal error, signalFence called twice on one Fence"--waitFence :: Fence a -> (a -> IO ()) -> IO ()-waitFence (Fence ref) call = join $ atomicModifyIORef ref $ \x -> case x of- Left queue -> (Left (call:queue), return ())- Right v -> (Right v, call v)--testFence :: Fence a -> IO (Maybe a)-testFence (Fence x) = either (const Nothing) Just <$> readIORef x
− General/Intern.hs
@@ -1,48 +0,0 @@-{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, MultiParamTypeClasses #-}--module General.Intern(- Intern, Id,- empty, insert, add, lookup, toList, fromList- ) where--import General.Binary-import Development.Shake.Classes-import Prelude hiding (lookup)-import qualified Data.HashMap.Strict as Map-import Data.List(foldl')----- Invariant: The first field is the highest value in the Map-data Intern a = Intern {-# UNPACK #-} !Word32 !(Map.HashMap a Id)--newtype Id = Id Word32- deriving (Eq,Hashable,Binary,Show,NFData)--instance BinaryWith w Id where- putWith ctx = put- getWith ctx = get---empty :: Intern a-empty = Intern 0 Map.empty---insert :: (Eq a, Hashable a) => a -> Id -> Intern a -> Intern a-insert k v@(Id i) (Intern n mp) = Intern (max n i) $ Map.insert k v mp---add :: (Eq a, Hashable a) => a -> Intern a -> (Intern a, Id)-add k (Intern v mp) = (Intern v2 $ Map.insert k (Id v2) mp, Id v2)- where v2 = v + 1---lookup :: (Eq a, Hashable a) => a -> Intern a -> Maybe Id-lookup k (Intern n mp) = Map.lookup k mp---toList :: Intern a -> [(a, Id)]-toList (Intern a b) = Map.toList b---fromList :: (Eq a, Hashable a) => [(a, Id)] -> Intern a-fromList xs = Intern (foldl' max 0 [i | (_, Id i) <- xs]) (Map.fromList xs)
− General/String.hs
@@ -1,65 +0,0 @@-{-# LANGUAGE GeneralizedNewtypeDeriving #-}--module General.String(- BS, pack, unpack, pack_, unpack_,- BSU, packU, unpackU, packU_, unpackU_, requireU- ) where--import qualified Data.ByteString as BS (any)-import qualified Data.ByteString.Char8 as BS hiding (any)-import qualified Data.ByteString.UTF8 as UTF8-import Development.Shake.Classes--------------------------------------------------------------------------- Data.ByteString--- Mostly because ByteString does not have an NFData instance in older GHC---- | ASCII ByteString-newtype BS = BS BS.ByteString- deriving (Hashable, Binary, Eq)--instance Show BS where- show (BS x) = show x--instance NFData BS where- -- some versions of ByteString do not have NFData instances, but seq is equivalent- -- for a strict bytestring. Therefore, we write our own instance.- rnf (BS x) = x `seq` ()----- | UTF8 ByteString-newtype BSU = BSU BS.ByteString- deriving (Hashable, Binary, Eq)--instance NFData BSU where- rnf (BSU x) = x `seq` ()----pack :: String -> BS-pack = pack_ . BS.pack--unpack :: BS -> String-unpack = BS.unpack . unpack_--pack_ :: BS.ByteString -> BS-pack_ = BS--unpack_ :: BS -> BS.ByteString-unpack_ (BS x) = x--packU :: String -> BSU-packU = packU_ . UTF8.fromString--unpackU :: BSU -> String-unpackU = UTF8.toString . unpackU_--unpackU_ :: BSU -> BS.ByteString-unpackU_ (BSU x) = x--packU_ :: BS.ByteString -> BSU-packU_ = BSU--requireU :: BSU -> Bool-requireU = BS.any (>= 0x80) . unpackU_
− General/Template.hs
@@ -1,30 +0,0 @@--module General.Template(runTemplate) where--import Control.Monad-import Data.Char-import qualified Data.ByteString.Lazy.Char8 as LBS----- | Template Engine. Perform the following replacements on a line basis:------ * <script src="foo"></script> ==> <script>[[foo]]</script>------ * <link href="foo" rel="stylesheet" type="text/css" /> ==> <style type="text/css">[[foo]]</style>-runTemplate :: Monad m => (FilePath -> m LBS.ByteString) -> LBS.ByteString -> m LBS.ByteString-runTemplate ask = liftM LBS.unlines . mapM f . LBS.lines- where- link = LBS.pack "<link href=\""- script = LBS.pack "<script src=\""-- f x | Just file <- lbs_stripPrefix script y = do res <- grab file; return $ LBS.pack "<script>\n" `LBS.append` res `LBS.append` LBS.pack "\n</script>"- | Just file <- lbs_stripPrefix link y = do res <- grab file; return $ LBS.pack "<style type=\"text/css\">\n" `LBS.append` res `LBS.append` LBS.pack "\n</style>"- | otherwise = return x- where- y = LBS.dropWhile isSpace x- grab = ask . takeWhile (/= '\"') . LBS.unpack---lbs_stripPrefix :: LBS.ByteString -> LBS.ByteString -> Maybe LBS.ByteString-lbs_stripPrefix prefix text = if a == prefix then Just b else Nothing- where (a,b) = LBS.splitAt (LBS.length prefix) text
− General/Timing.hs
@@ -1,52 +0,0 @@--module General.Timing(resetTimings, addTiming, printTimings) where--import Data.IORef-import Data.Time-import System.IO.Unsafe-import General.Base---{-# NOINLINE timings #-}-timings :: IORef [(UTCTime, String)] -- number of times called, newest first-timings = unsafePerformIO $ newIORef []---resetTimings :: IO ()-resetTimings = do- now <- getCurrentTime- writeIORef timings [(now, "Start")]----- | Print all withTiming information and clear the information.-printTimings :: IO ()-printTimings = do- now <- getCurrentTime- old <- atomicModifyIORef timings $ \ts -> ([(now, "Start")], ts)- putStr $ unlines $ showTimings now $ reverse old---addTiming :: String -> IO ()-addTiming msg = do- now <- getCurrentTime- atomicModifyIORef timings $ \ts -> ((now,msg):ts, ())---showTimings :: UTCTime -> [(UTCTime, String)] -> [String]-showTimings _ [] = []-showTimings stop times = showGap $- [(a ++ " ", showDP 3 b ++ "s " ++ showPerc b ++ " " ++ progress b) | (a,b) <- xs] ++- [("Total", showDP 3 sm ++ "s " ++ showPerc sm ++ " " ++ replicate 25 ' ')]- where- a // b = if b == 0 then 0 else a / b- showPerc x = let s = show $ floor $ x * 100 // sm in replicate (3 - length s) ' ' ++ s ++ "%"- progress x = let i = floor $ x * 25 // mx in replicate i '=' ++ replicate (25-i) ' '- mx = maximum $ map snd xs- sm = sum $ map snd xs- xs = [ (name, stop `diffTime` start)- | ((start, name), stop) <- zip times $ map fst (drop 1 times) ++ [stop]]---showGap :: [(String,String)] -> [String]-showGap xs = [a ++ replicate (n - length a - length b) ' ' ++ b | (a,b) <- xs]- where n = maximum [length a + length b | (a,b) <- xs]
− Main.hs
@@ -1,4 +0,0 @@--module Main(main) where--import Start
− Paths.hs
@@ -1,22 +0,0 @@--- | Fake cabal module for local building--module Paths_shake where--import Data.Version-import System.IO.Unsafe-import System.Directory-import Control.Exception----- We want getDataFileName to be relative to the current directory even if--- we issue a change directory command. Therefore, first call caches, future ones read.-curdir :: String-curdir = unsafePerformIO getCurrentDirectory--getDataFileName :: FilePath -> IO FilePath-getDataFileName x = do- evaluate curdir- return $ curdir ++ "/" ++ x--version :: Version-version = Version {versionBranch = [0,0], versionTags = []}
README.md view
@@ -34,3 +34,5 @@ #### Projects using Shake * [Kansas Lava build rules](https://github.com/gergoerdi/kansas-lava-shake).+* [shake-language-c](http://hackage.haskell.org/package/shake-language-c) is a small library on top of Shake that allows cross-compiling C, C++ and Objective-C code to various target platforms.+* [shake-cabal-build](http://hackage.haskell.org/package/shake-cabal-build) is a small script that uses Cabal sandboxes for initialising and updating build systems based on Shake.
− Start.hs
@@ -1,49 +0,0 @@--module Start(main) where--import Development.Make.All-import Development.Ninja.All-import System.Environment-import Development.Shake-import Development.Shake.FilePath-import General.Timing-import Data.Maybe-import qualified System.Directory as IO-import System.Console.GetOpt---main :: IO ()-main = do- resetTimings- args <- getArgs- withArgs ("--no-time":args) $- shakeArgsWith shakeOptions{shakeCreationCheck=False} flags $ \opts targets -> do- let tool = listToMaybe [x | Tool x <- opts]- makefile <- case reverse [x | UseMakefile x <- opts] of- x:_ -> return x- _ -> findMakefile- if takeExtension makefile == ".ninja" then- runNinja makefile targets tool- else if isJust tool then- error "--tool flag is not supported without a .ninja Makefile"- else- fmap Just $ runMakefile makefile targets---data Flag = UseMakefile FilePath- | Tool String--flags = [Option "f" ["file","makefile"] (ReqArg (Right . UseMakefile) "FILE") "Read FILE as a makefile."- ,Option "t" ["tool"] (ReqArg (Right . Tool) "TOOL") "Ninja-compatible tools."- ]---findMakefile :: IO FilePath-findMakefile = do- b <- IO.doesFileExist "makefile"- if b then return "makefile" else do- b <- IO.doesFileExist "Makefile"- if b then return "Makefile" else do- b <- IO.doesFileExist "build.ninja"- if b then return "build.ninja" else- error "Could not find `makefile', `Makefile' or `build.ninja'"
− Test.hs
@@ -1,131 +0,0 @@--module Main(main) where--import Control.Exception-import Control.Monad-import Data.Maybe-import System.Environment-import General.Base-import General.Timing-import Development.Shake.FileInfo-import General.String-import qualified Data.ByteString.Char8 as BS-import Test.Type(sleepFileTimeCalibrate)-import Control.Concurrent--import qualified Test.Assume as Assume-import qualified Test.Basic as Basic-import qualified Test.Benchmark as Benchmark-import qualified Test.C as C-import qualified Test.Cache as Cache-import qualified Test.Command as Command-import qualified Test.Config as Config-import qualified Test.Digest as Digest-import qualified Test.Directory as Directory-import qualified Test.Docs as Docs-import qualified Test.Errors as Errors-import qualified Test.Files as Files-import qualified Test.FilePath as FilePath-import qualified Test.FilePattern as FilePattern-import qualified Test.Journal as Journal-import qualified Test.Lint as Lint-import qualified Test.Live as Live-import qualified Test.Makefile as Makefile-import qualified Test.Manual as Manual-import qualified Test.Monad as Monad-import qualified Test.Ninja as Ninja-import qualified Test.Oracle as Oracle-import qualified Test.OrderOnly as OrderOnly-import qualified Test.Pool as Pool-import qualified Test.Progress as Progress-import qualified Test.Random as Random-import qualified Test.Resources as Resources-import qualified Test.Self as Self-import qualified Test.Tar as Tar-import qualified Test.Throttle as Throttle-import qualified Test.Unicode as Unicode-import qualified Test.Util as Util-import qualified Test.Verbosity as Verbosity--import qualified Start as Start---fakes = ["clean" * clean, "test" * test, "make" * makefile, "filetime" * filetime]- where (*) = (,)--mains = ["tar" * Tar.main, "self" * Self.main, "c" * C.main- ,"basic" * Basic.main, "cache" * Cache.main, "command" * Command.main- ,"config" * Config.main, "digest" * Digest.main, "directory" * Directory.main- ,"docs" * Docs.main, "errors" * Errors.main, "orderonly" * OrderOnly.main- ,"filepath" * FilePath.main, "filepattern" * FilePattern.main, "files" * Files.main- ,"journal" * Journal.main, "lint" * Lint.main, "live" * Live.main, "makefile" * Makefile.main, "manual" * Manual.main- ,"monad" * Monad.main, "pool" * Pool.main, "random" * Random.main, "ninja" * Ninja.main- ,"resources" * Resources.main, "assume" * Assume.main, "benchmark" * Benchmark.main- ,"oracle" * Oracle.main, "progress" * Progress.main, "unicode" * Unicode.main, "util" * Util.main- ,"throttle" * Throttle.main, "verbosity" * Verbosity.main]- where (*) = (,)---main :: IO ()-main = do- resetTimings- xs <- getArgs- exePath <- getExePath- case flip lookup (fakes ++ mains) =<< listToMaybe xs of- _ | null xs -> do- putStrLn "******************************************************************"- putStrLn "** Running shake test suite, run with '--help' to see arguments **"- putStrLn "******************************************************************"- withArgs ["test"] main- withArgs ["random","test","3m"] main- Nothing -> putStrLn $ unlines- ["Welcome to the Shake demo"- ,""- ,unwords $ "Modes:" : map fst fakes- ,unwords $ "Demos:" : map fst mains- ,""- ,"As an example, try:"- ,""- ,unwords [" ", exePath, "self", "--jobs=2", "--trace"]- ,""- ,"Which will build Shake, using Shake, on 2 threads."]- Just main -> main =<< sleepFileTimeCalibrate---makefile :: IO () -> IO ()-makefile _ = do- args <- getArgs- withArgs (drop 1 args) Start.main---filetime :: IO () -> IO ()-filetime _ = do- args <- getArgs- addTiming "Reading files"- files <- fmap concat $ forM (drop 1 args) $ \file ->- fmap (BS.lines . BS.filter (/= '\r')) $ BS.readFile file- let n = length files- evaluate n- addTiming "Modtime"- let (a,bcd) = splitAt (n `div` 4) files- let (b,cd) = splitAt (n `div` 4) bcd- let (c,d) = splitAt (n `div` 4) cd- vars <- forM [a,b,c,d] $ \xs -> do- mvar <- newEmptyMVar- forkIO $ do- mapM_ (getFileInfo . packU_) xs- putMVar mvar ()- return $ takeMVar mvar- sequence_ vars- printTimings---clean :: IO () -> IO ()-clean extra = sequence_ [withArgs [name,"clean"] $ main extra | (name,main) <- mains]---test :: IO () -> IO ()-test yield = do- args <- getArgs- flip onException (putStrLn "TESTS FAILED") $- sequence_ [withArgs (name:"test":drop 1 args) $ test yield | (name,test) <- mains, name /= "random"]
− Test/Assume.hs
@@ -1,45 +0,0 @@--module Test.Assume(main) where--import Development.Shake-import Test.Type-import Control.Monad-import Development.Shake.FilePath---main = shaken test $ \args obj -> do- want $ map obj args- obj "*.out" *> \out -> do- cs <- mapM (readFile' . obj . (:".src")) $ takeBaseName out- writeFile' out $ concat cs---test build obj = do- let set file c = writeFile (obj $ file : ".src") [c]- let ask file c = do src <- readFile (obj $ file ++ ".out"); src === c-- forM_ ['a'..'f'] $ \c -> set c c- build ["--sleep","abc.out"]- ask "abc" "abc"-- set 'b' 'd'- build ["--sleep","abc.out"]- ask "abc" "adc"- set 'b' 'p'- build ["--sleep","abc.out","--touch"]- build ["abc.out"]- ask "abc" "adc"- set 'c' 'z'- build ["--sleep","abc.out"]- ask "abc" "apz"-- build ["bc.out","c.out"]- ask "bc" "pz"- set 'b' 'r'- set 'c' 'n'- build ["--sleep","abc.out","--touch"]- ask "abc" "apz"- build ["ab.out","--always-make"]- ask "ab" "ar"- build ["c.out"]- ask "c" "z"
− Test/Basic.hs
@@ -1,132 +0,0 @@--module Test.Basic(main) where--import Development.Shake-import Test.Type-import System.Directory as IO-import Data.List-import Data.Maybe-import Control.Monad-import General.Base---main = shaken test $ \args obj -> do- want $ map (\x -> fromMaybe (obj x) $ stripPrefix "!" x) args-- obj "AB.txt" *> \out -> do- need [obj "A.txt", obj "B.txt"]- text1 <- readFile' $ obj "A.txt"- text2 <- readFile' $ obj "B.txt"- writeFile' out $ text1 ++ text2-- obj "twice.txt" *> \out -> do- let src = obj "once.txt"- need [src, src]- copyFile' src out-- obj "once.txt" *> \out -> do- src <- readFile' $ obj "zero.txt"- writeFile' out src-- phony "halfclean" $ do- removeFilesAfter (obj "") ["//*e.txt"]-- phony "cleaner" $ do- removeFilesAfter (obj "") ["//*"]-- phony (obj "configure") $ do- liftIO $ appendFile (obj "configure") "1"-- phony "install" $ do- need [obj "configure",obj "once.txt"]- liftIO $ appendFile (obj "install") "1"-- phony "dummy" $ do- liftIO $ appendFile (obj "dummy") "1"-- obj "dummer.txt" *> \out -> do- need ["dummy","dummy"]- need ["dummy"]- liftIO $ appendFile out "1"-- r <- newResource ".log file" 1- let trace x = withResource r 1 $ liftIO $ appendFile (obj ".log") x- obj "*.par" *> \out -> do- trace "["- (if "unsafe" `isInfixOf` out then unsafeExtraThread else id) $ liftIO $ sleep 0.1- trace "]"- writeFile' out out--test build obj = do- writeFile (obj "A.txt") "AAA"- writeFile (obj "B.txt") "BBB"- build ["AB.txt","--sleep"]- assertContents (obj "AB.txt") "AAABBB"- appendFile (obj "A.txt") "aaa"- build ["AB.txt"]- assertContents (obj "AB.txt") "AAAaaaBBB"-- writeFile (obj "zero.txt") "xxx"- build ["twice.txt","--sleep"]- assertContents (obj "twice.txt") "xxx"- writeFile (obj "zero.txt") "yyy"- build ["once.txt","--sleep"]- assertContents (obj "twice.txt") "xxx"- assertContents (obj "once.txt") "yyy"- writeFile (obj "zero.txt") "zzz"- build ["once.txt","twice.txt","--sleep"]- assertContents (obj "twice.txt") "zzz"- assertContents (obj "once.txt") "zzz"-- removeFile $ obj "twice.txt"- build ["twice.txt"]- assertContents (obj "twice.txt") "zzz"-- show shakeOptions === show shakeOptions-- build ["!halfclean"]- b <- IO.doesDirectoryExist (obj "")- assert b "Directory should exist, cleaner should not have removed it"-- build ["!cleaner"]- sleep 1 -- sometimes takes a while for the file system to notice- b <- IO.doesDirectoryExist (obj "")- assert (not b) "Directory should not exist, cleaner should have removed it"-- IO.createDirectory $ obj ""- writeFile (obj "zero.txt") ""- build ["configure"]- build ["!install"]- build ["!install"]- assertContents (obj "configure") "111"- assertContents (obj "install") "11"-- writeFile (obj "dummy.txt") ""- build ["!dummy"]- assertContents (obj "dummy") "1"- build ["!dummy"]- assertContents (obj "dummy") "11"- build ["!dummy","!dummy"]- assertContents (obj "dummy") "111"-- writeFile (obj "dummer.txt") ""- build ["dummer.txt"]- assertContents (obj "dummer.txt") "1"- build ["dummer.txt"]- assertContents (obj "dummer.txt") "11"-- build ["1.par","2.par","-j1"]- assertContents (obj ".log") "[][]"- writeFile (obj ".log") ""- build ["3.par","4.par","-j2"]- assertContents (obj ".log") "[[]]"- writeFile (obj ".log") ""- i <- getProcessorCount- putStrLn $ "getProcessorCount returned " ++ show i- when (i > 1) $ do- build ["5.par","6.par","-j0"]- assertContents (obj ".log") "[[]]"-- writeFile (obj ".log") ""- build ["unsafe1.par","unsafe2.par","-j2"]- assertContents (obj ".log") "[[]]"
− Test/Benchmark.hs
@@ -1,21 +0,0 @@--module Test.Benchmark(main) where--import Development.Shake-import Test.Type-import Data.List-import Development.Shake.FilePath----- | Given a breadth and depth come up with a set of build files-main = shaken (\_ _ -> return ()) $ \args obj -> do- let get ty = head $ [read $ drop (length ty + 1) a | a <- args, (ty ++ "=") `isPrefixOf` a] ++- error ("Could not find argument, expected " ++ ty ++ "=Number")- depth = get "depth"- breadth = get "breadth"-- want [obj $ "0." ++ show i | i <- [1..breadth]]- obj "*" *> \out -> do- let d = read $ takeBaseName out- need [obj $ show (d + 1) ++ "." ++ show i | d < depth, i <- [1..breadth]]- writeFile' out ""
− Test/C.hs
@@ -1,28 +0,0 @@--module Test.C(main) where--import Development.Shake-import Development.Shake.FilePath-import Test.Type--main = shaken noTest $ \args obj -> do- let src = "Test/C"- want [obj "Main.exe"]-- obj "Main.exe" *> \out -> do- cs <- getDirectoryFiles src ["*.c"]- let os = map (obj . (<.> "o")) cs- need os- cmd "gcc -o" [out] os-- obj "*.c.o" *> \out -> do- let c = src </> takeBaseName out- need [c]- headers <- cIncludes c- need $ map ((</>) src . takeFileName) headers- cmd "gcc -o" [out] "-c" [c]--cIncludes :: FilePath -> Action [FilePath]-cIncludes x = do- Stdout stdout <- cmd "gcc" ["-MM",x]- return $ drop 2 $ words stdout
− Test/C/constants.c
@@ -1,7 +0,0 @@--char msg[] = "Hello Shake Users!";--char* message()-{- return msg;-}
− Test/C/constants.h
@@ -1,1 +0,0 @@-char* message();
− Test/C/main.c
@@ -1,8 +0,0 @@-#include <stdio.h>-#include "constants.h"--int main()-{- printf("%s\n", message());- return 0;-}
− Test/Cache.hs
@@ -1,39 +0,0 @@--module Test.Cache(main) where--import Development.Shake-import Development.Shake.FilePath-import Data.Char-import Test.Type---main = shaken test $ \args obj -> do- want $ map obj args- vowels <- newCache $ \file -> do- src <- readFile' file- liftIO $ appendFile (obj "trace.txt") "1"- return $ length $ filter isDigit src- obj "*.out*" *> \x ->- writeFile' x . show =<< vowels (dropExtension x <.> "txt")---test build obj = do- writeFile (obj "trace.txt") ""- writeFile (obj "vowels.txt") "abc123a"- build ["vowels.out1","vowels.out2","-j3","--sleep"]- assertContents (obj "trace.txt") "1"- assertContents (obj "vowels.out1") "3"- assertContents (obj "vowels.out2") "3"-- build ["vowels.out2","-j3"]- assertContents (obj "trace.txt") "1"- assertContents (obj "vowels.out1") "3"-- writeFile (obj "vowels.txt") "12xyz34"- build ["vowels.out2","-j3","--sleep"]- assertContents (obj "trace.txt") "11"- assertContents (obj "vowels.out2") "4"-- build ["vowels.out1","-j3","--sleep"]- assertContents (obj "trace.txt") "111"- assertContents (obj "vowels.out1") "4"
− Test/Command.hs
@@ -1,60 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}--module Test.Command(main) where--import Development.Shake-import Test.Type---main = shaken test $ \args obj -> do- want $ map obj args-- let a !> b = obj a *> \out -> do alwaysRerun; res <- b; writeFile' out res-- "ghc-version" !> do- Stdout stdout <- cmd "ghc --version"- return stdout-- "ghc-random" !> do- (Stderr stderr, Exit _) <- cmd "ghc --random"- return stderr-- "ghc-random2" !> do- () <- cmd (EchoStderr False) (Cwd $ obj "") "ghc --random"- return ""-- "triple" !> do- (Exit exit, Stdout stdout, Stderr stderr) <- cmd "ghc --random"- return $ show (exit, stdout, stderr) -- must force all three parts-- obj "pwd space.hs" *> \out -> writeFileLines out ["import System.Directory","main = putStrLn =<< getCurrentDirectory"]- "pwd" !> do- need [obj "pwd space.hs"]- Stdout out <- cmd (Cwd $ obj "") "runhaskell" ["pwd space.hs"]- return out-- "env" !> do- (Exit _, Stdout out1) <- cmd (Env [("FOO","HELLO SHAKE")]) Shell "echo %FOO%"- (Exit _, Stdout out2) <- liftIO $ cmd (Env [("FOO","HELLO SHAKE")]) Shell "echo $FOO"- return $ unlines [out1, out2]---test build obj = do- let crash args parts = assertException parts (build $ "--quiet" : args)-- build ["ghc-version"]- assertContentsInfix (obj "ghc-version") "The Glorious Glasgow Haskell Compilation System"-- build ["ghc-random"]- assertContentsInfix (obj "ghc-random") "unrecognised flag"- assertContentsInfix (obj "ghc-random") "--random"-- crash ["ghc-random2"] [obj "","unrecognised flag","--random"]-- build ["pwd"]- assertContentsInfix (obj "pwd") "command"-- build ["env","--no-lint"] -- since it blows away the $PATH, which is necessary for lint-tracker- assertContentsInfix (obj "env") "HELLO SHAKE"-- build ["triple"]
− Test/Config.hs
@@ -1,57 +0,0 @@--module Test.Config(main) where--import Development.Shake-import Development.Shake.FilePath-import Development.Shake.Config-import Test.Type-import Data.Char-import qualified Data.HashMap.Strict as Map-import Data.Maybe-import System.Directory---main = shaken test $ \args obj -> do- want $ map obj ["hsflags.var","cflags.var","none.var"]- usingConfigFile $ obj "config"- obj "*.var" *> \out -> do- cfg <- getConfig $ map toUpper $ takeBaseName out- liftIO $ appendFile (out -<.> "times") "X"- writeFile' out $ fromMaybe "" cfg---test build obj = do- build ["clean"]- createDirectoryIfMissing True $ obj ""- writeFile (obj "config") $ unlines- ["HEADERS_DIR = /path/to/dir"- ,"CFLAGS = -O2 -I${HEADERS_DIR} -g"- ,"HSFLAGS = -O2"]- build []- assertContents (obj "cflags.var") "-O2 -I/path/to/dir -g"- assertContents (obj "hsflags.var") "-O2"- assertContents (obj "none.var") ""-- appendFile (obj "config") $ unlines- ["CFLAGS = $CFLAGS -w"]- build []- assertContents (obj "cflags.var") "-O2 -I/path/to/dir -g -w"- assertContents (obj "hsflags.var") "-O2"- assertContents (obj "cflags.times") "XX"- assertContents (obj "hsflags.times") "X"- assertContents (obj "none.times") "X"-- -- Test readConfigFileWithEnv- writeFile (obj "config") $ unlines- ["HEADERS_DIR = ${SOURCE_DIR}/path/to/dir"- ,"CFLAGS = -O2 -I${HEADERS_DIR} -g"]- vars <- readConfigFileWithEnv [("SOURCE_DIR", "/path/to/src")]- (obj "config")- assert (Map.lookup "HEADERS_DIR" vars == Just "/path/to/src/path/to/dir")- $ "readConfigFileWithEnv:"- ++ " Expected: " ++ show (Just "/path/to/src/path/to/dir")- ++ " Got: " ++ show (Map.lookup "HEADERS_DIR" vars)- assert (Map.lookup "CFLAGS" vars == Just "-O2 -I/path/to/src/path/to/dir -g")- $ "readConfigFileWithEnv:"- ++ " Expected: " ++ show (Just "-O2 -I/path/to/src/path/to/dir -g")- ++ " Got: " ++ show (Map.lookup "CFLAGS" vars)
− Test/Digest.hs
@@ -1,78 +0,0 @@--module Test.Digest(main) where--import Control.Monad-import Development.Shake-import Test.Type---main = shaken test $ \args obj -> do- want [obj "Out.txt",obj "Out2.txt"]-- obj "Out.txt" *> \out -> do- txt <- readFile' $ obj "In.txt"- liftIO $ appendFile out txt-- [obj "Out1.txt",obj "Out2.txt"] &*> \[out1,out2] -> do- txt <- readFile' $ obj "In.txt"- liftIO $ appendFile out1 txt- liftIO $ appendFile out2 txt---test build obj = do- let outs = take 1 $ map obj ["Out.txt","Out1.txt","Out2.txt"]- let writeOut x = forM_ outs $ \out -> writeFile out x- let writeIn x = writeFile (obj "In.txt") x- let assertOut x = forM_ outs $ \out -> assertContents out x-- writeOut ""- writeIn "X"- build ["--sleep","--digest-and"]- assertOut "X"-- -- should not involve a hash calculation (sadly no way to test that)- build ["--sleep","--digest-and"]- assertOut "X"-- writeIn "X"- build ["--sleep","--digest-and"]- assertOut "X"-- writeIn "X"- build ["--sleep","--digest-or"]- assertOut "XX"-- writeIn "X"- build ["--sleep","--digest-and"]- assertOut "XX"-- build ["--sleep","--digest-and"]- writeOut "XX"- build ["--sleep","--digest-and"]- assertOut "XX"-- build ["--sleep","--digest-and"]- writeOut "Y"- build ["--sleep","--digest-and"]- assertOut "YX"-- writeIn "X"- build ["--sleep","--digest"]- assertOut "YX"-- writeIn "Z"- build ["--sleep","--digest-and-input"]- assertOut "YXZ"-- build ["--sleep","--digest-and-input"]- writeOut "YXZ"- build ["--sleep","--digest-and-input"]- assertOut "YXZZ"-- writeIn "Q"- build ["--sleep","--digest-and-input"]- assertOut "YXZZQ"-- writeIn "Q"- build ["--sleep","--digest-and-input"]- assertOut "YXZZQ"
− Test/Directory.hs
@@ -1,109 +0,0 @@--module Test.Directory(main) where--import Development.Shake-import Development.Shake.FilePath-import Test.Type-import Data.List-import Control.Monad-import System.Directory(getCurrentDirectory, setCurrentDirectory, createDirectory, createDirectoryIfMissing)-import qualified System.Directory as IO----- Use escape characters, _o=* _l=/ __=<space>-readEsc ('_':'o':xs) = '*' : readEsc xs-readEsc ('_':'l':xs) = '/' : readEsc xs-readEsc ('_':'_':xs) = ' ' : readEsc xs-readEsc (x:xs) = x : readEsc xs-readEsc [] = []--showEsc = concatMap f- where f '*' = "_o"- f '/' = "_l"- f ' ' = "__"- f x = [x]---main = shaken test $ \args obj -> do- want $ map obj args- obj "*.contents" *> \out ->- writeFileLines out =<< getDirectoryContents (obj $ readEsc $ dropExtension $ unobj out)- obj "*.dirs" *> \out ->- writeFileLines out =<< getDirectoryDirs (obj $ readEsc $ dropExtension $ unobj out)- obj "*.files" *> \out -> do- let pats = readEsc $ dropExtension $ unobj out- let (x:xs) = ["" | " " `isPrefixOf` pats] ++ words pats- writeFileLines out =<< getDirectoryFiles (obj x) xs-- obj "*.exist" *> \out -> do- let xs = map obj $ words $ readEsc $ dropExtension $ unobj out- fs <- mapM doesFileExist xs- ds <- mapM doesDirectoryExist xs- let bool x = if x then "1" else "0"- writeFileLines out $ zipWith (\a b -> bool a ++ bool b) fs ds-- obj "dots" *> \out -> do- cwd <- liftIO getCurrentDirectory- liftIO $ setCurrentDirectory $ obj ""- b1 <- liftM2 (==) (getDirectoryContents ".") (getDirectoryContents "")- b2 <- liftM2 (==) (getDirectoryDirs ".") (getDirectoryDirs "")- b3 <- liftM2 (==) (getDirectoryFiles "." ["*.txt"]) (getDirectoryFiles "" ["*.txt"])- b4 <- liftM2 (==) (getDirectoryFiles "." ["C.txt/*.txt"]) (getDirectoryFiles "" ["C.txt/*.txt"])- b5 <- liftM2 (==) (getDirectoryFiles "." ["//*.txt"]) (getDirectoryFiles "" ["//*.txt"])- liftIO $ setCurrentDirectory cwd- writeFileLines out $ map show [b1,b2,b3,b4,b5]--test build obj = do- let demand x ys = let f = showEsc x in do build [f]; assertContents (obj f) $ unlines $ words ys- build ["clean"]- demand " *.txt.files" ""- demand " //*.txt.files" ""- demand ".dirs" ""- demand "A.txt B.txt C.txt.exist" "00 00 00"-- writeFile (obj "A.txt") ""- writeFile (obj "B.txt") ""- createDirectory (obj "C.txt")- writeFile (obj "C.txt/D.txt") ""- writeFile (obj "C.txt/E.xtx") ""- demand " *.txt.files" "A.txt B.txt"- demand ".dirs" "C.txt"- demand "A.txt B.txt C.txt.exist" "10 10 01"- demand " //*.txt.files" "A.txt B.txt C.txt/D.txt"- demand "C.txt *.txt.files" "D.txt"- demand " *.txt //*.xtx.files" "A.txt B.txt C.txt/E.xtx"- demand " C.txt/*.files" "C.txt/D.txt C.txt/E.xtx"-- build ["dots","--no-lint"]- assertContents (obj "dots") $ unlines $ words "True True True True True"-- let removeTest pat del keep = do- withTemporaryDirectory $ \dir -> do- forM_ (del ++ keep) $ \s -> do- createDirectoryIfMissing True $ dir </> takeDirectory s- when (not $ hasTrailingPathSeparator s) $- writeFile (dir </> s) ""- removeFiles dir pat- createDirectoryIfMissing True dir- forM_ (map ((,) False) del ++ map ((,) True) keep) $ \(b,s) -> do- b2 <- (if hasTrailingPathSeparator s then IO.doesDirectoryExist else IO.doesFileExist) $ dir </> s- when (b /= b2) $ do- let f b = if b then "present" else "missing"- error $ "removeFiles mismatch: with pattern " ++ show pat ++ ", " ++ s ++- " should be " ++ f b ++ " but is " ++ f b2-- removeTest ["//bob"] ["test/bob","more/bob"] ["extra/obo"]- removeTest ["bob"] ["bob/"] ["bar/"]- removeTest ["*.hs"] ["test.hs"] ["extra/more.hs","new.txt"]- removeTest ["baz"] ["baz"] ["foo","bar/bob"]- removeTest ["baz"] ["baz/bob","baz/"] ["foo","bar/bob"]- removeTest ["Foo//*"] ["Foo/bar","Foo/Quux/bar","Foo/Quux/"] []- removeTest ["Foo//*"] ["Foo/"] ["bar"]- removeTest ["baz"] [] ["test.hs","bar/","foo/"]- removeTest ["bob//*"] [] ["test/bob/"]- removeTest ["//bob"] ["test/bob/","test/"] []- removeTest ["//*.txt"] ["more/","more/a.txt"] []- removeTest ["//*.txt"] ["more/","more/a.txt/"] []- removeTest ["//*.txt"] ["more/","more/a.txt/","more/b.txt"] []- removeTest ["//*.txt"] [] ["more/"]- removeTest ["a//b"] ["a/c/b"] []
− Test/Docs.hs
@@ -1,266 +0,0 @@-{-# LANGUAGE PatternGuards #-}--module Test.Docs(main) where--import Development.Shake-import Development.Shake.FilePath-import Test.Type-import Control.Monad-import Data.Char-import Data.List-import Data.Maybe-import System.Directory-import System.Exit---reps from to = map (\x -> if x == from then to else x)--main = shaken noTest $ \args obj -> do- let index = "dist/doc/html/shake/index.html"- want [obj "Success.txt"]-- want $ map (\x -> fromMaybe (obj x) $ stripPrefix "!" x) args-- let needSource = need =<< getDirectoryFiles "." ["Development/Shake.hs","Development/Shake//*.hs","Development/Ninja/*.hs","General//*.hs"]-- index *> \_ -> do- needSource- need ["shake.cabal"]- trackAllow ["dist//*"]- res <- liftIO $ findExecutable "cabal"- if isJust res then cmd "cabal haddock" else do- Exit exit <- cmd "runhaskell Setup.hs haddock"- when (exit /= ExitSuccess) $ do- () <- cmd "runhaskell Setup.hs configure"- cmd "runhaskell Setup.hs haddock"-- obj "Paths_shake.hs" *> \out -> do- copyFile' "Paths.hs" out-- obj "Part_*.hs" *> \out -> do- need ["Test/Docs.hs"] -- so much of the generator is in this module- src <- if "_md" `isSuffixOf` takeBaseName out then- fmap (findCodeMarkdown . lines) $ readFile' $ "docs/" ++ drop 5 (reverse (drop 3 $ reverse $ takeBaseName out)) ++ ".md"- else- fmap findCodeHaddock $ readFile' $ "dist/doc/html/shake/" ++ reps '_' '-' (drop 5 $ takeBaseName out) ++ ".html"- let f i (Stmt x) | whitelist $ head x = []- | otherwise = restmt i $ map undefDots $ trims x- f i (Expr x) | takeWhile (not . isSpace) x `elem` types = ["type Expr_" ++ show i ++ " = " ++ x]- | "import " `isPrefixOf` x = [x]- | otherwise = ["expr_" ++ show i ++ " = (" ++ undefDots x2 ++ ")" | let x2 = trim $ dropComment x, not $ whitelist x2]- code = concat $ zipWith f [1..] (nub src)- (imports,rest) = partition ("import " `isPrefixOf`) code- writeFileLines out $- ["{-# LANGUAGE ConstraintKinds, DeriveDataTypeable, ExtendedDefaultRules, GeneralizedNewtypeDeriving, NoMonomorphismRestriction #-}"- ,"{-# OPTIONS_GHC -w #-}"- ,"module " ++ takeBaseName out ++ "() where"- ,"import Control.Concurrent"- ,"import Control.Monad"- ,"import Data.Char"- ,"import Data.Data"- ,"import Data.List"- ,"import Data.Maybe"- ,"import Data.Monoid"- ,"import Development.Shake"- ,"import Development.Shake.Classes"- ,"import Development.Shake.Rule"- ,"import Development.Shake.Util"- ,"import Development.Shake.FilePath"- ,"import System.Console.GetOpt"- ,"import System.Exit"- ,"import System.IO"] ++- ["import " ++ reps '_' '.' (drop 5 $ takeBaseName out) | not $ "_md.hs" `isSuffixOf` out] ++- imports ++- ["(==>) :: Bool -> Bool -> Bool"- ,"(==>) = undefined"- ,"infix 1 ==>"- ,"forAll f = f undefined"- ,"remaining = 1.1"- ,"done = 1.1"- ,"time_elapsed = 1.1"- ,"old = \"\""- ,"new = \"\""- ,"myfile = \"\""- ,"inputs = [\"\"]"- ,"files = [\"\"]"- ,"input = \"\""- ,"output = \"\""- ,"opts = shakeOptions"- ,"result = undefined :: IO (Maybe (Rules ()))"- ,"launchMissiles = undefined :: Bool -> IO ()"- ,"myVariable = ()"- ,"instance Eq (OptDescr a)"- ,"(foo,bar,baz) = undefined"- ,"str1 = \"\""- ,"str2 = \"\""- ,"str = \"\""- ,"((/./),(/../),(//)) = undefined"] ++- rest-- obj "Files.lst" *> \out -> do- need ["Test/Docs.hs"] -- so much of the generator is in this module- need [index,obj "Paths_shake.hs"]- filesHs <- getDirectoryFiles "dist/doc/html/shake" ["Development-*.html"]- filesMd <- getDirectoryFiles "docs" ["*.md"]- writeFileChanged out $ unlines $- ["Part_" ++ reps '-' '_' (takeBaseName x) | x <- filesHs, not $ "-Classes.html" `isSuffixOf` x] ++- ["Part_" ++ takeBaseName x ++ "_md" | x <- filesMd, takeBaseName x /= "Developing"]-- let needModules = do mods <- readFileLines $ obj "Files.lst"; need [obj m <.> "hs" | m <- mods]; return mods-- obj "Main.hs" *> \out -> do- mods <- needModules- writeFileLines out $ ["module Main(main) where"] ++ ["import " ++ m | m <- mods] ++ ["main = return ()"]-- obj "Success.txt" *> \out -> do- needModules- need [obj "Main.hs", obj "Paths_shake.hs"]- needSource- () <- cmd "runhaskell -ignore-package=hashmap" ["-i" ++ obj "", obj "Main.hs"]- writeFile' out ""---data Code = Stmt [String] | Expr String deriving (Show,Eq)--findCodeHaddock :: String -> [Code]-findCodeHaddock x | Just x <- stripPrefix "<pre>" x = f (Stmt . shift . lines . strip) "</pre>" x- | Just x <- stripPrefix "<code>" x = f (Expr . strip) "</code>" x- where- f ctor end x | Just x <- stripPrefix end x = ctor "" : findCodeHaddock x- f ctor end (x:xs) = f (ctor . (x:)) end xs-findCodeHaddock (x:xs) = findCodeHaddock xs-findCodeHaddock [] = []--findCodeMarkdown :: [String] -> [Code]-findCodeMarkdown (x:xs) | indented x && not (blank x) =- let (a,b) = span (\x -> indented x || blank x) (x:xs)- in Stmt (map (drop 4) a) : findCodeMarkdown b- where- indented x = length (takeWhile isSpace x) >= 4- blank x = all isSpace x-findCodeMarkdown (x:xs) = f x ++ findCodeMarkdown xs- where- f ('`':xs) = let (a,b) = break (== '`') xs in Expr a : f (drop 1 b)- f (x:xs) = f xs- f [] = []-findCodeMarkdown [] = []--trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace-trims = reverse . dropWhile (all isSpace) . reverse . dropWhile (all isSpace)--restmt i ("":xs) = restmt i xs-restmt i (x:xs) | " ?== " `isInfixOf` x || " == " `isInfixOf` x =- zipWith (\j x -> "hack_" ++ show i ++ "_" ++ show j ++ " = " ++ x) [1..] (x:xs)-restmt i (x:xs) |- not ("let" `isPrefixOf` x) && not ("[" `isPrefixOf` x) && (" = " `isInfixOf` x || " | " `isInfixOf` x) ||- "import " `isPrefixOf` x || "infix" `isPrefixOf` x || "instance " `isPrefixOf` x = map f $ x:xs- where f x = if takeWhile (not . isSpace) x `elem` dupes then "_" ++ show i ++ "_" ++ x else x-restmt i xs = ("stmt_" ++ show i ++ " = do") : map (" " ++) xs ++- [" undefined" | length xs == 1 && ("let" `isPrefixOf` (head xs) || "<-" `isInfixOf` (head xs))]---shift :: [String] -> [String]-shift xs | all null xs = xs- | all (\x -> null x || " " `isPrefixOf` x) xs = shift $ map (drop 1) xs- | otherwise = xs---dropComment ('-':'-':_) = []-dropComment xs = onTail dropComment xs---undefDots o = f o- where- f ('.':'.':'.':xs) =- (if "cmd" `elem` words o then "[\"\"]" else "undefined") ++- (if "..." `isSuffixOf` xs then "" else undefDots xs)- f xs = onTail f xs--strip :: String -> String-strip x- | Just x <- stripPrefix "<em>" x- , (a,b) <- break (== '<') x- , not $ ("</em>" `isPrefixOf` b) && a `elem` italics- = error $ "Unexpected italics in code block: " ++ a ++ take 5 b ++ "..."-strip ('<':xs) = strip $ drop 1 $ dropWhile (/= '>') xs-strip ('&':xs)- | Just xs <- stripPrefix "quot;" xs = '\"' : strip xs- | Just xs <- stripPrefix "lt;" xs = '<' : strip xs- | Just xs <- stripPrefix "gt;" xs = '>' : strip xs- | Just xs <- stripPrefix "amp;" xs = '&' : strip xs-strip xs = onTail strip xs--onTail f (x:xs) = x : f xs-onTail f [] = []---italics :: [String]-italics = words "extension command-name file-name"--whitelist :: String -> Bool-whitelist x | all (not . isSpace) x && takeExtension x `elem` words ".txt .hi .hs .o .exe .tar .cpp .cfg .dep .deps .h .c .html" = True-whitelist x | elem x $ words $- "newtype do MyFile.txt.digits excel a q m c x value key gcc cl os make contents tar ghc cabal clean _make distcc ghc " ++- ".. /./ /.. ./ // \\ ../ " ++- "ConstraintKinds GeneralizedNewtypeDeriving DeriveDataTypeable SetConsoleTitle " ++- "Data.List System.Directory Development.Shake.FilePath main.m run .rot13 " ++- "NoProgress Error src rot13 .js .json .trace about://tracing " ++- ".make/i586-linux-gcc/output _make/.database foo/.. file.src file.out build " ++- "/usr/special /usr/special/userbinary $CFLAGS %PATH% -O2 -j8 -j -j1 " ++- "-threaded -rtsopts -I0 Function extension $OUT $C_LINK_FLAGS $PATH xterm $TERM main opts result flagValues argValues " ++- "HEADERS_DIR /path/to/dir CFLAGS let -showincludes -MMD gcc.version linkFlags temp pwd touch code out err " ++- "_metadata/.database _shake _shake/build ./build.sh build.sh build.bat //* [out] manual/examples.zip manual " ++- "docs/manual _build _build/run ninja depfile build.ninja "- = True-whitelist x = x `elem`- ["[Foo.hi, Foo.o]"- ,"shake-progress"- ,"main -j6"- ,"main clean"- ,"1m25s (15%)"- ,"3m12s (82%)"- ,"getPkgVersion $ GhcPkgVersion \"shake\""- ,"# command-name (for file-name)"- ,"ghc --make MyBuildSystem -rtsopts -with-rtsopts=-I0"- ,"-with-rtsopts"- ,"-qg -qb"- ,"gcc -MM"- ,"# This is my Config file"- ,"-g -I/path/to/dir -O2"- ,"main _make/henry.txt"- ,"<i>build rules</i>"- ,"<i>actions</i>"- ,"() <- cmd ..."- ,"x <- inputs"- ,"shakeFiles=\"_build/\""- ,"#include \""- ,"pattern *> actions = (pattern ?==) ?> actions" -- because it overlaps- ,"buildDir = \"_build\""- ,"-MMD -MF"- ,"#!/bin/sh"- ,"build _build/main.o"- ,"build clean"- ,"build -j8"- ,"cabal update && cabal install shake"- ,"shake-build-system"- ,"runhaskell _build/run"- ,"runhaskell _build/run clean"- ,"gcc -c main.c -o main.o -MMD -MF main.m"- ,"\"_build\" </> x -<.> \"o\""- ,"cmd \"gcc -o\" [out] os"- ,"rot13 file.txt -o file.rot13"- ,"file.rot13"- ,"out -<.> \"txt\""- ,"[item1,item2,item2]"- ,"runhaskell Build.hs"- ,"cabal update"- ,"cabal install shake"- ,"shake -j4"- ,"cmd \"gcc -o _make/run _build/main.o _build/constants.o\""- ]--types = words $- "MVar IO Monad Monoid String FilePath Data Maybe [String] Eq Typeable Char ExitCode Change " ++- "Action Resource Assume FilePattern Lint Verbosity Rules Rule CmdOption CmdResult Int Double"--dupes = words "main progressSimple rules"
− Test/Errors.hs
@@ -1,120 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}--module Test.Errors(main) where--import Development.Shake-import Test.Type-import Control.Monad-import General.Base-import Control.Concurrent-import Control.Exception as E hiding (assert)-import System.Directory as IO---main = shaken test $ \args obj -> do- want $ map obj args-- obj "norule" *> \_ ->- need [obj "norule_isavailable"]-- obj "failcreate" *> \_ ->- return ()-- [obj "failcreates", obj "failcreates2"] &*> \_ ->- writeFile' (obj "failcreates") ""-- obj "recursive" *> \out ->- need [out]-- obj "systemcmd" *> \_ ->- cmd "random_missing_command"-- obj "stack1" *> \_ -> need [obj "stack2"]- obj "stack2" *> \_ -> need [obj "stack3"]- obj "stack3" *> \_ -> error "crash"-- obj "staunch1" *> \out -> do- liftIO $ sleep 0.1- writeFile' out "test"- obj "staunch2" *> \_ -> error "crash"-- let catcher out op = obj out *> \out -> do- writeFile' out "0"- op $ do src <- readFileStrict out; writeFile out $ show (read src + 1 :: Int)- catcher "finally1" $ actionFinally $ fail "die"- catcher "finally2" $ actionFinally $ return ()- catcher "finally3" $ actionFinally $ liftIO $ sleep 10- catcher "finally4" $ actionFinally $ need ["wait"]- "wait" ~> do liftIO $ sleep 10- catcher "exception1" $ actionOnException $ fail "die"- catcher "exception2" $ actionOnException $ return ()-- res <- newResource "resource_name" 1- obj "resource" *> \out -> do- withResource res 1 $- need ["resource-dep"]-- obj "overlap.txt" *> \out -> writeFile' out "overlap.txt"- obj "overlap.t*" *> \out -> writeFile' out "overlap.t*"- obj "overlap.*" *> \out -> writeFile' out "overlap.*"- alternatives $ do- obj "alternative.t*" *> \out -> writeFile' out "alternative.txt"- obj "alternative.*" *> \out -> writeFile' out "alternative.*"-- obj "chain.2" *> \out -> do- src <- readFile' $ obj "chain.1"- if src == "err" then error "err_chain" else writeFileChanged out src- obj "chain.3" *> \out -> copyFile' (obj "chain.2") out---test build obj = do- let crash args parts = assertException parts (build $ "--quiet" : args)- build ["clean"]- build ["--sleep"]-- writeFile (obj "chain.1") "x"- build ["chain.3","--sleep"]- writeFile (obj "chain.1") "err"- crash ["chain.3"] ["err_chain"]-- crash ["norule"] ["norule_isavailable"]- crash ["failcreate"] ["failcreate"]- crash ["failcreates"] ["failcreates"]- crash ["recursive"] ["recursive"]- crash ["systemcmd"] ["systemcmd","random_missing_command"]- crash ["stack1"] ["stack1","stack2","stack3","crash"]-- b <- IO.doesFileExist $ obj "staunch1"- when b $ removeFile $ obj "staunch1"- crash ["staunch1","staunch2","-j2"] ["crash"]- b <- IO.doesFileExist $ obj "staunch1"- assert (not b) "File should not exist, should have crashed first"- crash ["staunch1","staunch2","-j2","--keep-going","--silent"] ["crash"]- b <- IO.doesFileExist $ obj "staunch1"- assert b "File should exist, staunch should have let it be created"-- crash ["finally1"] ["die"]- assertContents (obj "finally1") "1"- build ["finally2"]- assertContents (obj "finally2") "1"- crash ["exception1"] ["die"]- assertContents (obj "exception1") "1"- build ["exception2"]- assertContents (obj "exception2") "0"-- forM_ ["finally3","finally4"] $ \name -> do- t <- forkIO $ build [name,"--exception"] `E.catch` \(_ :: SomeException) -> return ()- retry 10 $ sleep 0.1 >> assertContents (obj name) "0"- throwTo t (IndexOutOfBounds "test")- retry 10 $ sleep 0.1 >> assertContents (obj name) "1"-- crash ["resource"] ["cannot currently call apply","withResource","resource_name"]-- build ["overlap.foo"]- assertContents (obj "overlap.foo") "overlap.*"- build ["overlap.txt"]- assertContents (obj "overlap.txt") "overlap.txt"- crash ["overlap.txx"] ["key matches multiple rules","overlap.txx"]- build ["alternative.foo","alternative.txt"]- assertContents (obj "alternative.foo") "alternative.*"- assertContents (obj "alternative.txt") "alternative.txt"
− Test/FilePath.hs
@@ -1,96 +0,0 @@--module Test.FilePath(main) where--import Development.Shake.FilePath-import qualified System.FilePath as Native-import qualified System.FilePath.Posix as Posix-import General.Base-import Test.Type-import Test.QuickCheck-import Control.Monad-import Data.List-import qualified Data.ByteString.Char8 as BS-import qualified Development.Shake.ByteString as BS---main = shaken test $ \args obj -> return ()---newtype File = File String deriving Show--instance Arbitrary File where- arbitrary = fmap File $ listOf $ oneof $ map return "abc /\\:."---test build obj = do- let a === b = a Test.Type.=== b -- duplicate definition in QuickCheck 2.7 and above-- let norm x =- let s = normalise x- b = BS.unpack (BS.filepathNormalise $ BS.pack x)- in if s == b then s else error $ show ("Normalise functions differ",x,s,b)- -- basic examples- norm "" === "."- norm "." === "."- norm "/" === "/"- norm "./" === "./"- norm "/." === "/."- norm "/./" === "/"- norm "a/." === "a"- norm "./a" === "a"- norm "./a/." === "a"- norm "./a/./" === "a/"- norm "a/.." === "."- norm "a/./.." === "."- norm "a/../" === "./"- norm "/a/../" === "/"- norm "/a/./../" === "/"- norm "../a" === "../a"- norm "/../a/" === "/../a/"-- -- more realistic examples- norm "neil//./test/moo/../bar/bob/../foo" === "neil/test/bar/foo"- norm "bar/foo" === "bar/foo"- norm "bar/foo/" === "bar/foo/"- norm "../../foo" === "../../foo"- norm "foo/../..///" === "../"- norm "foo/bar/../../neil" === "neil"- norm "foo/../bar/../neil" === "neil"- norm "/foo/bar" === "/foo/bar"- norm "//./" === (if isWindows then "//" else "/")- norm "//foo/./bar" === (if isWindows then "//foo/bar" else "/foo/bar")- when isWindows $ norm "c:\\foo\\bar" === "c:/foo/bar"- Success{} <- quickCheckWithResult stdArgs{maxSuccess=1000} $ \(File x) ->- let y = norm x- sep = Native.isPathSeparator- noDrive = if isWindows then drop 1 else id- ps = [length y >= 1- ,null x || (sep (head x) == sep (head y) && sep (last x) == sep (last y))- ,not $ "/./" `isInfixOf` y- ,not isWindows || '\\' `notElem` y- ,not $ "//" `isInfixOf` noDrive y- ,".." `notElem` dropWhile (== "..") (splitDirectories $ dropWhile sep y)- ,norm y == y]- in if and ps then True else error $ show (x, y, ps)-- dropDirectory1 "aaa/bbb" === "bbb"- dropDirectory1 "aaa/" === ""- dropDirectory1 "aaa" === ""- dropDirectory1 "" === ""-- takeDirectory1 "aaa/bbb" === "aaa"- takeDirectory1 "aaa/" === "aaa"- takeDirectory1 "aaa" === "aaa"-- combine "." "ccc" === "ccc"- combine "aaa/bbb" "ccc" === "aaa/bbb/ccc"- combine "aaa/bbb" "./ccc" === "aaa/bbb/ccc"- combine "aaa/bbb" "../ccc" === "aaa/ccc"- combine "aaa/bbb" "../../ccc" === "ccc"- combine ".." "aaa" === "../aaa"- combine "../.." "aaa" === "../../aaa"- combine "./a" "../aaa" === "aaa"- combine ".." "../aaa" === "../../aaa"-- searchPathSeparator === Native.searchPathSeparator- pathSeparators === Posix.pathSeparators
− Test/FilePattern.hs
@@ -1,61 +0,0 @@--module Test.FilePattern(main) where--import Development.Shake.FilePattern-import Test.Type--main = shaken test $ \args obj -> return ()---test build obj = do- let f b pat file = assert (b == (pat ?== file)) $ show pat ++ " ?== " ++ show file ++ "\nEXPECTED: " ++ show b- f True "//*.c" "foo/bar/baz.c"- f True "*.c" "baz.c"- f True "//*.c" "baz.c"- f True "test.c" "test.c"- f False "*.c" "foor/bar.c"- f False "*/*.c" "foo/bar/baz.c"- f False "foo//bar" "foobar"- f False "foo//bar" "foobar/bar"- f False "foo//bar" "foo/foobar"- f True "foo//bar" "foo/bar"-- assert (compatible []) "compatible"- assert (compatible ["//*a.txt","foo//a*.txt"]) "compatible"- assert (not $ compatible ["//*a.txt","foo//a*.*txt"]) "compatible"- extract "//*a.txt" "foo/bar/testa.txt" === ["foo/bar/","test"]- extract "//*a.txt" "testa.txt" === ["","test"]- extract "//*a*.txt" "testada.txt" === ["","test","da"]- substitute ["","test","da"] "//*a*.txt" === "testada.txt"- substitute ["foo/bar/","test"] "//*a.txt" === "foo/bar/testa.txt"-- directories1 "*.xml" === ("",False)- directories1 "//*.xml" === ("",True)- directories1 "foo//*.xml" === ("foo",True)- directories1 "foo/bar/*.xml" === ("foo/bar",False)- directories1 "*/bar/*.xml" === ("",True)- directories ["*.xml","//*.c"] === [("",True)]- directories ["bar/*.xml","baz//*.c"] === [("bar",False),("baz",True)]- directories ["bar/*.xml","baz//*.c"] === [("bar",False),("baz",True)]--------------------------------------------------------------------------- LAZY SMALLCHECK PROPERTIES--{--newtype Pattern = Pattern FilePattern deriving (Show,Eq)-newtype Path = Path FilePath deriving (Show,Eq)---- Since / and * are the only "interesting" elements, just add ab to round out the set--instance Serial Pattern where- series = cons Pattern >< f- where f = cons [] \/ cons (:) >< const (drawnFrom "/*ab") >< f--instance Serial Path where- series = cons Path >< f- where f = cons [] \/ cons (:) >< const (drawnFrom "/ab") >< f--testSmallCheck = do- smallCheck 10 $ \(Pattern p) (Path x) -> p ?== x ==> substitute (extract p x) p == x--}
− Test/Files.hs
@@ -1,39 +0,0 @@--module Test.Files(main) where--import Development.Shake-import Test.Type-import Control.Monad-import Data.List---main = shaken test $ \args obj -> do- let fun = "@" `elem` args- let rest = delete "@" args- want $ map obj $ if null rest then ["even.txt","odd.txt"] else rest-- -- Since &?> and &*> are implemented separately we test everything in both modes- let deps &?*> act | fun = (\x -> if x `elem` deps then Just deps else Nothing) &?> act- | otherwise = deps &*> act-- map obj ["even.txt","odd.txt"] &?*> \[evens,odds] -> do- src <- readFileLines $ obj "numbers.txt"- let (es,os) = partition even $ map read src- writeFileLines evens $ map show es- writeFileLines odds $ map show os-- map obj ["dir1/out.txt","dir2/out.txt"] &?*> \[a,b] -> do- writeFile' a "a"- writeFile' b "b"---test build obj = do- forM_ [[],["@"]] $ \args -> do- let nums = unlines . map show- writeFile (obj "numbers.txt") $ nums [1,2,4,5,2,3,1]- build ("--sleep":args)- assertContents (obj "even.txt") $ nums [2,4,2]- assertContents (obj "odd.txt" ) $ nums [1,5,3,1]- build ["clean"]- build ["--no-build","--report=-"]- build ["dir1/out.txt"]
− Test/Journal.hs
@@ -1,44 +0,0 @@--module Test.Journal(main) where--import Control.Monad-import Data.IORef-import Development.Shake-import Development.Shake.FilePath-import Test.Type-import System.IO.Unsafe---{-# NOINLINE rebuilt #-}-rebuilt :: IORef Int-rebuilt = unsafePerformIO $ newIORef 0---main = shaken test $ \args obj -> do- want $ map obj ["a.out","b.out","c.out"]- obj "*.out" *> \out -> do- liftIO $ atomicModifyIORef rebuilt $ \a -> (a+1,())- copyFile' (out -<.> "in") out---test build obj = do- - let change x = writeFile (obj $ x <.> "in") x- let count x = do- before <- readIORef rebuilt- build ["--sleep"]- after <- readIORef rebuilt- x === after - before-- change "a"- change "b"- change "c"- count 3-- -- test that compressing the database doesn't corrupt anything- replicateM_ 4 $ do- change "a"- count 1- change "a"- change "c"- count 2
− Test/Lint.hs
@@ -1,119 +0,0 @@--module Test.Lint(main) where--import Development.Shake-import Development.Shake.FilePath-import Test.Type-import Control.Exception hiding (assert)-import System.Directory as IO-import Control.Monad-import Data.Maybe---main = shaken test $ \args obj -> do- want $ map obj args-- addOracle $ \() -> do- liftIO $ createDirectoryIfMissing True $ obj "dir"- liftIO $ setCurrentDirectory $ obj "dir"- return ()-- obj "changedir" *> \out -> do- () <- askOracle ()- writeFile' out ""-- obj "pause.*" *> \out -> do- liftIO $ sleep 0.1- need [obj "cdir" <.> takeExtension out]- writeFile' out ""-- obj "cdir.*" *> \out -> do- pwd <- liftIO getCurrentDirectory- let dir2 = obj $ "dir" ++ takeExtension out- liftIO $ createDirectoryIfMissing True dir2- liftIO $ setCurrentDirectory dir2- liftIO $ sleep 0.2- liftIO $ setCurrentDirectory pwd- writeFile' out ""-- obj "createonce" *> \out -> do- writeFile' out "X"-- obj "createtwice" *> \out -> do- need [obj "createonce"]- liftIO sleepFileTime- writeFile' (obj "createonce") "Y"- writeFile' out ""-- obj "listing" *> \out -> do- writeFile' (out <.> "ls1") ""- getDirectoryFiles (obj "") ["//*.ls*"]- writeFile' (out <.> "ls2") ""- writeFile' out ""-- obj "existance" *> \out -> do- Development.Shake.doesFileExist $ obj "exists"- writeFile' (obj "exists") ""- writeFile' out ""-- obj "gen*" *> \out -> do- writeFile' out out-- obj "needed1" *> \out -> do- needed [obj "gen1"]- writeFile' out ""-- obj "needed2" *> \out -> do- orderOnly [obj "gen2"]- needed [obj "gen2"]- writeFile' out ""-- obj "tracker-write1" *> \out -> do- () <- cmd "cmd /c" ["echo x > " ++ out <.> "txt"]- need [out <.> "txt"]- writeFile' out ""-- obj "tracker-write2" *> \out -> do- () <- cmd "cmd /c" ["echo x > " ++ out <.> "txt"]- writeFile' out ""-- obj "tracker-source2" *> \out -> copyFile' (obj "tracker-source1") out- obj "tracker-read1" *> \out -> do- () <- cmd "cmd /c" ["type " ++ toNative (obj "tracker-source1") ++ " > nul"]- writeFile' out ""- obj "tracker-read2" *> \out -> do- () <- cmd "cmd /c" ["type " ++ toNative (obj "tracker-source1") ++ " > nul"]- need [obj "tracker-source1"]- writeFile' out ""- obj "tracker-read3" *> \out -> do- () <- cmd "cmd /c" ["type " ++ toNative (obj "tracker-source2") ++ " > nul"]- need [obj "tracker-source2"]- writeFile' out ""---test build obj = do- dir <- getCurrentDirectory- let crash args parts = do- assertException parts (build $ "--quiet" : args)- `finally` setCurrentDirectory dir-- crash ["changedir"] ["current directory has changed"]- build ["cdir.1","cdir.2","-j1"]- build ["--clean","cdir.1","pause.2","-j1"]- crash ["--clean","cdir.1","pause.2","-j2"] ["before building output/lint/","current directory has changed"]- crash ["existance"] ["changed since being depended upon"]- crash ["createtwice"] ["changed since being depended upon"]- crash ["listing"] ["changed since being depended upon","output/lint"]- crash ["--clean","listing","existance"] ["changed since being depended upon"]- crash ["needed1"] ["'needed' file required rebuilding"]- build ["needed2"]-- tracker <- findExecutable "tracker.exe"- when (isJust tracker) $ do- writeFile (obj "tracker-source1") ""- writeFile (obj "tracker-source2") ""- crash ["tracker-write1"] ["not have its creation tracked","lint/tracker-write1","lint/tracker-write1.txt"]- build ["tracker-write2"]- crash ["tracker-read1"] ["used but not depended upon","lint/tracker-source1"]- build ["tracker-read2"]- crash ["tracker-read3"] ["depended upon after being used","lint/tracker-source2"]
− Test/Live.hs
@@ -1,29 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}--module Test.Live(main) where--import Development.Shake-import Test.Type---main = shaken test $ \args obj -> do- want $ map obj args-- obj "foo" *> \ out -> do- need [obj "bar"]- writeFile' out ""-- obj "bar" *> \out -> writeFile' out ""- obj "baz" *> \out -> writeFile' out ""---test build obj = do- build ["clean"]- build ["foo","baz","--live=" ++ obj "live.txt"]- assertContentsUnordered (obj "live.txt") $ map obj $ words "foo bar baz"- build ["foo","baz","--live=" ++ obj "live.txt"]- assertContentsUnordered (obj "live.txt") $ map obj $ words "foo bar baz"- build ["foo","--live=" ++ obj "live.txt"]- assertContentsUnordered (obj "live.txt") $ map obj $ words "foo bar"- build ["bar","--live=" ++ obj "live.txt"]- assertContentsUnordered (obj "live.txt") $ map obj $ words "bar"
− Test/MakeTutor/Makefile
@@ -1,17 +0,0 @@-# From http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/, Makefile 4--CC=gcc-CFLAGS=-I.-DEPS = hellomake.h-OBJ = hellomake.o hellofunc.o --hellomake$(EXE): $(OBJ)- $(CC) -o $@ $^ $(CFLAGS)--%.o: %.c $(DEPS)- $(CC) -c -o $@ $< $(CFLAGS)--.PHONY: clean-clean:- rm hellomake$(EXE)- rm *.o
− Test/MakeTutor/hellofunc.c
@@ -1,9 +0,0 @@-#include <stdio.h>-#include <hellomake.h>--void myPrintHelloMake(void) {-- printf("Hello makefiles!\n");-- return;-}
− Test/MakeTutor/hellomake.c
@@ -1,8 +0,0 @@-#include <hellomake.h>--int main() {- // call a function in another file- myPrintHelloMake();-- return(0);-}
− Test/MakeTutor/hellomake.h
@@ -1,5 +0,0 @@-/*-example include file-*/--void myPrintHelloMake(void);
− Test/Makefile.hs
@@ -1,24 +0,0 @@--module Test.Makefile(main) where--import Development.Shake(action, liftIO)-import qualified Start as Makefile-import System.Environment-import Test.Type-import Control.Monad-import Data.List-import Data.Maybe---main = shaken test $ \args obj ->- action $ liftIO $ do- unless (["@@"] `isPrefixOf` args) $- error "The 'makefile' example should only be used in test mode, to test using a makefile use the 'make' example."- withArgs [fromMaybe x $ stripPrefix "@" x | x <- drop 1 args] Makefile.main---test build obj = do- copyDirectoryChanged "Test/MakeTutor" $ obj "MakeTutor"- build ["@@","--directory=" ++ obj "MakeTutor","--no-report"]- build ["@@","--directory=" ++ obj "MakeTutor","--no-report"]- build ["@@","--directory=" ++ obj "MakeTutor","@clean","--no-report"]
− Test/Manual.hs
@@ -1,24 +0,0 @@--module Test.Manual(main) where--import Development.Shake hiding (copyFileChanged)-import Development.Shake.FilePath-import Test.Type-import General.Base---main = shaken test $ \args obj ->- action $ liftIO $ error "The 'manual' example should only be used in test mode"--test build obj = do- copyDirectoryChanged "docs/manual" $ obj "manual"- copyDirectoryChanged "Development" $ obj "manual/Development"- copyDirectoryChanged "General" $ obj "manual/General"- copyFileChanged "Paths.hs" $ obj "manual/Paths_shake.hs"- let cmdline = if isWindows then "build.bat" else "/bin/sh build.sh"- () <- cmd [Cwd $ obj "manual", Shell] cmdline "-j2"- assertExists $ obj "manual/_build/run" <.> exe- () <- cmd [Cwd $ obj "manual", Shell] cmdline- () <- cmd [Cwd $ obj "manual", Shell] [cmdline,"clean"]- assertMissing $ obj "manual/_build/run" <.> exe- return ()
− Test/Monad.hs
@@ -1,89 +0,0 @@--module Test.Monad(main) where--import Test.Type-import Development.Shake.Monad--import Data.IORef-import Control.Concurrent-import Control.Exception hiding (assert)-import Control.Monad-import Control.Monad.IO.Class---main = shaken test $ \args obj -> return ()---run :: ro -> rw -> RAW ro rw a -> IO a-run ro rw m = do- res <- newEmptyMVar- runRAW ro rw m $ void . tryPutMVar res- either throwIO return =<< readMVar res---test build obj = do- let conv x = either (Left . fromException) Right x :: Either (Maybe ArithException) Int- let dump ro rw = do liftIO . (=== ro) =<< getRO; liftIO . (=== rw) =<< getRW-- -- test the basics plus exception handling- run 1 "test" $ do- dump 1 "test"- putRW "more"- dump 1 "more"- res <- tryRAW $ withRO (+3) $ do- dump 4 "more"- withRW (++ "x") $ do- dump 4 "morex"- dump 4 "more"- return 100- liftIO $ conv res === Right 100- dump 1 "more"- putRW "new"- dump 1 "new"- res <- tryRAW $ withRO (+2) $ do- dump 3 "new"- withRW (++ "x") $ do- dump 3 "newx"- throwRAW Overflow- error "Should not have reached here"- return 9- liftIO $ conv res === Left (Just Overflow)- dump 1 "new"- catchRAW (catchRAW (throwRAW Overflow) $ \_ -> modifyRW (++ "x")) $- \_ -> modifyRW (++ "y")- dump 1 "newx"- catchRAW (catchRAW (throwRAW Overflow) $ \e -> modifyRW (++ "x") >> throwRAW e) $- \_ -> modifyRW (++ "y")- dump 1 "newxxy"-- -- test capture- run 1 "test" $ do- i <- captureRAW $ \k -> k $ Right 1- liftIO $ i === 1- i <- tryRAW $ captureRAW $ \k -> k $ Left $ toException Overflow- liftIO $ conv i === Left (Just Overflow)- captureRAW $ \k -> k $ Right ()- i <- tryRAW $ throwRAW Underflow- liftIO $ conv i === Left (Just Underflow)-- -- catch does not scope too far- res <- try $ run 1 "test" $- fmap (either show id) $ tryRAW $ captureRAW $ \k -> throwIO Overflow- res === Left Overflow- res <- try $ run 1 "test" $ do- captureRAW $ \k -> throwIO Overflow- return "x"- res === Left Overflow-- -- catch works properly if continuation called multiple times- ref <- newIORef []- run 1 "test" $- flip catchRAW (const $ liftIO $ modifyIORef ref ('x':)) $ do- captureRAW $ \k -> do- k $ Right ()- k $ Right ()- k $ Left $ toException Overflow- k $ Right ()- k $ Left $ toException Overflow- flip catchRAW (const $ liftIO $ modifyIORef ref ('y':)) $ throwRAW $ toException Overflow- (===) "xyxyy" =<< readIORef ref
− Test/Ninja.hs
@@ -1,87 +0,0 @@--module Test.Ninja(main) where--import Development.Shake-import Development.Shake.FilePath-import qualified Development.Shake.Config as Config-import System.Directory(copyFile)-import Control.Monad-import General.Base-import Test.Type-import qualified Data.HashMap.Strict as Map-import Data.List-import Data.Maybe-import qualified Start-import System.Environment---main = shaken test $ \args obj -> do- let args2 = ("-C" ++ obj "") : map tail (filter ("@" `isPrefixOf`) args)- let real = "real" `elem` args- action $- if real then cmd "ninja" args2 else liftIO $ withArgs args2 Start.main---test build obj = do- -- when calling run anything with a leading @ gets given to Shake, anything without gets given to Ninja- let run xs = build $ "--exception" : map (\x -> fromMaybe ('@':x) $ stripPrefix "@" x) (words xs)- let runFail xs bad = assertException [bad] $ run $ xs ++ " --quiet"-- build ["clean"]- run "-f../../Test/Ninja/test1.ninja"- assertExists $ obj "out1.txt"-- run "-f../../Test/Ninja/test2.ninja"- assertExists $ obj "out2.2"- assertMissing $ obj "out2.1"- build ["clean"]- run "-f../../Test/Ninja/test2.ninja out2.1"- assertExists $ obj "out2.1"- assertMissing $ obj "out2.2"-- copyFile "Test/Ninja/test3-sub.ninja" $ obj "test3-sub.ninja"- copyFile "Test/Ninja/test3-inc.ninja" $ obj "test3-inc.ninja"- copyFile ("Test/Ninja/" ++ if null exe then "test3-unix.ninja" else "test3-win.ninja") $ obj "test3-platform.ninja"- run "-f../../Test/Ninja/test3.ninja"- assertNonSpace (obj "out3.1") "g4+b1+++i1"- assertNonSpace (obj "out3.2") "g4++++i1"- assertNonSpace (obj "out3.3") "g4++++i1"- assertNonSpace (obj "out3.4") "g4+++s1+s2"-- run "-f../../Test/Ninja/test4.ninja out"- assertExists $ obj "out.txt"- assertExists $ obj "out2.txt"-- run "-f../../Test/Ninja/test5.ninja"- assertExists $ obj "output file"-- writeFile (obj "nocreate.log") ""- writeFile (obj "nocreate.in") ""- run "-f../../Test/Ninja/nocreate.ninja"- assertNonSpace (obj "nocreate.log") "x"- run "-f../../Test/Ninja/nocreate.ninja"- run "-f../../Test/Ninja/nocreate.ninja"- assertNonSpace (obj "nocreate.log") "xxx"-- writeFile (obj "input") ""- runFail "-f../../Test/Ninja/lint.ninja bad --lint" "'needed' file required rebuilding"- run "-f../../Test/Ninja/lint.ninja good --lint"- runFail "-f../../Test/Ninja/lint.ninja bad --lint" "not a pre-dependency"-- res <- fmap (drop 1 . lines) $ captureOutput $ run "-f../../Test/Ninja/compdb.ninja -t compdb cxx @--no-report @--quiet"- want <- fmap lines $ readFile "Test/Ninja/compdb.output"- let eq a b | (a1,'*':a2) <- break (== '*') a = unless (a1 `isPrefixOf` b && a2 `isSuffixOf` b) $ a === b- | otherwise = a === b- length want === length res- zipWithM_ eq want res-- -- Test initial variable bindings and variables in include/subninja statements- let test6 = obj "test6"-- copyFile "Test/Ninja/test6-sub.ninja" $ test6 ++ "-sub.ninja"- copyFile "Test/Ninja/test6-inc.ninja" $ test6 ++ "-inc.ninja"- copyFile "Test/Ninja/test6.ninja" $ test6 ++ ".ninja"-- config <- Config.readConfigFileWithEnv [("v1", test6)] $ test6 ++ ".ninja"- -- The file included by subninja should have a separate variable scope- Map.lookup "v2" config === Just "g2"
− Test/Ninja/compdb.ninja
@@ -1,45 +0,0 @@-# Copied from the Ninja repo--ninja_required_version = 1.3--builddir = build-cxx = g++-ar = ar-cflags = -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti $- -fno-exceptions -pipe -Wno-missing-field-initializers $- -DNINJA_PYTHON="python.exe" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501-ldflags = -L$builddir -static--rule cxx- command = $cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out- description = CXX $out- depfile = $out.d- deps = gcc--rule ar- command = cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out- description = AR $out--rule link- command = $cxx $ldflags -o $out $in $libs- description = LINK $out--# the depfile parser and ninja lexers are generated using re2c.--# Core source files all build into ninja library.-build $builddir\build.o: cxx src\build.cc-build $builddir\build_log.o: cxx src\build_log.cc-build $builddir\clean.o: cxx src\clean.cc--rule doxygen- command = doxygen $in- description = DOXYGEN $in-doxygen_mainpage_generator = src\gen_doxygen_mainpage.sh-rule doxygen_mainpage- command = $doxygen_mainpage_generator $in > $out- description = DOXYGEN_MAINPAGE $out-build $builddir\doxygen_mainpage: doxygen_mainpage README COPYING | $- $doxygen_mainpage_generator-build doxygen: doxygen doc\doxygen.config | $builddir\doxygen_mainpage--default ninja.exe
− Test/Ninja/compdb.output
@@ -1,17 +0,0 @@-[- {- "directory": "*",- "command": "g++ -MMD -MT build\\build.o -MF build\\build.o.d -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti -fno-exceptions -pipe -Wno-missing-field-initializers -DNINJA_PYTHON=\"python.exe\" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501 -c src\\build.cc -o build\\build.o",- "file": "src\\build.cc"- },- {- "directory": "*",- "command": "g++ -MMD -MT build\\build_log.o -MF build\\build_log.o.d -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti -fno-exceptions -pipe -Wno-missing-field-initializers -DNINJA_PYTHON=\"python.exe\" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501 -c src\\build_log.cc -o build\\build_log.o",- "file": "src\\build_log.cc"- },- {- "directory": "*",- "command": "g++ -MMD -MT build\\clean.o -MF build\\clean.o.d -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti -fno-exceptions -pipe -Wno-missing-field-initializers -DNINJA_PYTHON=\"python.exe\" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501 -c src\\clean.cc -o build\\clean.o",- "file": "src\\clean.cc"- }-]
− Test/Ninja/lint.ninja
@@ -1,13 +0,0 @@- -rule gen - command = echo $out > $out - -rule run - command = (echo $out : $out.gen > $out.d) && (echo $out > $out) - depfile = $out.d - -build good: run || good.gen bad.gen -build good.gen: gen - -build bad: run | input -build bad.gen: gen
− Test/Ninja/nocreate.ninja
@@ -1,5 +0,0 @@--rule gen- command = echo x >> nocreate.log--build nocreate.out: gen nocreate.in
− Test/Ninja/test1.ninja
@@ -1,5 +0,0 @@--rule run- command = touch $out--build out1.txt: run
− Test/Ninja/test2.ninja
@@ -1,8 +0,0 @@- -rule run - command = touch $out - -build out2.1: run -build out2.2: run - -default out2.2
− Test/Ninja/test3-inc.ninja
@@ -1,3 +0,0 @@-v5 = i1 - -build out3.3: dump
− Test/Ninja/test3-sub.ninja
@@ -1,6 +0,0 @@-v4 = s1 -v5 = s1 - -build out3.4: dump - -v5 = s2
− Test/Ninja/test3-unix.ninja
@@ -1,3 +0,0 @@- -rule dump - command = echo "$v1+$v2+$v3+$v4+$v5" > $out
− Test/Ninja/test3-win.ninja
@@ -1,3 +0,0 @@- -rule dump - command = cmd /c "echo $v1+$v2+$v3+$v4+$v5 > $out"
− Test/Ninja/test3.ninja
@@ -1,21 +0,0 @@- - -v1 = g1 -v5 = g1 - -include test3-platform.ninja - -v1 = g2 - -build out3.1: dump - v2 = b1 - -v1 = g3 - -subninja test3-sub.ninja - -include test3-inc.ninja - -build out3.2: dump - -v1 = g4
− Test/Ninja/test4.ninja
@@ -1,9 +0,0 @@- -rule run - command = touch $out - -build ./out.txt: run - -build dir/../out2.txt: run - -build out: phony ./out.txt out2.txt
− Test/Ninja/test5.ninja
@@ -1,5 +0,0 @@- -rule run - command = touch $out - -build output$ file: run
− Test/Ninja/test6-inc.ninja
@@ -1,1 +0,0 @@-v2 = g2
− Test/Ninja/test6-sub.ninja
@@ -1,1 +0,0 @@-v2 = g3
− Test/Ninja/test6.ninja
@@ -1,3 +0,0 @@-v2 = g1-include ${v1}-inc.ninja-subninja ${v1}-sub.ninja
− Test/Oracle.hs
@@ -1,76 +0,0 @@-{-# LANGUAGE ScopedTypeVariables, PatternGuards #-}--module Test.Oracle(main) where--import Development.Shake-import Test.Type-import Control.Monad---main = shaken test $ \args obj -> do- let f name lhs rhs = (,) name $- (do addOracle $ \k -> let _ = k `asTypeOf` lhs in return rhs; return ()- ,let o = obj name ++ ".txt" in do want [o]; o *> \_ -> do v <- askOracleWith lhs rhs; writeFile' o $ show v)- let tbl = [f "str-bool" "" True- ,f "str-int" "" (0::Int)- ,f "bool-str" True ""- ,f "int-str" (0::Int) ""]-- forM_ args $ \a -> case a of- '+':x | Just (add,_) <- lookup x tbl -> add- '*':x | Just (_,use) <- lookup x tbl -> use- '@':key -> do addOracle $ \() -> return key; return ()- '%':name -> let o = obj "unit.txt" in do want [o]; o *> \_ -> do {askOracleWith () ""; writeFile' o name}- '!':name -> do want [obj "rerun"]; obj "rerun" *> \out -> do alwaysRerun; writeFile' out name--test build obj = do- build ["clean"]-- -- check it rebuilds when it should- build ["@key","%name"]- assertContents (obj "unit.txt") "name"- build ["@key","%test"]- assertContents (obj "unit.txt") "name"- build ["@foo","%test"]- assertContents (obj "unit.txt") "test"-- -- check adding/removing redundant oracles does not trigger a rebuild- build ["@foo","%newer","+str-bool"]- assertContents (obj "unit.txt") "test"- build ["@foo","%newer","+str-int"]- assertContents (obj "unit.txt") "test"- build ["@foo","%newer"]- assertContents (obj "unit.txt") "test"-- -- check always run works- build ["!foo"]- assertContents (obj "rerun") "foo"- build ["!bar"]- assertContents (obj "rerun") "bar"-- -- check error messages are good- let errors args err = assertException [err] $ build $ "--quiet" : args-- build ["+str-int","*str-int"]- errors ["*str-int"] -- Building with an an Oracle that has been removed- "missing a call to addOracle"-- errors ["*str-bool"] -- Building with an Oracle that I know nothing about- "missing a call to addOracle"-- build ["+str-int","*str-int"]- errors ["+str-bool","*str-int"] -- Building with an Oracle that has changed type- "askOracle is used at the wrong type"-- errors ["+str-int","+str-bool"] -- Two Oracles with the same question type- "Only one call to addOracle is allowed"-- errors ["+str-int","*str-bool"] -- Using an Oracle at the wrong answer type- "askOracle is used at the wrong type"-- build ["+str-int","+str-int"] -- Two Oracles work if they aren't used- errors ["+str-int","+str-int","*str-int"] -- Two Oracles fail if they are used- "Only one call to addOracle is allowed"-- errors ["+str-int","+str-bool"] -- Two Oracles with the same answer type- "Only one call to addOracle is allowed"
− Test/OrderOnly.hs
@@ -1,41 +0,0 @@--module Test.OrderOnly(main) where--import Development.Shake-import Test.Type---main = shaken test $ \args obj -> do- want $ map obj args-- obj "bar.txt" *> \out -> do- alwaysRerun- writeFile' out =<< liftIO (readFile $ obj "bar.in")-- obj "foo.txt" *> \out -> do- let src = obj "bar.txt"- orderOnly [src]- writeFile' out =<< liftIO (readFile src)- need [src]-- obj "baz.txt" *> \out -> do- let src = obj "bar.txt"- orderOnly [src]- liftIO $ appendFile out "x"---test build obj = do- writeFile (obj "bar.in") "in"- build ["foo.txt","--sleep"]- assertContents (obj "foo.txt") "in"- writeFile (obj "bar.in") "out"- build ["foo.txt","--sleep"]- assertContents (obj "foo.txt") "out"-- writeFile (obj "baz.txt") ""- writeFile (obj "bar.in") "in"- build ["baz.txt","--sleep"]- assertContents (obj "baz.txt") "x"- writeFile (obj "bar.in") "out"- build ["baz.txt"]- assertContents (obj "baz.txt") "x"
− Test/Pool.hs
@@ -1,68 +0,0 @@--module Test.Pool(main) where--import Test.Type-import Development.Shake.Pool--import Control.Concurrent-import Control.Exception hiding (assert)-import Control.Monad---main = shaken test $ \args obj -> return ()---test build obj = do- let wait = sleep 0.01- forM_ [False,True] $ \deterministic -> do-- -- check that it aims for exactly the limit- forM_ [1..6] $ \n -> do- var <- newMVar (0,0) -- (maximum, current)- runPool deterministic n $ \pool ->- forM_ [1..5] $ \i ->- addPool pool $ do- modifyMVar_ var $ \(mx,now) -> return (max (now+1) mx, now+1)- wait- modifyMVar_ var $ \(mx,now) -> return (mx,now-1)- res <- takeMVar var- res === (min n 5, 0)-- -- check that exceptions are immediate- self <- myThreadId- handle (\(ErrorCall msg) -> msg === "pass") $- runPool deterministic 3 $ \pool -> do- addPool pool $ do- wait- error "pass"- addPool pool $ do- wait >> wait- throwTo self $ ErrorCall "fail" - wait >> wait -- give chance for a delayed exception-- -- check someone spawned when at zero todo still gets run- done <- newMVar False- runPool deterministic 1 $ \pool ->- addPool pool $ do- wait- addPool pool $ do- wait- modifyMVar_ done $ const $ return True- done <- readMVar done- assert done "Waiting on someone"-- -- check that killing a thread pool stops the tasks, bug 545- thread <- newEmptyMVar- done <- newEmptyMVar- res <- newMVar True- t <- forkIO $ finally (putMVar done ()) $ runPool deterministic 1 $ \pool ->- addPool pool $ do- t <- takeMVar thread- killThread t- wait -- allow the thread to die first- modifyMVar_ res (const $ return False)- putMVar thread t- takeMVar done- wait >> wait >> wait -- allow the bad thread to continue- res <- readMVar res- assert res "Early termination"
− Test/Progress.hs
@@ -1,63 +0,0 @@-{-# LANGUAGE DeriveDataTypeable #-}--module Test.Progress(main) where--import Development.Shake.Progress-import Test.Type-import Data.Monoid-import System.Directory-import System.FilePath---main = shaken test $ \args obj -> return ()----- | Given a list of todo times, get out a list of how long is predicted-prog = progEx 10000000000000000---progEx :: Double -> [Double] -> IO [Double]-progEx mxDone todo = do- let resolution = 10000 -- Use resolution to get extra detail on the numbers- let done = scanl (+) 0 $ map (min mxDone . max 0) $ zipWith (-) todo (tail todo)- let res = progressReplay $ zip (map (*resolution) [1..]) $ tail $ zipWith (\t d -> mempty{timeBuilt=d*resolution,timeTodo=(t*resolution,0)}) todo done- return $ (0/0) : map ((/ resolution) . actualSecs) res---test build obj = do- -- perfect functions should match perfectly- xs <- prog [10,9..1]- drop 2 xs === [8,7..1]- xs <- prog $ map (*5) [10,9..1]- drop 2 xs === [8,7..1]- xs <- prog $ map (*0.2) [10,9..1]- let dp3 x = fromIntegral (round $ x * 1000 :: Int) / 1000- map dp3 (drop 2 xs) === [8,7..1]-- -- The properties below this line could be weakened-- -- increasing functions can't match- xs <- prog [5,6,7]- last xs === 7-- -- the first value must be plausible, or missing- xs <- prog [187]- assert (isNaN $ head xs) "No first value"-- -- desirable properties, could be weakened- xs <- progEx 2 $ 100:map (*2) [10,9..1]- drop 5 xs === [6,5..1]- xs <- progEx 1 $ [10,9,100,8,7,6,5,4,3,2,1]- assert (all (<= 1.5) $ map abs $ zipWith (-) (drop 5 xs) [6,5..1]) "Close"-- -- if no progress is made, don't keep the time going up- xs <- prog [10,9,8,7,7,7,7,7]- drop 5 xs === [7,7,7]-- -- if the work rate changes, should somewhat reflect that- xs <- prog [10,9,8,7,6.5,6,5.5,5]- assert (last xs > 7.1) "Some discounting (factor=0 would give 7)"-- xs <- getDirectoryContents "Test/Progress"- build $ ["--progress=replay=Test/Progress/" ++ x | x <- xs, takeExtension x == ".prog"] ++- ["--no-report","--report=-","--report=" ++ obj "progress.html"]
− Test/Progress/self-clean-j2.prog
@@ -1,62 +0,0 @@-(1.120224,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 254, countUnknown = 0, countTodo = 145, timeSkipped = 0.0, timeBuilt = 0.8861771221272647, timeUnknown = 0.0, timeTodo = (0.0,145)}) -(2.4994998,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 258, countUnknown = 0, countTodo = 147, timeSkipped = 0.0, timeBuilt = 1.259251721901819, timeUnknown = 0.0, timeTodo = (0.0,147)}) -(5.156031,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 259, countUnknown = 0, countTodo = 146, timeSkipped = 0.0, timeBuilt = 3.8557707152795047, timeUnknown = 0.0, timeTodo = (0.0,146)}) -(6.4472423,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 261, countUnknown = 0, countTodo = 144, timeSkipped = 0.0, timeBuilt = 6.519303449196741, timeUnknown = 0.0, timeTodo = (0.0,144)}) -(7.737371,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 262, countUnknown = 0, countTodo = 143, timeSkipped = 0.0, timeBuilt = 9.126777537865564, timeUnknown = 0.0, timeTodo = (0.0,143)}) -(9.061503,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 267, countUnknown = 0, countTodo = 138, timeSkipped = 0.0, timeBuilt = 11.739121564431116, timeUnknown = 0.0, timeTodo = (0.0,138)}) -(10.368634,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 268, countUnknown = 0, countTodo = 137, timeSkipped = 0.0, timeBuilt = 14.354383119149134, timeUnknown = 0.0, timeTodo = (0.0,137)}) -(11.658763,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 272, countUnknown = 0, countTodo = 133, timeSkipped = 0.0, timeBuilt = 16.976646550698206, timeUnknown = 0.0, timeTodo = (0.0,133)}) -(12.941892,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 274, countUnknown = 0, countTodo = 131, timeSkipped = 0.0, timeBuilt = 19.57990659098141, timeUnknown = 0.0, timeTodo = (0.0,131)}) -(14.22602,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 279, countUnknown = 0, countTodo = 126, timeSkipped = 0.0, timeBuilt = 22.17116750101559, timeUnknown = 0.0, timeTodo = (0.0,126)}) -(15.511148,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 282, countUnknown = 0, countTodo = 123, timeSkipped = 0.0, timeBuilt = 24.74242699961178, timeUnknown = 0.0, timeTodo = (0.0,123)}) -(16.794277,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 283, countUnknown = 0, countTodo = 122, timeSkipped = 0.0, timeBuilt = 27.31368459085934, timeUnknown = 0.0, timeTodo = (0.0,122)}) -(18.085405,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 288, countUnknown = 0, countTodo = 117, timeSkipped = 0.0, timeBuilt = 29.8999453864526, timeUnknown = 0.0, timeTodo = (0.0,117)}) -(19.398537,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 294, countUnknown = 0, countTodo = 111, timeSkipped = 0.0, timeBuilt = 32.487208493752405, timeUnknown = 0.0, timeTodo = (0.0,111)}) -(21.451742,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 295, countUnknown = 0, countTodo = 110, timeSkipped = 0.0, timeBuilt = 35.872547277016565, timeUnknown = 0.0, timeTodo = (0.0,110)}) -(22.761873,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 297, countUnknown = 0, countTodo = 108, timeSkipped = 0.0, timeBuilt = 39.24288571695797, timeUnknown = 0.0, timeTodo = (0.0,108)}) -(24.060003,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 298, countUnknown = 0, countTodo = 107, timeSkipped = 0.0, timeBuilt = 41.825143941445276, timeUnknown = 0.0, timeTodo = (0.0,107)}) -(25.555153,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 304, countUnknown = 0, countTodo = 101, timeSkipped = 0.0, timeBuilt = 44.66642964701168, timeUnknown = 0.0, timeTodo = (0.0,101)}) -(26.868284,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 305, countUnknown = 0, countTodo = 100, timeSkipped = 0.0, timeBuilt = 47.460708745522425, timeUnknown = 0.0, timeTodo = (0.0,100)}) -(28.22642,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 306, countUnknown = 0, countTodo = 99, timeSkipped = 0.0, timeBuilt = 50.111974843544886, timeUnknown = 0.0, timeTodo = (0.0,99)}) -(29.52355,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 308, countUnknown = 0, countTodo = 97, timeSkipped = 0.0, timeBuilt = 52.788244374794886, timeUnknown = 0.0, timeTodo = (0.0,97)}) -(30.82868,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 309, countUnknown = 0, countTodo = 96, timeSkipped = 0.0, timeBuilt = 55.38850606302731, timeUnknown = 0.0, timeTodo = (0.0,96)}) -(31.83378,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 309, countUnknown = 0, countTodo = 96, timeSkipped = 0.0, timeBuilt = 55.38850606302731, timeUnknown = 0.0, timeTodo = (0.0,96)}) -(33.099907,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 311, countUnknown = 0, countTodo = 94, timeSkipped = 0.0, timeBuilt = 57.70873845438473, timeUnknown = 0.0, timeTodo = (0.0,94)}) -(34.455044,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 312, countUnknown = 0, countTodo = 93, timeSkipped = 0.0, timeBuilt = 62.583227284951136, timeUnknown = 0.0, timeTodo = (0.0,93)}) -(35.775173,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 323, countUnknown = 0, countTodo = 82, timeSkipped = 0.0, timeBuilt = 65.22149098734371, timeUnknown = 0.0, timeTodo = (0.0,82)}) -(37.087307,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 324, countUnknown = 0, countTodo = 81, timeSkipped = 0.0, timeBuilt = 67.89576161722653, timeUnknown = 0.0, timeTodo = (0.0,81)}) -(38.39644,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 332, countUnknown = 0, countTodo = 73, timeSkipped = 0.0, timeBuilt = 70.54603017191403, timeUnknown = 0.0, timeTodo = (0.0,73)}) -(39.705566,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 336, countUnknown = 0, countTodo = 69, timeSkipped = 0.0, timeBuilt = 73.18129933695309, timeUnknown = 0.0, timeTodo = (0.0,69)}) -(41.676765,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 339, countUnknown = 0, countTodo = 66, timeSkipped = 0.0, timeBuilt = 76.48663152079098, timeUnknown = 0.0, timeTodo = (0.0,66)}) -(42.969894,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 342, countUnknown = 0, countTodo = 63, timeSkipped = 0.0, timeBuilt = 79.77195943216793, timeUnknown = 0.0, timeTodo = (0.0,63)}) -(44.364033,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 345, countUnknown = 0, countTodo = 60, timeSkipped = 0.0, timeBuilt = 82.46222890238278, timeUnknown = 0.0, timeTodo = (0.0,60)}) -(45.367134,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 348, countUnknown = 0, countTodo = 57, timeSkipped = 0.0, timeBuilt = 85.15849507669918, timeUnknown = 0.0, timeTodo = (0.0,57)}) -(47.0483,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 351, countUnknown = 0, countTodo = 54, timeSkipped = 0.0, timeBuilt = 87.8587666831445, timeUnknown = 0.0, timeTodo = (0.0,54)}) -(48.052402,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 351, countUnknown = 0, countTodo = 54, timeSkipped = 0.0, timeBuilt = 87.8587666831445, timeUnknown = 0.0, timeTodo = (0.0,54)}) -(49.890587,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 0, countTodo = 51, timeSkipped = 0.0, timeBuilt = 90.69304478983395, timeUnknown = 0.0, timeTodo = (0.0,51)}) -(50.894688,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 0, countTodo = 51, timeSkipped = 0.0, timeBuilt = 90.69304478983395, timeUnknown = 0.0, timeTodo = (0.0,51)}) -(51.897785,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 0, countTodo = 51, timeSkipped = 0.0, timeBuilt = 90.69304478983395, timeUnknown = 0.0, timeTodo = (0.0,51)}) -(54.92909,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 0, countTodo = 48, timeSkipped = 0.0, timeBuilt = 94.47342885355465, timeUnknown = 0.0, timeTodo = (0.0,48)}) -(56.23222,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 358, countUnknown = 0, countTodo = 47, timeSkipped = 0.0, timeBuilt = 97.04368794779293, timeUnknown = 0.0, timeTodo = (0.0,47)}) -(57.53035,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 360, countUnknown = 0, countTodo = 45, timeSkipped = 0.0, timeBuilt = 100.92107594828121, timeUnknown = 0.0, timeTodo = (0.0,45)}) -(58.82748,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 361, countUnknown = 0, countTodo = 44, timeSkipped = 0.0, timeBuilt = 103.52433598856442, timeUnknown = 0.0, timeTodo = (0.0,44)}) -(60.104607,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 368, countUnknown = 0, countTodo = 37, timeSkipped = 0.0, timeBuilt = 106.14560521463864, timeUnknown = 0.0, timeTodo = (0.0,37)}) -(62.0268,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 369, countUnknown = 0, countTodo = 36, timeSkipped = 0.0, timeBuilt = 109.38093007425778, timeUnknown = 0.0, timeTodo = (0.0,36)}) -(63.33293,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 372, countUnknown = 0, countTodo = 33, timeSkipped = 0.0, timeBuilt = 112.58624852518551, timeUnknown = 0.0, timeTodo = (0.0,33)}) -(64.62606,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 374, countUnknown = 0, countTodo = 31, timeSkipped = 0.0, timeBuilt = 115.16150487284176, timeUnknown = 0.0, timeTodo = (0.0,31)}) -(65.925186,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 379, countUnknown = 0, countTodo = 26, timeSkipped = 0.0, timeBuilt = 117.77476704935543, timeUnknown = 0.0, timeTodo = (0.0,26)}) -(68.11641,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 0, countTodo = 18, timeSkipped = 0.0, timeBuilt = 122.62825597147457, timeUnknown = 0.0, timeTodo = (0.0,18)}) -(69.121506,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 0, countTodo = 18, timeSkipped = 0.0, timeBuilt = 122.62825597147457, timeUnknown = 0.0, timeTodo = (0.0,18)}) -(70.77867,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 390, countUnknown = 0, countTodo = 15, timeSkipped = 0.0, timeBuilt = 125.30251897196285, timeUnknown = 0.0, timeTodo = (0.0,15)}) -(74.353035,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 393, countUnknown = 0, countTodo = 12, timeSkipped = 0.0, timeBuilt = 127.54874242166989, timeUnknown = 0.0, timeTodo = (0.0,12)}) -(75.35613,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 396, countUnknown = 0, countTodo = 9, timeSkipped = 0.0, timeBuilt = 130.15401280741207, timeUnknown = 0.0, timeTodo = (0.0,9)}) -(76.85028,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 399, countUnknown = 0, countTodo = 6, timeSkipped = 0.0, timeBuilt = 133.99539006571285, timeUnknown = 0.0, timeTodo = (0.0,6)}) -(79.081505,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 402, countUnknown = 0, countTodo = 3, timeSkipped = 0.0, timeBuilt = 136.22862065653317, timeUnknown = 0.0, timeTodo = (0.0,3)}) -(81.25272,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(82.260826,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(83.26492,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(84.27003,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(85.274124,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(86.28023,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(87.284325,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)}) -(88.28843,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})
− Test/Progress/self-rebuild-j2.prog
@@ -1,56 +0,0 @@-(3.6053605,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 258, countUnknown = 1, countTodo = 147, timeSkipped = 0.0, timeBuilt = 1.054105345858261, timeUnknown = 0.0, timeTodo = (135.01951599121094,0)}) -(4.8964896,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 259, countUnknown = 1, countTodo = 146, timeSkipped = 0.0, timeBuilt = 3.6373634978663176, timeUnknown = 0.0, timeTodo = (132.3802523612976,0)}) -(6.189619,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 260, countUnknown = 1, countTodo = 145, timeSkipped = 0.0, timeBuilt = 6.2686262771021575, timeUnknown = 0.0, timeTodo = (129.85099935531616,0)}) -(7.4677467,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 262, countUnknown = 1, countTodo = 143, timeSkipped = 0.0, timeBuilt = 8.854884450091049, timeUnknown = 0.0, timeTodo = (127.25373983383179,0)}) -(8.742874,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 268, countUnknown = 1, countTodo = 137, timeSkipped = 0.0, timeBuilt = 11.444143597735092, timeUnknown = 0.0, timeTodo = (124.70048475265503,0)}) -(10.016002,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 271, countUnknown = 1, countTodo = 134, timeSkipped = 0.0, timeBuilt = 16.5466540500056, timeUnknown = 0.0, timeTodo = (119.64597797393799,0)}) -(11.30813,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 271, countUnknown = 1, countTodo = 134, timeSkipped = 0.0, timeBuilt = 16.5466540500056, timeUnknown = 0.0, timeTodo = (119.64597797393799,0)}) -(12.59526,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 276, countUnknown = 1, countTodo = 129, timeSkipped = 0.0, timeBuilt = 19.123910252703354, timeUnknown = 0.0, timeTodo = (117.0657205581665,0)}) -(13.876388,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 278, countUnknown = 1, countTodo = 127, timeSkipped = 0.0, timeBuilt = 21.708168332232162, timeUnknown = 0.0, timeTodo = (114.43845868110657,0)}) -(15.173517,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 280, countUnknown = 1, countTodo = 125, timeSkipped = 0.0, timeBuilt = 24.27642471040599, timeUnknown = 0.0, timeTodo = (111.89620327949524,0)}) -(16.456646,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 282, countUnknown = 1, countTodo = 123, timeSkipped = 0.0, timeBuilt = 26.85868198121898, timeUnknown = 0.0, timeTodo = (109.3659496307373,0)}) -(17.726772,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 284, countUnknown = 1, countTodo = 121, timeSkipped = 0.0, timeBuilt = 29.442940060747787, timeUnknown = 0.0, timeTodo = (106.83069705963135,0)}) -(19.027903,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 288, countUnknown = 1, countTodo = 117, timeSkipped = 0.0, timeBuilt = 32.00519592012279, timeUnknown = 0.0, timeTodo = (104.28944301605225,0)}) -(20.345034,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 292, countUnknown = 1, countTodo = 113, timeSkipped = 0.0, timeBuilt = 34.586452786577865, timeUnknown = 0.0, timeTodo = (101.74619007110596,0)}) -(21.648165,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 300, countUnknown = 1, countTodo = 105, timeSkipped = 0.0, timeBuilt = 37.32872611726634, timeUnknown = 0.0, timeTodo = (99.18993377685547,0)}) -(23.717371,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 301, countUnknown = 1, countTodo = 104, timeSkipped = 0.0, timeBuilt = 40.75507003511302, timeUnknown = 0.0, timeTodo = (96.41965675354004,0)}) -(25.022503,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 303, countUnknown = 1, countTodo = 102, timeSkipped = 0.0, timeBuilt = 44.12840873445384, timeUnknown = 0.0, timeTodo = (93.89340400695801,0)}) -(26.289629,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 304, countUnknown = 1, countTodo = 101, timeSkipped = 0.0, timeBuilt = 46.6976664706599, timeUnknown = 0.0, timeTodo = (91.36415100097656,0)}) -(27.576757,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 305, countUnknown = 1, countTodo = 100, timeSkipped = 0.0, timeBuilt = 49.27292472566478, timeUnknown = 0.0, timeTodo = (88.50186347961426,0)}) -(29.49495,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 308, countUnknown = 1, countTodo = 97, timeSkipped = 0.0, timeBuilt = 52.47924644197337, timeUnknown = 0.0, timeTodo = (84.93850708007813,0)}) -(31.11511,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 311, countUnknown = 1, countTodo = 94, timeSkipped = 0.0, timeBuilt = 56.04560119356029, timeUnknown = 0.0, timeTodo = (81.36915397644043,0)}) -(32.42124,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 313, countUnknown = 1, countTodo = 92, timeSkipped = 0.0, timeBuilt = 58.938888852251694, timeUnknown = 0.0, timeTodo = (78.84289932250977,0)}) -(33.68837,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 315, countUnknown = 1, countTodo = 90, timeSkipped = 0.0, timeBuilt = 61.51514465059154, timeUnknown = 0.0, timeTodo = (75.96561431884766,0)}) -(34.961494,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 322, countUnknown = 1, countTodo = 83, timeSkipped = 0.0, timeBuilt = 64.10740501130931, timeUnknown = 0.0, timeTodo = (73.41636085510254,0)}) -(36.245625,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 330, countUnknown = 1, countTodo = 75, timeSkipped = 0.0, timeBuilt = 66.67165786470287, timeUnknown = 0.0, timeTodo = (70.8551082611084,0)}) -(37.545753,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 331, countUnknown = 1, countTodo = 74, timeSkipped = 0.0, timeBuilt = 69.22791320527904, timeUnknown = 0.0, timeTodo = (68.3188533782959,0)}) -(38.944893,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 336, countUnknown = 1, countTodo = 69, timeSkipped = 0.0, timeBuilt = 71.91318160737865, timeUnknown = 0.0, timeTodo = (65.60857582092285,0)}) -(40.345036,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 337, countUnknown = 1, countTodo = 68, timeSkipped = 0.0, timeBuilt = 74.72146255220287, timeUnknown = 0.0, timeTodo = (62.849300384521484,0)}) -(41.651165,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 340, countUnknown = 1, countTodo = 65, timeSkipped = 0.0, timeBuilt = 77.43573409761302, timeUnknown = 0.0, timeTodo = (60.147029876708984,0)}) -(42.9913,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 345, countUnknown = 1, countTodo = 60, timeSkipped = 0.0, timeBuilt = 80.11199981416576, timeUnknown = 0.0, timeTodo = (57.615779876708984,0)}) -(44.28843,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 347, countUnknown = 1, countTodo = 58, timeSkipped = 0.0, timeBuilt = 82.76326781953685, timeUnknown = 0.0, timeTodo = (55.096527099609375,0)}) -(45.844585,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 350, countUnknown = 1, countTodo = 55, timeSkipped = 0.0, timeBuilt = 85.57555038179271, timeUnknown = 0.0, timeTodo = (53.285343170166016,0)}) -(46.848686,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 88.44083816255443, timeUnknown = 0.0, timeTodo = (50.76008987426758,0)}) -(47.852783,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 88.44083816255443, timeUnknown = 0.0, timeTodo = (50.76008987426758,0)}) -(50.848083,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 1, countTodo = 48, timeSkipped = 0.0, timeBuilt = 92.16721374238841, timeUnknown = 0.0, timeTodo = (48.103824615478516,0)}) -(52.852283,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 358, countUnknown = 1, countTodo = 47, timeSkipped = 0.0, timeBuilt = 95.5145495578181, timeUnknown = 0.0, timeTodo = (45.494564056396484,0)}) -(54.130413,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 362, countUnknown = 1, countTodo = 43, timeSkipped = 0.0, timeBuilt = 100.13300735200755, timeUnknown = 0.0, timeTodo = (41.70818328857422,0)}) -(55.41054,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 363, countUnknown = 1, countTodo = 42, timeSkipped = 0.0, timeBuilt = 102.67526275361888, timeUnknown = 0.0, timeTodo = (39.17192840576172,0)}) -(56.414642,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 369, countUnknown = 1, countTodo = 36, timeSkipped = 0.0, timeBuilt = 105.25251800264232, timeUnknown = 0.0, timeTodo = (36.63368225097656,0)}) -(59.073906,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 372, countUnknown = 1, countTodo = 33, timeSkipped = 0.0, timeBuilt = 107.67676574434154, timeUnknown = 0.0, timeTodo = (34.10843276977539,0)}) -(60.356033,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 374, countUnknown = 1, countTodo = 31, timeSkipped = 0.0, timeBuilt = 110.21202117647044, timeUnknown = 0.0, timeTodo = (31.546173095703125,0)}) -(61.641163,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 375, countUnknown = 1, countTodo = 30, timeSkipped = 0.0, timeBuilt = 114.02240401948802, timeUnknown = 0.0, timeTodo = (28.913909912109375,0)}) -(62.92029,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 381, countUnknown = 1, countTodo = 24, timeSkipped = 0.0, timeBuilt = 116.60766250337474, timeUnknown = 0.0, timeTodo = (26.366653442382813,0)}) -(65.09751,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 121.40914184297435, timeUnknown = 0.0, timeTodo = (22.06322479248047,0)}) -(66.10161,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 121.40914184297435, timeUnknown = 0.0, timeTodo = (22.06322479248047,0)}) -(67.678764,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 390, countUnknown = 1, countTodo = 15, timeSkipped = 0.0, timeBuilt = 123.98239928926341, timeUnknown = 0.0, timeTodo = (19.453964233398438,0)}) -(71.20812,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 393, countUnknown = 1, countTodo = 12, timeSkipped = 0.0, timeBuilt = 126.19761687959544, timeUnknown = 0.0, timeTodo = (17.226730346679688,0)}) -(72.21122,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 396, countUnknown = 1, countTodo = 9, timeSkipped = 0.0, timeBuilt = 128.785888974322, timeUnknown = 0.0, timeTodo = (14.163421630859375,0)}) -(73.53935,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 399, countUnknown = 1, countTodo = 6, timeSkipped = 0.0, timeBuilt = 133.6913836642634, timeUnknown = 0.0, timeTodo = (11.642166137695313,0)}) -(75.757576,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 402, countUnknown = 1, countTodo = 3, timeSkipped = 0.0, timeBuilt = 135.9266131564509, timeUnknown = 0.0, timeTodo = (8.530860900878906,0)}) -(77.91779,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)}) -(78.92289,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)}) -(79.925995,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)}) -(80.93109,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)}) -(81.93419,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)}) -(82.93929,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})
− Test/Progress/self-zero-j2.prog
@@ -1,57 +0,0 @@-(1.020102,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 254, countUnknown = 4, countTodo = 148, timeSkipped = 0.0, timeBuilt = 0.7620761110447347, timeUnknown = 2.0004000980407e-3, timeTodo = (146.13152742385864,0)}) -(3.7443745,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 258, countUnknown = 1, countTodo = 147, timeSkipped = 0.0, timeBuilt = 1.0521051175892353, timeUnknown = 0.0, timeTodo = (145.76045322418213,0)}) -(5.032503,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 260, countUnknown = 1, countTodo = 145, timeSkipped = 0.0, timeBuilt = 3.678367782384157, timeUnknown = 0.0, timeTodo = (143.16193342208862,0)}) -(6.339634,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 261, countUnknown = 1, countTodo = 144, timeSkipped = 0.0, timeBuilt = 6.317631412297487, timeUnknown = 0.0, timeTodo = (140.56067323684692,0)}) -(7.6067605,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 262, countUnknown = 1, countTodo = 143, timeSkipped = 0.0, timeBuilt = 8.911890674382448, timeUnknown = 0.0, timeTodo = (137.99141645431519,0)}) -(8.867887,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 265, countUnknown = 1, countTodo = 140, timeSkipped = 0.0, timeBuilt = 11.489148784428835, timeUnknown = 0.0, timeTodo = (135.31988191604614,0)}) -(10.124012,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 266, countUnknown = 1, countTodo = 139, timeSkipped = 0.0, timeBuilt = 14.01840179041028, timeUnknown = 0.0, timeTodo = (132.74862432479858,0)}) -(11.394139,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 270, countUnknown = 1, countTodo = 135, timeSkipped = 0.0, timeBuilt = 16.545654464513063, timeUnknown = 0.0, timeTodo = (130.13927960395813,0)}) -(12.661266,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 278, countUnknown = 1, countTodo = 127, timeSkipped = 0.0, timeBuilt = 19.09290998056531, timeUnknown = 0.0, timeTodo = (127.51380348205566,0)}) -(13.928392,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 280, countUnknown = 1, countTodo = 125, timeSkipped = 0.0, timeBuilt = 21.638164687901735, timeUnknown = 0.0, timeTodo = (124.94054412841797,0)}) -(15.19352,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 283, countUnknown = 1, countTodo = 122, timeSkipped = 0.0, timeBuilt = 24.176418472081423, timeUnknown = 0.0, timeTodo = (122.32628202438354,0)}) -(16.462646,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 284, countUnknown = 1, countTodo = 121, timeSkipped = 0.0, timeBuilt = 26.708671737462282, timeUnknown = 0.0, timeTodo = (119.71102046966553,0)}) -(17.723772,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 286, countUnknown = 1, countTodo = 119, timeSkipped = 0.0, timeBuilt = 29.24492471292615, timeUnknown = 0.0, timeTodo = (117.13076210021973,0)}) -(18.9989,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 290, countUnknown = 1, countTodo = 115, timeSkipped = 0.0, timeBuilt = 31.782178092747927, timeUnknown = 0.0, timeTodo = (114.32748413085938,0)}) -(20.265026,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 294, countUnknown = 1, countTodo = 111, timeSkipped = 0.0, timeBuilt = 34.328432250767946, timeUnknown = 0.0, timeTodo = (110.95114421844482,0)}) -(21.525152,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 296, countUnknown = 1, countTodo = 109, timeSkipped = 0.0, timeBuilt = 36.87168710306287, timeUnknown = 0.0, timeTodo = (108.3658857345581,0)}) -(22.792278,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 297, countUnknown = 1, countTodo = 108, timeSkipped = 0.0, timeBuilt = 39.39593904092908, timeUnknown = 0.0, timeTodo = (105.79362773895264,0)}) -(24.09941,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 301, countUnknown = 1, countTodo = 104, timeSkipped = 0.0, timeBuilt = 41.934190917760134, timeUnknown = 0.0, timeTodo = (103.46539211273193,0)}) -(25.552555,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 307, countUnknown = 1, countTodo = 98, timeSkipped = 0.0, timeBuilt = 44.71846978738904, timeUnknown = 0.0, timeTodo = (100.06105041503906,0)}) -(27.156715,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 310, countUnknown = 1, countTodo = 95, timeSkipped = 0.0, timeBuilt = 47.48474519327283, timeUnknown = 0.0, timeTodo = (97.22976875305176,0)}) -(28.427843,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 311, countUnknown = 1, countTodo = 94, timeSkipped = 0.0, timeBuilt = 50.347032714635134, timeUnknown = 0.0, timeTodo = (94.5565013885498,0)}) -(29.692968,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 312, countUnknown = 1, countTodo = 93, timeSkipped = 0.0, timeBuilt = 53.222318816930056, timeUnknown = 0.0, timeTodo = (91.93223762512207,0)}) -(30.960096,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 314, countUnknown = 1, countTodo = 91, timeSkipped = 0.0, timeBuilt = 55.76357476785779, timeUnknown = 0.0, timeTodo = (89.2559642791748,0)}) -(32.22322,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 317, countUnknown = 1, countTodo = 88, timeSkipped = 0.0, timeBuilt = 58.305828262120485, timeUnknown = 0.0, timeTodo = (86.59769439697266,0)}) -(33.50235,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 321, countUnknown = 1, countTodo = 84, timeSkipped = 0.0, timeBuilt = 60.847080398350954, timeUnknown = 0.0, timeTodo = (83.98942756652832,0)}) -(34.50545,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 321, countUnknown = 1, countTodo = 84, timeSkipped = 0.0, timeBuilt = 60.847080398350954, timeUnknown = 0.0, timeTodo = (83.98942756652832,0)}) -(35.778576,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 327, countUnknown = 1, countTodo = 78, timeSkipped = 0.0, timeBuilt = 64.42744653299451, timeUnknown = 0.0, timeTodo = (79.1019344329834,0)}) -(37.039703,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 331, countUnknown = 1, countTodo = 74, timeSkipped = 0.0, timeBuilt = 67.99280183389783, timeUnknown = 0.0, timeTodo = (75.79260063171387,0)}) -(38.30183,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 332, countUnknown = 1, countTodo = 73, timeSkipped = 0.0, timeBuilt = 70.5080529935658, timeUnknown = 0.0, timeTodo = (73.16133689880371,0)}) -(39.60196,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 337, countUnknown = 1, countTodo = 68, timeSkipped = 0.0, timeBuilt = 73.04030625894666, timeUnknown = 0.0, timeTodo = (70.54007148742676,0)}) -(40.9971,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 341, countUnknown = 1, countTodo = 64, timeSkipped = 0.0, timeBuilt = 75.7465783841908, timeUnknown = 0.0, timeTodo = (67.84580421447754,0)}) -(42.251225,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 343, countUnknown = 1, countTodo = 62, timeSkipped = 0.0, timeBuilt = 78.44684617593884, timeUnknown = 0.0, timeTodo = (64.56347465515137,0)}) -(43.51035,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 348, countUnknown = 1, countTodo = 57, timeSkipped = 0.0, timeBuilt = 80.97609345987439, timeUnknown = 0.0, timeTodo = (61.85720443725586,0)}) -(45.31053,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 85.3115312345326, timeUnknown = 0.0, timeTodo = (56.32666015625,0)}) -(46.31663,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 85.3115312345326, timeUnknown = 0.0, timeTodo = (56.32666015625,0)}) -(47.953796,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 1, countTodo = 48, timeSkipped = 0.0, timeBuilt = 87.96779649332166, timeUnknown = 0.0, timeTodo = (52.5462760925293,0)}) -(49.22192,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 1, countTodo = 48, timeSkipped = 0.0, timeBuilt = 87.96779649332166, timeUnknown = 0.0, timeTodo = (52.5462760925293,0)}) -(50.483047,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 358, countUnknown = 1, countTodo = 47, timeSkipped = 0.0, timeBuilt = 90.48504655435681, timeUnknown = 0.0, timeTodo = (49.943016052246094,0)}) -(51.742172,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 362, countUnknown = 1, countTodo = 43, timeSkipped = 0.0, timeBuilt = 94.27242677286267, timeUnknown = 0.0, timeTodo = (46.054622650146484,0)}) -(53.0143,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 364, countUnknown = 1, countTodo = 41, timeSkipped = 0.0, timeBuilt = 96.79567353799939, timeUnknown = 0.0, timeTodo = (43.455360412597656,0)}) -(54.279427,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 365, countUnknown = 1, countTodo = 40, timeSkipped = 0.0, timeBuilt = 99.32792680338025, timeUnknown = 0.0, timeTodo = (40.88410568237305,0)}) -(55.549553,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 368, countUnknown = 1, countTodo = 37, timeSkipped = 0.0, timeBuilt = 101.87118165567517, timeUnknown = 0.0, timeTodo = (38.3088493347168,0)}) -(56.90669,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 371, countUnknown = 1, countTodo = 34, timeSkipped = 0.0, timeBuilt = 104.48744599893689, timeUnknown = 0.0, timeTodo = (35.06652069091797,0)}) -(58.179817,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 372, countUnknown = 1, countTodo = 33, timeSkipped = 0.0, timeBuilt = 107.11970918253064, timeUnknown = 0.0, timeTodo = (32.46625900268555,0)}) -(59.453945,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 380, countUnknown = 1, countTodo = 25, timeSkipped = 0.0, timeBuilt = 109.69997041299939, timeUnknown = 0.0, timeTodo = (29.24193572998047,0)}) -(61.17312,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 114.0083963163197, timeUnknown = 0.0, timeTodo = (24.391448974609375,0)}) -(62.17922,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 114.0083963163197, timeUnknown = 0.0, timeTodo = (24.391448974609375,0)}) -(63.787376,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 390, countUnknown = 1, countTodo = 15, timeSkipped = 0.0, timeBuilt = 116.61765687540174, timeUnknown = 0.0, timeTodo = (21.717185974121094,0)}) -(67.25372,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 393, countUnknown = 1, countTodo = 12, timeSkipped = 0.0, timeBuilt = 118.84489076212049, timeUnknown = 0.0, timeTodo = (19.470962524414063,0)}) -(69.114914,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 399, countUnknown = 1, countTodo = 6, timeSkipped = 0.0, timeBuilt = 124.42945497110486, timeUnknown = 0.0, timeTodo = (13.024314880371094,0)}) -(70.91309,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 402, countUnknown = 1, countTodo = 3, timeSkipped = 0.0, timeBuilt = 127.54076020792127, timeUnknown = 0.0, timeTodo = (10.791084289550781,0)}) -(72.67527,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)}) -(73.68037,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)}) -(74.683464,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)}) -(75.68657,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)}) -(76.68967,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)}) -(77.69477,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})
− Test/Random.hs
@@ -1,138 +0,0 @@-{-# LANGUAGE PatternGuards #-}--module Test.Random(main) where--import Development.Shake-import Test.Type-import Control.Exception-import Control.Monad-import Data.List-import Data.Maybe-import System.Environment-import System.Exit-import System.Random-import General.Base---inputRange = [1..10]--data Value = Single Int | Multiple [[Value]]- deriving (Read,Show,Eq)--data Source = Input Int | Output Int | Bang- deriving (Read,Show)--data Logic = Logic Int [[Source]]- | Want [Int]- deriving (Read,Show)---main = shaken test $ \args obj -> do- let toFile (Input i) = obj $ "input-" ++ show i ++ ".txt"- toFile (Output i) = obj $ "output-" ++ show i ++ ".txt"- toFile Bang = error "BANG"-- let randomSleep = liftIO $ do- i <- randomRIO (0, 25)- sleep $ intToDouble i / 100-- forM_ (map read $ filter (isNothing . asDuration) args) $ \x -> case x of- Want xs -> want $ map (toFile . Output) xs- Logic out srcs -> toFile (Output out) *> \out -> do- res <- fmap (show . Multiple) $ forM srcs $ \src -> do- randomSleep- need $ map toFile src- mapM (liftIO . fmap read . readFileStrict . toFile) src- randomSleep- writeFileChanged out res---asDuration :: String -> Maybe Double-asDuration x- | "s" `isSuffixOf` x, [(i,"")] <- reads $ init x = Just i- | "m" `isSuffixOf` x, [(i,"")] <- reads $ init x = Just $ i * 60- | otherwise = Nothing---test build obj = do- limit <- do- args <- getArgs- let bound = listToMaybe $ reverse $ mapMaybe asDuration args- time <- offsetTime- return $ when (isJust bound) $ do- now <- time- when (now > fromJust bound) exitSuccess-- forM_ [1..] $ \count -> do- limit- putStrLn $ "* PERFORMING RANDOM TEST " ++ show count- build ["clean"]- build [] -- to create the directory- forM_ inputRange $ \i ->- writeFile (obj $ "input-" ++ show i ++ ".txt") $ show $ Single i- logic <- randomLogic- runLogic [] logic- chng <- filterM (const randomIO) inputRange - forM_ chng $ \i ->- writeFile (obj $ "input-" ++ show i ++ ".txt") $ show $ Single $ negate i- runLogic chng logic- forM_ inputRange $ \i ->- writeFile (obj $ "input-" ++ show i ++ ".txt") $ show $ Single i- logicBang <- addBang =<< addBang logic- j <- randomRIO (1::Int,8)- res <- try $ build $ "--exception" : ("-j" ++ show j) : map show (logicBang ++ [Want [i | Logic i _ <- logicBang]])- case res of- Left err- | "BANG" `isInfixOf` show (err :: SomeException) -> return () -- error I expected- | otherwise -> error $ "UNEXPECTED ERROR: " ++ show err- _ -> return () -- occasionally we only put BANG in places with no dependenies that don't get rebuilt- runLogic [] $ logic ++ [Want [i | Logic i _ <- logic]]- where- runLogic :: [Int] -> [Logic] -> IO ()- runLogic negated xs = do- let poss = [i | Logic i _ <- xs]- i <- randomRIO (0, 7)- wants <- replicateM i $ do- i <- randomRIO (0, 5)- replicateM i $ randomElem poss- sleepFileTime- j <- randomRIO (1::Int,8)- build $ ("-j" ++ show j) : map show (xs ++ map Want wants)-- let value i = case [ys | Logic j ys <- xs, j == i] of- [ys] -> Multiple $ flip map ys $ map $ \i -> case i of- Input i -> Single $ if i `elem` negated then negate i else i- Output i -> value i- forM_ (concat wants) $ \i -> do- let wanted = value i- got <- fmap read $ readFileStrict $ obj $ "output-" ++ show i ++ ".txt"- when (wanted /= got) $- error $ "INCORRECT VALUE for " ++ show i---addBang :: [Logic] -> IO [Logic]-addBang xs = do- i <- randomRIO (0, length xs - 1)- let (before,now:after) = splitAt i xs- now <- f now- return $ before ++ now : after- where- f (Logic log xs) = do- i <- randomRIO (0, length xs)- let (before,after) = splitAt i xs- return $ Logic log $ before ++ [Bang] : after---randomLogic :: IO [Logic] -- only Logic constructors-randomLogic = do- rules <- randomRIO (1,100)- f rules $ map Input inputRange- where- f 0 avail = return []- f i avail = do- needs <- randomRIO (0,3)- xs <- replicateM needs $ do- ns <- randomRIO (0,3)- replicateM ns $ randomElem avail- let r = Logic i xs- fmap (r:) $ f (i-1) (Output i:avail)
− Test/Resources.hs
@@ -1,33 +0,0 @@--module Test.Resources(main) where--import Development.Shake-import Test.Type-import Control.Monad-import Data.IORef---main extra = do- let cap = 2-- ref <- newIORef 0- flip (shaken test) extra $ \args obj -> do- want $ map obj ["file1.txt","file2.txt","file3.txt","file4.txt"]- res <- newResource "test" cap- res2 <- newResource "test" cap- unless (res < res2 || res2 < res) $ error "Resources should have a good ordering"- obj "*.txt" *> \out ->- withResource res 1 $ do- old <- liftIO $ atomicModifyIORef ref $ \i -> (i+1,i)- when (old >= cap) $ error "Too many resources in use at one time"- liftIO $ sleep 0.1- liftIO $ atomicModifyIORef ref $ \i -> (i-1,i)- writeFile' out ""--test build obj = do- build ["clean"]- build ["-j2"]- build ["clean"]- build ["-j4"]- build ["clean"]- build ["-j10"]
− Test/Self.hs
@@ -1,86 +0,0 @@-{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-}--module Test.Self(main) where--import Development.Shake-import Development.Shake.Classes-import Development.Shake.FilePath-import Test.Type--import Control.Monad-import Data.Char-import Data.List-import System.Info---newtype GhcPkg = GhcPkg () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)-newtype GhcFlags = GhcFlags () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)---main = shaken noTest $ \args obj -> do- let moduleToFile ext xs = map (\x -> if x == '.' then '/' else x) xs <.> ext- want $ if null args then [obj "Main" <.> exe] else args-- -- fixup to cope with Cabal's generated files- let fixPaths x = if x == "Paths_shake.hs" then "Paths.hs" else x-- ghcPkg <- addOracle $ \GhcPkg{} -> do- Stdout out <- quietly $ cmd "ghc-pkg list --simple-output"- return $ words out-- ghcFlags <- addOracle $ \GhcFlags{} -> do- pkgs <- readFileLines $ obj ".pkgs"- return $ map ("-package=" ++) pkgs-- let ghc args = do- -- since ghc-pkg includes the ghc package, it changes if the version does- ghcPkg $ GhcPkg ()- flags <- ghcFlags $ GhcFlags ()- cmd "ghc" flags args-- obj "Main" <.> exe *> \out -> do- src <- readFileLines $ out -<.> "deps"- let os = map (obj . moduleToFile "o") $ "Main":src- need os- ghc $ ["-o",out] ++ os-- obj "/*.deps" *> \out -> do- dep <- readFileLines $ out -<.> "dep"- let xs = map (obj . moduleToFile "deps") dep- need xs- ds <- fmap (nub . sort . (++) dep . concat) $ mapM readFileLines xs- writeFileLines out ds-- obj "/*.dep" *> \out -> do- src <- readFile' $ fixPaths $ unobj $ out -<.> "hs"- let xs = hsImports src- xs <- filterM (doesFileExist . fixPaths . moduleToFile "hs") xs- writeFileLines out xs-- [obj "/*.o",obj "/*.hi"] &*> \[out,_] -> do- deps <- readFileLines $ out -<.> "deps"- let hs = fixPaths $ unobj $ out -<.> "hs"- need $ hs : map (obj . moduleToFile "hi") deps- ghc $ ["-c",hs,"-hide-all-packages","-odir=output/self","-hidir=output/self","-i=output/self"] ++- ["-DPORTABLE","-fwarn-unused-imports","-Werror"] -- to test one CPP branch-- obj ".pkgs" *> \out -> do- src <- readFile' "shake.cabal"- writeFileLines out $ sort $ cabalBuildDepends src--------------------------------------------------------------------------- GRAB INFORMATION FROM FILES--hsImports :: String -> [String]-hsImports xs = [ takeWhile (\x -> isAlphaNum x || x `elem` "._") $ dropWhile (not . isUpper) x- | x <- lines xs, "import " `isPrefixOf` x]----- FIXME: Should actually parse the list from the contents of the .cabal file-cabalBuildDepends :: String -> [String]-cabalBuildDepends _ = packages ++ ["unix" | os /= "mingw32"]--packages = words $- "base transformers binary unordered-containers hashable time old-time bytestring " ++- "filepath directory process deepseq random utf8-string"
− Test/Tar.hs
@@ -1,13 +0,0 @@--module Test.Tar(main) where--import Development.Shake-import Test.Type---main = shaken noTest $ \args obj -> do- want [obj "result.tar"]- obj "result.tar" *> \out -> do- contents <- readFileLines "Test/Tar/list.txt"- need contents- cmd "tar -cf" [out] contents
− Test/Tar/list.txt
@@ -1,3 +0,0 @@-Test/Tar.hs-Main.hs-Test/Tar/list.txt
− Test/Throttle.hs
@@ -1,29 +0,0 @@--module Test.Throttle(main) where--import Development.Shake-import General.Base-import Development.Shake.FilePath-import Test.Type-import Control.Monad---main = shaken test $ \args obj -> do- res <- newThrottle "test" 2 0.2- want $ map obj ["file1.1","file2.1","file3.2","file4.1","file5.2"]- obj "*.*" *> \out -> do- withResource res (read $ drop 1 $ takeExtension out) $- when (takeBaseName out == "file3") $ liftIO $ sleep 0.1- writeFile' out ""--test build obj = do- forM_ [[],["-j8"]] $ \flags -> do- -- we are sometimes over the window if the machine is "a bit loaded" at some particular time- -- therefore we rerun the test three times, and only fail if it fails on all of them- retry 3 $ do- build ["clean"]- (s, _) <- duration $ build []- -- the 0.1s cap is a guess at an upper bound for how long everything else should take- -- and should be raised on slower machines- assert (s >= 0.7 && s < 0.8) $- "Bad throttling, expected to take 0.7s + computation time (cap of 0.1s), took " ++ show s ++ "s"
− Test/Type.hs
@@ -1,211 +0,0 @@--module Test.Type(sleep, module Test.Type) where--import Development.Shake hiding (copyFileChanged)-import Development.Shake.Rule() -- ensure the module gets imported, and thus tested-import General.Base-import General.String-import Development.Shake.FileInfo-import Development.Shake.FilePath--import Control.Exception hiding (assert)-import Control.Monad-import Data.Char-import Data.List-import Data.Maybe-import qualified Data.ByteString as BS-import System.Directory as IO-import System.Environment-import System.Random-import System.Console.GetOpt-import System.IO---shaken- :: (([String] -> IO ()) -> (String -> String) -> IO ())- -> ([String] -> (String -> String) -> Rules ())- -> IO ()- -> IO ()-shaken test rules sleeper = do- name:args <- getArgs- when ("--sleep" `elem` args) sleeper- putStrLn $ "## BUILD " ++ unwords (name:args)- args <- return $ delete "--sleep" args- let out = "output/" ++ name ++ "/"- createDirectoryIfMissing True out- case args of- "test":extra -> do- putStrLn $ "## TESTING " ++ name- -- if the extra arguments are not --quiet/--loud it's probably going to go wrong- let obj x = if "/" `isPrefixOf` x then init out ++ x else out ++ x- test (\args -> withArgs (name:args ++ extra) $ shaken test rules sleeper) obj- putStrLn $ "## FINISHED TESTING " ++ name- "clean":_ -> removeDirectoryRecursive out-{-- "lint":args -> do- let dbfile = out ++ ".database"- tempfile = "output/" ++ name ++ ".database"- b <- IO.doesFileExist dbfile- when b $ renameFile dbfile tempfile- removeDirectoryRecursive out- createDirectoryIfMissing True out- when b $ renameFile tempfile dbfile- shake shakeOptions{shakeFiles=out, shakeLint=True} $ rules args (out++)--}-- "perturb":args -> forever $ do- del <- removeFilesRandom out- threads <- randomRIO (1,4)- putStrLn $ "## TESTING PERTURBATION (" ++ show del ++ " files, " ++ show threads ++ " threads)"- shake shakeOptions{shakeFiles=out, shakeThreads=threads, shakeVerbosity=Quiet} $ rules args (out++)-- args -> do- let (_,files,_) = getOpt Permute [] args- tracker <- findExecutable "tracker.exe"- withArgs (args \\ files) $- shakeWithClean- (removeDirectoryRecursive out) - (shakeOptions{shakeFiles=out, shakeReport=["output/" ++ name ++ "/report.html"], shakeLint=Just $ if isJust tracker then LintTracker else LintBasic})- (rules files (out++))---shakeWithClean :: IO () -> ShakeOptions -> Rules () -> IO ()-shakeWithClean clean opts rules = shakeArgsWith opts [cleanOpt] f- where- cleanOpt = Option "c" ["clean"] (NoArg $ Right ()) "Clean before building."-- f extra files = do- when (extra /= []) clean- if "clean" `elem` files then- clean >> return Nothing- else- return $ Just $ if null files then rules else want files >> withoutActions rules---unobj :: FilePath -> FilePath-unobj = dropDirectory1 . dropDirectory1--assert :: Bool -> String -> IO ()-assert b msg = unless b $ error $ "ASSERTION FAILED: " ++ msg--infix 4 ===--(===) :: (Show a, Eq a) => a -> a -> IO ()-a === b = assert (a == b) $ "failed in ===\nLHS: " ++ show a ++ "\nRHS: " ++ show b---assertExists :: FilePath -> IO ()-assertExists file = do- b <- IO.doesFileExist file- assert b $ "File was expected to exist, but is missing: " ++ file--assertMissing :: FilePath -> IO ()-assertMissing file = do- b <- IO.doesFileExist file- assert (not b) $ "File was expected to be missing, but exists: " ++ file--assertContents :: FilePath -> String -> IO ()-assertContents file want = do- got <- readFile file- assert (want == got) $ "File contents are wrong: " ++ file ++ "\nWANT: " ++ want ++ "\nGOT: " ++ got--assertContentsOn :: (String -> String) -> FilePath -> String -> IO ()-assertContentsOn f file want = do- got <- readFile file- assert (f want == f got) $ "File contents are wrong: " ++ file ++ "\nWANT: " ++ want ++ "\nGOT: " ++ got ++- "\nWANT (transformed): " ++ f want ++ "\nGOT (transformed): " ++ f got--assertNonSpace :: FilePath -> String -> IO ()-assertNonSpace = assertContentsOn $ filter (not . isSpace)--assertContentsInfix :: FilePath -> String -> IO ()-assertContentsInfix file want = do- got <- readFile file- assert (want `isInfixOf` got) $ "File contents are wrong: " ++ file ++ "\nWANT (anywhere): " ++ want ++ "\nGOT: " ++ got--assertContentsUnordered :: FilePath -> [String] -> IO ()-assertContentsUnordered file xs = assertContentsOn (unlines . sort . lines) file (unlines xs)--assertException :: [String] -> IO () -> IO ()-assertException parts act = do- res <- try act- case res of- Left err -> let s = show (err :: SomeException) in forM_ parts $ \p ->- assert (p `isInfixOf` s) $ "Incorrect exception, missing part:\nGOT: " ++ s ++ "\nWANTED: " ++ p- Right _ -> error "Expected an exception but succeeded"---noTest :: ([String] -> IO ()) -> (String -> String) -> IO ()-noTest build obj = do- build ["--abbrev=output=$OUT","-j3"]- build ["--no-build","--report=-"]- build []----- | Sleep long enough for the modification time resolution to catch up-sleepFileTime :: IO ()-sleepFileTime = sleep 1---sleepFileTimeCalibrate :: IO (IO ())-sleepFileTimeCalibrate = do- let file = "output/calibrate"- createDirectoryIfMissing True $ takeDirectory file- mtimes <- forM [1..10] $ \i -> fmap fst $ duration $ do- writeFile file $ show i- let time = fmap (fst . fromMaybe (error "File missing during sleepFileTimeCalibrate")) $ getFileInfo $ packU file- t1 <- time- flip loopM 0 $ \j -> do- writeFile file $ show (i,j)- t2 <- time- return $ if t1 == t2 then Left $ j+1 else Right ()- putStrLn $ "Longest file modification time lag was " ++ show (ceiling (maximum mtimes * 1000)) ++ "ms"- return $ sleep $ min 1 $ maximum mtimes * 2---removeFilesRandom :: FilePath -> IO Int-removeFilesRandom x = do- files <- getDirectoryContentsRecursive x- n <- randomRIO (0,length files)- rs <- replicateM (length files) (randomIO :: IO Double)- mapM_ (removeFile . snd) $ sort $ zip rs files- return n---getDirectoryContentsRecursive :: FilePath -> IO [FilePath]-getDirectoryContentsRecursive dir = do- xs <- IO.getDirectoryContents dir- (dirs,files) <- partitionM IO.doesDirectoryExist [dir </> x | x <- xs, not $ "." `isPrefixOf` x]- rest <- concatMapM getDirectoryContentsRecursive dirs- return $ files++rest---copyDirectoryChanged :: FilePath -> FilePath -> IO ()-copyDirectoryChanged old new = do- xs <- getDirectoryContentsRecursive old- forM_ xs $ \from -> do- let to = new </> drop (length $ addTrailingPathSeparator old) from- createDirectoryIfMissing True $ takeDirectory to- copyFileChanged from to---copyFileChanged :: FilePath -> FilePath -> IO ()-copyFileChanged old new = do- good <- IO.doesFileExist new- good <- if not good then return False else liftM2 (==) (BS.readFile old) (BS.readFile new)- when (not good) $ copyFile old new---withTemporaryDirectory :: (FilePath -> IO ()) -> IO ()-withTemporaryDirectory act = do- tdir <- getTemporaryDirectory- bracket- (openTempFile tdir "shake.hs")- (removeFile . fst)- $ \(file,h) -> do- hClose h- let dir = file ++ "_"- bracket_ (createDirectory dir) (removeDirectoryRecursive dir) (act dir)--skip :: Monad m => a -> m ()-skip x = return ()
− Test/Unicode.hs
@@ -1,61 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}--module Test.Unicode(main) where--import Development.Shake-import Development.Shake.FilePath-import Test.Type-import Control.Exception-import Control.Monad-import System.Directory(createDirectoryIfMissing)----- | Decode a dull ASCII string to certain unicode points, necessary because--- withArgs (even the UTF8 version) throws an encoding error on the > 256 code points-decode :: String -> String-decode ('e':'^':xs) = '\xEA' : decode xs -- Latin Small Letter E With Circumflex-decode (':':')':xs) = '\x263A' : decode xs -- White Smiling Face-decode (x:xs) = x : decode xs-decode [] = []---main = shaken test $ \xs obj -> do- let pre:args = map decode xs- want $ map obj args-- obj (pre ++ "dir/*") *> \out -> do- let src = takeDirectory (takeDirectory out) </> takeFileName out- copyFile' src out-- obj (pre ++ ".out") *> \out -> do- a <- readFile' $ obj $ pre ++ "dir" </> pre <.> "source"- b <- readFile' $ obj pre <.> "multi1"- writeFile' out $ a ++ b-- map obj ["*.multi1","*.multi2"] &*> \[m1,m2] -> do- b <- doesFileExist $ m1 -<.> "exist"- writeFile' m1 $ show b- writeFile' m2 $ show b---test build obj = do- build ["clean"]- -- Useful, if the error message starts crashing...- -- IO.hSetEncoding IO.stdout IO.char8- -- IO.hSetEncoding IO.stderr IO.char8- forM_ ["normal","e^",":)","e^-:)"] $ \pre -> do- createDirectoryIfMissing True $ obj ""- let ext x = obj $ decode pre <.> x- res <- try $ writeFile (ext "source") "x"- case res of- Left (err :: SomeException) ->- putStrLn $ "WARNING: Failed to write file " ++ pre ++ ", skipping unicode test (LANG=C ?)"- Right _ -> do- build [pre,pre <.> "out","--sleep"]- assertContents (ext "out") $ "x" ++ "False"- writeFile (ext "source") "y"- build [pre,pre <.> "out","--sleep"]- assertContents (ext "out") $ "y" ++ "False"- writeFile (ext "exist") ""- build [pre,pre <.> "out"]- assertContents (ext "out") $ "y" ++ "True"
− Test/Util.hs
@@ -1,20 +0,0 @@--module Test.Util(main) where--import Development.Shake.Util-import Test.Type---main = shaken test $ \args obj -> return ()---test build obj = do- parseMakefile "" === []- parseMakefile "a:b c\ndef : ee" === [("a",["b","c"]),("def",["ee"])]- parseMakefile "a: #comment\n#comment : b\nc : d" === [("a",[]),("c",["d"])]- parseMakefile "a \\\n\t:b" === [("a",["b"])]- parseMakefile "#comment\\ a : b" === []- parseMakefile "a: b c \\\n d e\n\nf:g" === [("a",["b","c","d","e"]),("f",["g"])]- parseMakefile "foo/bar: \\\r\n c:/a1 \\\r\n x\r\n" === [("foo/bar",["c:/a1","x"])]- parseMakefile "output.o: src/file/with\\ space.cpp" === [("output.o",["src/file/with space.cpp"])]- parseMakefile "a: b\\ c" === [("a",["b ","c"])]
− Test/Verbosity.hs
@@ -1,39 +0,0 @@--module Test.Verbosity(main) where--import Development.Shake-import Test.Type---main = shaken test $ \args obj -> do- want $ map obj args-- obj "in.txt" *> \out -> do- a <- getVerbosity- b <- withVerbosity Normal $ getVerbosity- writeFile' out $ unwords $ map show [a,b]-- obj "out.txt" *> \out -> do- x <- getVerbosity- ys <- withVerbosity Loud $ do- a <- getVerbosity- need [obj "in.txt"] -- make sure the inherited verbosity does not get passed along- b <- getVerbosity- c <- quietly getVerbosity- d <- fmap shakeVerbosity getShakeOptions- return [a,b,c,d]- z <- getVerbosity- writeFile' out $ unwords $ map show $ [x] ++ ys ++ [z]--test build obj = do- build ["out.txt","--clean"]- assertContents (obj "in.txt") "Normal Normal"- assertContents (obj "out.txt") "Normal Loud Loud Quiet Normal Normal"-- build ["out.txt","--clean","--verbose"]- assertContents (obj "in.txt") "Loud Normal"- assertContents (obj "out.txt") "Loud Loud Loud Quiet Loud Loud"-- build ["out.txt","--clean","--quiet"]- assertContents (obj "in.txt") "Quiet Normal"- assertContents (obj "out.txt") "Quiet Loud Loud Quiet Quiet Quiet"
docs/Manual.md view
@@ -17,13 +17,13 @@ putNormal "Cleaning files in _build" removeFilesAfter "_build" ["//*"] - "_build/run" <.> exe *> \out -> do+ "_build/run" <.> exe %> \out -> do cs <- getDirectoryFiles "" ["//*.c"] let os = ["_build" </> c -<.> "o" | c <- cs] need os cmd "gcc -o" [out] os - "_build//*.o" *> \out -> do+ "_build//*.o" %> \out -> do let c = dropDirectory1 $ out -<.> "c" let m = out -<.> "m" () <- cmd "gcc -c" [c] "-o" [out] "-MMD -MF" [m]@@ -37,7 +37,7 @@ 1. Install the [Haskell Platform](http://www.haskell.org/platform/), which provides a Haskell compiler and standard libraries. 2. Type `cabal update`, to download information about the latest versions of all Haskell packages.-3. Type `cabal install shake`, to build and install Shake and all its dependencies. +3. Type `cabal install shake`, to build and install Shake and all its dependencies. 4. Type `shake --demo`, which will create a directory containing a sample project, the above Shake script, and execute it. For more details see a [trace of `shake --demo`](Demo.md). ## Basic syntax@@ -53,7 +53,7 @@ import Development.Shake.Command import Development.Shake.FilePath import Development.Shake.Util-+  main :: IO () main = shakeArgs shakeOptions{shakeFiles="_build/"} $ do <i>build rules</i>@@ -84,15 +84,15 @@ <i>actions</i> </pre> -The <tt><i>pattern</i></tt> is a string saying which files this rule can build. It may be a specific file (e.g. `"manual/examples.txt" *> ...`) or may use wildcards:+The <tt><i>pattern</i></tt> is a string saying which files this rule can build. It may be a specific file (e.g. `"manual/examples.txt" %> ...`) or may use wildcards: * The `*` wildcard matches anything apart from a directory separator. For example `"manual/*.txt"` would define a rule for any `.txt` file in the `manual` directory, including `manual/examples.txt`, but would not match `manual/examples.zip`, `examples.txt` or `manual/docs/examples.txt`. * The `//` wildcard matches any number of complete path components. For example `//*.txt` would define a rule for any `.txt` file, including `manual/examples.txt`. As another example, `manual//examples.txt` would match any file named `examples.txt` inside `manual`, including both `manual/examples.txt` and `manual/docs/examples.txt`. It is an error for multiple patterns to match a file being built, so you should keep patterns minimal. Looking at the two rules in the initial example: - "_build/run" <.> exe *> ...- "_build//*.o" *> ...+ "_build/run" <.> exe %> ...+ "_build//*.o" %> ... The first matches only the `run` executable, using `<.> exe` to ensure the executable is correctly named on all platforms. The second matches any `.o` file anywhere under `_build`. As examples, `_build/main.o` and `_build/foo/bar.o` both match while `main.o` and `_build/main.txt` do not. @@ -104,7 +104,7 @@ Let's look at a simple example of a rule: - "*.rot13" *> \out -> do+ "*.rot13" %> \out -> do let src = out -<.> "txt" need [src] cmd "rot13" src "-o" out@@ -131,7 +131,7 @@ Variables are evaluated by substituting the <tt><i>expression</i></tt> everywhere the <tt><i>variable</i></tt> is used. In the simple example we could have equivalently written: - "*.rot13" *> \out -> do+ "*.rot13" %> \out -> do need [out -<.> "txt"] cmd "rot13" (out -<.> "txt") "-o" out @@ -231,7 +231,7 @@ Now, if either `main.c` or any headers transitively imported by `main.c` change, the file will be rebuilt. In the initial example the complete rule is: - "_build//*.o" *> \out -> do+ "_build//*.o" %> \out -> do let c = dropDirectory1 $ out -<.> "c" let m = out -<.> "m" () <- cmd "gcc -c" [c] "-o" [out] "-MMD -MF" [m]@@ -251,7 +251,7 @@ We can now write: - buildDir ("run" <.> exe) *> \out -> do+ buildDir ("run" <.> exe) %> \out -> do ... All top-level variables and functions can be though of as being expanded wherever they are used, although in practice may have their evaluation shared.@@ -305,6 +305,8 @@ Most flags can also be set within the program by modifying the `shakeOptions` value. As an example, `build --metadata=_metadata/` causes all Shake metadata files to be stored with names such as `_metadata/.database`. Alternatively we can write `shakeOptions{shakeFiles="_metadata/"}` instead of our existing `shakeFiles="_build/"`. Values passed on the command line take preference over those given by `shakeOptions`. Multiple overrides can be given to `shakeOptions` by separating them with a comma, for example `shakeOptions{shakeFiles="_build/",shakeThreads=8}`. +<span class="target" id="progress"></span>+ #### Progress prediction One useful feature of Shake is that it can predict the remaining build time, based on how long previous builds have taken. The number is only a prediction, but it does take account of which files require rebuilding, how fast your machine is currently running, parallelism settings etc. You can display progress messages in the titlebar of a Window by either:@@ -318,6 +320,8 @@ Progress prediction is likely to be relatively poor during the first build and after running `build clean`, as then Shake has no information about the predicted execution time for each rule. To rebuild from scratch without running clean (because you really want to see the progress bar!) you can use the argument `--always-make`, which assumes all rules need rerunning. +<span class="target" id="lint"></span>+ #### Lint Shake features a built in "lint" features to check the build system is well formed. To run `build --lint`. You are likely to catch more lint violations if you first `build clean`. Sadly, lint does _not_ catch missing dependencies. However, it does catch:@@ -327,6 +331,8 @@ There is a performance penalty for building with `--lint`, but it is typically small. +<span class="target" id="profiling"></span>+ #### Profiling Shake features an advanced profiling feature. To build with profiling run `build --report`, which will generate an interactive HTML profile named `report.html`. This report lets you examine what happened in that run, what takes most time to run, what rules depend on what etc. There is a help page included in the profiling output, and a [profiling tutorial/demo](https://cdn.rawgit.com/ndmitchell/shake/35fbe03c8d3bafeae17b58af89497ff3fdd54b22/html/demo.html).@@ -378,7 +384,7 @@ Using Shake we can depend on arbitrary extra information, such as the version of `gcc`, allowing us to automatically rebuild all C files when a different compiler is placed on the path. To track the version, we can define a rule for the file `gcc.version` which changes only when `gcc --version` changes: - "gcc.version" *> \out -> do+ "gcc.version" %> \out -> do alwaysRerun Stdout stdout <- cmd "gcc --version" writeFileChanged out stdout@@ -393,19 +399,19 @@ disk <- newResource "Disk" 4 want [show i <.> "exe" | i <- [1..100]]- "*.exe" *> \out -> do+ "*.exe" %> \out -> do withResource disk 1 $ do cmd "ld -o" [out] ...- "*.o" *> \out -> do+ "*.o" %> \out -> do cmd "cl -o" [out] ... Assuming `-j8`, this allows up to 8 compilers, but only a maximum of 4 linkers. #### Multiple outputs -Some tools, for example [bison](http://www.gnu.org/software/bison/), can generate multiple outputs from one execution. We can track these in Shake using the `&*>` operator to define rules:+Some tools, for example [bison](http://www.gnu.org/software/bison/), can generate multiple outputs from one execution. We can track these in Shake using the `&%>` operator to define rules: - ["//*.bison.h","//*.bison.c"] &*> \[outh, outc] -> do+ ["//*.bison.h","//*.bison.c"] &%> \[outh, outc] -> do let src = outc -<.> "y" cmd "bison -d -o" [outc] [src] @@ -438,9 +444,9 @@ We first get the extension with `takeExtension`, then use `drop 1` to remove the leading `.` that `takeExtension` includes, then test that all the characters are numeric. -The standard `*>` operator is actually defined as:+The standard `%>` operator is actually defined as: - pattern *> actions = (pattern ?==) ?> actions+ pattern %> actions = (pattern ?==) ?> actions Where `?==` is a function for matching file patterns. @@ -475,7 +481,7 @@ Assuming all interesting headers are only included directly by the C file (a restriction we remove in the next section), we can write the build rule as: - "_build//*.o" *> \out -> do+ "_build//*.o" %> \out -> do let c = dropDirectory1 $ out -<.> "c" src <- readFile' c need $ usedHeaders src@@ -488,23 +494,23 @@ The previous section described how to deal with generated include files, but only coped with headers included directly by the C file. This section describes how to extend that to work with generated headers used either in C or header files, even when used by headers that were themselves generated. We can write: - ["*.c.dep","*.h.dep"] |*> \out -> do+ ["*.c.dep","*.h.dep"] |%> \out -> do src <- readFile' $ dropExtension out writeFileLines out $ usedHeaders src - "*.deps" *> \out -> do+ "*.deps" %> \out -> do dep <- readFileLines $ out -<.> "dep" deps <- mapM (readFileLines . (<.> "deps")) dep writeFileLines out $ nub $ dropExtension out : concat deps - "*.o" *> \out -> do+ "*.o" %> \out -> do deps <- readFileLines $ out -<.> "c.deps" need deps cmd "gcc -c" [dropExtension out] "-o" out For simplicity, this code assumes all files are in a single directory and all objects are generated files are placed in the same directory. We define three rules: -* The `*.c.dep` and `*.h.dep` rule uses `|*>`, which defines a single action that matches multiple patterns. The file `foo.h.dep` contains a list of headers directly included by `foo.h`, using `usedHeaders` from the previous section.+* The `*.c.dep` and `*.h.dep` rule uses `|%>`, which defines a single action that matches multiple patterns. The file `foo.h.dep` contains a list of headers directly included by `foo.h`, using `usedHeaders` from the previous section. * The `*.deps` rule takes the transitive closure of dependencies, so `foo.h.deps` contains `foo.h` and all headers that `foo.h` pulls in. The rule takes the target file, and all the `.deps` for anything in the `.dep` file, and combines them. More abstractly, the rule calculates the transitive closure of _a_, namely _a*_, by taking the dependencies of _a_ (say _b_ and _c_) and computing _a\* = union(a, b\*, c\*)_. * The `*.o` rule reads the associated `.deps` file (ensuring it is up to date) and then depends on its contents.
docs/Why.md view
@@ -78,7 +78,7 @@ This document sets out the reasons you _should_ use Shake, but naturally there are some disadvantages: -* Shake build systems are written in Haskell. While that provides many benefits, it does mean the Shake syntax follows that of Haskell, and some Shake errors are reported by the compiler as Haskell type errors. Despite being written in Haskell, the [user manual](https://github.com/ndmitchell/shake/blob/master/docs/Manual.md#readme) introduces Shake assuming no Haskell knowledge, so Haskell knowledge is not a requirement and hopefully should not be a barrier to using Shake.+* Shake build systems are written in Haskell. While that provides many benefits, it does mean the Shake syntax follows that of Haskell, and some Shake errors are reported by the compiler as Haskell type errors. Despite being written in Haskell, the [user manual](Manual.md#readme) introduces Shake assuming no Haskell knowledge, so Haskell knowledge is not a requirement and hopefully should not be a barrier to using Shake. * Shake is not likely to be installed by default, while make almost always is. * Shake does not provide default build rules, requiring everything to be expressed in your build system. In practice it seems that the default rules included with make are unsuitable for most large scale projects, but smaller projects may find themselves writing a few additional rules. It is hoped that additional experience with Shake will lead to a library of build rules being developed.
docs/manual/Build.hs view
@@ -11,13 +11,13 @@ putNormal "Cleaning files in _build" removeFilesAfter "_build" ["//*"] - "_build/run" <.> exe *> \out -> do+ "_build/run" <.> exe %> \out -> do cs <- getDirectoryFiles "" ["//*.c"] let os = ["_build" </> c -<.> "o" | c <- cs] need os cmd "gcc -o" [out] os - "_build//*.o" *> \out -> do+ "_build//*.o" %> \out -> do let c = dropDirectory1 $ out -<.> "c" let m = out -<.> "m" () <- cmd "gcc -c" [c] "-o" [out] "-MMD -MF" [m]
− html/jquery.flot.js
@@ -1,28 +0,0 @@-/* Javascript plotting library for jQuery, version 0.8.0.--Copyright (c) 2007-2013 IOLA and Ole Laursen.-Licensed under the MIT license.--*/-/* Plugin for jQuery for working with colors.- *- * Version 1.1.- *- * Inspiration from jQuery color animation plugin by John Resig.- *- * Released under the MIT license by Ole Laursen, October 2009.- *- * Examples:- *- * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()- * var c = $.color.extract($("#mydiv"), 'background-color');- * console.log(c.r, c.g, c.b, c.a);- * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"- *- * Note that .scale() and .add() return the same modified object- * instead of making a new one.- *- * V. 1.1: Fix error handling so e.g. parsing an empty string does- * produce a color rather than just crashing.- */(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);-(function(e){function n(t,n){var r=n.children("."+t)[0];if(r==null){r=document.createElement("canvas"),r.className=t,e(r).css({direction:"ltr",position:"absolute",left:0,top:0}).appendTo(n);if(!r.getContext){if(!window.G_vmlCanvasManager)throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");r=window.G_vmlCanvasManager.initElement(r)}}this.element=r;var i=this.context=r.getContext("2d"),s=window.devicePixelRatio||1,o=i.webkitBackingStorePixelRatio||i.mozBackingStorePixelRatio||i.msBackingStorePixelRatio||i.oBackingStorePixelRatio||i.backingStorePixelRatio||1;this.pixelRatio=s/o,this.resize(n.width(),n.height()),this.textContainer=null,this.text={},this._textCache={}}function r(t,r,s,o){function E(e,t){t=[w].concat(t);for(var n=0;n<e.length;++n)e[n].apply(this,t)}function S(){var t={Canvas:n};for(var r=0;r<o.length;++r){var i=o[r];i.init(w,t),i.options&&e.extend(!0,a,i.options)}}function x(n){e.extend(!0,a,n),a.xaxis.color==null&&(a.xaxis.color=e.color.parse(a.grid.color).scale("a",.22).toString()),a.yaxis.color==null&&(a.yaxis.color=e.color.parse(a.grid.color).scale("a",.22).toString()),a.xaxis.tickColor==null&&(a.xaxis.tickColor=a.grid.tickColor||a.xaxis.color),a.yaxis.tickColor==null&&(a.yaxis.tickColor=a.grid.tickColor||a.yaxis.color),a.grid.borderColor==null&&(a.grid.borderColor=a.grid.color),a.grid.tickColor==null&&(a.grid.tickColor=e.color.parse(a.grid.color).scale("a",.22).toString());var r,i,s,o={style:t.css("font-style"),size:Math.round(.8*(+t.css("font-size").replace("px","")||13)),variant:t.css("font-variant"),weight:t.css("font-weight"),family:t.css("font-family")};o.lineHeight=o.size*1.15,s=a.xaxes.length||1;for(r=0;r<s;++r)i=a.xaxes[r],i&&!i.tickColor&&(i.tickColor=i.color),i=e.extend(!0,{},a.xaxis,i),a.xaxes[r]=i,i.font&&(i.font=e.extend({},o,i.font),i.font.color||(i.font.color=i.color));s=a.yaxes.length||1;for(r=0;r<s;++r)i=a.yaxes[r],i&&!i.tickColor&&(i.tickColor=i.color),i=e.extend(!0,{},a.yaxis,i),a.yaxes[r]=i,i.font&&(i.font=e.extend({},o,i.font),i.font.color||(i.font.color=i.color));a.xaxis.noTicks&&a.xaxis.ticks==null&&(a.xaxis.ticks=a.xaxis.noTicks),a.yaxis.noTicks&&a.yaxis.ticks==null&&(a.yaxis.ticks=a.yaxis.noTicks),a.x2axis&&(a.xaxes[1]=e.extend(!0,{},a.xaxis,a.x2axis),a.xaxes[1].position="top"),a.y2axis&&(a.yaxes[1]=e.extend(!0,{},a.yaxis,a.y2axis),a.yaxes[1].position="right"),a.grid.coloredAreas&&(a.grid.markings=a.grid.coloredAreas),a.grid.coloredAreasColor&&(a.grid.markingsColor=a.grid.coloredAreasColor),a.lines&&e.extend(!0,a.series.lines,a.lines),a.points&&e.extend(!0,a.series.points,a.points),a.bars&&e.extend(!0,a.series.bars,a.bars),a.shadowSize!=null&&(a.series.shadowSize=a.shadowSize),a.highlightColor!=null&&(a.series.highlightColor=a.highlightColor);for(r=0;r<a.xaxes.length;++r)O(d,r+1).options=a.xaxes[r];for(r=0;r<a.yaxes.length;++r)O(v,r+1).options=a.yaxes[r];for(var u in b)a.hooks[u]&&a.hooks[u].length&&(b[u]=b[u].concat(a.hooks[u]));E(b.processOptions,[a])}function T(e){u=N(e),M(),_()}function N(t){var n=[];for(var r=0;r<t.length;++r){var i=e.extend(!0,{},a.series);t[r].data!=null?(i.data=t[r].data,delete t[r].data,e.extend(!0,i,t[r]),t[r].data=i.data):i.data=t[r],n.push(i)}return n}function C(e,t){var n=e[t+"axis"];return typeof n=="object"&&(n=n.n),typeof n!="number"&&(n=1),n}function k(){return e.grep(d.concat(v),function(e){return e})}function L(e){var t={},n,r;for(n=0;n<d.length;++n)r=d[n],r&&r.used&&(t["x"+r.n]=r.c2p(e.left));for(n=0;n<v.length;++n)r=v[n],r&&r.used&&(t["y"+r.n]=r.c2p(e.top));return t.x1!==undefined&&(t.x=t.x1),t.y1!==undefined&&(t.y=t.y1),t}function A(e){var t={},n,r,i;for(n=0;n<d.length;++n){r=d[n];if(r&&r.used){i="x"+r.n,e[i]==null&&r.n==1&&(i="x");if(e[i]!=null){t.left=r.p2c(e[i]);break}}}for(n=0;n<v.length;++n){r=v[n];if(r&&r.used){i="y"+r.n,e[i]==null&&r.n==1&&(i="y");if(e[i]!=null){t.top=r.p2c(e[i]);break}}}return t}function O(t,n){return t[n-1]||(t[n-1]={n:n,direction:t==d?"x":"y",options:e.extend(!0,{},t==d?a.xaxis:a.yaxis)}),t[n-1]}function M(){var t=u.length,n=-1,r;for(r=0;r<u.length;++r){var i=u[r].color;i!=null&&(t--,typeof i=="number"&&i>n&&(n=i))}t<=n&&(t=n+1);var s,o=[],f=a.colors,l=f.length,c=0;for(r=0;r<t;r++)s=e.color.parse(f[r%l]||"#666"),r%l==0&&r&&(c>=0?c<.5?c=-c-.2:c=0:c=-c),o[r]=s.scale("rgb",1+c);var h=0,p;for(r=0;r<u.length;++r){p=u[r],p.color==null?(p.color=o[h].toString(),++h):typeof p.color=="number"&&(p.color=o[p.color].toString());if(p.lines.show==null){var m,g=!0;for(m in p)if(p[m]&&p[m].show){g=!1;break}g&&(p.lines.show=!0)}p.lines.zero==null&&(p.lines.zero=!!p.lines.fill),p.xaxis=O(d,C(p,"x")),p.yaxis=O(v,C(p,"y"))}}function _(){function x(e,t,n){t<e.datamin&&t!=-r&&(e.datamin=t),n>e.datamax&&n!=r&&(e.datamax=n)}var t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,r=Number.MAX_VALUE,i,s,o,a,f,l,c,h,p,d,v,m,g,y,w,S;e.each(k(),function(e,r){r.datamin=t,r.datamax=n,r.used=!1});for(i=0;i<u.length;++i)l=u[i],l.datapoints={points:[]},E(b.processRawData,[l,l.data,l.datapoints]);for(i=0;i<u.length;++i){l=u[i],w=l.data,S=l.datapoints.format;if(!S){S=[],S.push({x:!0,number:!0,required:!0}),S.push({y:!0,number:!0,required:!0});if(l.bars.show||l.lines.show&&l.lines.fill){var T=!!(l.bars.show&&l.bars.zero||l.lines.show&&l.lines.zero);S.push({y:!0,number:!0,required:!1,defaultValue:0,autoscale:T}),l.bars.horizontal&&(delete S[S.length-1].y,S[S.length-1].x=!0)}l.datapoints.format=S}if(l.datapoints.pointsize!=null)continue;l.datapoints.pointsize=S.length,h=l.datapoints.pointsize,c=l.datapoints.points;var N=l.lines.show&&l.lines.steps;l.xaxis.used=l.yaxis.used=!0;for(s=o=0;s<w.length;++s,o+=h){y=w[s];var C=y==null;if(!C)for(a=0;a<h;++a)m=y[a],g=S[a],g&&(g.number&&m!=null&&(m=+m,isNaN(m)?m=null:m==Infinity?m=r:m==-Infinity&&(m=-r)),m==null&&(g.required&&(C=!0),g.defaultValue!=null&&(m=g.defaultValue))),c[o+a]=m;if(C)for(a=0;a<h;++a)m=c[o+a],m!=null&&(g=S[a],g.x&&x(l.xaxis,m,m),g.y&&x(l.yaxis,m,m)),c[o+a]=null;else if(N&&o>0&&c[o-h]!=null&&c[o-h]!=c[o]&&c[o-h+1]!=c[o+1]){for(a=0;a<h;++a)c[o+h+a]=c[o+a];c[o+1]=c[o-h+1],o+=h}}}for(i=0;i<u.length;++i)l=u[i],E(b.processDatapoints,[l,l.datapoints]);for(i=0;i<u.length;++i){l=u[i],c=l.datapoints.points,h=l.datapoints.pointsize,S=l.datapoints.format;var L=t,A=t,O=n,M=n;for(s=0;s<c.length;s+=h){if(c[s]==null)continue;for(a=0;a<h;++a){m=c[s+a],g=S[a];if(!g||g.autoscale===!1||m==r||m==-r)continue;g.x&&(m<L&&(L=m),m>O&&(O=m)),g.y&&(m<A&&(A=m),m>M&&(M=m))}}if(l.bars.show){var _;switch(l.bars.align){case"left":_=0;break;case"right":_=-l.bars.barWidth;break;case"center":_=-l.bars.barWidth/2;break;default:throw new Error("Invalid bar alignment: "+l.bars.align)}l.bars.horizontal?(A+=_,M+=_+l.bars.barWidth):(L+=_,O+=_+l.bars.barWidth)}x(l.xaxis,L,O),x(l.yaxis,A,M)}e.each(k(),function(e,r){r.datamin==t&&(r.datamin=null),r.datamax==n&&(r.datamax=null)})}function D(){t.css("padding",0).children(":not(.flot-base,.flot-overlay)").remove(),t.css("position")=="static"&&t.css("position","relative"),f=new n("flot-base",t),l=new n("flot-overlay",t),h=f.context,p=l.context,c=e(l.element).unbind();var r=t.data("plot");r&&(r.shutdown(),l.clear()),t.data("plot",w)}function P(){a.grid.hoverable&&(c.mousemove(at),c.bind("mouseleave",ft)),a.grid.clickable&&c.click(lt),E(b.bindEvents,[c])}function H(){ot&&clearTimeout(ot),c.unbind("mousemove",at),c.unbind("mouseleave",ft),c.unbind("click",lt),E(b.shutdown,[c])}function B(e){function t(e){return e}var n,r,i=e.options.transform||t,s=e.options.inverseTransform;e.direction=="x"?(n=e.scale=g/Math.abs(i(e.max)-i(e.min)),r=Math.min(i(e.max),i(e.min))):(n=e.scale=y/Math.abs(i(e.max)-i(e.min)),n=-n,r=Math.max(i(e.max),i(e.min))),i==t?e.p2c=function(e){return(e-r)*n}:e.p2c=function(e){return(i(e)-r)*n},s?e.c2p=function(e){return s(r+e/n)}:e.c2p=function(e){return r+e/n}}function j(e){var t=e.options,n=e.ticks||[],r=t.labelWidth||0,i=t.labelHeight||0,s=e.direction+"Axis "+e.direction+e.n+"Axis",o="flot-"+e.direction+"-axis flot-"+e.direction+e.n+"-axis "+s,u=t.font||"flot-tick-label tickLabel";for(var a=0;a<n.length;++a){var l=n[a];if(!l.label)continue;var c=f.getTextInfo(o,l.label,u);t.labelWidth==null&&(r=Math.max(r,c.width)),t.labelHeight==null&&(i=Math.max(i,c.height))}e.labelWidth=Math.ceil(r),e.labelHeight=Math.ceil(i)}function F(t){var n=t.labelWidth,r=t.labelHeight,i=t.options.position,s=t.options.tickLength,o=a.grid.axisMargin,u=a.grid.labelMargin,l=t.direction=="x"?d:v,c,h,p=e.grep(l,function(e){return e&&e.options.position==i&&e.reserveSpace});e.inArray(t,p)==p.length-1&&(o=0);if(s==null){var g=e.grep(l,function(e){return e&&e.reserveSpace});h=e.inArray(t,g)==0,h?s="full":s=5}isNaN(+s)||(u+=+s),t.direction=="x"?(r+=u,i=="bottom"?(m.bottom+=r+o,t.box={top:f.height-m.bottom,height:r}):(t.box={top:m.top+o,height:r},m.top+=r+o)):(n+=u,i=="left"?(t.box={left:m.left+o,width:n},m.left+=n+o):(m.right+=n+o,t.box={left:f.width-m.right,width:n})),t.position=i,t.tickLength=s,t.box.padding=u,t.innermost=h}function I(e){e.direction=="x"?(e.box.left=m.left-e.labelWidth/2,e.box.width=f.width-m.left-m.right+e.labelWidth):(e.box.top=m.top-e.labelHeight/2,e.box.height=f.height-m.bottom-m.top+e.labelHeight)}function q(){var t=a.grid.minBorderMargin,n={x:0,y:0},r,i;if(t==null){t=0;for(r=0;r<u.length;++r)t=Math.max(t,2*(u[r].points.radius+u[r].points.lineWidth/2))}n.x=n.y=Math.ceil(t),e.each(k(),function(e,t){var r=t.direction;t.reserveSpace&&(n[r]=Math.ceil(Math.max(n[r],(r=="x"?t.labelWidth:t.labelHeight)/2)))}),m.left=Math.max(n.x,m.left),m.right=Math.max(n.x,m.right),m.top=Math.max(n.y,m.top),m.bottom=Math.max(n.y,m.bottom)}function R(){var t,n=k(),r=a.grid.show;for(var i in m){var s=a.grid.margin||0;m[i]=typeof s=="number"?s:s[i]||0}E(b.processOffset,[m]);for(var i in m)typeof a.grid.borderWidth=="object"?m[i]+=r?a.grid.borderWidth[i]:0:m[i]+=r?a.grid.borderWidth:0;e.each(n,function(e,t){t.show=t.options.show,t.show==null&&(t.show=t.used),t.reserveSpace=t.show||t.options.reserveSpace,U(t)});if(r){var o=e.grep(n,function(e){return e.reserveSpace});e.each(o,function(e,t){z(t),W(t),X(t,t.ticks),j(t)});for(t=o.length-1;t>=0;--t)F(o[t]);q(),e.each(o,function(e,t){I(t)})}g=f.width-m.left-m.right,y=f.height-m.bottom-m.top,e.each(n,function(e,t){B(t)}),r&&G(),it()}function U(e){var t=e.options,n=+(t.min!=null?t.min:e.datamin),r=+(t.max!=null?t.max:e.datamax),i=r-n;if(i==0){var s=r==0?1:.01;t.min==null&&(n-=s);if(t.max==null||t.min!=null)r+=s}else{var o=t.autoscaleMargin;o!=null&&(t.min==null&&(n-=i*o,n<0&&e.datamin!=null&&e.datamin>=0&&(n=0)),t.max==null&&(r+=i*o,r>0&&e.datamax!=null&&e.datamax<=0&&(r=0)))}e.min=n,e.max=r}function z(t){var n=t.options,r;typeof n.ticks=="number"&&n.ticks>0?r=n.ticks:r=.3*Math.sqrt(t.direction=="x"?f.width:f.height);var s=(t.max-t.min)/r,o=-Math.floor(Math.log(s)/Math.LN10),u=n.tickDecimals;u!=null&&o>u&&(o=u);var a=Math.pow(10,-o),l=s/a,c;l<1.5?c=1:l<3?(c=2,l>2.25&&(u==null||o+1<=u)&&(c=2.5,++o)):l<7.5?c=5:c=10,c*=a,n.minTickSize!=null&&c<n.minTickSize&&(c=n.minTickSize),t.delta=s,t.tickDecimals=Math.max(0,u!=null?u:o),t.tickSize=n.tickSize||c;if(n.mode=="time"&&!t.tickGenerator)throw new Error("Time mode requires the flot.time plugin.");t.tickGenerator||(t.tickGenerator=function(e){var t=[],n=i(e.min,e.tickSize),r=0,s=Number.NaN,o;do o=s,s=n+r*e.tickSize,t.push(s),++r;while(s<e.max&&s!=o);return t},t.tickFormatter=function(e,t){var n=t.tickDecimals?Math.pow(10,t.tickDecimals):1,r=""+Math.round(e*n)/n;if(t.tickDecimals!=null){var i=r.indexOf("."),s=i==-1?0:r.length-i-1;if(s<t.tickDecimals)return(s?r:r+".")+(""+n).substr(1,t.tickDecimals-s)}return r}),e.isFunction(n.tickFormatter)&&(t.tickFormatter=function(e,t){return""+n.tickFormatter(e,t)});if(n.alignTicksWithAxis!=null){var h=(t.direction=="x"?d:v)[n.alignTicksWithAxis-1];if(h&&h.used&&h!=t){var p=t.tickGenerator(t);p.length>0&&(n.min==null&&(t.min=Math.min(t.min,p[0])),n.max==null&&p.length>1&&(t.max=Math.max(t.max,p[p.length-1]))),t.tickGenerator=function(e){var t=[],n,r;for(r=0;r<h.ticks.length;++r)n=(h.ticks[r].v-h.min)/(h.max-h.min),n=e.min+n*(e.max-e.min),t.push(n);return t};if(!t.mode&&n.tickDecimals==null){var m=Math.max(0,-Math.floor(Math.log(t.delta)/Math.LN10)+1),g=t.tickGenerator(t);g.length>1&&/\..*0$/.test((g[1]-g[0]).toFixed(m))||(t.tickDecimals=m)}}}}function W(t){var n=t.options.ticks,r=[];n==null||typeof n=="number"&&n>0?r=t.tickGenerator(t):n&&(e.isFunction(n)?r=n(t):r=n);var i,s;t.ticks=[];for(i=0;i<r.length;++i){var o=null,u=r[i];typeof u=="object"?(s=+u[0],u.length>1&&(o=u[1])):s=+u,o==null&&(o=t.tickFormatter(s,t)),isNaN(s)||t.ticks.push({v:s,label:o})}}function X(e,t){e.options.autoscaleMargin&&t.length>0&&(e.options.min==null&&(e.min=Math.min(e.min,t[0].v)),e.options.max==null&&t.length>1&&(e.max=Math.max(e.max,t[t.length-1].v)))}function V(){f.clear(),E(b.drawBackground,[h]);var e=a.grid;e.show&&e.backgroundColor&&K(),e.show&&!e.aboveData&&Q();for(var t=0;t<u.length;++t)E(b.drawSeries,[h,u[t]]),Y(u[t]);E(b.draw,[h]),e.show&&e.aboveData&&Q(),f.render()}function J(e,t){var n,r,i,s,o=k();for(var u=0;u<o.length;++u){n=o[u];if(n.direction==t){s=t+n.n+"axis",!e[s]&&n.n==1&&(s=t+"axis");if(e[s]){r=e[s].from,i=e[s].to;break}}}e[s]||(n=t=="x"?d[0]:v[0],r=e[t+"1"],i=e[t+"2"]);if(r!=null&&i!=null&&r>i){var a=r;r=i,i=a}return{from:r,to:i,axis:n}}function K(){h.save(),h.translate(m.left,m.top),h.fillStyle=bt(a.grid.backgroundColor,y,0,"rgba(255, 255, 255, 0)"),h.fillRect(0,0,g,y),h.restore()}function Q(){var t,n,r,i;h.save(),h.translate(m.left,m.top);var s=a.grid.markings;if(s){e.isFunction(s)&&(n=w.getAxes(),n.xmin=n.xaxis.min,n.xmax=n.xaxis.max,n.ymin=n.yaxis.min,n.ymax=n.yaxis.max,s=s(n));for(t=0;t<s.length;++t){var o=s[t],u=J(o,"x"),f=J(o,"y");u.from==null&&(u.from=u.axis.min),u.to==null&&(u.to=u.axis.max),f.from==null&&(f.from=f.axis.min),f.to==null&&(f.to=f.axis.max);if(u.to<u.axis.min||u.from>u.axis.max||f.to<f.axis.min||f.from>f.axis.max)continue;u.from=Math.max(u.from,u.axis.min),u.to=Math.min(u.to,u.axis.max),f.from=Math.max(f.from,f.axis.min),f.to=Math.min(f.to,f.axis.max);if(u.from==u.to&&f.from==f.to)continue;u.from=u.axis.p2c(u.from),u.to=u.axis.p2c(u.to),f.from=f.axis.p2c(f.from),f.to=f.axis.p2c(f.to),u.from==u.to||f.from==f.to?(h.beginPath(),h.strokeStyle=o.color||a.grid.markingsColor,h.lineWidth=o.lineWidth||a.grid.markingsLineWidth,h.moveTo(u.from,f.from),h.lineTo(u.to,f.to),h.stroke()):(h.fillStyle=o.color||a.grid.markingsColor,h.fillRect(u.from,f.to,u.to-u.from,f.from-f.to))}}n=k(),r=a.grid.borderWidth;for(var l=0;l<n.length;++l){var c=n[l],p=c.box,d=c.tickLength,v,b,E,S;if(!c.show||c.ticks.length==0)continue;h.lineWidth=1,c.direction=="x"?(v=0,d=="full"?b=c.position=="top"?0:y:b=p.top-m.top+(c.position=="top"?p.height:0)):(b=0,d=="full"?v=c.position=="left"?0:g:v=p.left-m.left+(c.position=="left"?p.width:0)),c.innermost||(h.strokeStyle=c.options.color,h.beginPath(),E=S=0,c.direction=="x"?E=g+1:S=y+1,h.lineWidth==1&&(c.direction=="x"?b=Math.floor(b)+.5:v=Math.floor(v)+.5),h.moveTo(v,b),h.lineTo(v+E,b+S),h.stroke()),h.strokeStyle=c.options.tickColor,h.beginPath();for(t=0;t<c.ticks.length;++t){var x=c.ticks[t].v;E=S=0;if(isNaN(x)||x<c.min||x>c.max||d=="full"&&(typeof r=="object"&&r[c.position]>0||r>0)&&(x==c.min||x==c.max))continue;c.direction=="x"?(v=c.p2c(x),S=d=="full"?-y:d,c.position=="top"&&(S=-S)):(b=c.p2c(x),E=d=="full"?-g:d,c.position=="left"&&(E=-E)),h.lineWidth==1&&(c.direction=="x"?v=Math.floor(v)+.5:b=Math.floor(b)+.5),h.moveTo(v,b),h.lineTo(v+E,b+S)}h.stroke()}r&&(i=a.grid.borderColor,typeof r=="object"||typeof i=="object"?(typeof r!="object"&&(r={top:r,right:r,bottom:r,left:r}),typeof i!="object"&&(i={top:i,right:i,bottom:i,left:i}),r.top>0&&(h.strokeStyle=i.top,h.lineWidth=r.top,h.beginPath(),h.moveTo(0-r.left,0-r.top/2),h.lineTo(g,0-r.top/2),h.stroke()),r.right>0&&(h.strokeStyle=i.right,h.lineWidth=r.right,h.beginPath(),h.moveTo(g+r.right/2,0-r.top),h.lineTo(g+r.right/2,y),h.stroke()),r.bottom>0&&(h.strokeStyle=i.bottom,h.lineWidth=r.bottom,h.beginPath(),h.moveTo(g+r.right,y+r.bottom/2),h.lineTo(0,y+r.bottom/2),h.stroke()),r.left>0&&(h.strokeStyle=i.left,h.lineWidth=r.left,h.beginPath(),h.moveTo(0-r.left/2,y+r.bottom),h.lineTo(0-r.left/2,0),h.stroke())):(h.lineWidth=r,h.strokeStyle=a.grid.borderColor,h.strokeRect(-r/2,-r/2,g+r,y+r))),h.restore()}function G(){e.each(k(),function(e,t){if(!t.show||t.ticks.length==0)return;var n=t.box,r=t.direction+"Axis "+t.direction+t.n+"Axis",i="flot-"+t.direction+"-axis flot-"+t.direction+t.n+"-axis "+r,s=t.options.font||"flot-tick-label tickLabel",o,u,a,l,c;f.removeText(i);for(var h=0;h<t.ticks.length;++h){o=t.ticks[h];if(!o.label||o.v<t.min||o.v>t.max)continue;t.direction=="x"?(l="center",u=m.left+t.p2c(o.v),t.position=="bottom"?a=n.top+n.padding:(a=n.top+n.height-n.padding,c="bottom")):(c="middle",a=m.top+t.p2c(o.v),t.position=="left"?(u=n.left+n.width-n.padding,l="right"):u=n.left+n.padding),f.addText(i,u,a,o.label,s,null,l,c)}})}function Y(e){e.lines.show&&Z(e),e.bars.show&&nt(e),e.points.show&&et(e)}function Z(e){function t(e,t,n,r,i){var s=e.points,o=e.pointsize,u=null,a=null;h.beginPath();for(var f=o;f<s.length;f+=o){var l=s[f-o],c=s[f-o+1],p=s[f],d=s[f+1];if(l==null||p==null)continue;if(c<=d&&c<i.min){if(d<i.min)continue;l=(i.min-c)/(d-c)*(p-l)+l,c=i.min}else if(d<=c&&d<i.min){if(c<i.min)continue;p=(i.min-c)/(d-c)*(p-l)+l,d=i.min}if(c>=d&&c>i.max){if(d>i.max)continue;l=(i.max-c)/(d-c)*(p-l)+l,c=i.max}else if(d>=c&&d>i.max){if(c>i.max)continue;p=(i.max-c)/(d-c)*(p-l)+l,d=i.max}if(l<=p&&l<r.min){if(p<r.min)continue;c=(r.min-l)/(p-l)*(d-c)+c,l=r.min}else if(p<=l&&p<r.min){if(l<r.min)continue;d=(r.min-l)/(p-l)*(d-c)+c,p=r.min}if(l>=p&&l>r.max){if(p>r.max)continue;c=(r.max-l)/(p-l)*(d-c)+c,l=r.max}else if(p>=l&&p>r.max){if(l>r.max)continue;d=(r.max-l)/(p-l)*(d-c)+c,p=r.max}(l!=u||c!=a)&&h.moveTo(r.p2c(l)+t,i.p2c(c)+n),u=p,a=d,h.lineTo(r.p2c(p)+t,i.p2c(d)+n)}h.stroke()}function n(e,t,n){var r=e.points,i=e.pointsize,s=Math.min(Math.max(0,n.min),n.max),o=0,u,a=!1,f=1,l=0,c=0;for(;;){if(i>0&&o>r.length+i)break;o+=i;var p=r[o-i],d=r[o-i+f],v=r[o],m=r[o+f];if(a){if(i>0&&p!=null&&v==null){c=o,i=-i,f=2;continue}if(i<0&&o==l+i){h.fill(),a=!1,i=-i,f=1,o=l=c+i;continue}}if(p==null||v==null)continue;if(p<=v&&p<t.min){if(v<t.min)continue;d=(t.min-p)/(v-p)*(m-d)+d,p=t.min}else if(v<=p&&v<t.min){if(p<t.min)continue;m=(t.min-p)/(v-p)*(m-d)+d,v=t.min}if(p>=v&&p>t.max){if(v>t.max)continue;d=(t.max-p)/(v-p)*(m-d)+d,p=t.max}else if(v>=p&&v>t.max){if(p>t.max)continue;m=(t.max-p)/(v-p)*(m-d)+d,v=t.max}a||(h.beginPath(),h.moveTo(t.p2c(p),n.p2c(s)),a=!0);if(d>=n.max&&m>=n.max){h.lineTo(t.p2c(p),n.p2c(n.max)),h.lineTo(t.p2c(v),n.p2c(n.max));continue}if(d<=n.min&&m<=n.min){h.lineTo(t.p2c(p),n.p2c(n.min)),h.lineTo(t.p2c(v),n.p2c(n.min));continue}var g=p,y=v;d<=m&&d<n.min&&m>=n.min?(p=(n.min-d)/(m-d)*(v-p)+p,d=n.min):m<=d&&m<n.min&&d>=n.min&&(v=(n.min-d)/(m-d)*(v-p)+p,m=n.min),d>=m&&d>n.max&&m<=n.max?(p=(n.max-d)/(m-d)*(v-p)+p,d=n.max):m>=d&&m>n.max&&d<=n.max&&(v=(n.max-d)/(m-d)*(v-p)+p,m=n.max),p!=g&&h.lineTo(t.p2c(g),n.p2c(d)),h.lineTo(t.p2c(p),n.p2c(d)),h.lineTo(t.p2c(v),n.p2c(m)),v!=y&&(h.lineTo(t.p2c(v),n.p2c(m)),h.lineTo(t.p2c(y),n.p2c(m)))}}h.save(),h.translate(m.left,m.top),h.lineJoin="round";var r=e.lines.lineWidth,i=e.shadowSize;if(r>0&&i>0){h.lineWidth=i,h.strokeStyle="rgba(0,0,0,0.1)";var s=Math.PI/18;t(e.datapoints,Math.sin(s)*(r/2+i/2),Math.cos(s)*(r/2+i/2),e.xaxis,e.yaxis),h.lineWidth=i/2,t(e.datapoints,Math.sin(s)*(r/2+i/4),Math.cos(s)*(r/2+i/4),e.xaxis,e.yaxis)}h.lineWidth=r,h.strokeStyle=e.color;var o=rt(e.lines,e.color,0,y);o&&(h.fillStyle=o,n(e.datapoints,e.xaxis,e.yaxis)),r>0&&t(e.datapoints,0,0,e.xaxis,e.yaxis),h.restore()}function et(e){function t(e,t,n,r,i,s,o,u){var a=e.points,f=e.pointsize;for(var l=0;l<a.length;l+=f){var c=a[l],p=a[l+1];if(c==null||c<s.min||c>s.max||p<o.min||p>o.max)continue;h.beginPath(),c=s.p2c(c),p=o.p2c(p)+r,u=="circle"?h.arc(c,p,t,0,i?Math.PI:Math.PI*2,!1):u(h,c,p,t,i),h.closePath(),n&&(h.fillStyle=n,h.fill()),h.stroke()}}h.save(),h.translate(m.left,m.top);var n=e.points.lineWidth,r=e.shadowSize,i=e.points.radius,s=e.points.symbol;n==0&&(n=1e-4);if(n>0&&r>0){var o=r/2;h.lineWidth=o,h.strokeStyle="rgba(0,0,0,0.1)",t(e.datapoints,i,null,o+o/2,!0,e.xaxis,e.yaxis,s),h.strokeStyle="rgba(0,0,0,0.2)",t(e.datapoints,i,null,o/2,!0,e.xaxis,e.yaxis,s)}h.lineWidth=n,h.strokeStyle=e.color,t(e.datapoints,i,rt(e.points,e.color),0,!1,e.xaxis,e.yaxis,s),h.restore()}function tt(e,t,n,r,i,s,o,u,a,f,l,c){var h,p,d,v,m,g,y,b,w;l?(b=g=y=!0,m=!1,h=n,p=e,v=t+r,d=t+i,p<h&&(w=p,p=h,h=w,m=!0,g=!1)):(m=g=y=!0,b=!1,h=e+r,p=e+i,d=n,v=t,v<d&&(w=v,v=d,d=w,b=!0,y=!1));if(p<u.min||h>u.max||v<a.min||d>a.max)return;h<u.min&&(h=u.min,m=!1),p>u.max&&(p=u.max,g=!1),d<a.min&&(d=a.min,b=!1),v>a.max&&(v=a.max,y=!1),h=u.p2c(h),d=a.p2c(d),p=u.p2c(p),v=a.p2c(v),o&&(f.beginPath(),f.moveTo(h,d),f.lineTo(h,v),f.lineTo(p,v),f.lineTo(p,d),f.fillStyle=o(d,v),f.fill()),c>0&&(m||g||y||b)&&(f.beginPath(),f.moveTo(h,d+s),m?f.lineTo(h,v+s):f.moveTo(h,v+s),y?f.lineTo(p,v+s):f.moveTo(p,v+s),g?f.lineTo(p,d+s):f.moveTo(p,d+s),b?f.lineTo(h,d+s):f.moveTo(h,d+s),f.stroke())}function nt(e){function t(t,n,r,i,s,o,u){var a=t.points,f=t.pointsize;for(var l=0;l<a.length;l+=f){if(a[l]==null)continue;tt(a[l],a[l+1],a[l+2],n,r,i,s,o,u,h,e.bars.horizontal,e.bars.lineWidth)}}h.save(),h.translate(m.left,m.top),h.lineWidth=e.bars.lineWidth,h.strokeStyle=e.color;var n;switch(e.bars.align){case"left":n=0;break;case"right":n=-e.bars.barWidth;break;case"center":n=-e.bars.barWidth/2;break;default:throw new Error("Invalid bar alignment: "+e.bars.align)}var r=e.bars.fill?function(t,n){return rt(e.bars,e.color,t,n)}:null;t(e.datapoints,n,n+e.bars.barWidth,0,r,e.xaxis,e.yaxis),h.restore()}function rt(t,n,r,i){var s=t.fill;if(!s)return null;if(t.fillColor)return bt(t.fillColor,r,i,n);var o=e.color.parse(n);return o.a=typeof s=="number"?s:.4,o.normalize(),o.toString()}function it(){t.find(".legend").remove();if(!a.legend.show)return;var n=[],r=[],i=!1,s=a.legend.labelFormatter,o,f;for(var l=0;l<u.length;++l)o=u[l],o.label&&(f=s?s(o.label,o):o.label,f&&r.push({label:f,color:o.color}));if(a.legend.sorted)if(e.isFunction(a.legend.sorted))r.sort(a.legend.sorted);else if(a.legend.sorted=="reverse")r.reverse();else{var c=a.legend.sorted!="descending";r.sort(function(e,t){return e.label==t.label?0:e.label<t.label!=c?1:-1})}for(var l=0;l<r.length;++l){var h=r[l];l%a.legend.noColumns==0&&(i&&n.push("</tr>"),n.push("<tr>"),i=!0),n.push('<td class="legendColorBox"><div style="border:1px solid '+a.legend.labelBoxBorderColor+';padding:1px"><div style="width:4px;height:0;border:5px solid '+h.color+';overflow:hidden"></div></div></td>'+'<td class="legendLabel">'+h.label+"</td>")}i&&n.push("</tr>");if(n.length==0)return;var p='<table style="font-size:smaller;color:'+a.grid.color+'">'+n.join("")+"</table>";if(a.legend.container!=null)e(a.legend.container).html(p);else{var d="",v=a.legend.position,g=a.legend.margin;g[0]==null&&(g=[g,g]),v.charAt(0)=="n"?d+="top:"+(g[1]+m.top)+"px;":v.charAt(0)=="s"&&(d+="bottom:"+(g[1]+m.bottom)+"px;"),v.charAt(1)=="e"?d+="right:"+(g[0]+m.right)+"px;":v.charAt(1)=="w"&&(d+="left:"+(g[0]+m.left)+"px;");var y=e('<div class="legend">'+p.replace('style="','style="position:absolute;'+d+";")+"</div>").appendTo(t);if(a.legend.backgroundOpacity!=0){var b=a.legend.backgroundColor;b==null&&(b=a.grid.backgroundColor,b&&typeof b=="string"?b=e.color.parse(b):b=e.color.extract(y,"background-color"),b.a=1,b=b.toString());var w=y.children();e('<div style="position:absolute;width:'+w.width()+"px;height:"+w.height()+"px;"+d+"background-color:"+b+';"> </div>').prependTo(y).css("opacity",a.legend.backgroundOpacity)}}}function ut(e,t,n){var r=a.grid.mouseActiveRadius,i=r*r+1,s=null,o=!1,f,l,c;for(f=u.length-1;f>=0;--f){if(!n(u[f]))continue;var h=u[f],p=h.xaxis,d=h.yaxis,v=h.datapoints.points,m=p.c2p(e),g=d.c2p(t),y=r/p.scale,b=r/d.scale;c=h.datapoints.pointsize,p.options.inverseTransform&&(y=Number.MAX_VALUE),d.options.inverseTransform&&(b=Number.MAX_VALUE);if(h.lines.show||h.points.show)for(l=0;l<v.length;l+=c){var w=v[l],E=v[l+1];if(w==null)continue;if(w-m>y||w-m<-y||E-g>b||E-g<-b)continue;var S=Math.abs(p.p2c(w)-e),x=Math.abs(d.p2c(E)-t),T=S*S+x*x;T<i&&(i=T,s=[f,l/c])}if(h.bars.show&&!s){var N=h.bars.align=="left"?0:-h.bars.barWidth/2,C=N+h.bars.barWidth;for(l=0;l<v.length;l+=c){var w=v[l],E=v[l+1],k=v[l+2];if(w==null)continue;if(u[f].bars.horizontal?m<=Math.max(k,w)&&m>=Math.min(k,w)&&g>=E+N&&g<=E+C:m>=w+N&&m<=w+C&&g>=Math.min(k,E)&&g<=Math.max(k,E))s=[f,l/c]}}}return s?(f=s[0],l=s[1],c=u[f].datapoints.pointsize,{datapoint:u[f].datapoints.points.slice(l*c,(l+1)*c),dataIndex:l,series:u[f],seriesIndex:f}):null}function at(e){a.grid.hoverable&&ct("plothover",e,function(e){return e["hoverable"]!=0})}function ft(e){a.grid.hoverable&&ct("plothover",e,function(e){return!1})}function lt(e){ct("plotclick",e,function(e){return e["clickable"]!=0})}function ct(e,n,r){var i=c.offset(),s=n.pageX-i.left-m.left,o=n.pageY-i.top-m.top,u=L({left:s,top:o});u.pageX=n.pageX,u.pageY=n.pageY;var f=ut(s,o,r);f&&(f.pageX=parseInt(f.series.xaxis.p2c(f.datapoint[0])+i.left+m.left,10),f.pageY=parseInt(f.series.yaxis.p2c(f.datapoint[1])+i.top+m.top,10));if(a.grid.autoHighlight){for(var l=0;l<st.length;++l){var h=st[l];h.auto==e&&(!f||h.series!=f.series||h.point[0]!=f.datapoint[0]||h.point[1]!=f.datapoint[1])&&vt(h.series,h.point)}f&&dt(f.series,f.datapoint,e)}t.trigger(e,[u,f])}function ht(){var e=a.interaction.redrawOverlayInterval;if(e==-1){pt();return}ot||(ot=setTimeout(pt,e))}function pt(){ot=null,p.save(),l.clear(),p.translate(m.left,m.top);var e,t;for(e=0;e<st.length;++e)t=st[e],t.series.bars.show?yt(t.series,t.point):gt(t.series,t.point);p.restore(),E(b.drawOverlay,[p])}function dt(e,t,n){typeof e=="number"&&(e=u[e]);if(typeof t=="number"){var r=e.datapoints.pointsize;t=e.datapoints.points.slice(r*t,r*(t+1))}var i=mt(e,t);i==-1?(st.push({series:e,point:t,auto:n}),ht()):n||(st[i].auto=!1)}function vt(e,t){if(e==null&&t==null){st=[],ht();return}typeof e=="number"&&(e=u[e]);if(typeof t=="number"){var n=e.datapoints.pointsize;t=e.datapoints.points.slice(n*t,n*(t+1))}var r=mt(e,t);r!=-1&&(st.splice(r,1),ht())}function mt(e,t){for(var n=0;n<st.length;++n){var r=st[n];if(r.series==e&&r.point[0]==t[0]&&r.point[1]==t[1])return n}return-1}function gt(t,n){var r=n[0],i=n[1],s=t.xaxis,o=t.yaxis,u=typeof t.highlightColor=="string"?t.highlightColor:e.color.parse(t.color).scale("a",.5).toString();if(r<s.min||r>s.max||i<o.min||i>o.max)return;var a=t.points.radius+t.points.lineWidth/2;p.lineWidth=a,p.strokeStyle=u;var f=1.5*a;r=s.p2c(r),i=o.p2c(i),p.beginPath(),t.points.symbol=="circle"?p.arc(r,i,f,0,2*Math.PI,!1):t.points.symbol(p,r,i,f,!1),p.closePath(),p.stroke()}function yt(t,n){var r=typeof t.highlightColor=="string"?t.highlightColor:e.color.parse(t.color).scale("a",.5).toString(),i=r,s=t.bars.align=="left"?0:-t.bars.barWidth/2;p.lineWidth=t.bars.lineWidth,p.strokeStyle=r,tt(n[0],n[1],n[2]||0,s,s+t.bars.barWidth,0,function(){return i},t.xaxis,t.yaxis,p,t.bars.horizontal,t.bars.lineWidth)}function bt(t,n,r,i){if(typeof t=="string")return t;var s=h.createLinearGradient(0,r,0,n);for(var o=0,u=t.colors.length;o<u;++o){var a=t.colors[o];if(typeof a!="string"){var f=e.color.parse(i);a.brightness!=null&&(f=f.scale("rgb",a.brightness)),a.opacity!=null&&(f.a*=a.opacity),a=f.toString()}s.addColorStop(o/(u-1),a)}return s}var u=[],a={colors:["#edc240","#afd8f8","#cb4b4b","#4da74d","#9440ed"],legend:{show:!0,noColumns:1,labelFormatter:null,labelBoxBorderColor:"#ccc",container:null,position:"ne",margin:5,backgroundColor:null,backgroundOpacity:.85,sorted:null},xaxis:{show:null,position:"bottom",mode:null,font:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null},yaxis:{autoscaleMargin:.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:!1,radius:3,lineWidth:2,fill:!0,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:!1,fillColor:null,steps:!1},bars:{show:!1,lineWidth:2,barWidth:1,fill:!0,fillColor:null,align:"left",horizontal:!1,zero:!0},shadowSize:3,highlightColor:null},grid:{show:!0,aboveData:!1,color:"#545454",backgroundColor:null,borderColor:null,tickColor:null,margin:0,labelMargin:5,axisMargin:8,borderWidth:2,minBorderMargin:null,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:!1,hoverable:!1,autoHighlight:!0,mouseActiveRadius:10},interaction:{redrawOverlayInterval:1e3/60},hooks:{}},f=null,l=null,c=null,h=null,p=null,d=[],v=[],m={left:0,right:0,top:0,bottom:0},g=0,y=0,b={processOptions:[],processRawData:[],processDatapoints:[],processOffset:[],drawBackground:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},w=this;w.setData=T,w.setupGrid=R,w.draw=V,w.getPlaceholder=function(){return t},w.getCanvas=function(){return f.element},w.getPlotOffset=function(){return m},w.width=function(){return g},w.height=function(){return y},w.offset=function(){var e=c.offset();return e.left+=m.left,e.top+=m.top,e},w.getData=function(){return u},w.getAxes=function(){var t={},n;return e.each(d.concat(v),function(e,n){n&&(t[n.direction+(n.n!=1?n.n:"")+"axis"]=n)}),t},w.getXAxes=function(){return d},w.getYAxes=function(){return v},w.c2p=L,w.p2c=A,w.getOptions=function(){return a},w.highlight=dt,w.unhighlight=vt,w.triggerRedrawOverlay=ht,w.pointOffset=function(e){return{left:parseInt(d[C(e,"x")-1].p2c(+e.x)+m.left,10),top:parseInt(v[C(e,"y")-1].p2c(+e.y)+m.top,10)}},w.shutdown=H,w.resize=function(){var e=t.width(),n=t.height();f.resize(e,n),l.resize(e,n)},w.hooks=b,S(w),x(s),D(),T(r),R(),V(),P();var st=[],ot=null}function i(e,t){return t*Math.floor(e/t)}var t=Object.prototype.hasOwnProperty;n.prototype.resize=function(e,t){if(e<=0||t<=0)throw new Error("Invalid dimensions for plot, width = "+e+", height = "+t);var n=this.element,r=this.context,i=this.pixelRatio;this.width!=e&&(n.width=e*i,n.style.width=e+"px",this.width=e),this.height!=t&&(n.height=t*i,n.style.height=t+"px",this.height=t),r.restore(),r.save(),r.scale(i,i)},n.prototype.clear=function(){this.context.clearRect(0,0,this.width,this.height)},n.prototype.render=function(){var e=this._textCache;for(var n in e)if(t.call(e,n)){var r=this.getTextLayer(n),i=e[n];r.hide();for(var s in i)if(t.call(i,s)){var o=i[s];for(var u in o)if(t.call(o,u)){var a=o[u];a.active?a.rendered||(r.append(a.element),a.rendered=!0):(delete o[u],a.rendered&&a.element.detach())}}r.show()}},n.prototype.getTextLayer=function(t){var n=this.text[t];return n==null&&(this.textContainer==null&&(this.textContainer=e("<div class='flot-text'></div>").css({position:"absolute",top:0,left:0,bottom:0,right:0,"font-size":"smaller",color:"#545454"}).insertAfter(this.element)),n=this.text[t]=e("<div></div>").addClass(t).css({position:"absolute",top:0,left:0,bottom:0,right:0}).appendTo(this.textContainer)),n},n.prototype.getTextInfo=function(t,n,r,i){var s,o,u,a;n=""+n,typeof r=="object"?s=r.style+" "+r.variant+" "+r.weight+" "+r.size+"px/"+r.lineHeight+"px "+r.family:s=r,o=this._textCache[t],o==null&&(o=this._textCache[t]={}),u=o[s],u==null&&(u=o[s]={}),a=u[n];if(a==null){var f=e("<div></div>").html(n).css({position:"absolute",top:-9999}).appendTo(this.getTextLayer(t));typeof r=="object"?f.css({font:s,color:r.color}):typeof r=="string"&&f.addClass(r),a=u[n]={active:!1,rendered:!1,element:f,width:f.outerWidth(!0),height:f.outerHeight(!0)},f.detach()}return a},n.prototype.addText=function(e,t,n,r,i,s,o,u){var a=this.getTextInfo(e,r,i,s);a.active=!0,o=="center"?t-=a.width/2:o=="right"&&(t-=a.width),u=="middle"?n-=a.height/2:u=="bottom"&&(n-=a.height),a.element.css({top:Math.round(n),left:Math.round(t)})},n.prototype.removeText=function(e,n,r,i){if(n==null){var s=this._textCache[e];if(s!=null)for(var o in s)if(t.call(s,o)){var u=s[o];for(var a in u)t.call(u,a)&&(u[a].active=!1)}}else this.getTextInfo(e,n,r,i).active=!1},e.plot=function(t,n,i){var s=new r(e(t),n,i,e.plot.plugins);return s},e.plot.version="0.8.0",e.plot.plugins=[],e.fn.plot=function(t,n){return this.each(function(){e.plot(this,t,n)})}})(jQuery);
− html/jquery.flot.stack.js
@@ -1,36 +0,0 @@-/* Flot plugin for stacking data sets rather than overlyaing them.--Copyright (c) 2007-2013 IOLA and Ole Laursen.-Licensed under the MIT license.--The plugin assumes the data is sorted on x (or y if stacking horizontally).-For line charts, it is assumed that if a line has an undefined gap (from a-null point), then the line above it should have the same gap - insert zeros-instead of "null" if you want another behaviour. This also holds for the start-and end of the chart. Note that stacking a mix of positive and negative values-in most instances doesn't make sense (so it looks weird).--Two or more series are stacked when their "stack" attribute is set to the same-key (which can be any number or string or just "true"). To specify the default-stack, you can set the stack option like this:-- series: {- stack: null/false, true, or a key (number/string)- }--You can also specify it for a single series, like this:-- $.plot( $("#placeholder"), [{- data: [ ... ],- stack: true- }])--The stacking order is determined by the order of the data series in the array-(later series end up on top of the previous).--Internally, the plugin modifies the datapoints in each series, adding an-offset to the y value. For line series, extra data points are inserted through-interpolation. If there's a second y value, it's also adjusted (e.g for bar-charts or filled areas).--*/(function(e){function n(e){function t(e,t){var n=null;for(var r=0;r<t.length;++r){if(e==t[r])break;t[r].stack==e.stack&&(n=t[r])}return n}function n(e,n,r){if(n.stack==null||n.stack===!1)return;var i=t(n,e.getData());if(!i)return;var s=r.pointsize,o=r.points,u=i.datapoints.pointsize,a=i.datapoints.points,f=[],l,c,h,p,d,v,m=n.lines.show,g=n.bars.horizontal,y=s>2&&(g?r.format[2].x:r.format[2].y),b=m&&n.lines.steps,w=!0,E=g?1:0,S=g?0:1,x=0,T=0,N,C;for(;;){if(x>=o.length)break;N=f.length;if(o[x]==null){for(C=0;C<s;++C)f.push(o[x+C]);x+=s}else if(T>=a.length){if(!m)for(C=0;C<s;++C)f.push(o[x+C]);x+=s}else if(a[T]==null){for(C=0;C<s;++C)f.push(null);w=!0,T+=u}else{l=o[x+E],c=o[x+S],p=a[T+E],d=a[T+S],v=0;if(l==p){for(C=0;C<s;++C)f.push(o[x+C]);f[N+S]+=d,v=d,x+=s,T+=u}else if(l>p){if(m&&x>0&&o[x-s]!=null){h=c+(o[x-s+S]-c)*(p-l)/(o[x-s+E]-l),f.push(p),f.push(h+d);for(C=2;C<s;++C)f.push(o[x+C]);v=d}T+=u}else{if(w&&m){x+=s;continue}for(C=0;C<s;++C)f.push(o[x+C]);m&&T>0&&a[T-u]!=null&&(v=d+(a[T-u+S]-d)*(l-p)/(a[T-u+E]-p)),f[N+S]+=v,x+=s}w=!1,N!=f.length&&y&&(f[N+2]+=v)}if(b&&N!=f.length&&N>0&&f[N]!=null&&f[N]!=f[N-s]&&f[N+1]!=f[N-s+1]){for(C=0;C<s;++C)f[N+s+C]=f[N+C];f[N+1]=f[N-s+1]}}r.points=f}e.hooks.processDatapoints.push(n)}var t={series:{stack:null}};e.plot.plugins.push({init:n,options:t,name:"stack",version:"1.2"})})(jQuery);
− html/jquery.js
@@ -1,2 +0,0 @@-/*! jQuery v1.8.3 jquery.com | jquery.org/license */ -(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
html/profile.html view
@@ -6,9 +6,9 @@ <title>Shake report</title> <!-- Libraries -->-<script src="jquery.js"></script>-<script src="jquery.flot.js"></script>-<script src="jquery.flot.stack.js"></script>+<script src="lib/jquery.js"></script>+<script src="lib/jquery.flot.js"></script>+<script src="lib/jquery.flot.stack.js"></script> <script src="viz.js"></script> <!-- Profiling output --> <script src="profile-data.js"></script>
html/progress.html view
@@ -6,9 +6,9 @@ <title>Shake progress diagnostic</title> <!-- Libraries -->-<script src="jquery.js"></script>-<script src="jquery.flot.js"></script>-<script src="jquery.flot.stack.js"></script>+<script src="lib/jquery.js"></script>+<script src="lib/jquery.flot.js"></script>+<script src="lib/jquery.flot.stack.js"></script> <!-- Progress output --> <script src="progress-data.js"></script> <script src="version.js"></script>
− js-src/flot-0.8.0.zip
binary file changed (642293 → absent bytes)
− js-src/jquery-1.8.3.js
@@ -1,9472 +0,0 @@-/*!- * jQuery JavaScript Library v1.8.3- * http://jquery.com/- *- * Includes Sizzle.js- * http://sizzlejs.com/- *- * Copyright 2012 jQuery Foundation and other contributors- * Released under the MIT license- * http://jquery.org/license- *- * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)- */-(function( window, undefined ) {-var- // A central reference to the root jQuery(document)- rootjQuery,-- // The deferred used on DOM ready- readyList,-- // Use the correct document accordingly with window argument (sandbox)- document = window.document,- location = window.location,- navigator = window.navigator,-- // Map over jQuery in case of overwrite- _jQuery = window.jQuery,-- // Map over the $ in case of overwrite- _$ = window.$,-- // Save a reference to some core methods- core_push = Array.prototype.push,- core_slice = Array.prototype.slice,- core_indexOf = Array.prototype.indexOf,- core_toString = Object.prototype.toString,- core_hasOwn = Object.prototype.hasOwnProperty,- core_trim = String.prototype.trim,-- // Define a local copy of jQuery- jQuery = function( selector, context ) {- // The jQuery object is actually just the init constructor 'enhanced'- return new jQuery.fn.init( selector, context, rootjQuery );- },-- // Used for matching numbers- core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,-- // Used for detecting and trimming whitespace- core_rnotwhite = /\S/,- core_rspace = /\s+/,-- // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)- rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,-- // A simple way to check for HTML strings- // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)- rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,-- // Match a standalone tag- rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,-- // JSON RegExp- rvalidchars = /^[\],:{}\s]*$/,- rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,- rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,- rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,-- // Matches dashed string for camelizing- rmsPrefix = /^-ms-/,- rdashAlpha = /-([\da-z])/gi,-- // Used by jQuery.camelCase as callback to replace()- fcamelCase = function( all, letter ) {- return ( letter + "" ).toUpperCase();- },-- // The ready event handler and self cleanup method- DOMContentLoaded = function() {- if ( document.addEventListener ) {- document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );- jQuery.ready();- } else if ( document.readyState === "complete" ) {- // we're here because readyState === "complete" in oldIE- // which is good enough for us to call the dom ready!- document.detachEvent( "onreadystatechange", DOMContentLoaded );- jQuery.ready();- }- },-- // [[Class]] -> type pairs- class2type = {};--jQuery.fn = jQuery.prototype = {- constructor: jQuery,- init: function( selector, context, rootjQuery ) {- var match, elem, ret, doc;-- // Handle $(""), $(null), $(undefined), $(false)- if ( !selector ) {- return this;- }-- // Handle $(DOMElement)- if ( selector.nodeType ) {- this.context = this[0] = selector;- this.length = 1;- return this;- }-- // Handle HTML strings- if ( typeof selector === "string" ) {- if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {- // Assume that strings that start and end with <> are HTML and skip the regex check- match = [ null, selector, null ];-- } else {- match = rquickExpr.exec( selector );- }-- // Match html or make sure no context is specified for #id- if ( match && (match[1] || !context) ) {-- // HANDLE: $(html) -> $(array)- if ( match[1] ) {- context = context instanceof jQuery ? context[0] : context;- doc = ( context && context.nodeType ? context.ownerDocument || context : document );-- // scripts is true for back-compat- selector = jQuery.parseHTML( match[1], doc, true );- if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {- this.attr.call( selector, context, true );- }-- return jQuery.merge( this, selector );-- // HANDLE: $(#id)- } else {- elem = document.getElementById( match[2] );-- // Check parentNode to catch when Blackberry 4.6 returns- // nodes that are no longer in the document #6963- if ( elem && elem.parentNode ) {- // Handle the case where IE and Opera return items- // by name instead of ID- if ( elem.id !== match[2] ) {- return rootjQuery.find( selector );- }-- // Otherwise, we inject the element directly into the jQuery object- this.length = 1;- this[0] = elem;- }-- this.context = document;- this.selector = selector;- return this;- }-- // HANDLE: $(expr, $(...))- } else if ( !context || context.jquery ) {- return ( context || rootjQuery ).find( selector );-- // HANDLE: $(expr, context)- // (which is just equivalent to: $(context).find(expr)- } else {- return this.constructor( context ).find( selector );- }-- // HANDLE: $(function)- // Shortcut for document ready- } else if ( jQuery.isFunction( selector ) ) {- return rootjQuery.ready( selector );- }-- if ( selector.selector !== undefined ) {- this.selector = selector.selector;- this.context = selector.context;- }-- return jQuery.makeArray( selector, this );- },-- // Start with an empty selector- selector: "",-- // The current version of jQuery being used- jquery: "1.8.3",-- // The default length of a jQuery object is 0- length: 0,-- // The number of elements contained in the matched element set- size: function() {- return this.length;- },-- toArray: function() {- return core_slice.call( this );- },-- // Get the Nth element in the matched element set OR- // Get the whole matched element set as a clean array- get: function( num ) {- return num == null ?-- // Return a 'clean' array- this.toArray() :-- // Return just the object- ( num < 0 ? this[ this.length + num ] : this[ num ] );- },-- // Take an array of elements and push it onto the stack- // (returning the new matched element set)- pushStack: function( elems, name, selector ) {-- // Build a new jQuery matched element set- var ret = jQuery.merge( this.constructor(), elems );-- // Add the old object onto the stack (as a reference)- ret.prevObject = this;-- ret.context = this.context;-- if ( name === "find" ) {- ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;- } else if ( name ) {- ret.selector = this.selector + "." + name + "(" + selector + ")";- }-- // Return the newly-formed element set- return ret;- },-- // Execute a callback for every element in the matched set.- // (You can seed the arguments with an array of args, but this is- // only used internally.)- each: function( callback, args ) {- return jQuery.each( this, callback, args );- },-- ready: function( fn ) {- // Add the callback- jQuery.ready.promise().done( fn );-- return this;- },-- eq: function( i ) {- i = +i;- return i === -1 ?- this.slice( i ) :- this.slice( i, i + 1 );- },-- first: function() {- return this.eq( 0 );- },-- last: function() {- return this.eq( -1 );- },-- slice: function() {- return this.pushStack( core_slice.apply( this, arguments ),- "slice", core_slice.call(arguments).join(",") );- },-- map: function( callback ) {- return this.pushStack( jQuery.map(this, function( elem, i ) {- return callback.call( elem, i, elem );- }));- },-- end: function() {- return this.prevObject || this.constructor(null);- },-- // For internal use only.- // Behaves like an Array's method, not like a jQuery method.- push: core_push,- sort: [].sort,- splice: [].splice-};--// Give the init function the jQuery prototype for later instantiation-jQuery.fn.init.prototype = jQuery.fn;--jQuery.extend = jQuery.fn.extend = function() {- var options, name, src, copy, copyIsArray, clone,- target = arguments[0] || {},- i = 1,- length = arguments.length,- deep = false;-- // Handle a deep copy situation- if ( typeof target === "boolean" ) {- deep = target;- target = arguments[1] || {};- // skip the boolean and the target- i = 2;- }-- // Handle case when target is a string or something (possible in deep copy)- if ( typeof target !== "object" && !jQuery.isFunction(target) ) {- target = {};- }-- // extend jQuery itself if only one argument is passed- if ( length === i ) {- target = this;- --i;- }-- for ( ; i < length; i++ ) {- // Only deal with non-null/undefined values- if ( (options = arguments[ i ]) != null ) {- // Extend the base object- for ( name in options ) {- src = target[ name ];- copy = options[ name ];-- // Prevent never-ending loop- if ( target === copy ) {- continue;- }-- // Recurse if we're merging plain objects or arrays- if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {- if ( copyIsArray ) {- copyIsArray = false;- clone = src && jQuery.isArray(src) ? src : [];-- } else {- clone = src && jQuery.isPlainObject(src) ? src : {};- }-- // Never move original objects, clone them- target[ name ] = jQuery.extend( deep, clone, copy );-- // Don't bring in undefined values- } else if ( copy !== undefined ) {- target[ name ] = copy;- }- }- }- }-- // Return the modified object- return target;-};--jQuery.extend({- noConflict: function( deep ) {- if ( window.$ === jQuery ) {- window.$ = _$;- }-- if ( deep && window.jQuery === jQuery ) {- window.jQuery = _jQuery;- }-- return jQuery;- },-- // Is the DOM ready to be used? Set to true once it occurs.- isReady: false,-- // A counter to track how many items to wait for before- // the ready event fires. See #6781- readyWait: 1,-- // Hold (or release) the ready event- holdReady: function( hold ) {- if ( hold ) {- jQuery.readyWait++;- } else {- jQuery.ready( true );- }- },-- // Handle when the DOM is ready- ready: function( wait ) {-- // Abort if there are pending holds or we're already ready- if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {- return;- }-- // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).- if ( !document.body ) {- return setTimeout( jQuery.ready, 1 );- }-- // Remember that the DOM is ready- jQuery.isReady = true;-- // If a normal DOM Ready event fired, decrement, and wait if need be- if ( wait !== true && --jQuery.readyWait > 0 ) {- return;- }-- // If there are functions bound, to execute- readyList.resolveWith( document, [ jQuery ] );-- // Trigger any bound ready events- if ( jQuery.fn.trigger ) {- jQuery( document ).trigger("ready").off("ready");- }- },-- // See test/unit/core.js for details concerning isFunction.- // Since version 1.3, DOM methods and functions like alert- // aren't supported. They return false on IE (#2968).- isFunction: function( obj ) {- return jQuery.type(obj) === "function";- },-- isArray: Array.isArray || function( obj ) {- return jQuery.type(obj) === "array";- },-- isWindow: function( obj ) {- return obj != null && obj == obj.window;- },-- isNumeric: function( obj ) {- return !isNaN( parseFloat(obj) ) && isFinite( obj );- },-- type: function( obj ) {- return obj == null ?- String( obj ) :- class2type[ core_toString.call(obj) ] || "object";- },-- isPlainObject: function( obj ) {- // Must be an Object.- // Because of IE, we also have to check the presence of the constructor property.- // Make sure that DOM nodes and window objects don't pass through, as well- if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {- return false;- }-- try {- // Not own constructor property must be Object- if ( obj.constructor &&- !core_hasOwn.call(obj, "constructor") &&- !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {- return false;- }- } catch ( e ) {- // IE8,9 Will throw exceptions on certain host objects #9897- return false;- }-- // Own properties are enumerated firstly, so to speed up,- // if last one is own, then all properties are own.-- var key;- for ( key in obj ) {}-- return key === undefined || core_hasOwn.call( obj, key );- },-- isEmptyObject: function( obj ) {- var name;- for ( name in obj ) {- return false;- }- return true;- },-- error: function( msg ) {- throw new Error( msg );- },-- // data: string of html- // context (optional): If specified, the fragment will be created in this context, defaults to document- // scripts (optional): If true, will include scripts passed in the html string- parseHTML: function( data, context, scripts ) {- var parsed;- if ( !data || typeof data !== "string" ) {- return null;- }- if ( typeof context === "boolean" ) {- scripts = context;- context = 0;- }- context = context || document;-- // Single tag- if ( (parsed = rsingleTag.exec( data )) ) {- return [ context.createElement( parsed[1] ) ];- }-- parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );- return jQuery.merge( [],- (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );- },-- parseJSON: function( data ) {- if ( !data || typeof data !== "string") {- return null;- }-- // Make sure leading/trailing whitespace is removed (IE can't handle it)- data = jQuery.trim( data );-- // Attempt to parse using the native JSON parser first- if ( window.JSON && window.JSON.parse ) {- return window.JSON.parse( data );- }-- // Make sure the incoming data is actual JSON- // Logic borrowed from http://json.org/json2.js- if ( rvalidchars.test( data.replace( rvalidescape, "@" )- .replace( rvalidtokens, "]" )- .replace( rvalidbraces, "")) ) {-- return ( new Function( "return " + data ) )();-- }- jQuery.error( "Invalid JSON: " + data );- },-- // Cross-browser xml parsing- parseXML: function( data ) {- var xml, tmp;- if ( !data || typeof data !== "string" ) {- return null;- }- try {- if ( window.DOMParser ) { // Standard- tmp = new DOMParser();- xml = tmp.parseFromString( data , "text/xml" );- } else { // IE- xml = new ActiveXObject( "Microsoft.XMLDOM" );- xml.async = "false";- xml.loadXML( data );- }- } catch( e ) {- xml = undefined;- }- if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {- jQuery.error( "Invalid XML: " + data );- }- return xml;- },-- noop: function() {},-- // Evaluates a script in a global context- // Workarounds based on findings by Jim Driscoll- // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context- globalEval: function( data ) {- if ( data && core_rnotwhite.test( data ) ) {- // We use execScript on Internet Explorer- // We use an anonymous function so that context is window- // rather than jQuery in Firefox- ( window.execScript || function( data ) {- window[ "eval" ].call( window, data );- } )( data );- }- },-- // Convert dashed to camelCase; used by the css and data modules- // Microsoft forgot to hump their vendor prefix (#9572)- camelCase: function( string ) {- return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );- },-- nodeName: function( elem, name ) {- return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();- },-- // args is for internal usage only- each: function( obj, callback, args ) {- var name,- i = 0,- length = obj.length,- isObj = length === undefined || jQuery.isFunction( obj );-- if ( args ) {- if ( isObj ) {- for ( name in obj ) {- if ( callback.apply( obj[ name ], args ) === false ) {- break;- }- }- } else {- for ( ; i < length; ) {- if ( callback.apply( obj[ i++ ], args ) === false ) {- break;- }- }- }-- // A special, fast, case for the most common use of each- } else {- if ( isObj ) {- for ( name in obj ) {- if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {- break;- }- }- } else {- for ( ; i < length; ) {- if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {- break;- }- }- }- }-- return obj;- },-- // Use native String.trim function wherever possible- trim: core_trim && !core_trim.call("\uFEFF\xA0") ?- function( text ) {- return text == null ?- "" :- core_trim.call( text );- } :-- // Otherwise use our own trimming functionality- function( text ) {- return text == null ?- "" :- ( text + "" ).replace( rtrim, "" );- },-- // results is for internal usage only- makeArray: function( arr, results ) {- var type,- ret = results || [];-- if ( arr != null ) {- // The window, strings (and functions) also have 'length'- // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930- type = jQuery.type( arr );-- if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {- core_push.call( ret, arr );- } else {- jQuery.merge( ret, arr );- }- }-- return ret;- },-- inArray: function( elem, arr, i ) {- var len;-- if ( arr ) {- if ( core_indexOf ) {- return core_indexOf.call( arr, elem, i );- }-- len = arr.length;- i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;-- for ( ; i < len; i++ ) {- // Skip accessing in sparse arrays- if ( i in arr && arr[ i ] === elem ) {- return i;- }- }- }-- return -1;- },-- merge: function( first, second ) {- var l = second.length,- i = first.length,- j = 0;-- if ( typeof l === "number" ) {- for ( ; j < l; j++ ) {- first[ i++ ] = second[ j ];- }-- } else {- while ( second[j] !== undefined ) {- first[ i++ ] = second[ j++ ];- }- }-- first.length = i;-- return first;- },-- grep: function( elems, callback, inv ) {- var retVal,- ret = [],- i = 0,- length = elems.length;- inv = !!inv;-- // Go through the array, only saving the items- // that pass the validator function- for ( ; i < length; i++ ) {- retVal = !!callback( elems[ i ], i );- if ( inv !== retVal ) {- ret.push( elems[ i ] );- }- }-- return ret;- },-- // arg is for internal usage only- map: function( elems, callback, arg ) {- var value, key,- ret = [],- i = 0,- length = elems.length,- // jquery objects are treated as arrays- isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;-- // Go through the array, translating each of the items to their- if ( isArray ) {- for ( ; i < length; i++ ) {- value = callback( elems[ i ], i, arg );-- if ( value != null ) {- ret[ ret.length ] = value;- }- }-- // Go through every key on the object,- } else {- for ( key in elems ) {- value = callback( elems[ key ], key, arg );-- if ( value != null ) {- ret[ ret.length ] = value;- }- }- }-- // Flatten any nested arrays- return ret.concat.apply( [], ret );- },-- // A global GUID counter for objects- guid: 1,-- // Bind a function to a context, optionally partially applying any- // arguments.- proxy: function( fn, context ) {- var tmp, args, proxy;-- if ( typeof context === "string" ) {- tmp = fn[ context ];- context = fn;- fn = tmp;- }-- // Quick check to determine if target is callable, in the spec- // this throws a TypeError, but we will just return undefined.- if ( !jQuery.isFunction( fn ) ) {- return undefined;- }-- // Simulated bind- args = core_slice.call( arguments, 2 );- proxy = function() {- return fn.apply( context, args.concat( core_slice.call( arguments ) ) );- };-- // Set the guid of unique handler to the same of original handler, so it can be removed- proxy.guid = fn.guid = fn.guid || jQuery.guid++;-- return proxy;- },-- // Multifunctional method to get and set values of a collection- // The value/s can optionally be executed if it's a function- access: function( elems, fn, key, value, chainable, emptyGet, pass ) {- var exec,- bulk = key == null,- i = 0,- length = elems.length;-- // Sets many values- if ( key && typeof key === "object" ) {- for ( i in key ) {- jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );- }- chainable = 1;-- // Sets one value- } else if ( value !== undefined ) {- // Optionally, function values get executed if exec is true- exec = pass === undefined && jQuery.isFunction( value );-- if ( bulk ) {- // Bulk operations only iterate when executing function values- if ( exec ) {- exec = fn;- fn = function( elem, key, value ) {- return exec.call( jQuery( elem ), value );- };-- // Otherwise they run against the entire set- } else {- fn.call( elems, value );- fn = null;- }- }-- if ( fn ) {- for (; i < length; i++ ) {- fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );- }- }-- chainable = 1;- }-- return chainable ?- elems :-- // Gets- bulk ?- fn.call( elems ) :- length ? fn( elems[0], key ) : emptyGet;- },-- now: function() {- return ( new Date() ).getTime();- }-});--jQuery.ready.promise = function( obj ) {- if ( !readyList ) {-- readyList = jQuery.Deferred();-- // Catch cases where $(document).ready() is called after the browser event has already occurred.- // we once tried to use readyState "interactive" here, but it caused issues like the one- // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15- if ( document.readyState === "complete" ) {- // Handle it asynchronously to allow scripts the opportunity to delay ready- setTimeout( jQuery.ready, 1 );-- // Standards-based browsers support DOMContentLoaded- } else if ( document.addEventListener ) {- // Use the handy event callback- document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );-- // A fallback to window.onload, that will always work- window.addEventListener( "load", jQuery.ready, false );-- // If IE event model is used- } else {- // Ensure firing before onload, maybe late but safe also for iframes- document.attachEvent( "onreadystatechange", DOMContentLoaded );-- // A fallback to window.onload, that will always work- window.attachEvent( "onload", jQuery.ready );-- // If IE and not a frame- // continually check to see if the document is ready- var top = false;-- try {- top = window.frameElement == null && document.documentElement;- } catch(e) {}-- if ( top && top.doScroll ) {- (function doScrollCheck() {- if ( !jQuery.isReady ) {-- try {- // Use the trick by Diego Perini- // http://javascript.nwbox.com/IEContentLoaded/- top.doScroll("left");- } catch(e) {- return setTimeout( doScrollCheck, 50 );- }-- // and execute any waiting functions- jQuery.ready();- }- })();- }- }- }- return readyList.promise( obj );-};--// Populate the class2type map-jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {- class2type[ "[object " + name + "]" ] = name.toLowerCase();-});--// All jQuery objects should point back to these-rootjQuery = jQuery(document);-// String to Object options format cache-var optionsCache = {};--// Convert String-formatted options into Object-formatted ones and store in cache-function createOptions( options ) {- var object = optionsCache[ options ] = {};- jQuery.each( options.split( core_rspace ), function( _, flag ) {- object[ flag ] = true;- });- return object;-}--/*- * Create a callback list using the following parameters:- *- * options: an optional list of space-separated options that will change how- * the callback list behaves or a more traditional option object- *- * By default a callback list will act like an event callback list and can be- * "fired" multiple times.- *- * Possible options:- *- * once: will ensure the callback list can only be fired once (like a Deferred)- *- * memory: will keep track of previous values and will call any callback added- * after the list has been fired right away with the latest "memorized"- * values (like a Deferred)- *- * unique: will ensure a callback can only be added once (no duplicate in the list)- *- * stopOnFalse: interrupt callings when a callback returns false- *- */-jQuery.Callbacks = function( options ) {-- // Convert options from String-formatted to Object-formatted if needed- // (we check in cache first)- options = typeof options === "string" ?- ( optionsCache[ options ] || createOptions( options ) ) :- jQuery.extend( {}, options );-- var // Last fire value (for non-forgettable lists)- memory,- // Flag to know if list was already fired- fired,- // Flag to know if list is currently firing- firing,- // First callback to fire (used internally by add and fireWith)- firingStart,- // End of the loop when firing- firingLength,- // Index of currently firing callback (modified by remove if needed)- firingIndex,- // Actual callback list- list = [],- // Stack of fire calls for repeatable lists- stack = !options.once && [],- // Fire callbacks- fire = function( data ) {- memory = options.memory && data;- fired = true;- firingIndex = firingStart || 0;- firingStart = 0;- firingLength = list.length;- firing = true;- for ( ; list && firingIndex < firingLength; firingIndex++ ) {- if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {- memory = false; // To prevent further calls using add- break;- }- }- firing = false;- if ( list ) {- if ( stack ) {- if ( stack.length ) {- fire( stack.shift() );- }- } else if ( memory ) {- list = [];- } else {- self.disable();- }- }- },- // Actual Callbacks object- self = {- // Add a callback or a collection of callbacks to the list- add: function() {- if ( list ) {- // First, we save the current length- var start = list.length;- (function add( args ) {- jQuery.each( args, function( _, arg ) {- var type = jQuery.type( arg );- if ( type === "function" ) {- if ( !options.unique || !self.has( arg ) ) {- list.push( arg );- }- } else if ( arg && arg.length && type !== "string" ) {- // Inspect recursively- add( arg );- }- });- })( arguments );- // Do we need to add the callbacks to the- // current firing batch?- if ( firing ) {- firingLength = list.length;- // With memory, if we're not firing then- // we should call right away- } else if ( memory ) {- firingStart = start;- fire( memory );- }- }- return this;- },- // Remove a callback from the list- remove: function() {- if ( list ) {- jQuery.each( arguments, function( _, arg ) {- var index;- while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {- list.splice( index, 1 );- // Handle firing indexes- if ( firing ) {- if ( index <= firingLength ) {- firingLength--;- }- if ( index <= firingIndex ) {- firingIndex--;- }- }- }- });- }- return this;- },- // Control if a given callback is in the list- has: function( fn ) {- return jQuery.inArray( fn, list ) > -1;- },- // Remove all callbacks from the list- empty: function() {- list = [];- return this;- },- // Have the list do nothing anymore- disable: function() {- list = stack = memory = undefined;- return this;- },- // Is it disabled?- disabled: function() {- return !list;- },- // Lock the list in its current state- lock: function() {- stack = undefined;- if ( !memory ) {- self.disable();- }- return this;- },- // Is it locked?- locked: function() {- return !stack;- },- // Call all callbacks with the given context and arguments- fireWith: function( context, args ) {- args = args || [];- args = [ context, args.slice ? args.slice() : args ];- if ( list && ( !fired || stack ) ) {- if ( firing ) {- stack.push( args );- } else {- fire( args );- }- }- return this;- },- // Call all the callbacks with the given arguments- fire: function() {- self.fireWith( this, arguments );- return this;- },- // To know if the callbacks have already been called at least once- fired: function() {- return !!fired;- }- };-- return self;-};-jQuery.extend({-- Deferred: function( func ) {- var tuples = [- // action, add listener, listener list, final state- [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],- [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],- [ "notify", "progress", jQuery.Callbacks("memory") ]- ],- state = "pending",- promise = {- state: function() {- return state;- },- always: function() {- deferred.done( arguments ).fail( arguments );- return this;- },- then: function( /* fnDone, fnFail, fnProgress */ ) {- var fns = arguments;- return jQuery.Deferred(function( newDefer ) {- jQuery.each( tuples, function( i, tuple ) {- var action = tuple[ 0 ],- fn = fns[ i ];- // deferred[ done | fail | progress ] for forwarding actions to newDefer- deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?- function() {- var returned = fn.apply( this, arguments );- if ( returned && jQuery.isFunction( returned.promise ) ) {- returned.promise()- .done( newDefer.resolve )- .fail( newDefer.reject )- .progress( newDefer.notify );- } else {- newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );- }- } :- newDefer[ action ]- );- });- fns = null;- }).promise();- },- // Get a promise for this deferred- // If obj is provided, the promise aspect is added to the object- promise: function( obj ) {- return obj != null ? jQuery.extend( obj, promise ) : promise;- }- },- deferred = {};-- // Keep pipe for back-compat- promise.pipe = promise.then;-- // Add list-specific methods- jQuery.each( tuples, function( i, tuple ) {- var list = tuple[ 2 ],- stateString = tuple[ 3 ];-- // promise[ done | fail | progress ] = list.add- promise[ tuple[1] ] = list.add;-- // Handle state- if ( stateString ) {- list.add(function() {- // state = [ resolved | rejected ]- state = stateString;-- // [ reject_list | resolve_list ].disable; progress_list.lock- }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );- }-- // deferred[ resolve | reject | notify ] = list.fire- deferred[ tuple[0] ] = list.fire;- deferred[ tuple[0] + "With" ] = list.fireWith;- });-- // Make the deferred a promise- promise.promise( deferred );-- // Call given func if any- if ( func ) {- func.call( deferred, deferred );- }-- // All done!- return deferred;- },-- // Deferred helper- when: function( subordinate /* , ..., subordinateN */ ) {- var i = 0,- resolveValues = core_slice.call( arguments ),- length = resolveValues.length,-- // the count of uncompleted subordinates- remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,-- // the master Deferred. If resolveValues consist of only a single Deferred, just use that.- deferred = remaining === 1 ? subordinate : jQuery.Deferred(),-- // Update function for both resolve and progress values- updateFunc = function( i, contexts, values ) {- return function( value ) {- contexts[ i ] = this;- values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;- if( values === progressValues ) {- deferred.notifyWith( contexts, values );- } else if ( !( --remaining ) ) {- deferred.resolveWith( contexts, values );- }- };- },-- progressValues, progressContexts, resolveContexts;-- // add listeners to Deferred subordinates; treat others as resolved- if ( length > 1 ) {- progressValues = new Array( length );- progressContexts = new Array( length );- resolveContexts = new Array( length );- for ( ; i < length; i++ ) {- if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {- resolveValues[ i ].promise()- .done( updateFunc( i, resolveContexts, resolveValues ) )- .fail( deferred.reject )- .progress( updateFunc( i, progressContexts, progressValues ) );- } else {- --remaining;- }- }- }-- // if we're not waiting on anything, resolve the master- if ( !remaining ) {- deferred.resolveWith( resolveContexts, resolveValues );- }-- return deferred.promise();- }-});-jQuery.support = (function() {-- var support,- all,- a,- select,- opt,- input,- fragment,- eventName,- i,- isSupported,- clickFn,- div = document.createElement("div");-- // Setup- div.setAttribute( "className", "t" );- div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";-- // Support tests won't run in some limited or non-browser environments- all = div.getElementsByTagName("*");- a = div.getElementsByTagName("a")[ 0 ];- if ( !all || !a || !all.length ) {- return {};- }-- // First batch of tests- select = document.createElement("select");- opt = select.appendChild( document.createElement("option") );- input = div.getElementsByTagName("input")[ 0 ];-- a.style.cssText = "top:1px;float:left;opacity:.5";- support = {- // IE strips leading whitespace when .innerHTML is used- leadingWhitespace: ( div.firstChild.nodeType === 3 ),-- // Make sure that tbody elements aren't automatically inserted- // IE will insert them into empty tables- tbody: !div.getElementsByTagName("tbody").length,-- // Make sure that link elements get serialized correctly by innerHTML- // This requires a wrapper element in IE- htmlSerialize: !!div.getElementsByTagName("link").length,-- // Get the style information from getAttribute- // (IE uses .cssText instead)- style: /top/.test( a.getAttribute("style") ),-- // Make sure that URLs aren't manipulated- // (IE normalizes it by default)- hrefNormalized: ( a.getAttribute("href") === "/a" ),-- // Make sure that element opacity exists- // (IE uses filter instead)- // Use a regex to work around a WebKit issue. See #5145- opacity: /^0.5/.test( a.style.opacity ),-- // Verify style float existence- // (IE uses styleFloat instead of cssFloat)- cssFloat: !!a.style.cssFloat,-- // Make sure that if no value is specified for a checkbox- // that it defaults to "on".- // (WebKit defaults to "" instead)- checkOn: ( input.value === "on" ),-- // Make sure that a selected-by-default option has a working selected property.- // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)- optSelected: opt.selected,-- // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)- getSetAttribute: div.className !== "t",-- // Tests for enctype support on a form (#6743)- enctype: !!document.createElement("form").enctype,-- // Makes sure cloning an html5 element does not cause problems- // Where outerHTML is undefined, this still works- html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",-- // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode- boxModel: ( document.compatMode === "CSS1Compat" ),-- // Will be defined later- submitBubbles: true,- changeBubbles: true,- focusinBubbles: false,- deleteExpando: true,- noCloneEvent: true,- inlineBlockNeedsLayout: false,- shrinkWrapBlocks: false,- reliableMarginRight: true,- boxSizingReliable: true,- pixelPosition: false- };-- // Make sure checked status is properly cloned- input.checked = true;- support.noCloneChecked = input.cloneNode( true ).checked;-- // Make sure that the options inside disabled selects aren't marked as disabled- // (WebKit marks them as disabled)- select.disabled = true;- support.optDisabled = !opt.disabled;-- // Test to see if it's possible to delete an expando from an element- // Fails in Internet Explorer- try {- delete div.test;- } catch( e ) {- support.deleteExpando = false;- }-- if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {- div.attachEvent( "onclick", clickFn = function() {- // Cloning a node shouldn't copy over any- // bound event handlers (IE does this)- support.noCloneEvent = false;- });- div.cloneNode( true ).fireEvent("onclick");- div.detachEvent( "onclick", clickFn );- }-- // Check if a radio maintains its value- // after being appended to the DOM- input = document.createElement("input");- input.value = "t";- input.setAttribute( "type", "radio" );- support.radioValue = input.value === "t";-- input.setAttribute( "checked", "checked" );-- // #11217 - WebKit loses check when the name is after the checked attribute- input.setAttribute( "name", "t" );-- div.appendChild( input );- fragment = document.createDocumentFragment();- fragment.appendChild( div.lastChild );-- // WebKit doesn't clone checked state correctly in fragments- support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;-- // Check if a disconnected checkbox will retain its checked- // value of true after appended to the DOM (IE6/7)- support.appendChecked = input.checked;-- fragment.removeChild( input );- fragment.appendChild( div );-- // Technique from Juriy Zaytsev- // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/- // We only care about the case where non-standard event systems- // are used, namely in IE. Short-circuiting here helps us to- // avoid an eval call (in setAttribute) which can cause CSP- // to go haywire. See: https://developer.mozilla.org/en/Security/CSP- if ( div.attachEvent ) {- for ( i in {- submit: true,- change: true,- focusin: true- }) {- eventName = "on" + i;- isSupported = ( eventName in div );- if ( !isSupported ) {- div.setAttribute( eventName, "return;" );- isSupported = ( typeof div[ eventName ] === "function" );- }- support[ i + "Bubbles" ] = isSupported;- }- }-- // Run tests that need a body at doc ready- jQuery(function() {- var container, div, tds, marginDiv,- divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",- body = document.getElementsByTagName("body")[0];-- if ( !body ) {- // Return for frameset docs that don't have a body- return;- }-- container = document.createElement("div");- container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";- body.insertBefore( container, body.firstChild );-- // Construct the test element- div = document.createElement("div");- container.appendChild( div );-- // Check if table cells still have offsetWidth/Height when they are set- // to display:none and there are still other visible table cells in a- // table row; if so, offsetWidth/Height are not reliable for use when- // determining if an element has been hidden directly using- // display:none (it is still safe to use offsets if a parent element is- // hidden; don safety goggles and see bug #4512 for more information).- // (only IE 8 fails this test)- div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";- tds = div.getElementsByTagName("td");- tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";- isSupported = ( tds[ 0 ].offsetHeight === 0 );-- tds[ 0 ].style.display = "";- tds[ 1 ].style.display = "none";-- // Check if empty table cells still have offsetWidth/Height- // (IE <= 8 fail this test)- support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );-- // Check box-sizing and margin behavior- div.innerHTML = "";- div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";- support.boxSizing = ( div.offsetWidth === 4 );- support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );-- // NOTE: To any future maintainer, we've window.getComputedStyle- // because jsdom on node.js will break without it.- if ( window.getComputedStyle ) {- support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";- support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";-- // Check if div with explicit width and no margin-right incorrectly- // gets computed margin-right based on width of container. For more- // info see bug #3333- // Fails in WebKit before Feb 2011 nightlies- // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right- marginDiv = document.createElement("div");- marginDiv.style.cssText = div.style.cssText = divReset;- marginDiv.style.marginRight = marginDiv.style.width = "0";- div.style.width = "1px";- div.appendChild( marginDiv );- support.reliableMarginRight =- !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );- }-- if ( typeof div.style.zoom !== "undefined" ) {- // Check if natively block-level elements act like inline-block- // elements when setting their display to 'inline' and giving- // them layout- // (IE < 8 does this)- div.innerHTML = "";- div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";- support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );-- // Check if elements with layout shrink-wrap their children- // (IE 6 does this)- div.style.display = "block";- div.style.overflow = "visible";- div.innerHTML = "<div></div>";- div.firstChild.style.width = "5px";- support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );-- container.style.zoom = 1;- }-- // Null elements to avoid leaks in IE- body.removeChild( container );- container = div = tds = marginDiv = null;- });-- // Null elements to avoid leaks in IE- fragment.removeChild( div );- all = a = select = opt = input = fragment = div = null;-- return support;-})();-var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,- rmultiDash = /([A-Z])/g;--jQuery.extend({- cache: {},-- deletedIds: [],-- // Remove at next major release (1.9/2.0)- uuid: 0,-- // Unique for each copy of jQuery on the page- // Non-digits removed to match rinlinejQuery- expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),-- // The following elements throw uncatchable exceptions if you- // attempt to add expando properties to them.- noData: {- "embed": true,- // Ban all objects except for Flash (which handle expandos)- "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",- "applet": true- },-- hasData: function( elem ) {- elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];- return !!elem && !isEmptyDataObject( elem );- },-- data: function( elem, name, data, pvt /* Internal Use Only */ ) {- if ( !jQuery.acceptData( elem ) ) {- return;- }-- var thisCache, ret,- internalKey = jQuery.expando,- getByName = typeof name === "string",-- // We have to handle DOM nodes and JS objects differently because IE6-7- // can't GC object references properly across the DOM-JS boundary- isNode = elem.nodeType,-- // Only DOM nodes need the global jQuery cache; JS object data is- // attached directly to the object so GC can occur automatically- cache = isNode ? jQuery.cache : elem,-- // Only defining an ID for JS objects if its cache already exists allows- // the code to shortcut on the same path as a DOM node with no cache- id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;-- // Avoid doing any more work than we need to when trying to get data on an- // object that has no data at all- if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {- return;- }-- if ( !id ) {- // Only DOM nodes need a new unique ID for each element since their data- // ends up in the global cache- if ( isNode ) {- elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;- } else {- id = internalKey;- }- }-- if ( !cache[ id ] ) {- cache[ id ] = {};-- // Avoids exposing jQuery metadata on plain JS objects when the object- // is serialized using JSON.stringify- if ( !isNode ) {- cache[ id ].toJSON = jQuery.noop;- }- }-- // An object can be passed to jQuery.data instead of a key/value pair; this gets- // shallow copied over onto the existing cache- if ( typeof name === "object" || typeof name === "function" ) {- if ( pvt ) {- cache[ id ] = jQuery.extend( cache[ id ], name );- } else {- cache[ id ].data = jQuery.extend( cache[ id ].data, name );- }- }-- thisCache = cache[ id ];-- // jQuery data() is stored in a separate object inside the object's internal data- // cache in order to avoid key collisions between internal data and user-defined- // data.- if ( !pvt ) {- if ( !thisCache.data ) {- thisCache.data = {};- }-- thisCache = thisCache.data;- }-- if ( data !== undefined ) {- thisCache[ jQuery.camelCase( name ) ] = data;- }-- // Check for both converted-to-camel and non-converted data property names- // If a data property was specified- if ( getByName ) {-- // First Try to find as-is property data- ret = thisCache[ name ];-- // Test for null|undefined property data- if ( ret == null ) {-- // Try to find the camelCased property- ret = thisCache[ jQuery.camelCase( name ) ];- }- } else {- ret = thisCache;- }-- return ret;- },-- removeData: function( elem, name, pvt /* Internal Use Only */ ) {- if ( !jQuery.acceptData( elem ) ) {- return;- }-- var thisCache, i, l,-- isNode = elem.nodeType,-- // See jQuery.data for more information- cache = isNode ? jQuery.cache : elem,- id = isNode ? elem[ jQuery.expando ] : jQuery.expando;-- // If there is already no cache entry for this object, there is no- // purpose in continuing- if ( !cache[ id ] ) {- return;- }-- if ( name ) {-- thisCache = pvt ? cache[ id ] : cache[ id ].data;-- if ( thisCache ) {-- // Support array or space separated string names for data keys- if ( !jQuery.isArray( name ) ) {-- // try the string as a key before any manipulation- if ( name in thisCache ) {- name = [ name ];- } else {-- // split the camel cased version by spaces unless a key with the spaces exists- name = jQuery.camelCase( name );- if ( name in thisCache ) {- name = [ name ];- } else {- name = name.split(" ");- }- }- }-- for ( i = 0, l = name.length; i < l; i++ ) {- delete thisCache[ name[i] ];- }-- // If there is no data left in the cache, we want to continue- // and let the cache object itself get destroyed- if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {- return;- }- }- }-- // See jQuery.data for more information- if ( !pvt ) {- delete cache[ id ].data;-- // Don't destroy the parent cache unless the internal data object- // had been the only thing left in it- if ( !isEmptyDataObject( cache[ id ] ) ) {- return;- }- }-- // Destroy the cache- if ( isNode ) {- jQuery.cleanData( [ elem ], true );-- // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)- } else if ( jQuery.support.deleteExpando || cache != cache.window ) {- delete cache[ id ];-- // When all else fails, null- } else {- cache[ id ] = null;- }- },-- // For internal use only.- _data: function( elem, name, data ) {- return jQuery.data( elem, name, data, true );- },-- // A method for determining if a DOM node can handle the data expando- acceptData: function( elem ) {- var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];-- // nodes accept data unless otherwise specified; rejection can be conditional- return !noData || noData !== true && elem.getAttribute("classid") === noData;- }-});--jQuery.fn.extend({- data: function( key, value ) {- var parts, part, attr, name, l,- elem = this[0],- i = 0,- data = null;-- // Gets all values- if ( key === undefined ) {- if ( this.length ) {- data = jQuery.data( elem );-- if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {- attr = elem.attributes;- for ( l = attr.length; i < l; i++ ) {- name = attr[i].name;-- if ( !name.indexOf( "data-" ) ) {- name = jQuery.camelCase( name.substring(5) );-- dataAttr( elem, name, data[ name ] );- }- }- jQuery._data( elem, "parsedAttrs", true );- }- }-- return data;- }-- // Sets multiple values- if ( typeof key === "object" ) {- return this.each(function() {- jQuery.data( this, key );- });- }-- parts = key.split( ".", 2 );- parts[1] = parts[1] ? "." + parts[1] : "";- part = parts[1] + "!";-- return jQuery.access( this, function( value ) {-- if ( value === undefined ) {- data = this.triggerHandler( "getData" + part, [ parts[0] ] );-- // Try to fetch any internally stored data first- if ( data === undefined && elem ) {- data = jQuery.data( elem, key );- data = dataAttr( elem, key, data );- }-- return data === undefined && parts[1] ?- this.data( parts[0] ) :- data;- }-- parts[1] = value;- this.each(function() {- var self = jQuery( this );-- self.triggerHandler( "setData" + part, parts );- jQuery.data( this, key, value );- self.triggerHandler( "changeData" + part, parts );- });- }, null, value, arguments.length > 1, null, false );- },-- removeData: function( key ) {- return this.each(function() {- jQuery.removeData( this, key );- });- }-});--function dataAttr( elem, key, data ) {- // If nothing was found internally, try to fetch any- // data from the HTML5 data-* attribute- if ( data === undefined && elem.nodeType === 1 ) {-- var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();-- data = elem.getAttribute( name );-- if ( typeof data === "string" ) {- try {- data = data === "true" ? true :- data === "false" ? false :- data === "null" ? null :- // Only convert to a number if it doesn't change the string- +data + "" === data ? +data :- rbrace.test( data ) ? jQuery.parseJSON( data ) :- data;- } catch( e ) {}-- // Make sure we set the data so it isn't changed later- jQuery.data( elem, key, data );-- } else {- data = undefined;- }- }-- return data;-}--// checks a cache object for emptiness-function isEmptyDataObject( obj ) {- var name;- for ( name in obj ) {-- // if the public data object is empty, the private is still empty- if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {- continue;- }- if ( name !== "toJSON" ) {- return false;- }- }-- return true;-}-jQuery.extend({- queue: function( elem, type, data ) {- var queue;-- if ( elem ) {- type = ( type || "fx" ) + "queue";- queue = jQuery._data( elem, type );-- // Speed up dequeue by getting out quickly if this is just a lookup- if ( data ) {- if ( !queue || jQuery.isArray(data) ) {- queue = jQuery._data( elem, type, jQuery.makeArray(data) );- } else {- queue.push( data );- }- }- return queue || [];- }- },-- dequeue: function( elem, type ) {- type = type || "fx";-- var queue = jQuery.queue( elem, type ),- startLength = queue.length,- fn = queue.shift(),- hooks = jQuery._queueHooks( elem, type ),- next = function() {- jQuery.dequeue( elem, type );- };-- // If the fx queue is dequeued, always remove the progress sentinel- if ( fn === "inprogress" ) {- fn = queue.shift();- startLength--;- }-- if ( fn ) {-- // Add a progress sentinel to prevent the fx queue from being- // automatically dequeued- if ( type === "fx" ) {- queue.unshift( "inprogress" );- }-- // clear up the last queue stop function- delete hooks.stop;- fn.call( elem, next, hooks );- }-- if ( !startLength && hooks ) {- hooks.empty.fire();- }- },-- // not intended for public consumption - generates a queueHooks object, or returns the current one- _queueHooks: function( elem, type ) {- var key = type + "queueHooks";- return jQuery._data( elem, key ) || jQuery._data( elem, key, {- empty: jQuery.Callbacks("once memory").add(function() {- jQuery.removeData( elem, type + "queue", true );- jQuery.removeData( elem, key, true );- })- });- }-});--jQuery.fn.extend({- queue: function( type, data ) {- var setter = 2;-- if ( typeof type !== "string" ) {- data = type;- type = "fx";- setter--;- }-- if ( arguments.length < setter ) {- return jQuery.queue( this[0], type );- }-- return data === undefined ?- this :- this.each(function() {- var queue = jQuery.queue( this, type, data );-- // ensure a hooks for this queue- jQuery._queueHooks( this, type );-- if ( type === "fx" && queue[0] !== "inprogress" ) {- jQuery.dequeue( this, type );- }- });- },- dequeue: function( type ) {- return this.each(function() {- jQuery.dequeue( this, type );- });- },- // Based off of the plugin by Clint Helfers, with permission.- // http://blindsignals.com/index.php/2009/07/jquery-delay/- delay: function( time, type ) {- time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;- type = type || "fx";-- return this.queue( type, function( next, hooks ) {- var timeout = setTimeout( next, time );- hooks.stop = function() {- clearTimeout( timeout );- };- });- },- clearQueue: function( type ) {- return this.queue( type || "fx", [] );- },- // Get a promise resolved when queues of a certain type- // are emptied (fx is the type by default)- promise: function( type, obj ) {- var tmp,- count = 1,- defer = jQuery.Deferred(),- elements = this,- i = this.length,- resolve = function() {- if ( !( --count ) ) {- defer.resolveWith( elements, [ elements ] );- }- };-- if ( typeof type !== "string" ) {- obj = type;- type = undefined;- }- type = type || "fx";-- while( i-- ) {- tmp = jQuery._data( elements[ i ], type + "queueHooks" );- if ( tmp && tmp.empty ) {- count++;- tmp.empty.add( resolve );- }- }- resolve();- return defer.promise( obj );- }-});-var nodeHook, boolHook, fixSpecified,- rclass = /[\t\r\n]/g,- rreturn = /\r/g,- rtype = /^(?:button|input)$/i,- rfocusable = /^(?:button|input|object|select|textarea)$/i,- rclickable = /^a(?:rea|)$/i,- rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,- getSetAttribute = jQuery.support.getSetAttribute;--jQuery.fn.extend({- attr: function( name, value ) {- return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );- },-- removeAttr: function( name ) {- return this.each(function() {- jQuery.removeAttr( this, name );- });- },-- prop: function( name, value ) {- return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );- },-- removeProp: function( name ) {- name = jQuery.propFix[ name ] || name;- return this.each(function() {- // try/catch handles cases where IE balks (such as removing a property on window)- try {- this[ name ] = undefined;- delete this[ name ];- } catch( e ) {}- });- },-- addClass: function( value ) {- var classNames, i, l, elem,- setClass, c, cl;-- if ( jQuery.isFunction( value ) ) {- return this.each(function( j ) {- jQuery( this ).addClass( value.call(this, j, this.className) );- });- }-- if ( value && typeof value === "string" ) {- classNames = value.split( core_rspace );-- for ( i = 0, l = this.length; i < l; i++ ) {- elem = this[ i ];-- if ( elem.nodeType === 1 ) {- if ( !elem.className && classNames.length === 1 ) {- elem.className = value;-- } else {- setClass = " " + elem.className + " ";-- for ( c = 0, cl = classNames.length; c < cl; c++ ) {- if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {- setClass += classNames[ c ] + " ";- }- }- elem.className = jQuery.trim( setClass );- }- }- }- }-- return this;- },-- removeClass: function( value ) {- var removes, className, elem, c, cl, i, l;-- if ( jQuery.isFunction( value ) ) {- return this.each(function( j ) {- jQuery( this ).removeClass( value.call(this, j, this.className) );- });- }- if ( (value && typeof value === "string") || value === undefined ) {- removes = ( value || "" ).split( core_rspace );-- for ( i = 0, l = this.length; i < l; i++ ) {- elem = this[ i ];- if ( elem.nodeType === 1 && elem.className ) {-- className = (" " + elem.className + " ").replace( rclass, " " );-- // loop over each item in the removal list- for ( c = 0, cl = removes.length; c < cl; c++ ) {- // Remove until there is nothing to remove,- while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {- className = className.replace( " " + removes[ c ] + " " , " " );- }- }- elem.className = value ? jQuery.trim( className ) : "";- }- }- }-- return this;- },-- toggleClass: function( value, stateVal ) {- var type = typeof value,- isBool = typeof stateVal === "boolean";-- if ( jQuery.isFunction( value ) ) {- return this.each(function( i ) {- jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );- });- }-- return this.each(function() {- if ( type === "string" ) {- // toggle individual class names- var className,- i = 0,- self = jQuery( this ),- state = stateVal,- classNames = value.split( core_rspace );-- while ( (className = classNames[ i++ ]) ) {- // check each className given, space separated list- state = isBool ? state : !self.hasClass( className );- self[ state ? "addClass" : "removeClass" ]( className );- }-- } else if ( type === "undefined" || type === "boolean" ) {- if ( this.className ) {- // store className if set- jQuery._data( this, "__className__", this.className );- }-- // toggle whole className- this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";- }- });- },-- hasClass: function( selector ) {- var className = " " + selector + " ",- i = 0,- l = this.length;- for ( ; i < l; i++ ) {- if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {- return true;- }- }-- return false;- },-- val: function( value ) {- var hooks, ret, isFunction,- elem = this[0];-- if ( !arguments.length ) {- if ( elem ) {- hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];-- if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {- return ret;- }-- ret = elem.value;-- return typeof ret === "string" ?- // handle most common string cases- ret.replace(rreturn, "") :- // handle cases where value is null/undef or number- ret == null ? "" : ret;- }-- return;- }-- isFunction = jQuery.isFunction( value );-- return this.each(function( i ) {- var val,- self = jQuery(this);-- if ( this.nodeType !== 1 ) {- return;- }-- if ( isFunction ) {- val = value.call( this, i, self.val() );- } else {- val = value;- }-- // Treat null/undefined as ""; convert numbers to string- if ( val == null ) {- val = "";- } else if ( typeof val === "number" ) {- val += "";- } else if ( jQuery.isArray( val ) ) {- val = jQuery.map(val, function ( value ) {- return value == null ? "" : value + "";- });- }-- hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];-- // If set returns undefined, fall back to normal setting- if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {- this.value = val;- }- });- }-});--jQuery.extend({- valHooks: {- option: {- get: function( elem ) {- // attributes.value is undefined in Blackberry 4.7 but- // uses .value. See #6932- var val = elem.attributes.value;- return !val || val.specified ? elem.value : elem.text;- }- },- select: {- get: function( elem ) {- var value, option,- options = elem.options,- index = elem.selectedIndex,- one = elem.type === "select-one" || index < 0,- values = one ? null : [],- max = one ? index + 1 : options.length,- i = index < 0 ?- max :- one ? index : 0;-- // Loop through all the selected options- for ( ; i < max; i++ ) {- option = options[ i ];-- // oldIE doesn't update selected after form reset (#2551)- if ( ( option.selected || i === index ) &&- // Don't return options that are disabled or in a disabled optgroup- ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&- ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {-- // Get the specific value for the option- value = jQuery( option ).val();-- // We don't need an array for one selects- if ( one ) {- return value;- }-- // Multi-Selects return an array- values.push( value );- }- }-- return values;- },-- set: function( elem, value ) {- var values = jQuery.makeArray( value );-- jQuery(elem).find("option").each(function() {- this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;- });-- if ( !values.length ) {- elem.selectedIndex = -1;- }- return values;- }- }- },-- // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9- attrFn: {},-- attr: function( elem, name, value, pass ) {- var ret, hooks, notxml,- nType = elem.nodeType;-- // don't get/set attributes on text, comment and attribute nodes- if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {- return;- }-- if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {- return jQuery( elem )[ name ]( value );- }-- // Fallback to prop when attributes are not supported- if ( typeof elem.getAttribute === "undefined" ) {- return jQuery.prop( elem, name, value );- }-- notxml = nType !== 1 || !jQuery.isXMLDoc( elem );-- // All attributes are lowercase- // Grab necessary hook if one is defined- if ( notxml ) {- name = name.toLowerCase();- hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );- }-- if ( value !== undefined ) {-- if ( value === null ) {- jQuery.removeAttr( elem, name );- return;-- } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {- return ret;-- } else {- elem.setAttribute( name, value + "" );- return value;- }-- } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {- return ret;-- } else {-- ret = elem.getAttribute( name );-- // Non-existent attributes return null, we normalize to undefined- return ret === null ?- undefined :- ret;- }- },-- removeAttr: function( elem, value ) {- var propName, attrNames, name, isBool,- i = 0;-- if ( value && elem.nodeType === 1 ) {-- attrNames = value.split( core_rspace );-- for ( ; i < attrNames.length; i++ ) {- name = attrNames[ i ];-- if ( name ) {- propName = jQuery.propFix[ name ] || name;- isBool = rboolean.test( name );-- // See #9699 for explanation of this approach (setting first, then removal)- // Do not do this for boolean attributes (see #10870)- if ( !isBool ) {- jQuery.attr( elem, name, "" );- }- elem.removeAttribute( getSetAttribute ? name : propName );-- // Set corresponding property to false for boolean attributes- if ( isBool && propName in elem ) {- elem[ propName ] = false;- }- }- }- }- },-- attrHooks: {- type: {- set: function( elem, value ) {- // We can't allow the type property to be changed (since it causes problems in IE)- if ( rtype.test( elem.nodeName ) && elem.parentNode ) {- jQuery.error( "type property can't be changed" );- } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {- // Setting the type on a radio button after the value resets the value in IE6-9- // Reset value to it's default in case type is set after value- // This is for element creation- var val = elem.value;- elem.setAttribute( "type", value );- if ( val ) {- elem.value = val;- }- return value;- }- }- },- // Use the value property for back compat- // Use the nodeHook for button elements in IE6/7 (#1954)- value: {- get: function( elem, name ) {- if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {- return nodeHook.get( elem, name );- }- return name in elem ?- elem.value :- null;- },- set: function( elem, value, name ) {- if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {- return nodeHook.set( elem, value, name );- }- // Does not return so that setAttribute is also used- elem.value = value;- }- }- },-- propFix: {- tabindex: "tabIndex",- readonly: "readOnly",- "for": "htmlFor",- "class": "className",- maxlength: "maxLength",- cellspacing: "cellSpacing",- cellpadding: "cellPadding",- rowspan: "rowSpan",- colspan: "colSpan",- usemap: "useMap",- frameborder: "frameBorder",- contenteditable: "contentEditable"- },-- prop: function( elem, name, value ) {- var ret, hooks, notxml,- nType = elem.nodeType;-- // don't get/set properties on text, comment and attribute nodes- if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {- return;- }-- notxml = nType !== 1 || !jQuery.isXMLDoc( elem );-- if ( notxml ) {- // Fix name and attach hooks- name = jQuery.propFix[ name ] || name;- hooks = jQuery.propHooks[ name ];- }-- if ( value !== undefined ) {- if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {- return ret;-- } else {- return ( elem[ name ] = value );- }-- } else {- if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {- return ret;-- } else {- return elem[ name ];- }- }- },-- propHooks: {- tabIndex: {- get: function( elem ) {- // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set- // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/- var attributeNode = elem.getAttributeNode("tabindex");-- return attributeNode && attributeNode.specified ?- parseInt( attributeNode.value, 10 ) :- rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?- 0 :- undefined;- }- }- }-});--// Hook for boolean attributes-boolHook = {- get: function( elem, name ) {- // Align boolean attributes with corresponding properties- // Fall back to attribute presence where some booleans are not supported- var attrNode,- property = jQuery.prop( elem, name );- return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?- name.toLowerCase() :- undefined;- },- set: function( elem, value, name ) {- var propName;- if ( value === false ) {- // Remove boolean attributes when set to false- jQuery.removeAttr( elem, name );- } else {- // value is true since we know at this point it's type boolean and not false- // Set boolean attributes to the same name and set the DOM property- propName = jQuery.propFix[ name ] || name;- if ( propName in elem ) {- // Only set the IDL specifically if it already exists on the element- elem[ propName ] = true;- }-- elem.setAttribute( name, name.toLowerCase() );- }- return name;- }-};--// IE6/7 do not support getting/setting some attributes with get/setAttribute-if ( !getSetAttribute ) {-- fixSpecified = {- name: true,- id: true,- coords: true- };-- // Use this for any attribute in IE6/7- // This fixes almost every IE6/7 issue- nodeHook = jQuery.valHooks.button = {- get: function( elem, name ) {- var ret;- ret = elem.getAttributeNode( name );- return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?- ret.value :- undefined;- },- set: function( elem, value, name ) {- // Set the existing or create a new attribute node- var ret = elem.getAttributeNode( name );- if ( !ret ) {- ret = document.createAttribute( name );- elem.setAttributeNode( ret );- }- return ( ret.value = value + "" );- }- };-- // Set width and height to auto instead of 0 on empty string( Bug #8150 )- // This is for removals- jQuery.each([ "width", "height" ], function( i, name ) {- jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {- set: function( elem, value ) {- if ( value === "" ) {- elem.setAttribute( name, "auto" );- return value;- }- }- });- });-- // Set contenteditable to false on removals(#10429)- // Setting to empty string throws an error as an invalid value- jQuery.attrHooks.contenteditable = {- get: nodeHook.get,- set: function( elem, value, name ) {- if ( value === "" ) {- value = "false";- }- nodeHook.set( elem, value, name );- }- };-}---// Some attributes require a special call on IE-if ( !jQuery.support.hrefNormalized ) {- jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {- jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {- get: function( elem ) {- var ret = elem.getAttribute( name, 2 );- return ret === null ? undefined : ret;- }- });- });-}--if ( !jQuery.support.style ) {- jQuery.attrHooks.style = {- get: function( elem ) {- // Return undefined in the case of empty string- // Normalize to lowercase since IE uppercases css property names- return elem.style.cssText.toLowerCase() || undefined;- },- set: function( elem, value ) {- return ( elem.style.cssText = value + "" );- }- };-}--// Safari mis-reports the default selected property of an option-// Accessing the parent's selectedIndex property fixes it-if ( !jQuery.support.optSelected ) {- jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {- get: function( elem ) {- var parent = elem.parentNode;-- if ( parent ) {- parent.selectedIndex;-- // Make sure that it also works with optgroups, see #5701- if ( parent.parentNode ) {- parent.parentNode.selectedIndex;- }- }- return null;- }- });-}--// IE6/7 call enctype encoding-if ( !jQuery.support.enctype ) {- jQuery.propFix.enctype = "encoding";-}--// Radios and checkboxes getter/setter-if ( !jQuery.support.checkOn ) {- jQuery.each([ "radio", "checkbox" ], function() {- jQuery.valHooks[ this ] = {- get: function( elem ) {- // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified- return elem.getAttribute("value") === null ? "on" : elem.value;- }- };- });-}-jQuery.each([ "radio", "checkbox" ], function() {- jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {- set: function( elem, value ) {- if ( jQuery.isArray( value ) ) {- return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );- }- }- });-});-var rformElems = /^(?:textarea|input|select)$/i,- rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,- rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,- rkeyEvent = /^key/,- rmouseEvent = /^(?:mouse|contextmenu)|click/,- rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,- hoverHack = function( events ) {- return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );- };--/*- * Helper functions for managing events -- not part of the public interface.- * Props to Dean Edwards' addEvent library for many of the ideas.- */-jQuery.event = {-- add: function( elem, types, handler, data, selector ) {-- var elemData, eventHandle, events,- t, tns, type, namespaces, handleObj,- handleObjIn, handlers, special;-- // Don't attach events to noData or text/comment nodes (allow plain objects tho)- if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {- return;- }-- // Caller can pass in an object of custom data in lieu of the handler- if ( handler.handler ) {- handleObjIn = handler;- handler = handleObjIn.handler;- selector = handleObjIn.selector;- }-- // Make sure that the handler has a unique ID, used to find/remove it later- if ( !handler.guid ) {- handler.guid = jQuery.guid++;- }-- // Init the element's event structure and main handler, if this is the first- events = elemData.events;- if ( !events ) {- elemData.events = events = {};- }- eventHandle = elemData.handle;- if ( !eventHandle ) {- elemData.handle = eventHandle = function( e ) {- // Discard the second event of a jQuery.event.trigger() and- // when an event is called after a page has unloaded- return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?- jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :- undefined;- };- // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events- eventHandle.elem = elem;- }-- // Handle multiple events separated by a space- // jQuery(...).bind("mouseover mouseout", fn);- types = jQuery.trim( hoverHack(types) ).split( " " );- for ( t = 0; t < types.length; t++ ) {-- tns = rtypenamespace.exec( types[t] ) || [];- type = tns[1];- namespaces = ( tns[2] || "" ).split( "." ).sort();-- // If event changes its type, use the special event handlers for the changed type- special = jQuery.event.special[ type ] || {};-- // If selector defined, determine special event api type, otherwise given type- type = ( selector ? special.delegateType : special.bindType ) || type;-- // Update special based on newly reset type- special = jQuery.event.special[ type ] || {};-- // handleObj is passed to all event handlers- handleObj = jQuery.extend({- type: type,- origType: tns[1],- data: data,- handler: handler,- guid: handler.guid,- selector: selector,- needsContext: selector && jQuery.expr.match.needsContext.test( selector ),- namespace: namespaces.join(".")- }, handleObjIn );-- // Init the event handler queue if we're the first- handlers = events[ type ];- if ( !handlers ) {- handlers = events[ type ] = [];- handlers.delegateCount = 0;-- // Only use addEventListener/attachEvent if the special events handler returns false- if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {- // Bind the global event handler to the element- if ( elem.addEventListener ) {- elem.addEventListener( type, eventHandle, false );-- } else if ( elem.attachEvent ) {- elem.attachEvent( "on" + type, eventHandle );- }- }- }-- if ( special.add ) {- special.add.call( elem, handleObj );-- if ( !handleObj.handler.guid ) {- handleObj.handler.guid = handler.guid;- }- }-- // Add to the element's handler list, delegates in front- if ( selector ) {- handlers.splice( handlers.delegateCount++, 0, handleObj );- } else {- handlers.push( handleObj );- }-- // Keep track of which events have ever been used, for event optimization- jQuery.event.global[ type ] = true;- }-- // Nullify elem to prevent memory leaks in IE- elem = null;- },-- global: {},-- // Detach an event or set of events from an element- remove: function( elem, types, handler, selector, mappedTypes ) {-- var t, tns, type, origType, namespaces, origCount,- j, events, special, eventType, handleObj,- elemData = jQuery.hasData( elem ) && jQuery._data( elem );-- if ( !elemData || !(events = elemData.events) ) {- return;- }-- // Once for each type.namespace in types; type may be omitted- types = jQuery.trim( hoverHack( types || "" ) ).split(" ");- for ( t = 0; t < types.length; t++ ) {- tns = rtypenamespace.exec( types[t] ) || [];- type = origType = tns[1];- namespaces = tns[2];-- // Unbind all events (on this namespace, if provided) for the element- if ( !type ) {- for ( type in events ) {- jQuery.event.remove( elem, type + types[ t ], handler, selector, true );- }- continue;- }-- special = jQuery.event.special[ type ] || {};- type = ( selector? special.delegateType : special.bindType ) || type;- eventType = events[ type ] || [];- origCount = eventType.length;- namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;-- // Remove matching events- for ( j = 0; j < eventType.length; j++ ) {- handleObj = eventType[ j ];-- if ( ( mappedTypes || origType === handleObj.origType ) &&- ( !handler || handler.guid === handleObj.guid ) &&- ( !namespaces || namespaces.test( handleObj.namespace ) ) &&- ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {- eventType.splice( j--, 1 );-- if ( handleObj.selector ) {- eventType.delegateCount--;- }- if ( special.remove ) {- special.remove.call( elem, handleObj );- }- }- }-- // Remove generic event handler if we removed something and no more handlers exist- // (avoids potential for endless recursion during removal of special event handlers)- if ( eventType.length === 0 && origCount !== eventType.length ) {- if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {- jQuery.removeEvent( elem, type, elemData.handle );- }-- delete events[ type ];- }- }-- // Remove the expando if it's no longer used- if ( jQuery.isEmptyObject( events ) ) {- delete elemData.handle;-- // removeData also checks for emptiness and clears the expando if empty- // so use it instead of delete- jQuery.removeData( elem, "events", true );- }- },-- // Events that are safe to short-circuit if no handlers are attached.- // Native DOM events should not be added, they may have inline handlers.- customEvent: {- "getData": true,- "setData": true,- "changeData": true- },-- trigger: function( event, data, elem, onlyHandlers ) {- // Don't do events on text and comment nodes- if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {- return;- }-- // Event object or event type- var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,- type = event.type || event,- namespaces = [];-- // focus/blur morphs to focusin/out; ensure we're not firing them right now- if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {- return;- }-- if ( type.indexOf( "!" ) >= 0 ) {- // Exclusive events trigger only for the exact event (no namespaces)- type = type.slice(0, -1);- exclusive = true;- }-- if ( type.indexOf( "." ) >= 0 ) {- // Namespaced trigger; create a regexp to match event type in handle()- namespaces = type.split(".");- type = namespaces.shift();- namespaces.sort();- }-- if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {- // No jQuery handlers for this event type, and it can't have inline handlers- return;- }-- // Caller can pass in an Event, Object, or just an event type string- event = typeof event === "object" ?- // jQuery.Event object- event[ jQuery.expando ] ? event :- // Object literal- new jQuery.Event( type, event ) :- // Just the event type (string)- new jQuery.Event( type );-- event.type = type;- event.isTrigger = true;- event.exclusive = exclusive;- event.namespace = namespaces.join( "." );- event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;- ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";-- // Handle a global trigger- if ( !elem ) {-- // TODO: Stop taunting the data cache; remove global events and always attach to document- cache = jQuery.cache;- for ( i in cache ) {- if ( cache[ i ].events && cache[ i ].events[ type ] ) {- jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );- }- }- return;- }-- // Clean up the event in case it is being reused- event.result = undefined;- if ( !event.target ) {- event.target = elem;- }-- // Clone any incoming data and prepend the event, creating the handler arg list- data = data != null ? jQuery.makeArray( data ) : [];- data.unshift( event );-- // Allow special events to draw outside the lines- special = jQuery.event.special[ type ] || {};- if ( special.trigger && special.trigger.apply( elem, data ) === false ) {- return;- }-- // Determine event propagation path in advance, per W3C events spec (#9951)- // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)- eventPath = [[ elem, special.bindType || type ]];- if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {-- bubbleType = special.delegateType || type;- cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;- for ( old = elem; cur; cur = cur.parentNode ) {- eventPath.push([ cur, bubbleType ]);- old = cur;- }-- // Only add window if we got to document (e.g., not plain obj or detached DOM)- if ( old === (elem.ownerDocument || document) ) {- eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);- }- }-- // Fire handlers on the event path- for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {-- cur = eventPath[i][0];- event.type = eventPath[i][1];-- handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );- if ( handle ) {- handle.apply( cur, data );- }- // Note that this is a bare JS function and not a jQuery handler- handle = ontype && cur[ ontype ];- if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {- event.preventDefault();- }- }- event.type = type;-- // If nobody prevented the default action, do it now- if ( !onlyHandlers && !event.isDefaultPrevented() ) {-- if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&- !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {-- // Call a native DOM method on the target with the same name name as the event.- // Can't use an .isFunction() check here because IE6/7 fails that test.- // Don't do default actions on window, that's where global variables be (#6170)- // IE<9 dies on focus/blur to hidden element (#1486)- if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {-- // Don't re-trigger an onFOO event when we call its FOO() method- old = elem[ ontype ];-- if ( old ) {- elem[ ontype ] = null;- }-- // Prevent re-triggering of the same event, since we already bubbled it above- jQuery.event.triggered = type;- elem[ type ]();- jQuery.event.triggered = undefined;-- if ( old ) {- elem[ ontype ] = old;- }- }- }- }-- return event.result;- },-- dispatch: function( event ) {-- // Make a writable jQuery.Event from the native event object- event = jQuery.event.fix( event || window.event );-- var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,- handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),- delegateCount = handlers.delegateCount,- args = core_slice.call( arguments ),- run_all = !event.exclusive && !event.namespace,- special = jQuery.event.special[ event.type ] || {},- handlerQueue = [];-- // Use the fix-ed jQuery.Event rather than the (read-only) native event- args[0] = event;- event.delegateTarget = this;-- // Call the preDispatch hook for the mapped type, and let it bail if desired- if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {- return;- }-- // Determine handlers that should run if there are delegated events- // Avoid non-left-click bubbling in Firefox (#3861)- if ( delegateCount && !(event.button && event.type === "click") ) {-- for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {-- // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)- if ( cur.disabled !== true || event.type !== "click" ) {- selMatch = {};- matches = [];- for ( i = 0; i < delegateCount; i++ ) {- handleObj = handlers[ i ];- sel = handleObj.selector;-- if ( selMatch[ sel ] === undefined ) {- selMatch[ sel ] = handleObj.needsContext ?- jQuery( sel, this ).index( cur ) >= 0 :- jQuery.find( sel, this, null, [ cur ] ).length;- }- if ( selMatch[ sel ] ) {- matches.push( handleObj );- }- }- if ( matches.length ) {- handlerQueue.push({ elem: cur, matches: matches });- }- }- }- }-- // Add the remaining (directly-bound) handlers- if ( handlers.length > delegateCount ) {- handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });- }-- // Run delegates first; they may want to stop propagation beneath us- for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {- matched = handlerQueue[ i ];- event.currentTarget = matched.elem;-- for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {- handleObj = matched.matches[ j ];-- // Triggered event must either 1) be non-exclusive and have no namespace, or- // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).- if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {-- event.data = handleObj.data;- event.handleObj = handleObj;-- ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )- .apply( matched.elem, args );-- if ( ret !== undefined ) {- event.result = ret;- if ( ret === false ) {- event.preventDefault();- event.stopPropagation();- }- }- }- }- }-- // Call the postDispatch hook for the mapped type- if ( special.postDispatch ) {- special.postDispatch.call( this, event );- }-- return event.result;- },-- // Includes some event props shared by KeyEvent and MouseEvent- // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***- props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),-- fixHooks: {},-- keyHooks: {- props: "char charCode key keyCode".split(" "),- filter: function( event, original ) {-- // Add which for key events- if ( event.which == null ) {- event.which = original.charCode != null ? original.charCode : original.keyCode;- }-- return event;- }- },-- mouseHooks: {- props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),- filter: function( event, original ) {- var eventDoc, doc, body,- button = original.button,- fromElement = original.fromElement;-- // Calculate pageX/Y if missing and clientX/Y available- if ( event.pageX == null && original.clientX != null ) {- eventDoc = event.target.ownerDocument || document;- doc = eventDoc.documentElement;- body = eventDoc.body;-- event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );- event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );- }-- // Add relatedTarget, if necessary- if ( !event.relatedTarget && fromElement ) {- event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;- }-- // Add which for click: 1 === left; 2 === middle; 3 === right- // Note: button is not normalized, so don't use it- if ( !event.which && button !== undefined ) {- event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );- }-- return event;- }- },-- fix: function( event ) {- if ( event[ jQuery.expando ] ) {- return event;- }-- // Create a writable copy of the event object and normalize some properties- var i, prop,- originalEvent = event,- fixHook = jQuery.event.fixHooks[ event.type ] || {},- copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;-- event = jQuery.Event( originalEvent );-- for ( i = copy.length; i; ) {- prop = copy[ --i ];- event[ prop ] = originalEvent[ prop ];- }-- // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)- if ( !event.target ) {- event.target = originalEvent.srcElement || document;- }-- // Target should not be a text node (#504, Safari)- if ( event.target.nodeType === 3 ) {- event.target = event.target.parentNode;- }-- // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)- event.metaKey = !!event.metaKey;-- return fixHook.filter? fixHook.filter( event, originalEvent ) : event;- },-- special: {- load: {- // Prevent triggered image.load events from bubbling to window.load- noBubble: true- },-- focus: {- delegateType: "focusin"- },- blur: {- delegateType: "focusout"- },-- beforeunload: {- setup: function( data, namespaces, eventHandle ) {- // We only want to do this special case on windows- if ( jQuery.isWindow( this ) ) {- this.onbeforeunload = eventHandle;- }- },-- teardown: function( namespaces, eventHandle ) {- if ( this.onbeforeunload === eventHandle ) {- this.onbeforeunload = null;- }- }- }- },-- simulate: function( type, elem, event, bubble ) {- // Piggyback on a donor event to simulate a different one.- // Fake originalEvent to avoid donor's stopPropagation, but if the- // simulated event prevents default then we do the same on the donor.- var e = jQuery.extend(- new jQuery.Event(),- event,- { type: type,- isSimulated: true,- originalEvent: {}- }- );- if ( bubble ) {- jQuery.event.trigger( e, null, elem );- } else {- jQuery.event.dispatch.call( elem, e );- }- if ( e.isDefaultPrevented() ) {- event.preventDefault();- }- }-};--// Some plugins are using, but it's undocumented/deprecated and will be removed.-// The 1.7 special event interface should provide all the hooks needed now.-jQuery.event.handle = jQuery.event.dispatch;--jQuery.removeEvent = document.removeEventListener ?- function( elem, type, handle ) {- if ( elem.removeEventListener ) {- elem.removeEventListener( type, handle, false );- }- } :- function( elem, type, handle ) {- var name = "on" + type;-- if ( elem.detachEvent ) {-- // #8545, #7054, preventing memory leaks for custom events in IE6-8- // detachEvent needed property on element, by name of that event, to properly expose it to GC- if ( typeof elem[ name ] === "undefined" ) {- elem[ name ] = null;- }-- elem.detachEvent( name, handle );- }- };--jQuery.Event = function( src, props ) {- // Allow instantiation without the 'new' keyword- if ( !(this instanceof jQuery.Event) ) {- return new jQuery.Event( src, props );- }-- // Event object- if ( src && src.type ) {- this.originalEvent = src;- this.type = src.type;-- // Events bubbling up the document may have been marked as prevented- // by a handler lower down the tree; reflect the correct value.- this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||- src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;-- // Event type- } else {- this.type = src;- }-- // Put explicitly provided properties onto the event object- if ( props ) {- jQuery.extend( this, props );- }-- // Create a timestamp if incoming event doesn't have one- this.timeStamp = src && src.timeStamp || jQuery.now();-- // Mark it as fixed- this[ jQuery.expando ] = true;-};--function returnFalse() {- return false;-}-function returnTrue() {- return true;-}--// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding-// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html-jQuery.Event.prototype = {- preventDefault: function() {- this.isDefaultPrevented = returnTrue;-- var e = this.originalEvent;- if ( !e ) {- return;- }-- // if preventDefault exists run it on the original event- if ( e.preventDefault ) {- e.preventDefault();-- // otherwise set the returnValue property of the original event to false (IE)- } else {- e.returnValue = false;- }- },- stopPropagation: function() {- this.isPropagationStopped = returnTrue;-- var e = this.originalEvent;- if ( !e ) {- return;- }- // if stopPropagation exists run it on the original event- if ( e.stopPropagation ) {- e.stopPropagation();- }- // otherwise set the cancelBubble property of the original event to true (IE)- e.cancelBubble = true;- },- stopImmediatePropagation: function() {- this.isImmediatePropagationStopped = returnTrue;- this.stopPropagation();- },- isDefaultPrevented: returnFalse,- isPropagationStopped: returnFalse,- isImmediatePropagationStopped: returnFalse-};--// Create mouseenter/leave events using mouseover/out and event-time checks-jQuery.each({- mouseenter: "mouseover",- mouseleave: "mouseout"-}, function( orig, fix ) {- jQuery.event.special[ orig ] = {- delegateType: fix,- bindType: fix,-- handle: function( event ) {- var ret,- target = this,- related = event.relatedTarget,- handleObj = event.handleObj,- selector = handleObj.selector;-- // For mousenter/leave call the handler if related is outside the target.- // NB: No relatedTarget if the mouse left/entered the browser window- if ( !related || (related !== target && !jQuery.contains( target, related )) ) {- event.type = handleObj.origType;- ret = handleObj.handler.apply( this, arguments );- event.type = fix;- }- return ret;- }- };-});--// IE submit delegation-if ( !jQuery.support.submitBubbles ) {-- jQuery.event.special.submit = {- setup: function() {- // Only need this for delegated form submit events- if ( jQuery.nodeName( this, "form" ) ) {- return false;- }-- // Lazy-add a submit handler when a descendant form may potentially be submitted- jQuery.event.add( this, "click._submit keypress._submit", function( e ) {- // Node name check avoids a VML-related crash in IE (#9807)- var elem = e.target,- form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;- if ( form && !jQuery._data( form, "_submit_attached" ) ) {- jQuery.event.add( form, "submit._submit", function( event ) {- event._submit_bubble = true;- });- jQuery._data( form, "_submit_attached", true );- }- });- // return undefined since we don't need an event listener- },-- postDispatch: function( event ) {- // If form was submitted by the user, bubble the event up the tree- if ( event._submit_bubble ) {- delete event._submit_bubble;- if ( this.parentNode && !event.isTrigger ) {- jQuery.event.simulate( "submit", this.parentNode, event, true );- }- }- },-- teardown: function() {- // Only need this for delegated form submit events- if ( jQuery.nodeName( this, "form" ) ) {- return false;- }-- // Remove delegated handlers; cleanData eventually reaps submit handlers attached above- jQuery.event.remove( this, "._submit" );- }- };-}--// IE change delegation and checkbox/radio fix-if ( !jQuery.support.changeBubbles ) {-- jQuery.event.special.change = {-- setup: function() {-- if ( rformElems.test( this.nodeName ) ) {- // IE doesn't fire change on a check/radio until blur; trigger it on click- // after a propertychange. Eat the blur-change in special.change.handle.- // This still fires onchange a second time for check/radio after blur.- if ( this.type === "checkbox" || this.type === "radio" ) {- jQuery.event.add( this, "propertychange._change", function( event ) {- if ( event.originalEvent.propertyName === "checked" ) {- this._just_changed = true;- }- });- jQuery.event.add( this, "click._change", function( event ) {- if ( this._just_changed && !event.isTrigger ) {- this._just_changed = false;- }- // Allow triggered, simulated change events (#11500)- jQuery.event.simulate( "change", this, event, true );- });- }- return false;- }- // Delegated event; lazy-add a change handler on descendant inputs- jQuery.event.add( this, "beforeactivate._change", function( e ) {- var elem = e.target;-- if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {- jQuery.event.add( elem, "change._change", function( event ) {- if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {- jQuery.event.simulate( "change", this.parentNode, event, true );- }- });- jQuery._data( elem, "_change_attached", true );- }- });- },-- handle: function( event ) {- var elem = event.target;-- // Swallow native change events from checkbox/radio, we already triggered them above- if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {- return event.handleObj.handler.apply( this, arguments );- }- },-- teardown: function() {- jQuery.event.remove( this, "._change" );-- return !rformElems.test( this.nodeName );- }- };-}--// Create "bubbling" focus and blur events-if ( !jQuery.support.focusinBubbles ) {- jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {-- // Attach a single capturing handler while someone wants focusin/focusout- var attaches = 0,- handler = function( event ) {- jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );- };-- jQuery.event.special[ fix ] = {- setup: function() {- if ( attaches++ === 0 ) {- document.addEventListener( orig, handler, true );- }- },- teardown: function() {- if ( --attaches === 0 ) {- document.removeEventListener( orig, handler, true );- }- }- };- });-}--jQuery.fn.extend({-- on: function( types, selector, data, fn, /*INTERNAL*/ one ) {- var origFn, type;-- // Types can be a map of types/handlers- if ( typeof types === "object" ) {- // ( types-Object, selector, data )- if ( typeof selector !== "string" ) { // && selector != null- // ( types-Object, data )- data = data || selector;- selector = undefined;- }- for ( type in types ) {- this.on( type, selector, data, types[ type ], one );- }- return this;- }-- if ( data == null && fn == null ) {- // ( types, fn )- fn = selector;- data = selector = undefined;- } else if ( fn == null ) {- if ( typeof selector === "string" ) {- // ( types, selector, fn )- fn = data;- data = undefined;- } else {- // ( types, data, fn )- fn = data;- data = selector;- selector = undefined;- }- }- if ( fn === false ) {- fn = returnFalse;- } else if ( !fn ) {- return this;- }-- if ( one === 1 ) {- origFn = fn;- fn = function( event ) {- // Can use an empty set, since event contains the info- jQuery().off( event );- return origFn.apply( this, arguments );- };- // Use same guid so caller can remove using origFn- fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );- }- return this.each( function() {- jQuery.event.add( this, types, fn, data, selector );- });- },- one: function( types, selector, data, fn ) {- return this.on( types, selector, data, fn, 1 );- },- off: function( types, selector, fn ) {- var handleObj, type;- if ( types && types.preventDefault && types.handleObj ) {- // ( event ) dispatched jQuery.Event- handleObj = types.handleObj;- jQuery( types.delegateTarget ).off(- handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,- handleObj.selector,- handleObj.handler- );- return this;- }- if ( typeof types === "object" ) {- // ( types-object [, selector] )- for ( type in types ) {- this.off( type, selector, types[ type ] );- }- return this;- }- if ( selector === false || typeof selector === "function" ) {- // ( types [, fn] )- fn = selector;- selector = undefined;- }- if ( fn === false ) {- fn = returnFalse;- }- return this.each(function() {- jQuery.event.remove( this, types, fn, selector );- });- },-- bind: function( types, data, fn ) {- return this.on( types, null, data, fn );- },- unbind: function( types, fn ) {- return this.off( types, null, fn );- },-- live: function( types, data, fn ) {- jQuery( this.context ).on( types, this.selector, data, fn );- return this;- },- die: function( types, fn ) {- jQuery( this.context ).off( types, this.selector || "**", fn );- return this;- },-- delegate: function( selector, types, data, fn ) {- return this.on( types, selector, data, fn );- },- undelegate: function( selector, types, fn ) {- // ( namespace ) or ( selector, types [, fn] )- return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );- },-- trigger: function( type, data ) {- return this.each(function() {- jQuery.event.trigger( type, data, this );- });- },- triggerHandler: function( type, data ) {- if ( this[0] ) {- return jQuery.event.trigger( type, data, this[0], true );- }- },-- toggle: function( fn ) {- // Save reference to arguments for access in closure- var args = arguments,- guid = fn.guid || jQuery.guid++,- i = 0,- toggler = function( event ) {- // Figure out which function to execute- var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;- jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );-- // Make sure that clicks stop- event.preventDefault();-- // and execute the function- return args[ lastToggle ].apply( this, arguments ) || false;- };-- // link all the functions, so any of them can unbind this click handler- toggler.guid = guid;- while ( i < args.length ) {- args[ i++ ].guid = guid;- }-- return this.click( toggler );- },-- hover: function( fnOver, fnOut ) {- return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );- }-});--jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +- "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +- "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {-- // Handle event binding- jQuery.fn[ name ] = function( data, fn ) {- if ( fn == null ) {- fn = data;- data = null;- }-- return arguments.length > 0 ?- this.on( name, null, data, fn ) :- this.trigger( name );- };-- if ( rkeyEvent.test( name ) ) {- jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;- }-- if ( rmouseEvent.test( name ) ) {- jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;- }-});-/*!- * Sizzle CSS Selector Engine- * Copyright 2012 jQuery Foundation and other contributors- * Released under the MIT license- * http://sizzlejs.com/- */-(function( window, undefined ) {--var cachedruns,- assertGetIdNotName,- Expr,- getText,- isXML,- contains,- compile,- sortOrder,- hasDuplicate,- outermostContext,-- baseHasDuplicate = true,- strundefined = "undefined",-- expando = ( "sizcache" + Math.random() ).replace( ".", "" ),-- Token = String,- document = window.document,- docElem = document.documentElement,- dirruns = 0,- done = 0,- pop = [].pop,- push = [].push,- slice = [].slice,- // Use a stripped-down indexOf if a native one is unavailable- indexOf = [].indexOf || function( elem ) {- var i = 0,- len = this.length;- for ( ; i < len; i++ ) {- if ( this[i] === elem ) {- return i;- }- }- return -1;- },-- // Augment a function for special use by Sizzle- markFunction = function( fn, value ) {- fn[ expando ] = value == null || value;- return fn;- },-- createCache = function() {- var cache = {},- keys = [];-- return markFunction(function( key, value ) {- // Only keep the most recent entries- if ( keys.push( key ) > Expr.cacheLength ) {- delete cache[ keys.shift() ];- }-- // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)- return (cache[ key + " " ] = value);- }, cache );- },-- classCache = createCache(),- tokenCache = createCache(),- compilerCache = createCache(),-- // Regex-- // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace- whitespace = "[\\x20\\t\\r\\n\\f]",- // http://www.w3.org/TR/css3-syntax/#characters- characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",-- // Loosely modeled on CSS identifier characters- // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)- // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier- identifier = characterEncoding.replace( "w", "w#" ),-- // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors- operators = "([*^$|!~]?=)",- attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +- "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",-- // Prefer arguments not in parens/brackets,- // then attribute selectors and non-pseudos (denoted by :),- // then anything else- // These preferences are here to reduce the number of selectors- // needing tokenize in the PSEUDO preFilter- pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",-- // For matchExpr.POS and matchExpr.needsContext- pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +- "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",-- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),-- rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),- rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),- rpseudo = new RegExp( pseudos ),-- // Easily-parseable/retrievable ID or TAG or CLASS selectors- rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,-- rnot = /^:not/,- rsibling = /[\x20\t\r\n\f]*[+~]/,- rendsWithNot = /:not\($/,-- rheader = /h\d/i,- rinputs = /input|select|textarea|button/i,-- rbackslash = /\\(?!\\)/g,-- matchExpr = {- "ID": new RegExp( "^#(" + characterEncoding + ")" ),- "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),- "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),- "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),- "ATTR": new RegExp( "^" + attributes ),- "PSEUDO": new RegExp( "^" + pseudos ),- "POS": new RegExp( pos, "i" ),- "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),- // For use in libraries implementing .is()- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )- },-- // Support-- // Used for testing something on an element- assert = function( fn ) {- var div = document.createElement("div");-- try {- return fn( div );- } catch (e) {- return false;- } finally {- // release memory in IE- div = null;- }- },-- // Check if getElementsByTagName("*") returns only elements- assertTagNameNoComments = assert(function( div ) {- div.appendChild( document.createComment("") );- return !div.getElementsByTagName("*").length;- }),-- // Check if getAttribute returns normalized href attributes- assertHrefNotNormalized = assert(function( div ) {- div.innerHTML = "<a href='#'></a>";- return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&- div.firstChild.getAttribute("href") === "#";- }),-- // Check if attributes should be retrieved by attribute nodes- assertAttributes = assert(function( div ) {- div.innerHTML = "<select></select>";- var type = typeof div.lastChild.getAttribute("multiple");- // IE8 returns a string for some attributes even when not present- return type !== "boolean" && type !== "string";- }),-- // Check if getElementsByClassName can be trusted- assertUsableClassName = assert(function( div ) {- // Opera can't find a second classname (in 9.6)- div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";- if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {- return false;- }-- // Safari 3.2 caches class attributes and doesn't catch changes- div.lastChild.className = "e";- return div.getElementsByClassName("e").length === 2;- }),-- // Check if getElementById returns elements by name- // Check if getElementsByName privileges form controls or returns elements by ID- assertUsableName = assert(function( div ) {- // Inject content- div.id = expando + 0;- div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";- docElem.insertBefore( div, docElem.firstChild );-- // Test- var pass = document.getElementsByName &&- // buggy browsers will return fewer than the correct 2- document.getElementsByName( expando ).length === 2 +- // buggy browsers will return more than the correct 0- document.getElementsByName( expando + 0 ).length;- assertGetIdNotName = !document.getElementById( expando );-- // Cleanup- docElem.removeChild( div );-- return pass;- });--// If slice is not available, provide a backup-try {- slice.call( docElem.childNodes, 0 )[0].nodeType;-} catch ( e ) {- slice = function( i ) {- var elem,- results = [];- for ( ; (elem = this[i]); i++ ) {- results.push( elem );- }- return results;- };-}--function Sizzle( selector, context, results, seed ) {- results = results || [];- context = context || document;- var match, elem, xml, m,- nodeType = context.nodeType;-- if ( !selector || typeof selector !== "string" ) {- return results;- }-- if ( nodeType !== 1 && nodeType !== 9 ) {- return [];- }-- xml = isXML( context );-- if ( !xml && !seed ) {- if ( (match = rquickExpr.exec( selector )) ) {- // Speed-up: Sizzle("#ID")- if ( (m = match[1]) ) {- if ( nodeType === 9 ) {- elem = context.getElementById( m );- // Check parentNode to catch when Blackberry 4.6 returns- // nodes that are no longer in the document #6963- if ( elem && elem.parentNode ) {- // Handle the case where IE, Opera, and Webkit return items- // by name instead of ID- if ( elem.id === m ) {- results.push( elem );- return results;- }- } else {- return results;- }- } else {- // Context is not a document- if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&- contains( context, elem ) && elem.id === m ) {- results.push( elem );- return results;- }- }-- // Speed-up: Sizzle("TAG")- } else if ( match[2] ) {- push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );- return results;-- // Speed-up: Sizzle(".CLASS")- } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {- push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );- return results;- }- }- }-- // All others- return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );-}--Sizzle.matches = function( expr, elements ) {- return Sizzle( expr, null, null, elements );-};--Sizzle.matchesSelector = function( elem, expr ) {- return Sizzle( expr, null, null, [ elem ] ).length > 0;-};--// Returns a function to use in pseudos for input types-function createInputPseudo( type ) {- return function( elem ) {- var name = elem.nodeName.toLowerCase();- return name === "input" && elem.type === type;- };-}--// Returns a function to use in pseudos for buttons-function createButtonPseudo( type ) {- return function( elem ) {- var name = elem.nodeName.toLowerCase();- return (name === "input" || name === "button") && elem.type === type;- };-}--// Returns a function to use in pseudos for positionals-function createPositionalPseudo( fn ) {- return markFunction(function( argument ) {- argument = +argument;- return markFunction(function( seed, matches ) {- var j,- matchIndexes = fn( [], seed.length, argument ),- i = matchIndexes.length;-- // Match elements found at the specified indexes- while ( i-- ) {- if ( seed[ (j = matchIndexes[i]) ] ) {- seed[j] = !(matches[j] = seed[j]);- }- }- });- });-}--/**- * Utility function for retrieving the text value of an array of DOM nodes- * @param {Array|Element} elem- */-getText = Sizzle.getText = function( elem ) {- var node,- ret = "",- i = 0,- nodeType = elem.nodeType;-- if ( nodeType ) {- if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {- // Use textContent for elements- // innerText usage removed for consistency of new lines (see #11153)- if ( typeof elem.textContent === "string" ) {- return elem.textContent;- } else {- // Traverse its children- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {- ret += getText( elem );- }- }- } else if ( nodeType === 3 || nodeType === 4 ) {- return elem.nodeValue;- }- // Do not include comment or processing instruction nodes- } else {-- // If no nodeType, this is expected to be an array- for ( ; (node = elem[i]); i++ ) {- // Do not traverse comment nodes- ret += getText( node );- }- }- return ret;-};--isXML = Sizzle.isXML = function( elem ) {- // documentElement is verified for cases where it doesn't yet exist- // (such as loading iframes in IE - #4833)- var documentElement = elem && (elem.ownerDocument || elem).documentElement;- return documentElement ? documentElement.nodeName !== "HTML" : false;-};--// Element contains another-contains = Sizzle.contains = docElem.contains ?- function( a, b ) {- var adown = a.nodeType === 9 ? a.documentElement : a,- bup = b && b.parentNode;- return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );- } :- docElem.compareDocumentPosition ?- function( a, b ) {- return b && !!( a.compareDocumentPosition( b ) & 16 );- } :- function( a, b ) {- while ( (b = b.parentNode) ) {- if ( b === a ) {- return true;- }- }- return false;- };--Sizzle.attr = function( elem, name ) {- var val,- xml = isXML( elem );-- if ( !xml ) {- name = name.toLowerCase();- }- if ( (val = Expr.attrHandle[ name ]) ) {- return val( elem );- }- if ( xml || assertAttributes ) {- return elem.getAttribute( name );- }- val = elem.getAttributeNode( name );- return val ?- typeof elem[ name ] === "boolean" ?- elem[ name ] ? name : null :- val.specified ? val.value : null :- null;-};--Expr = Sizzle.selectors = {-- // Can be adjusted by the user- cacheLength: 50,-- createPseudo: markFunction,-- match: matchExpr,-- // IE6/7 return a modified href- attrHandle: assertHrefNotNormalized ?- {} :- {- "href": function( elem ) {- return elem.getAttribute( "href", 2 );- },- "type": function( elem ) {- return elem.getAttribute("type");- }- },-- find: {- "ID": assertGetIdNotName ?- function( id, context, xml ) {- if ( typeof context.getElementById !== strundefined && !xml ) {- var m = context.getElementById( id );- // Check parentNode to catch when Blackberry 4.6 returns- // nodes that are no longer in the document #6963- return m && m.parentNode ? [m] : [];- }- } :- function( id, context, xml ) {- if ( typeof context.getElementById !== strundefined && !xml ) {- var m = context.getElementById( id );-- return m ?- m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?- [m] :- undefined :- [];- }- },-- "TAG": assertTagNameNoComments ?- function( tag, context ) {- if ( typeof context.getElementsByTagName !== strundefined ) {- return context.getElementsByTagName( tag );- }- } :- function( tag, context ) {- var results = context.getElementsByTagName( tag );-- // Filter out possible comments- if ( tag === "*" ) {- var elem,- tmp = [],- i = 0;-- for ( ; (elem = results[i]); i++ ) {- if ( elem.nodeType === 1 ) {- tmp.push( elem );- }- }-- return tmp;- }- return results;- },-- "NAME": assertUsableName && function( tag, context ) {- if ( typeof context.getElementsByName !== strundefined ) {- return context.getElementsByName( name );- }- },-- "CLASS": assertUsableClassName && function( className, context, xml ) {- if ( typeof context.getElementsByClassName !== strundefined && !xml ) {- return context.getElementsByClassName( className );- }- }- },-- relative: {- ">": { dir: "parentNode", first: true },- " ": { dir: "parentNode" },- "+": { dir: "previousSibling", first: true },- "~": { dir: "previousSibling" }- },-- preFilter: {- "ATTR": function( match ) {- match[1] = match[1].replace( rbackslash, "" );-- // Move the given value to match[3] whether quoted or unquoted- match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );-- if ( match[2] === "~=" ) {- match[3] = " " + match[3] + " ";- }-- return match.slice( 0, 4 );- },-- "CHILD": function( match ) {- /* matches from matchExpr["CHILD"]- 1 type (only|nth|...)- 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)- 3 xn-component of xn+y argument ([+-]?\d*n|)- 4 sign of xn-component- 5 x of xn-component- 6 sign of y-component- 7 y of y-component- */- match[1] = match[1].toLowerCase();-- if ( match[1] === "nth" ) {- // nth-child requires argument- if ( !match[2] ) {- Sizzle.error( match[0] );- }-- // numeric x and y parameters for Expr.filter.CHILD- // remember that false/true cast respectively to 0/1- match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );- match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );-- // other types prohibit arguments- } else if ( match[2] ) {- Sizzle.error( match[0] );- }-- return match;- },-- "PSEUDO": function( match ) {- var unquoted, excess;- if ( matchExpr["CHILD"].test( match[0] ) ) {- return null;- }-- if ( match[3] ) {- match[2] = match[3];- } else if ( (unquoted = match[4]) ) {- // Only check arguments that contain a pseudo- if ( rpseudo.test(unquoted) &&- // Get excess from tokenize (recursively)- (excess = tokenize( unquoted, true )) &&- // advance to the next closing parenthesis- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {-- // excess is a negative index- unquoted = unquoted.slice( 0, excess );- match[0] = match[0].slice( 0, excess );- }- match[2] = unquoted;- }-- // Return only captures needed by the pseudo filter method (type and argument)- return match.slice( 0, 3 );- }- },-- filter: {- "ID": assertGetIdNotName ?- function( id ) {- id = id.replace( rbackslash, "" );- return function( elem ) {- return elem.getAttribute("id") === id;- };- } :- function( id ) {- id = id.replace( rbackslash, "" );- return function( elem ) {- var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");- return node && node.value === id;- };- },-- "TAG": function( nodeName ) {- if ( nodeName === "*" ) {- return function() { return true; };- }- nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();-- return function( elem ) {- return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;- };- },-- "CLASS": function( className ) {- var pattern = classCache[ expando ][ className + " " ];-- return pattern ||- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&- classCache( className, function( elem ) {- return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );- });- },-- "ATTR": function( name, operator, check ) {- return function( elem, context ) {- var result = Sizzle.attr( elem, name );-- if ( result == null ) {- return operator === "!=";- }- if ( !operator ) {- return true;- }-- result += "";-- return operator === "=" ? result === check :- operator === "!=" ? result !== check :- operator === "^=" ? check && result.indexOf( check ) === 0 :- operator === "*=" ? check && result.indexOf( check ) > -1 :- operator === "$=" ? check && result.substr( result.length - check.length ) === check :- operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :- operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :- false;- };- },-- "CHILD": function( type, argument, first, last ) {-- if ( type === "nth" ) {- return function( elem ) {- var node, diff,- parent = elem.parentNode;-- if ( first === 1 && last === 0 ) {- return true;- }-- if ( parent ) {- diff = 0;- for ( node = parent.firstChild; node; node = node.nextSibling ) {- if ( node.nodeType === 1 ) {- diff++;- if ( elem === node ) {- break;- }- }- }- }-- // Incorporate the offset (or cast to NaN), then check against cycle size- diff -= last;- return diff === first || ( diff % first === 0 && diff / first >= 0 );- };- }-- return function( elem ) {- var node = elem;-- switch ( type ) {- case "only":- case "first":- while ( (node = node.previousSibling) ) {- if ( node.nodeType === 1 ) {- return false;- }- }-- if ( type === "first" ) {- return true;- }-- node = elem;-- /* falls through */- case "last":- while ( (node = node.nextSibling) ) {- if ( node.nodeType === 1 ) {- return false;- }- }-- return true;- }- };- },-- "PSEUDO": function( pseudo, argument ) {- // pseudo-class names are case-insensitive- // http://www.w3.org/TR/selectors/#pseudo-classes- // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters- // Remember that setFilters inherits from pseudos- var args,- fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||- Sizzle.error( "unsupported pseudo: " + pseudo );-- // The user may use createPseudo to indicate that- // arguments are needed to create the filter function- // just as Sizzle does- if ( fn[ expando ] ) {- return fn( argument );- }-- // But maintain support for old signatures- if ( fn.length > 1 ) {- args = [ pseudo, pseudo, "", argument ];- return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?- markFunction(function( seed, matches ) {- var idx,- matched = fn( seed, argument ),- i = matched.length;- while ( i-- ) {- idx = indexOf.call( seed, matched[i] );- seed[ idx ] = !( matches[ idx ] = matched[i] );- }- }) :- function( elem ) {- return fn( elem, 0, args );- };- }-- return fn;- }- },-- pseudos: {- "not": markFunction(function( selector ) {- // Trim the selector passed to compile- // to avoid treating leading and trailing- // spaces as combinators- var input = [],- results = [],- matcher = compile( selector.replace( rtrim, "$1" ) );-- return matcher[ expando ] ?- markFunction(function( seed, matches, context, xml ) {- var elem,- unmatched = matcher( seed, null, xml, [] ),- i = seed.length;-- // Match elements unmatched by `matcher`- while ( i-- ) {- if ( (elem = unmatched[i]) ) {- seed[i] = !(matches[i] = elem);- }- }- }) :- function( elem, context, xml ) {- input[0] = elem;- matcher( input, null, xml, results );- return !results.pop();- };- }),-- "has": markFunction(function( selector ) {- return function( elem ) {- return Sizzle( selector, elem ).length > 0;- };- }),-- "contains": markFunction(function( text ) {- return function( elem ) {- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;- };- }),-- "enabled": function( elem ) {- return elem.disabled === false;- },-- "disabled": function( elem ) {- return elem.disabled === true;- },-- "checked": function( elem ) {- // In CSS3, :checked should return both checked and selected elements- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked- var nodeName = elem.nodeName.toLowerCase();- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);- },-- "selected": function( elem ) {- // Accessing this property makes selected-by-default- // options in Safari work properly- if ( elem.parentNode ) {- elem.parentNode.selectedIndex;- }-- return elem.selected === true;- },-- "parent": function( elem ) {- return !Expr.pseudos["empty"]( elem );- },-- "empty": function( elem ) {- // http://www.w3.org/TR/selectors/#empty-pseudo- // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),- // not comment, processing instructions, or others- // Thanks to Diego Perini for the nodeName shortcut- // Greater than "@" means alpha characters (specifically not starting with "#" or "?")- var nodeType;- elem = elem.firstChild;- while ( elem ) {- if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {- return false;- }- elem = elem.nextSibling;- }- return true;- },-- "header": function( elem ) {- return rheader.test( elem.nodeName );- },-- "text": function( elem ) {- var type, attr;- // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)- // use getAttribute instead to test this case- return elem.nodeName.toLowerCase() === "input" &&- (type = elem.type) === "text" &&- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );- },-- // Input types- "radio": createInputPseudo("radio"),- "checkbox": createInputPseudo("checkbox"),- "file": createInputPseudo("file"),- "password": createInputPseudo("password"),- "image": createInputPseudo("image"),-- "submit": createButtonPseudo("submit"),- "reset": createButtonPseudo("reset"),-- "button": function( elem ) {- var name = elem.nodeName.toLowerCase();- return name === "input" && elem.type === "button" || name === "button";- },-- "input": function( elem ) {- return rinputs.test( elem.nodeName );- },-- "focus": function( elem ) {- var doc = elem.ownerDocument;- return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);- },-- "active": function( elem ) {- return elem === elem.ownerDocument.activeElement;- },-- // Positional types- "first": createPositionalPseudo(function() {- return [ 0 ];- }),-- "last": createPositionalPseudo(function( matchIndexes, length ) {- return [ length - 1 ];- }),-- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {- return [ argument < 0 ? argument + length : argument ];- }),-- "even": createPositionalPseudo(function( matchIndexes, length ) {- for ( var i = 0; i < length; i += 2 ) {- matchIndexes.push( i );- }- return matchIndexes;- }),-- "odd": createPositionalPseudo(function( matchIndexes, length ) {- for ( var i = 1; i < length; i += 2 ) {- matchIndexes.push( i );- }- return matchIndexes;- }),-- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {- for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {- matchIndexes.push( i );- }- return matchIndexes;- }),-- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {- for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {- matchIndexes.push( i );- }- return matchIndexes;- })- }-};--function siblingCheck( a, b, ret ) {- if ( a === b ) {- return ret;- }-- var cur = a.nextSibling;-- while ( cur ) {- if ( cur === b ) {- return -1;- }-- cur = cur.nextSibling;- }-- return 1;-}--sortOrder = docElem.compareDocumentPosition ?- function( a, b ) {- if ( a === b ) {- hasDuplicate = true;- return 0;- }-- return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?- a.compareDocumentPosition :- a.compareDocumentPosition(b) & 4- ) ? -1 : 1;- } :- function( a, b ) {- // The nodes are identical, we can exit early- if ( a === b ) {- hasDuplicate = true;- return 0;-- // Fallback to using sourceIndex (in IE) if it's available on both nodes- } else if ( a.sourceIndex && b.sourceIndex ) {- return a.sourceIndex - b.sourceIndex;- }-- var al, bl,- ap = [],- bp = [],- aup = a.parentNode,- bup = b.parentNode,- cur = aup;-- // If the nodes are siblings (or identical) we can do a quick check- if ( aup === bup ) {- return siblingCheck( a, b );-- // If no parents were found then the nodes are disconnected- } else if ( !aup ) {- return -1;-- } else if ( !bup ) {- return 1;- }-- // Otherwise they're somewhere else in the tree so we need- // to build up a full list of the parentNodes for comparison- while ( cur ) {- ap.unshift( cur );- cur = cur.parentNode;- }-- cur = bup;-- while ( cur ) {- bp.unshift( cur );- cur = cur.parentNode;- }-- al = ap.length;- bl = bp.length;-- // Start walking down the tree looking for a discrepancy- for ( var i = 0; i < al && i < bl; i++ ) {- if ( ap[i] !== bp[i] ) {- return siblingCheck( ap[i], bp[i] );- }- }-- // We ended someplace up the tree so do a sibling check- return i === al ?- siblingCheck( a, bp[i], -1 ) :- siblingCheck( ap[i], b, 1 );- };--// Always assume the presence of duplicates if sort doesn't-// pass them to our comparison function (as in Google Chrome).-[0, 0].sort( sortOrder );-baseHasDuplicate = !hasDuplicate;--// Document sorting and removing duplicates-Sizzle.uniqueSort = function( results ) {- var elem,- duplicates = [],- i = 1,- j = 0;-- hasDuplicate = baseHasDuplicate;- results.sort( sortOrder );-- if ( hasDuplicate ) {- for ( ; (elem = results[i]); i++ ) {- if ( elem === results[ i - 1 ] ) {- j = duplicates.push( i );- }- }- while ( j-- ) {- results.splice( duplicates[ j ], 1 );- }- }-- return results;-};--Sizzle.error = function( msg ) {- throw new Error( "Syntax error, unrecognized expression: " + msg );-};--function tokenize( selector, parseOnly ) {- var matched, match, tokens, type,- soFar, groups, preFilters,- cached = tokenCache[ expando ][ selector + " " ];-- if ( cached ) {- return parseOnly ? 0 : cached.slice( 0 );- }-- soFar = selector;- groups = [];- preFilters = Expr.preFilter;-- while ( soFar ) {-- // Comma and first run- if ( !matched || (match = rcomma.exec( soFar )) ) {- if ( match ) {- // Don't consume trailing commas as valid- soFar = soFar.slice( match[0].length ) || soFar;- }- groups.push( tokens = [] );- }-- matched = false;-- // Combinators- if ( (match = rcombinators.exec( soFar )) ) {- tokens.push( matched = new Token( match.shift() ) );- soFar = soFar.slice( matched.length );-- // Cast descendant combinators to space- matched.type = match[0].replace( rtrim, " " );- }-- // Filters- for ( type in Expr.filter ) {- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||- (match = preFilters[ type ]( match ))) ) {-- tokens.push( matched = new Token( match.shift() ) );- soFar = soFar.slice( matched.length );- matched.type = type;- matched.matches = match;- }- }-- if ( !matched ) {- break;- }- }-- // Return the length of the invalid excess- // if we're just parsing- // Otherwise, throw an error or return tokens- return parseOnly ?- soFar.length :- soFar ?- Sizzle.error( selector ) :- // Cache the tokens- tokenCache( selector, groups ).slice( 0 );-}--function addCombinator( matcher, combinator, base ) {- var dir = combinator.dir,- checkNonElements = base && combinator.dir === "parentNode",- doneName = done++;-- return combinator.first ?- // Check against closest ancestor/preceding element- function( elem, context, xml ) {- while ( (elem = elem[ dir ]) ) {- if ( checkNonElements || elem.nodeType === 1 ) {- return matcher( elem, context, xml );- }- }- } :-- // Check against all ancestor/preceding elements- function( elem, context, xml ) {- // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching- if ( !xml ) {- var cache,- dirkey = dirruns + " " + doneName + " ",- cachedkey = dirkey + cachedruns;- while ( (elem = elem[ dir ]) ) {- if ( checkNonElements || elem.nodeType === 1 ) {- if ( (cache = elem[ expando ]) === cachedkey ) {- return elem.sizset;- } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {- if ( elem.sizset ) {- return elem;- }- } else {- elem[ expando ] = cachedkey;- if ( matcher( elem, context, xml ) ) {- elem.sizset = true;- return elem;- }- elem.sizset = false;- }- }- }- } else {- while ( (elem = elem[ dir ]) ) {- if ( checkNonElements || elem.nodeType === 1 ) {- if ( matcher( elem, context, xml ) ) {- return elem;- }- }- }- }- };-}--function elementMatcher( matchers ) {- return matchers.length > 1 ?- function( elem, context, xml ) {- var i = matchers.length;- while ( i-- ) {- if ( !matchers[i]( elem, context, xml ) ) {- return false;- }- }- return true;- } :- matchers[0];-}--function condense( unmatched, map, filter, context, xml ) {- var elem,- newUnmatched = [],- i = 0,- len = unmatched.length,- mapped = map != null;-- for ( ; i < len; i++ ) {- if ( (elem = unmatched[i]) ) {- if ( !filter || filter( elem, context, xml ) ) {- newUnmatched.push( elem );- if ( mapped ) {- map.push( i );- }- }- }- }-- return newUnmatched;-}--function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {- if ( postFilter && !postFilter[ expando ] ) {- postFilter = setMatcher( postFilter );- }- if ( postFinder && !postFinder[ expando ] ) {- postFinder = setMatcher( postFinder, postSelector );- }- return markFunction(function( seed, results, context, xml ) {- var temp, i, elem,- preMap = [],- postMap = [],- preexisting = results.length,-- // Get initial elements from seed or context- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),-- // Prefilter to get matcher input, preserving a map for seed-results synchronization- matcherIn = preFilter && ( seed || !selector ) ?- condense( elems, preMap, preFilter, context, xml ) :- elems,-- matcherOut = matcher ?- // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,- postFinder || ( seed ? preFilter : preexisting || postFilter ) ?-- // ...intermediate processing is necessary- [] :-- // ...otherwise use results directly- results :- matcherIn;-- // Find primary matches- if ( matcher ) {- matcher( matcherIn, matcherOut, context, xml );- }-- // Apply postFilter- if ( postFilter ) {- temp = condense( matcherOut, postMap );- postFilter( temp, [], context, xml );-- // Un-match failing elements by moving them back to matcherIn- i = temp.length;- while ( i-- ) {- if ( (elem = temp[i]) ) {- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);- }- }- }-- if ( seed ) {- if ( postFinder || preFilter ) {- if ( postFinder ) {- // Get the final matcherOut by condensing this intermediate into postFinder contexts- temp = [];- i = matcherOut.length;- while ( i-- ) {- if ( (elem = matcherOut[i]) ) {- // Restore matcherIn since elem is not yet a final match- temp.push( (matcherIn[i] = elem) );- }- }- postFinder( null, (matcherOut = []), temp, xml );- }-- // Move matched elements from seed to results to keep them synchronized- i = matcherOut.length;- while ( i-- ) {- if ( (elem = matcherOut[i]) &&- (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {-- seed[temp] = !(results[temp] = elem);- }- }- }-- // Add elements to results, through postFinder if defined- } else {- matcherOut = condense(- matcherOut === results ?- matcherOut.splice( preexisting, matcherOut.length ) :- matcherOut- );- if ( postFinder ) {- postFinder( null, results, matcherOut, xml );- } else {- push.apply( results, matcherOut );- }- }- });-}--function matcherFromTokens( tokens ) {- var checkContext, matcher, j,- len = tokens.length,- leadingRelative = Expr.relative[ tokens[0].type ],- implicitRelative = leadingRelative || Expr.relative[" "],- i = leadingRelative ? 1 : 0,-- // The foundational matcher ensures that elements are reachable from top-level context(s)- matchContext = addCombinator( function( elem ) {- return elem === checkContext;- }, implicitRelative, true ),- matchAnyContext = addCombinator( function( elem ) {- return indexOf.call( checkContext, elem ) > -1;- }, implicitRelative, true ),- matchers = [ function( elem, context, xml ) {- return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (- (checkContext = context).nodeType ?- matchContext( elem, context, xml ) :- matchAnyContext( elem, context, xml ) );- } ];-- for ( ; i < len; i++ ) {- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {- matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];- } else {- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );-- // Return special upon seeing a positional matcher- if ( matcher[ expando ] ) {- // Find the next relative operator (if any) for proper handling- j = ++i;- for ( ; j < len; j++ ) {- if ( Expr.relative[ tokens[j].type ] ) {- break;- }- }- return setMatcher(- i > 1 && elementMatcher( matchers ),- i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),- matcher,- i < j && matcherFromTokens( tokens.slice( i, j ) ),- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),- j < len && tokens.join("")- );- }- matchers.push( matcher );- }- }-- return elementMatcher( matchers );-}--function matcherFromGroupMatchers( elementMatchers, setMatchers ) {- var bySet = setMatchers.length > 0,- byElement = elementMatchers.length > 0,- superMatcher = function( seed, context, xml, results, expandContext ) {- var elem, j, matcher,- setMatched = [],- matchedCount = 0,- i = "0",- unmatched = seed && [],- outermost = expandContext != null,- contextBackup = outermostContext,- // We must always have either seed elements or context- elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),- // Nested matchers should use non-integer dirruns- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);-- if ( outermost ) {- outermostContext = context !== document && context;- cachedruns = superMatcher.el;- }-- // Add elements passing elementMatchers directly to results- for ( ; (elem = elems[i]) != null; i++ ) {- if ( byElement && elem ) {- for ( j = 0; (matcher = elementMatchers[j]); j++ ) {- if ( matcher( elem, context, xml ) ) {- results.push( elem );- break;- }- }- if ( outermost ) {- dirruns = dirrunsUnique;- cachedruns = ++superMatcher.el;- }- }-- // Track unmatched elements for set filters- if ( bySet ) {- // They will have gone through all possible matchers- if ( (elem = !matcher && elem) ) {- matchedCount--;- }-- // Lengthen the array for every element, matched or not- if ( seed ) {- unmatched.push( elem );- }- }- }-- // Apply set filters to unmatched elements- matchedCount += i;- if ( bySet && i !== matchedCount ) {- for ( j = 0; (matcher = setMatchers[j]); j++ ) {- matcher( unmatched, setMatched, context, xml );- }-- if ( seed ) {- // Reintegrate element matches to eliminate the need for sorting- if ( matchedCount > 0 ) {- while ( i-- ) {- if ( !(unmatched[i] || setMatched[i]) ) {- setMatched[i] = pop.call( results );- }- }- }-- // Discard index placeholder values to get only actual matches- setMatched = condense( setMatched );- }-- // Add matches to results- push.apply( results, setMatched );-- // Seedless set matches succeeding multiple successful matchers stipulate sorting- if ( outermost && !seed && setMatched.length > 0 &&- ( matchedCount + setMatchers.length ) > 1 ) {-- Sizzle.uniqueSort( results );- }- }-- // Override manipulation of globals by nested matchers- if ( outermost ) {- dirruns = dirrunsUnique;- outermostContext = contextBackup;- }-- return unmatched;- };-- superMatcher.el = 0;- return bySet ?- markFunction( superMatcher ) :- superMatcher;-}--compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {- var i,- setMatchers = [],- elementMatchers = [],- cached = compilerCache[ expando ][ selector + " " ];-- if ( !cached ) {- // Generate a function of recursive functions that can be used to check each element- if ( !group ) {- group = tokenize( selector );- }- i = group.length;- while ( i-- ) {- cached = matcherFromTokens( group[i] );- if ( cached[ expando ] ) {- setMatchers.push( cached );- } else {- elementMatchers.push( cached );- }- }-- // Cache the compiled function- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );- }- return cached;-};--function multipleContexts( selector, contexts, results ) {- var i = 0,- len = contexts.length;- for ( ; i < len; i++ ) {- Sizzle( selector, contexts[i], results );- }- return results;-}--function select( selector, context, results, seed, xml ) {- var i, tokens, token, type, find,- match = tokenize( selector ),- j = match.length;-- if ( !seed ) {- // Try to minimize operations if there is only one group- if ( match.length === 1 ) {-- // Take a shortcut and set the context if the root selector is an ID- tokens = match[0] = match[0].slice( 0 );- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&- context.nodeType === 9 && !xml &&- Expr.relative[ tokens[1].type ] ) {-- context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];- if ( !context ) {- return results;- }-- selector = selector.slice( tokens.shift().length );- }-- // Fetch a seed set for right-to-left matching- for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {- token = tokens[i];-- // Abort if we hit a combinator- if ( Expr.relative[ (type = token.type) ] ) {- break;- }- if ( (find = Expr.find[ type ]) ) {- // Search, expanding context for leading sibling combinators- if ( (seed = find(- token.matches[0].replace( rbackslash, "" ),- rsibling.test( tokens[0].type ) && context.parentNode || context,- xml- )) ) {-- // If seed is empty or no tokens remain, we can return early- tokens.splice( i, 1 );- selector = seed.length && tokens.join("");- if ( !selector ) {- push.apply( results, slice.call( seed, 0 ) );- return results;- }-- break;- }- }- }- }- }-- // Compile and execute a filtering function- // Provide `match` to avoid retokenization if we modified the selector above- compile( selector, match )(- seed,- context,- xml,- results,- rsibling.test( selector )- );- return results;-}--if ( document.querySelectorAll ) {- (function() {- var disconnectedMatch,- oldSelect = select,- rescape = /'|\\/g,- rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,-- // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA- // A support test would require too much code (would include document ready)- rbuggyQSA = [ ":focus" ],-- // matchesSelector(:active) reports false when true (IE9/Opera 11.5)- // A support test would require too much code (would include document ready)- // just skip matchesSelector for :active- rbuggyMatches = [ ":active" ],- matches = docElem.matchesSelector ||- docElem.mozMatchesSelector ||- docElem.webkitMatchesSelector ||- docElem.oMatchesSelector ||- docElem.msMatchesSelector;-- // Build QSA regex- // Regex strategy adopted from Diego Perini- assert(function( div ) {- // Select is set to empty string on purpose- // This is to test IE's treatment of not explictly- // setting a boolean content attribute,- // since its presence should be enough- // http://bugs.jquery.com/ticket/12359- div.innerHTML = "<select><option selected=''></option></select>";-- // IE8 - Some boolean attributes are not treated correctly- if ( !div.querySelectorAll("[selected]").length ) {- rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );- }-- // Webkit/Opera - :checked should return selected option elements- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked- // IE8 throws error here (do not put tests after this one)- if ( !div.querySelectorAll(":checked").length ) {- rbuggyQSA.push(":checked");- }- });-- assert(function( div ) {-- // Opera 10-12/IE9 - ^= $= *= and empty values- // Should not select anything- div.innerHTML = "<p test=''></p>";- if ( div.querySelectorAll("[test^='']").length ) {- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );- }-- // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)- // IE8 throws error here (do not put tests after this one)- div.innerHTML = "<input type='hidden'/>";- if ( !div.querySelectorAll(":enabled").length ) {- rbuggyQSA.push(":enabled", ":disabled");- }- });-- // rbuggyQSA always contains :focus, so no need for a length check- rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );-- select = function( selector, context, results, seed, xml ) {- // Only use querySelectorAll when not filtering,- // when this is not xml,- // and when no QSA bugs apply- if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {- var groups, i,- old = true,- nid = expando,- newContext = context,- newSelector = context.nodeType === 9 && selector;-- // qSA works strangely on Element-rooted queries- // We can work around this by specifying an extra ID on the root- // and working up from there (Thanks to Andrew Dupont for the technique)- // IE 8 doesn't work on object elements- if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {- groups = tokenize( selector );-- if ( (old = context.getAttribute("id")) ) {- nid = old.replace( rescape, "\\$&" );- } else {- context.setAttribute( "id", nid );- }- nid = "[id='" + nid + "'] ";-- i = groups.length;- while ( i-- ) {- groups[i] = nid + groups[i].join("");- }- newContext = rsibling.test( selector ) && context.parentNode || context;- newSelector = groups.join(",");- }-- if ( newSelector ) {- try {- push.apply( results, slice.call( newContext.querySelectorAll(- newSelector- ), 0 ) );- return results;- } catch(qsaError) {- } finally {- if ( !old ) {- context.removeAttribute("id");- }- }- }- }-- return oldSelect( selector, context, results, seed, xml );- };-- if ( matches ) {- assert(function( div ) {- // Check to see if it's possible to do matchesSelector- // on a disconnected node (IE 9)- disconnectedMatch = matches.call( div, "div" );-- // This should fail with an exception- // Gecko does not error, returns false instead- try {- matches.call( div, "[test!='']:sizzle" );- rbuggyMatches.push( "!=", pseudos );- } catch ( e ) {}- });-- // rbuggyMatches always contains :active and :focus, so no need for a length check- rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );-- Sizzle.matchesSelector = function( elem, expr ) {- // Make sure that attribute selectors are quoted- expr = expr.replace( rattributeQuotes, "='$1']" );-- // rbuggyMatches always contains :active, so no need for an existence check- if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {- try {- var ret = matches.call( elem, expr );-- // IE 9's matchesSelector returns false on disconnected nodes- if ( ret || disconnectedMatch ||- // As well, disconnected nodes are said to be in a document- // fragment in IE 9- elem.document && elem.document.nodeType !== 11 ) {- return ret;- }- } catch(e) {}- }-- return Sizzle( expr, null, null, [ elem ] ).length > 0;- };- }- })();-}--// Deprecated-Expr.pseudos["nth"] = Expr.pseudos["eq"];--// Back-compat-function setFilters() {}-Expr.filters = setFilters.prototype = Expr.pseudos;-Expr.setFilters = new setFilters();--// Override sizzle attribute retrieval-Sizzle.attr = jQuery.attr;-jQuery.find = Sizzle;-jQuery.expr = Sizzle.selectors;-jQuery.expr[":"] = jQuery.expr.pseudos;-jQuery.unique = Sizzle.uniqueSort;-jQuery.text = Sizzle.getText;-jQuery.isXMLDoc = Sizzle.isXML;-jQuery.contains = Sizzle.contains;---})( window );-var runtil = /Until$/,- rparentsprev = /^(?:parents|prev(?:Until|All))/,- isSimple = /^.[^:#\[\.,]*$/,- rneedsContext = jQuery.expr.match.needsContext,- // methods guaranteed to produce a unique set when starting from a unique set- guaranteedUnique = {- children: true,- contents: true,- next: true,- prev: true- };--jQuery.fn.extend({- find: function( selector ) {- var i, l, length, n, r, ret,- self = this;-- if ( typeof selector !== "string" ) {- return jQuery( selector ).filter(function() {- for ( i = 0, l = self.length; i < l; i++ ) {- if ( jQuery.contains( self[ i ], this ) ) {- return true;- }- }- });- }-- ret = this.pushStack( "", "find", selector );-- for ( i = 0, l = this.length; i < l; i++ ) {- length = ret.length;- jQuery.find( selector, this[i], ret );-- if ( i > 0 ) {- // Make sure that the results are unique- for ( n = length; n < ret.length; n++ ) {- for ( r = 0; r < length; r++ ) {- if ( ret[r] === ret[n] ) {- ret.splice(n--, 1);- break;- }- }- }- }- }-- return ret;- },-- has: function( target ) {- var i,- targets = jQuery( target, this ),- len = targets.length;-- return this.filter(function() {- for ( i = 0; i < len; i++ ) {- if ( jQuery.contains( this, targets[i] ) ) {- return true;- }- }- });- },-- not: function( selector ) {- return this.pushStack( winnow(this, selector, false), "not", selector);- },-- filter: function( selector ) {- return this.pushStack( winnow(this, selector, true), "filter", selector );- },-- is: function( selector ) {- return !!selector && (- typeof selector === "string" ?- // If this is a positional/relative selector, check membership in the returned set- // so $("p:first").is("p:last") won't return true for a doc with two "p".- rneedsContext.test( selector ) ?- jQuery( selector, this.context ).index( this[0] ) >= 0 :- jQuery.filter( selector, this ).length > 0 :- this.filter( selector ).length > 0 );- },-- closest: function( selectors, context ) {- var cur,- i = 0,- l = this.length,- ret = [],- pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?- jQuery( selectors, context || this.context ) :- 0;-- for ( ; i < l; i++ ) {- cur = this[i];-- while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {- if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {- ret.push( cur );- break;- }- cur = cur.parentNode;- }- }-- ret = ret.length > 1 ? jQuery.unique( ret ) : ret;-- return this.pushStack( ret, "closest", selectors );- },-- // Determine the position of an element within- // the matched set of elements- index: function( elem ) {-- // No argument, return index in parent- if ( !elem ) {- return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;- }-- // index in selector- if ( typeof elem === "string" ) {- return jQuery.inArray( this[0], jQuery( elem ) );- }-- // Locate the position of the desired element- return jQuery.inArray(- // If it receives a jQuery object, the first element is used- elem.jquery ? elem[0] : elem, this );- },-- add: function( selector, context ) {- var set = typeof selector === "string" ?- jQuery( selector, context ) :- jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),- all = jQuery.merge( this.get(), set );-- return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?- all :- jQuery.unique( all ) );- },-- addBack: function( selector ) {- return this.add( selector == null ?- this.prevObject : this.prevObject.filter(selector)- );- }-});--jQuery.fn.andSelf = jQuery.fn.addBack;--// A painfully simple check to see if an element is disconnected-// from a document (should be improved, where feasible).-function isDisconnected( node ) {- return !node || !node.parentNode || node.parentNode.nodeType === 11;-}--function sibling( cur, dir ) {- do {- cur = cur[ dir ];- } while ( cur && cur.nodeType !== 1 );-- return cur;-}--jQuery.each({- parent: function( elem ) {- var parent = elem.parentNode;- return parent && parent.nodeType !== 11 ? parent : null;- },- parents: function( elem ) {- return jQuery.dir( elem, "parentNode" );- },- parentsUntil: function( elem, i, until ) {- return jQuery.dir( elem, "parentNode", until );- },- next: function( elem ) {- return sibling( elem, "nextSibling" );- },- prev: function( elem ) {- return sibling( elem, "previousSibling" );- },- nextAll: function( elem ) {- return jQuery.dir( elem, "nextSibling" );- },- prevAll: function( elem ) {- return jQuery.dir( elem, "previousSibling" );- },- nextUntil: function( elem, i, until ) {- return jQuery.dir( elem, "nextSibling", until );- },- prevUntil: function( elem, i, until ) {- return jQuery.dir( elem, "previousSibling", until );- },- siblings: function( elem ) {- return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );- },- children: function( elem ) {- return jQuery.sibling( elem.firstChild );- },- contents: function( elem ) {- return jQuery.nodeName( elem, "iframe" ) ?- elem.contentDocument || elem.contentWindow.document :- jQuery.merge( [], elem.childNodes );- }-}, function( name, fn ) {- jQuery.fn[ name ] = function( until, selector ) {- var ret = jQuery.map( this, fn, until );-- if ( !runtil.test( name ) ) {- selector = until;- }-- if ( selector && typeof selector === "string" ) {- ret = jQuery.filter( selector, ret );- }-- ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;-- if ( this.length > 1 && rparentsprev.test( name ) ) {- ret = ret.reverse();- }-- return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );- };-});--jQuery.extend({- filter: function( expr, elems, not ) {- if ( not ) {- expr = ":not(" + expr + ")";- }-- return elems.length === 1 ?- jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :- jQuery.find.matches(expr, elems);- },-- dir: function( elem, dir, until ) {- var matched = [],- cur = elem[ dir ];-- while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {- if ( cur.nodeType === 1 ) {- matched.push( cur );- }- cur = cur[dir];- }- return matched;- },-- sibling: function( n, elem ) {- var r = [];-- for ( ; n; n = n.nextSibling ) {- if ( n.nodeType === 1 && n !== elem ) {- r.push( n );- }- }-- return r;- }-});--// Implement the identical functionality for filter and not-function winnow( elements, qualifier, keep ) {-- // Can't pass null or undefined to indexOf in Firefox 4- // Set to 0 to skip string check- qualifier = qualifier || 0;-- if ( jQuery.isFunction( qualifier ) ) {- return jQuery.grep(elements, function( elem, i ) {- var retVal = !!qualifier.call( elem, i, elem );- return retVal === keep;- });-- } else if ( qualifier.nodeType ) {- return jQuery.grep(elements, function( elem, i ) {- return ( elem === qualifier ) === keep;- });-- } else if ( typeof qualifier === "string" ) {- var filtered = jQuery.grep(elements, function( elem ) {- return elem.nodeType === 1;- });-- if ( isSimple.test( qualifier ) ) {- return jQuery.filter(qualifier, filtered, !keep);- } else {- qualifier = jQuery.filter( qualifier, filtered );- }- }-- return jQuery.grep(elements, function( elem, i ) {- return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;- });-}-function createSafeFragment( document ) {- var list = nodeNames.split( "|" ),- safeFrag = document.createDocumentFragment();-- if ( safeFrag.createElement ) {- while ( list.length ) {- safeFrag.createElement(- list.pop()- );- }- }- return safeFrag;-}--var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +- "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",- rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,- rleadingWhitespace = /^\s+/,- rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,- rtagName = /<([\w:]+)/,- rtbody = /<tbody/i,- rhtml = /<|&#?\w+;/,- rnoInnerhtml = /<(?:script|style|link)/i,- rnocache = /<(?:script|object|embed|option|style)/i,- rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),- rcheckableType = /^(?:checkbox|radio)$/,- // checked="checked" or checked- rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,- rscriptType = /\/(java|ecma)script/i,- rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,- wrapMap = {- option: [ 1, "<select multiple='multiple'>", "</select>" ],- legend: [ 1, "<fieldset>", "</fieldset>" ],- thead: [ 1, "<table>", "</table>" ],- tr: [ 2, "<table><tbody>", "</tbody></table>" ],- td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],- col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],- area: [ 1, "<map>", "</map>" ],- _default: [ 0, "", "" ]- },- safeFragment = createSafeFragment( document ),- fragmentDiv = safeFragment.appendChild( document.createElement("div") );--wrapMap.optgroup = wrapMap.option;-wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;-wrapMap.th = wrapMap.td;--// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,-// unless wrapped in a div with non-breaking characters in front of it.-if ( !jQuery.support.htmlSerialize ) {- wrapMap._default = [ 1, "X<div>", "</div>" ];-}--jQuery.fn.extend({- text: function( value ) {- return jQuery.access( this, function( value ) {- return value === undefined ?- jQuery.text( this ) :- this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );- }, null, value, arguments.length );- },-- wrapAll: function( html ) {- if ( jQuery.isFunction( html ) ) {- return this.each(function(i) {- jQuery(this).wrapAll( html.call(this, i) );- });- }-- if ( this[0] ) {- // The elements to wrap the target around- var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);-- if ( this[0].parentNode ) {- wrap.insertBefore( this[0] );- }-- wrap.map(function() {- var elem = this;-- while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {- elem = elem.firstChild;- }-- return elem;- }).append( this );- }-- return this;- },-- wrapInner: function( html ) {- if ( jQuery.isFunction( html ) ) {- return this.each(function(i) {- jQuery(this).wrapInner( html.call(this, i) );- });- }-- return this.each(function() {- var self = jQuery( this ),- contents = self.contents();-- if ( contents.length ) {- contents.wrapAll( html );-- } else {- self.append( html );- }- });- },-- wrap: function( html ) {- var isFunction = jQuery.isFunction( html );-- return this.each(function(i) {- jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );- });- },-- unwrap: function() {- return this.parent().each(function() {- if ( !jQuery.nodeName( this, "body" ) ) {- jQuery( this ).replaceWith( this.childNodes );- }- }).end();- },-- append: function() {- return this.domManip(arguments, true, function( elem ) {- if ( this.nodeType === 1 || this.nodeType === 11 ) {- this.appendChild( elem );- }- });- },-- prepend: function() {- return this.domManip(arguments, true, function( elem ) {- if ( this.nodeType === 1 || this.nodeType === 11 ) {- this.insertBefore( elem, this.firstChild );- }- });- },-- before: function() {- if ( !isDisconnected( this[0] ) ) {- return this.domManip(arguments, false, function( elem ) {- this.parentNode.insertBefore( elem, this );- });- }-- if ( arguments.length ) {- var set = jQuery.clean( arguments );- return this.pushStack( jQuery.merge( set, this ), "before", this.selector );- }- },-- after: function() {- if ( !isDisconnected( this[0] ) ) {- return this.domManip(arguments, false, function( elem ) {- this.parentNode.insertBefore( elem, this.nextSibling );- });- }-- if ( arguments.length ) {- var set = jQuery.clean( arguments );- return this.pushStack( jQuery.merge( this, set ), "after", this.selector );- }- },-- // keepData is for internal use only--do not document- remove: function( selector, keepData ) {- var elem,- i = 0;-- for ( ; (elem = this[i]) != null; i++ ) {- if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {- if ( !keepData && elem.nodeType === 1 ) {- jQuery.cleanData( elem.getElementsByTagName("*") );- jQuery.cleanData( [ elem ] );- }-- if ( elem.parentNode ) {- elem.parentNode.removeChild( elem );- }- }- }-- return this;- },-- empty: function() {- var elem,- i = 0;-- for ( ; (elem = this[i]) != null; i++ ) {- // Remove element nodes and prevent memory leaks- if ( elem.nodeType === 1 ) {- jQuery.cleanData( elem.getElementsByTagName("*") );- }-- // Remove any remaining nodes- while ( elem.firstChild ) {- elem.removeChild( elem.firstChild );- }- }-- return this;- },-- clone: function( dataAndEvents, deepDataAndEvents ) {- dataAndEvents = dataAndEvents == null ? false : dataAndEvents;- deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;-- return this.map( function () {- return jQuery.clone( this, dataAndEvents, deepDataAndEvents );- });- },-- html: function( value ) {- return jQuery.access( this, function( value ) {- var elem = this[0] || {},- i = 0,- l = this.length;-- if ( value === undefined ) {- return elem.nodeType === 1 ?- elem.innerHTML.replace( rinlinejQuery, "" ) :- undefined;- }-- // See if we can take a shortcut and just use innerHTML- if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&- ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&- ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&- !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {-- value = value.replace( rxhtmlTag, "<$1></$2>" );-- try {- for (; i < l; i++ ) {- // Remove element nodes and prevent memory leaks- elem = this[i] || {};- if ( elem.nodeType === 1 ) {- jQuery.cleanData( elem.getElementsByTagName( "*" ) );- elem.innerHTML = value;- }- }-- elem = 0;-- // If using innerHTML throws an exception, use the fallback method- } catch(e) {}- }-- if ( elem ) {- this.empty().append( value );- }- }, null, value, arguments.length );- },-- replaceWith: function( value ) {- if ( !isDisconnected( this[0] ) ) {- // Make sure that the elements are removed from the DOM before they are inserted- // this can help fix replacing a parent with child elements- if ( jQuery.isFunction( value ) ) {- return this.each(function(i) {- var self = jQuery(this), old = self.html();- self.replaceWith( value.call( this, i, old ) );- });- }-- if ( typeof value !== "string" ) {- value = jQuery( value ).detach();- }-- return this.each(function() {- var next = this.nextSibling,- parent = this.parentNode;-- jQuery( this ).remove();-- if ( next ) {- jQuery(next).before( value );- } else {- jQuery(parent).append( value );- }- });- }-- return this.length ?- this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :- this;- },-- detach: function( selector ) {- return this.remove( selector, true );- },-- domManip: function( args, table, callback ) {-- // Flatten any nested arrays- args = [].concat.apply( [], args );-- var results, first, fragment, iNoClone,- i = 0,- value = args[0],- scripts = [],- l = this.length;-- // We can't cloneNode fragments that contain checked, in WebKit- if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {- return this.each(function() {- jQuery(this).domManip( args, table, callback );- });- }-- if ( jQuery.isFunction(value) ) {- return this.each(function(i) {- var self = jQuery(this);- args[0] = value.call( this, i, table ? self.html() : undefined );- self.domManip( args, table, callback );- });- }-- if ( this[0] ) {- results = jQuery.buildFragment( args, this, scripts );- fragment = results.fragment;- first = fragment.firstChild;-- if ( fragment.childNodes.length === 1 ) {- fragment = first;- }-- if ( first ) {- table = table && jQuery.nodeName( first, "tr" );-- // Use the original fragment for the last item instead of the first because it can end up- // being emptied incorrectly in certain situations (#8070).- // Fragments from the fragment cache must always be cloned and never used in place.- for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {- callback.call(- table && jQuery.nodeName( this[i], "table" ) ?- findOrAppend( this[i], "tbody" ) :- this[i],- i === iNoClone ?- fragment :- jQuery.clone( fragment, true, true )- );- }- }-- // Fix #11809: Avoid leaking memory- fragment = first = null;-- if ( scripts.length ) {- jQuery.each( scripts, function( i, elem ) {- if ( elem.src ) {- if ( jQuery.ajax ) {- jQuery.ajax({- url: elem.src,- type: "GET",- dataType: "script",- async: false,- global: false,- "throws": true- });- } else {- jQuery.error("no ajax");- }- } else {- jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );- }-- if ( elem.parentNode ) {- elem.parentNode.removeChild( elem );- }- });- }- }-- return this;- }-});--function findOrAppend( elem, tag ) {- return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );-}--function cloneCopyEvent( src, dest ) {-- if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {- return;- }-- var type, i, l,- oldData = jQuery._data( src ),- curData = jQuery._data( dest, oldData ),- events = oldData.events;-- if ( events ) {- delete curData.handle;- curData.events = {};-- for ( type in events ) {- for ( i = 0, l = events[ type ].length; i < l; i++ ) {- jQuery.event.add( dest, type, events[ type ][ i ] );- }- }- }-- // make the cloned public data object a copy from the original- if ( curData.data ) {- curData.data = jQuery.extend( {}, curData.data );- }-}--function cloneFixAttributes( src, dest ) {- var nodeName;-- // We do not need to do anything for non-Elements- if ( dest.nodeType !== 1 ) {- return;- }-- // clearAttributes removes the attributes, which we don't want,- // but also removes the attachEvent events, which we *do* want- if ( dest.clearAttributes ) {- dest.clearAttributes();- }-- // mergeAttributes, in contrast, only merges back on the- // original attributes, not the events- if ( dest.mergeAttributes ) {- dest.mergeAttributes( src );- }-- nodeName = dest.nodeName.toLowerCase();-- if ( nodeName === "object" ) {- // IE6-10 improperly clones children of object elements using classid.- // IE10 throws NoModificationAllowedError if parent is null, #12132.- if ( dest.parentNode ) {- dest.outerHTML = src.outerHTML;- }-- // This path appears unavoidable for IE9. When cloning an object- // element in IE9, the outerHTML strategy above is not sufficient.- // If the src has innerHTML and the destination does not,- // copy the src.innerHTML into the dest.innerHTML. #10324- if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {- dest.innerHTML = src.innerHTML;- }-- } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {- // IE6-8 fails to persist the checked state of a cloned checkbox- // or radio button. Worse, IE6-7 fail to give the cloned element- // a checked appearance if the defaultChecked value isn't also set-- dest.defaultChecked = dest.checked = src.checked;-- // IE6-7 get confused and end up setting the value of a cloned- // checkbox/radio button to an empty string instead of "on"- if ( dest.value !== src.value ) {- dest.value = src.value;- }-- // IE6-8 fails to return the selected option to the default selected- // state when cloning options- } else if ( nodeName === "option" ) {- dest.selected = src.defaultSelected;-- // IE6-8 fails to set the defaultValue to the correct value when- // cloning other types of input fields- } else if ( nodeName === "input" || nodeName === "textarea" ) {- dest.defaultValue = src.defaultValue;-- // IE blanks contents when cloning scripts- } else if ( nodeName === "script" && dest.text !== src.text ) {- dest.text = src.text;- }-- // Event data gets referenced instead of copied if the expando- // gets copied too- dest.removeAttribute( jQuery.expando );-}--jQuery.buildFragment = function( args, context, scripts ) {- var fragment, cacheable, cachehit,- first = args[ 0 ];-- // Set context from what may come in as undefined or a jQuery collection or a node- // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &- // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception- context = context || document;- context = !context.nodeType && context[0] || context;- context = context.ownerDocument || context;-- // Only cache "small" (1/2 KB) HTML strings that are associated with the main document- // Cloning options loses the selected state, so don't cache them- // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment- // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache- // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501- if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&- first.charAt(0) === "<" && !rnocache.test( first ) &&- (jQuery.support.checkClone || !rchecked.test( first )) &&- (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {-- // Mark cacheable and look for a hit- cacheable = true;- fragment = jQuery.fragments[ first ];- cachehit = fragment !== undefined;- }-- if ( !fragment ) {- fragment = context.createDocumentFragment();- jQuery.clean( args, context, fragment, scripts );-- // Update the cache, but only store false- // unless this is a second parsing of the same content- if ( cacheable ) {- jQuery.fragments[ first ] = cachehit && fragment;- }- }-- return { fragment: fragment, cacheable: cacheable };-};--jQuery.fragments = {};--jQuery.each({- appendTo: "append",- prependTo: "prepend",- insertBefore: "before",- insertAfter: "after",- replaceAll: "replaceWith"-}, function( name, original ) {- jQuery.fn[ name ] = function( selector ) {- var elems,- i = 0,- ret = [],- insert = jQuery( selector ),- l = insert.length,- parent = this.length === 1 && this[0].parentNode;-- if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {- insert[ original ]( this[0] );- return this;- } else {- for ( ; i < l; i++ ) {- elems = ( i > 0 ? this.clone(true) : this ).get();- jQuery( insert[i] )[ original ]( elems );- ret = ret.concat( elems );- }-- return this.pushStack( ret, name, insert.selector );- }- };-});--function getAll( elem ) {- if ( typeof elem.getElementsByTagName !== "undefined" ) {- return elem.getElementsByTagName( "*" );-- } else if ( typeof elem.querySelectorAll !== "undefined" ) {- return elem.querySelectorAll( "*" );-- } else {- return [];- }-}--// Used in clean, fixes the defaultChecked property-function fixDefaultChecked( elem ) {- if ( rcheckableType.test( elem.type ) ) {- elem.defaultChecked = elem.checked;- }-}--jQuery.extend({- clone: function( elem, dataAndEvents, deepDataAndEvents ) {- var srcElements,- destElements,- i,- clone;-- if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {- clone = elem.cloneNode( true );-- // IE<=8 does not properly clone detached, unknown element nodes- } else {- fragmentDiv.innerHTML = elem.outerHTML;- fragmentDiv.removeChild( clone = fragmentDiv.firstChild );- }-- if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&- (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {- // IE copies events bound via attachEvent when using cloneNode.- // Calling detachEvent on the clone will also remove the events- // from the original. In order to get around this, we use some- // proprietary methods to clear the events. Thanks to MooTools- // guys for this hotness.-- cloneFixAttributes( elem, clone );-- // Using Sizzle here is crazy slow, so we use getElementsByTagName instead- srcElements = getAll( elem );- destElements = getAll( clone );-- // Weird iteration because IE will replace the length property- // with an element if you are cloning the body and one of the- // elements on the page has a name or id of "length"- for ( i = 0; srcElements[i]; ++i ) {- // Ensure that the destination node is not null; Fixes #9587- if ( destElements[i] ) {- cloneFixAttributes( srcElements[i], destElements[i] );- }- }- }-- // Copy the events from the original to the clone- if ( dataAndEvents ) {- cloneCopyEvent( elem, clone );-- if ( deepDataAndEvents ) {- srcElements = getAll( elem );- destElements = getAll( clone );-- for ( i = 0; srcElements[i]; ++i ) {- cloneCopyEvent( srcElements[i], destElements[i] );- }- }- }-- srcElements = destElements = null;-- // Return the cloned set- return clone;- },-- clean: function( elems, context, fragment, scripts ) {- var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,- safe = context === document && safeFragment,- ret = [];-- // Ensure that context is a document- if ( !context || typeof context.createDocumentFragment === "undefined" ) {- context = document;- }-- // Use the already-created safe fragment if context permits- for ( i = 0; (elem = elems[i]) != null; i++ ) {- if ( typeof elem === "number" ) {- elem += "";- }-- if ( !elem ) {- continue;- }-- // Convert html string into DOM nodes- if ( typeof elem === "string" ) {- if ( !rhtml.test( elem ) ) {- elem = context.createTextNode( elem );- } else {- // Ensure a safe container in which to render the html- safe = safe || createSafeFragment( context );- div = context.createElement("div");- safe.appendChild( div );-- // Fix "XHTML"-style tags in all browsers- elem = elem.replace(rxhtmlTag, "<$1></$2>");-- // Go to html and back, then peel off extra wrappers- tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();- wrap = wrapMap[ tag ] || wrapMap._default;- depth = wrap[0];- div.innerHTML = wrap[1] + elem + wrap[2];-- // Move to the right depth- while ( depth-- ) {- div = div.lastChild;- }-- // Remove IE's autoinserted <tbody> from table fragments- if ( !jQuery.support.tbody ) {-- // String was a <table>, *may* have spurious <tbody>- hasBody = rtbody.test(elem);- tbody = tag === "table" && !hasBody ?- div.firstChild && div.firstChild.childNodes :-- // String was a bare <thead> or <tfoot>- wrap[1] === "<table>" && !hasBody ?- div.childNodes :- [];-- for ( j = tbody.length - 1; j >= 0 ; --j ) {- if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {- tbody[ j ].parentNode.removeChild( tbody[ j ] );- }- }- }-- // IE completely kills leading whitespace when innerHTML is used- if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {- div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );- }-- elem = div.childNodes;-- // Take out of fragment container (we need a fresh div each time)- div.parentNode.removeChild( div );- }- }-- if ( elem.nodeType ) {- ret.push( elem );- } else {- jQuery.merge( ret, elem );- }- }-- // Fix #11356: Clear elements from safeFragment- if ( div ) {- elem = div = safe = null;- }-- // Reset defaultChecked for any radios and checkboxes- // about to be appended to the DOM in IE 6/7 (#8060)- if ( !jQuery.support.appendChecked ) {- for ( i = 0; (elem = ret[i]) != null; i++ ) {- if ( jQuery.nodeName( elem, "input" ) ) {- fixDefaultChecked( elem );- } else if ( typeof elem.getElementsByTagName !== "undefined" ) {- jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );- }- }- }-- // Append elements to a provided document fragment- if ( fragment ) {- // Special handling of each script element- handleScript = function( elem ) {- // Check if we consider it executable- if ( !elem.type || rscriptType.test( elem.type ) ) {- // Detach the script and store it in the scripts array (if provided) or the fragment- // Return truthy to indicate that it has been handled- return scripts ?- scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :- fragment.appendChild( elem );- }- };-- for ( i = 0; (elem = ret[i]) != null; i++ ) {- // Check if we're done after handling an executable script- if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {- // Append to fragment and handle embedded scripts- fragment.appendChild( elem );- if ( typeof elem.getElementsByTagName !== "undefined" ) {- // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration- jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );-- // Splice the scripts into ret after their former ancestor and advance our index beyond them- ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );- i += jsTags.length;- }- }- }- }-- return ret;- },-- cleanData: function( elems, /* internal */ acceptData ) {- var data, id, elem, type,- i = 0,- internalKey = jQuery.expando,- cache = jQuery.cache,- deleteExpando = jQuery.support.deleteExpando,- special = jQuery.event.special;-- for ( ; (elem = elems[i]) != null; i++ ) {-- if ( acceptData || jQuery.acceptData( elem ) ) {-- id = elem[ internalKey ];- data = id && cache[ id ];-- if ( data ) {- if ( data.events ) {- for ( type in data.events ) {- if ( special[ type ] ) {- jQuery.event.remove( elem, type );-- // This is a shortcut to avoid jQuery.event.remove's overhead- } else {- jQuery.removeEvent( elem, type, data.handle );- }- }- }-- // Remove cache only if it was not already removed by jQuery.event.remove- if ( cache[ id ] ) {-- delete cache[ id ];-- // IE does not allow us to delete expando properties from nodes,- // nor does it have a removeAttribute function on Document nodes;- // we must handle all of these cases- if ( deleteExpando ) {- delete elem[ internalKey ];-- } else if ( elem.removeAttribute ) {- elem.removeAttribute( internalKey );-- } else {- elem[ internalKey ] = null;- }-- jQuery.deletedIds.push( id );- }- }- }- }- }-});-// Limit scope pollution from any deprecated API-(function() {--var matched, browser;--// Use of jQuery.browser is frowned upon.-// More details: http://api.jquery.com/jQuery.browser-// jQuery.uaMatch maintained for back-compat-jQuery.uaMatch = function( ua ) {- ua = ua.toLowerCase();-- var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||- /(webkit)[ \/]([\w.]+)/.exec( ua ) ||- /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||- /(msie) ([\w.]+)/.exec( ua ) ||- ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||- [];-- return {- browser: match[ 1 ] || "",- version: match[ 2 ] || "0"- };-};--matched = jQuery.uaMatch( navigator.userAgent );-browser = {};--if ( matched.browser ) {- browser[ matched.browser ] = true;- browser.version = matched.version;-}--// Chrome is Webkit, but Webkit is also Safari.-if ( browser.chrome ) {- browser.webkit = true;-} else if ( browser.webkit ) {- browser.safari = true;-}--jQuery.browser = browser;--jQuery.sub = function() {- function jQuerySub( selector, context ) {- return new jQuerySub.fn.init( selector, context );- }- jQuery.extend( true, jQuerySub, this );- jQuerySub.superclass = this;- jQuerySub.fn = jQuerySub.prototype = this();- jQuerySub.fn.constructor = jQuerySub;- jQuerySub.sub = this.sub;- jQuerySub.fn.init = function init( selector, context ) {- if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {- context = jQuerySub( context );- }-- return jQuery.fn.init.call( this, selector, context, rootjQuerySub );- };- jQuerySub.fn.init.prototype = jQuerySub.fn;- var rootjQuerySub = jQuerySub(document);- return jQuerySub;-};--})();-var curCSS, iframe, iframeDoc,- ralpha = /alpha\([^)]*\)/i,- ropacity = /opacity=([^)]*)/,- rposition = /^(top|right|bottom|left)$/,- // swappable if display is none or starts with table except "table", "table-cell", or "table-caption"- // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display- rdisplayswap = /^(none|table(?!-c[ea]).+)/,- rmargin = /^margin/,- rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),- rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),- rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),- elemdisplay = { BODY: "block" },-- cssShow = { position: "absolute", visibility: "hidden", display: "block" },- cssNormalTransform = {- letterSpacing: 0,- fontWeight: 400- },-- cssExpand = [ "Top", "Right", "Bottom", "Left" ],- cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],-- eventsToggle = jQuery.fn.toggle;--// return a css property mapped to a potentially vendor prefixed property-function vendorPropName( style, name ) {-- // shortcut for names that are not vendor prefixed- if ( name in style ) {- return name;- }-- // check for vendor prefixed names- var capName = name.charAt(0).toUpperCase() + name.slice(1),- origName = name,- i = cssPrefixes.length;-- while ( i-- ) {- name = cssPrefixes[ i ] + capName;- if ( name in style ) {- return name;- }- }-- return origName;-}--function isHidden( elem, el ) {- elem = el || elem;- return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );-}--function showHide( elements, show ) {- var elem, display,- values = [],- index = 0,- length = elements.length;-- for ( ; index < length; index++ ) {- elem = elements[ index ];- if ( !elem.style ) {- continue;- }- values[ index ] = jQuery._data( elem, "olddisplay" );- if ( show ) {- // Reset the inline display of this element to learn if it is- // being hidden by cascaded rules or not- if ( !values[ index ] && elem.style.display === "none" ) {- elem.style.display = "";- }-- // Set elements which have been overridden with display: none- // in a stylesheet to whatever the default browser style is- // for such an element- if ( elem.style.display === "" && isHidden( elem ) ) {- values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );- }- } else {- display = curCSS( elem, "display" );-- if ( !values[ index ] && display !== "none" ) {- jQuery._data( elem, "olddisplay", display );- }- }- }-- // Set the display of most of the elements in a second loop- // to avoid the constant reflow- for ( index = 0; index < length; index++ ) {- elem = elements[ index ];- if ( !elem.style ) {- continue;- }- if ( !show || elem.style.display === "none" || elem.style.display === "" ) {- elem.style.display = show ? values[ index ] || "" : "none";- }- }-- return elements;-}--jQuery.fn.extend({- css: function( name, value ) {- return jQuery.access( this, function( elem, name, value ) {- return value !== undefined ?- jQuery.style( elem, name, value ) :- jQuery.css( elem, name );- }, name, value, arguments.length > 1 );- },- show: function() {- return showHide( this, true );- },- hide: function() {- return showHide( this );- },- toggle: function( state, fn2 ) {- var bool = typeof state === "boolean";-- if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {- return eventsToggle.apply( this, arguments );- }-- return this.each(function() {- if ( bool ? state : isHidden( this ) ) {- jQuery( this ).show();- } else {- jQuery( this ).hide();- }- });- }-});--jQuery.extend({- // Add in style property hooks for overriding the default- // behavior of getting and setting a style property- cssHooks: {- opacity: {- get: function( elem, computed ) {- if ( computed ) {- // We should always get a number back from opacity- var ret = curCSS( elem, "opacity" );- return ret === "" ? "1" : ret;-- }- }- }- },-- // Exclude the following css properties to add px- cssNumber: {- "fillOpacity": true,- "fontWeight": true,- "lineHeight": true,- "opacity": true,- "orphans": true,- "widows": true,- "zIndex": true,- "zoom": true- },-- // Add in properties whose names you wish to fix before- // setting or getting the value- cssProps: {- // normalize float css property- "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"- },-- // Get and set the style property on a DOM Node- style: function( elem, name, value, extra ) {- // Don't set styles on text and comment nodes- if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {- return;- }-- // Make sure that we're working with the right name- var ret, type, hooks,- origName = jQuery.camelCase( name ),- style = elem.style;-- name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );-- // gets hook for the prefixed version- // followed by the unprefixed version- hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];-- // Check if we're setting a value- if ( value !== undefined ) {- type = typeof value;-- // convert relative number strings (+= or -=) to relative numbers. #7345- if ( type === "string" && (ret = rrelNum.exec( value )) ) {- value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );- // Fixes bug #9237- type = "number";- }-- // Make sure that NaN and null values aren't set. See: #7116- if ( value == null || type === "number" && isNaN( value ) ) {- return;- }-- // If a number was passed in, add 'px' to the (except for certain CSS properties)- if ( type === "number" && !jQuery.cssNumber[ origName ] ) {- value += "px";- }-- // If a hook was provided, use that value, otherwise just set the specified value- if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {- // Wrapped to prevent IE from throwing errors when 'invalid' values are provided- // Fixes bug #5509- try {- style[ name ] = value;- } catch(e) {}- }-- } else {- // If a hook was provided get the non-computed value from there- if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {- return ret;- }-- // Otherwise just get the value from the style object- return style[ name ];- }- },-- css: function( elem, name, numeric, extra ) {- var val, num, hooks,- origName = jQuery.camelCase( name );-- // Make sure that we're working with the right name- name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );-- // gets hook for the prefixed version- // followed by the unprefixed version- hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];-- // If a hook was provided get the computed value from there- if ( hooks && "get" in hooks ) {- val = hooks.get( elem, true, extra );- }-- // Otherwise, if a way to get the computed value exists, use that- if ( val === undefined ) {- val = curCSS( elem, name );- }-- //convert "normal" to computed value- if ( val === "normal" && name in cssNormalTransform ) {- val = cssNormalTransform[ name ];- }-- // Return, converting to number if forced or a qualifier was provided and val looks numeric- if ( numeric || extra !== undefined ) {- num = parseFloat( val );- return numeric || jQuery.isNumeric( num ) ? num || 0 : val;- }- return val;- },-- // A method for quickly swapping in/out CSS properties to get correct calculations- swap: function( elem, options, callback ) {- var ret, name,- old = {};-- // Remember the old values, and insert the new ones- for ( name in options ) {- old[ name ] = elem.style[ name ];- elem.style[ name ] = options[ name ];- }-- ret = callback.call( elem );-- // Revert the old values- for ( name in options ) {- elem.style[ name ] = old[ name ];- }-- return ret;- }-});--// NOTE: To any future maintainer, we've window.getComputedStyle-// because jsdom on node.js will break without it.-if ( window.getComputedStyle ) {- curCSS = function( elem, name ) {- var ret, width, minWidth, maxWidth,- computed = window.getComputedStyle( elem, null ),- style = elem.style;-- if ( computed ) {-- // getPropertyValue is only needed for .css('filter') in IE9, see #12537- ret = computed.getPropertyValue( name ) || computed[ name ];-- if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {- ret = jQuery.style( elem, name );- }-- // A tribute to the "awesome hack by Dean Edwards"- // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right- // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels- // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values- if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {- width = style.width;- minWidth = style.minWidth;- maxWidth = style.maxWidth;-- style.minWidth = style.maxWidth = style.width = ret;- ret = computed.width;-- style.width = width;- style.minWidth = minWidth;- style.maxWidth = maxWidth;- }- }-- return ret;- };-} else if ( document.documentElement.currentStyle ) {- curCSS = function( elem, name ) {- var left, rsLeft,- ret = elem.currentStyle && elem.currentStyle[ name ],- style = elem.style;-- // Avoid setting ret to empty string here- // so we don't default to auto- if ( ret == null && style && style[ name ] ) {- ret = style[ name ];- }-- // From the awesome hack by Dean Edwards- // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291-- // If we're not dealing with a regular pixel number- // but a number that has a weird ending, we need to convert it to pixels- // but not position css attributes, as those are proportional to the parent element instead- // and we can't measure the parent instead because it might trigger a "stacking dolls" problem- if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {-- // Remember the original values- left = style.left;- rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;-- // Put in the new values to get a computed value out- if ( rsLeft ) {- elem.runtimeStyle.left = elem.currentStyle.left;- }- style.left = name === "fontSize" ? "1em" : ret;- ret = style.pixelLeft + "px";-- // Revert the changed values- style.left = left;- if ( rsLeft ) {- elem.runtimeStyle.left = rsLeft;- }- }-- return ret === "" ? "auto" : ret;- };-}--function setPositiveNumber( elem, value, subtract ) {- var matches = rnumsplit.exec( value );- return matches ?- Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :- value;-}--function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {- var i = extra === ( isBorderBox ? "border" : "content" ) ?- // If we already have the right measurement, avoid augmentation- 4 :- // Otherwise initialize for horizontal or vertical properties- name === "width" ? 1 : 0,-- val = 0;-- for ( ; i < 4; i += 2 ) {- // both box models exclude margin, so add it if we want it- if ( extra === "margin" ) {- // we use jQuery.css instead of curCSS here- // because of the reliableMarginRight CSS hook!- val += jQuery.css( elem, extra + cssExpand[ i ], true );- }-- // From this point on we use curCSS for maximum performance (relevant in animations)- if ( isBorderBox ) {- // border-box includes padding, so remove it if we want content- if ( extra === "content" ) {- val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;- }-- // at this point, extra isn't border nor margin, so remove border- if ( extra !== "margin" ) {- val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;- }- } else {- // at this point, extra isn't content, so add padding- val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;-- // at this point, extra isn't content nor padding, so add border- if ( extra !== "padding" ) {- val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;- }- }- }-- return val;-}--function getWidthOrHeight( elem, name, extra ) {-- // Start with offset property, which is equivalent to the border-box value- var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,- valueIsBorderBox = true,- isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";-- // some non-html elements return undefined for offsetWidth, so check for null/undefined- // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285- // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668- if ( val <= 0 || val == null ) {- // Fall back to computed then uncomputed css if necessary- val = curCSS( elem, name );- if ( val < 0 || val == null ) {- val = elem.style[ name ];- }-- // Computed unit is not pixels. Stop here and return.- if ( rnumnonpx.test(val) ) {- return val;- }-- // we need the check for style in case a browser which returns unreliable values- // for getComputedStyle silently falls back to the reliable elem.style- valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );-- // Normalize "", auto, and prepare for extra- val = parseFloat( val ) || 0;- }-- // use the active box-sizing model to add/subtract irrelevant styles- return ( val +- augmentWidthOrHeight(- elem,- name,- extra || ( isBorderBox ? "border" : "content" ),- valueIsBorderBox- )- ) + "px";-}---// Try to determine the default display value of an element-function css_defaultDisplay( nodeName ) {- if ( elemdisplay[ nodeName ] ) {- return elemdisplay[ nodeName ];- }-- var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),- display = elem.css("display");- elem.remove();-- // If the simple way fails,- // get element's real default display by attaching it to a temp iframe- if ( display === "none" || display === "" ) {- // Use the already-created iframe if possible- iframe = document.body.appendChild(- iframe || jQuery.extend( document.createElement("iframe"), {- frameBorder: 0,- width: 0,- height: 0- })- );-- // Create a cacheable copy of the iframe document on first call.- // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML- // document to it; WebKit & Firefox won't allow reusing the iframe document.- if ( !iframeDoc || !iframe.createElement ) {- iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;- iframeDoc.write("<!doctype html><html><body>");- iframeDoc.close();- }-- elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );-- display = curCSS( elem, "display" );- document.body.removeChild( iframe );- }-- // Store the correct default display- elemdisplay[ nodeName ] = display;-- return display;-}--jQuery.each([ "height", "width" ], function( i, name ) {- jQuery.cssHooks[ name ] = {- get: function( elem, computed, extra ) {- if ( computed ) {- // certain elements can have dimension info if we invisibly show them- // however, it must have a current display style that would benefit from this- if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {- return jQuery.swap( elem, cssShow, function() {- return getWidthOrHeight( elem, name, extra );- });- } else {- return getWidthOrHeight( elem, name, extra );- }- }- },-- set: function( elem, value, extra ) {- return setPositiveNumber( elem, value, extra ?- augmentWidthOrHeight(- elem,- name,- extra,- jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"- ) : 0- );- }- };-});--if ( !jQuery.support.opacity ) {- jQuery.cssHooks.opacity = {- get: function( elem, computed ) {- // IE uses filters for opacity- return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?- ( 0.01 * parseFloat( RegExp.$1 ) ) + "" :- computed ? "1" : "";- },-- set: function( elem, value ) {- var style = elem.style,- currentStyle = elem.currentStyle,- opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",- filter = currentStyle && currentStyle.filter || style.filter || "";-- // IE has trouble with opacity if it does not have layout- // Force it by setting the zoom level- style.zoom = 1;-- // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652- if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&- style.removeAttribute ) {-- // Setting style.filter to null, "" & " " still leave "filter:" in the cssText- // if "filter:" is present at all, clearType is disabled, we want to avoid this- // style.removeAttribute is IE Only, but so apparently is this code path...- style.removeAttribute( "filter" );-- // if there there is no filter style applied in a css rule, we are done- if ( currentStyle && !currentStyle.filter ) {- return;- }- }-- // otherwise, set new filter values- style.filter = ralpha.test( filter ) ?- filter.replace( ralpha, opacity ) :- filter + " " + opacity;- }- };-}--// These hooks cannot be added until DOM ready because the support test-// for it is not run until after DOM ready-jQuery(function() {- if ( !jQuery.support.reliableMarginRight ) {- jQuery.cssHooks.marginRight = {- get: function( elem, computed ) {- // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right- // Work around by temporarily setting element display to inline-block- return jQuery.swap( elem, { "display": "inline-block" }, function() {- if ( computed ) {- return curCSS( elem, "marginRight" );- }- });- }- };- }-- // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084- // getComputedStyle returns percent when specified for top/left/bottom/right- // rather than make the css module depend on the offset module, we just check for it here- if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {- jQuery.each( [ "top", "left" ], function( i, prop ) {- jQuery.cssHooks[ prop ] = {- get: function( elem, computed ) {- if ( computed ) {- var ret = curCSS( elem, prop );- // if curCSS returns percentage, fallback to offset- return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;- }- }- };- });- }--});--if ( jQuery.expr && jQuery.expr.filters ) {- jQuery.expr.filters.hidden = function( elem ) {- return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");- };-- jQuery.expr.filters.visible = function( elem ) {- return !jQuery.expr.filters.hidden( elem );- };-}--// These hooks are used by animate to expand properties-jQuery.each({- margin: "",- padding: "",- border: "Width"-}, function( prefix, suffix ) {- jQuery.cssHooks[ prefix + suffix ] = {- expand: function( value ) {- var i,-- // assumes a single number if not a string- parts = typeof value === "string" ? value.split(" ") : [ value ],- expanded = {};-- for ( i = 0; i < 4; i++ ) {- expanded[ prefix + cssExpand[ i ] + suffix ] =- parts[ i ] || parts[ i - 2 ] || parts[ 0 ];- }-- return expanded;- }- };-- if ( !rmargin.test( prefix ) ) {- jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;- }-});-var r20 = /%20/g,- rbracket = /\[\]$/,- rCRLF = /\r?\n/g,- rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,- rselectTextarea = /^(?:select|textarea)/i;--jQuery.fn.extend({- serialize: function() {- return jQuery.param( this.serializeArray() );- },- serializeArray: function() {- return this.map(function(){- return this.elements ? jQuery.makeArray( this.elements ) : this;- })- .filter(function(){- return this.name && !this.disabled &&- ( this.checked || rselectTextarea.test( this.nodeName ) ||- rinput.test( this.type ) );- })- .map(function( i, elem ){- var val = jQuery( this ).val();-- return val == null ?- null :- jQuery.isArray( val ) ?- jQuery.map( val, function( val, i ){- return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };- }) :- { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };- }).get();- }-});--//Serialize an array of form elements or a set of-//key/values into a query string-jQuery.param = function( a, traditional ) {- var prefix,- s = [],- add = function( key, value ) {- // If value is a function, invoke it and return its value- value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );- s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );- };-- // Set traditional to true for jQuery <= 1.3.2 behavior.- if ( traditional === undefined ) {- traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;- }-- // If an array was passed in, assume that it is an array of form elements.- if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {- // Serialize the form elements- jQuery.each( a, function() {- add( this.name, this.value );- });-- } else {- // If traditional, encode the "old" way (the way 1.3.2 or older- // did it), otherwise encode params recursively.- for ( prefix in a ) {- buildParams( prefix, a[ prefix ], traditional, add );- }- }-- // Return the resulting serialization- return s.join( "&" ).replace( r20, "+" );-};--function buildParams( prefix, obj, traditional, add ) {- var name;-- if ( jQuery.isArray( obj ) ) {- // Serialize array item.- jQuery.each( obj, function( i, v ) {- if ( traditional || rbracket.test( prefix ) ) {- // Treat each array item as a scalar.- add( prefix, v );-- } else {- // If array item is non-scalar (array or object), encode its- // numeric index to resolve deserialization ambiguity issues.- // Note that rack (as of 1.0.0) can't currently deserialize- // nested arrays properly, and attempting to do so may cause- // a server error. Possible fixes are to modify rack's- // deserialization algorithm or to provide an option or flag- // to force array serialization to be shallow.- buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );- }- });-- } else if ( !traditional && jQuery.type( obj ) === "object" ) {- // Serialize object item.- for ( name in obj ) {- buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );- }-- } else {- // Serialize scalar item.- add( prefix, obj );- }-}-var- // Document location- ajaxLocParts,- ajaxLocation,-- rhash = /#.*$/,- rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL- // #7653, #8125, #8152: local protocol detection- rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,- rnoContent = /^(?:GET|HEAD)$/,- rprotocol = /^\/\//,- rquery = /\?/,- rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,- rts = /([?&])_=[^&]*/,- rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,-- // Keep a copy of the old load method- _load = jQuery.fn.load,-- /* Prefilters- * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)- * 2) These are called:- * - BEFORE asking for a transport- * - AFTER param serialization (s.data is a string if s.processData is true)- * 3) key is the dataType- * 4) the catchall symbol "*" can be used- * 5) execution will start with transport dataType and THEN continue down to "*" if needed- */- prefilters = {},-- /* Transports bindings- * 1) key is the dataType- * 2) the catchall symbol "*" can be used- * 3) selection will start with transport dataType and THEN go to "*" if needed- */- transports = {},-- // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression- allTypes = ["*/"] + ["*"];--// #8138, IE may throw an exception when accessing-// a field from window.location if document.domain has been set-try {- ajaxLocation = location.href;-} catch( e ) {- // Use the href attribute of an A element- // since IE will modify it given document.location- ajaxLocation = document.createElement( "a" );- ajaxLocation.href = "";- ajaxLocation = ajaxLocation.href;-}--// Segment location into parts-ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];--// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport-function addToPrefiltersOrTransports( structure ) {-- // dataTypeExpression is optional and defaults to "*"- return function( dataTypeExpression, func ) {-- if ( typeof dataTypeExpression !== "string" ) {- func = dataTypeExpression;- dataTypeExpression = "*";- }-- var dataType, list, placeBefore,- dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),- i = 0,- length = dataTypes.length;-- if ( jQuery.isFunction( func ) ) {- // For each dataType in the dataTypeExpression- for ( ; i < length; i++ ) {- dataType = dataTypes[ i ];- // We control if we're asked to add before- // any existing element- placeBefore = /^\+/.test( dataType );- if ( placeBefore ) {- dataType = dataType.substr( 1 ) || "*";- }- list = structure[ dataType ] = structure[ dataType ] || [];- // then we add to the structure accordingly- list[ placeBefore ? "unshift" : "push" ]( func );- }- }- };-}--// Base inspection function for prefilters and transports-function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,- dataType /* internal */, inspected /* internal */ ) {-- dataType = dataType || options.dataTypes[ 0 ];- inspected = inspected || {};-- inspected[ dataType ] = true;-- var selection,- list = structure[ dataType ],- i = 0,- length = list ? list.length : 0,- executeOnly = ( structure === prefilters );-- for ( ; i < length && ( executeOnly || !selection ); i++ ) {- selection = list[ i ]( options, originalOptions, jqXHR );- // If we got redirected to another dataType- // we try there if executing only and not done already- if ( typeof selection === "string" ) {- if ( !executeOnly || inspected[ selection ] ) {- selection = undefined;- } else {- options.dataTypes.unshift( selection );- selection = inspectPrefiltersOrTransports(- structure, options, originalOptions, jqXHR, selection, inspected );- }- }- }- // If we're only executing or nothing was selected- // we try the catchall dataType if not done already- if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {- selection = inspectPrefiltersOrTransports(- structure, options, originalOptions, jqXHR, "*", inspected );- }- // unnecessary when only executing (prefilters)- // but it'll be ignored by the caller in that case- return selection;-}--// A special extend for ajax options-// that takes "flat" options (not to be deep extended)-// Fixes #9887-function ajaxExtend( target, src ) {- var key, deep,- flatOptions = jQuery.ajaxSettings.flatOptions || {};- for ( key in src ) {- if ( src[ key ] !== undefined ) {- ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];- }- }- if ( deep ) {- jQuery.extend( true, target, deep );- }-}--jQuery.fn.load = function( url, params, callback ) {- if ( typeof url !== "string" && _load ) {- return _load.apply( this, arguments );- }-- // Don't do a request if no elements are being requested- if ( !this.length ) {- return this;- }-- var selector, type, response,- self = this,- off = url.indexOf(" ");-- if ( off >= 0 ) {- selector = url.slice( off, url.length );- url = url.slice( 0, off );- }-- // If it's a function- if ( jQuery.isFunction( params ) ) {-- // We assume that it's the callback- callback = params;- params = undefined;-- // Otherwise, build a param string- } else if ( params && typeof params === "object" ) {- type = "POST";- }-- // Request the remote document- jQuery.ajax({- url: url,-- // if "type" variable is undefined, then "GET" method will be used- type: type,- dataType: "html",- data: params,- complete: function( jqXHR, status ) {- if ( callback ) {- self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );- }- }- }).done(function( responseText ) {-- // Save response for use in complete callback- response = arguments;-- // See if a selector was specified- self.html( selector ?-- // Create a dummy div to hold the results- jQuery("<div>")-- // inject the contents of the document in, removing the scripts- // to avoid any 'Permission Denied' errors in IE- .append( responseText.replace( rscript, "" ) )-- // Locate the specified elements- .find( selector ) :-- // If not, just inject the full result- responseText );-- });-- return this;-};--// Attach a bunch of functions for handling common AJAX events-jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){- jQuery.fn[ o ] = function( f ){- return this.on( o, f );- };-});--jQuery.each( [ "get", "post" ], function( i, method ) {- jQuery[ method ] = function( url, data, callback, type ) {- // shift arguments if data argument was omitted- if ( jQuery.isFunction( data ) ) {- type = type || callback;- callback = data;- data = undefined;- }-- return jQuery.ajax({- type: method,- url: url,- data: data,- success: callback,- dataType: type- });- };-});--jQuery.extend({-- getScript: function( url, callback ) {- return jQuery.get( url, undefined, callback, "script" );- },-- getJSON: function( url, data, callback ) {- return jQuery.get( url, data, callback, "json" );- },-- // Creates a full fledged settings object into target- // with both ajaxSettings and settings fields.- // If target is omitted, writes into ajaxSettings.- ajaxSetup: function( target, settings ) {- if ( settings ) {- // Building a settings object- ajaxExtend( target, jQuery.ajaxSettings );- } else {- // Extending ajaxSettings- settings = target;- target = jQuery.ajaxSettings;- }- ajaxExtend( target, settings );- return target;- },-- ajaxSettings: {- url: ajaxLocation,- isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),- global: true,- type: "GET",- contentType: "application/x-www-form-urlencoded; charset=UTF-8",- processData: true,- async: true,- /*- timeout: 0,- data: null,- dataType: null,- username: null,- password: null,- cache: null,- throws: false,- traditional: false,- headers: {},- */-- accepts: {- xml: "application/xml, text/xml",- html: "text/html",- text: "text/plain",- json: "application/json, text/javascript",- "*": allTypes- },-- contents: {- xml: /xml/,- html: /html/,- json: /json/- },-- responseFields: {- xml: "responseXML",- text: "responseText"- },-- // List of data converters- // 1) key format is "source_type destination_type" (a single space in-between)- // 2) the catchall symbol "*" can be used for source_type- converters: {-- // Convert anything to text- "* text": window.String,-- // Text to html (true = no transformation)- "text html": true,-- // Evaluate text as a json expression- "text json": jQuery.parseJSON,-- // Parse text as xml- "text xml": jQuery.parseXML- },-- // For options that shouldn't be deep extended:- // you can add your own custom options here if- // and when you create one that shouldn't be- // deep extended (see ajaxExtend)- flatOptions: {- context: true,- url: true- }- },-- ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),- ajaxTransport: addToPrefiltersOrTransports( transports ),-- // Main method- ajax: function( url, options ) {-- // If url is an object, simulate pre-1.5 signature- if ( typeof url === "object" ) {- options = url;- url = undefined;- }-- // Force options to be an object- options = options || {};-- var // ifModified key- ifModifiedKey,- // Response headers- responseHeadersString,- responseHeaders,- // transport- transport,- // timeout handle- timeoutTimer,- // Cross-domain detection vars- parts,- // To know if global events are to be dispatched- fireGlobals,- // Loop variable- i,- // Create the final options object- s = jQuery.ajaxSetup( {}, options ),- // Callbacks context- callbackContext = s.context || s,- // Context for global events- // It's the callbackContext if one was provided in the options- // and if it's a DOM node or a jQuery collection- globalEventContext = callbackContext !== s &&- ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?- jQuery( callbackContext ) : jQuery.event,- // Deferreds- deferred = jQuery.Deferred(),- completeDeferred = jQuery.Callbacks( "once memory" ),- // Status-dependent callbacks- statusCode = s.statusCode || {},- // Headers (they are sent all at once)- requestHeaders = {},- requestHeadersNames = {},- // The jqXHR state- state = 0,- // Default abort message- strAbort = "canceled",- // Fake xhr- jqXHR = {-- readyState: 0,-- // Caches the header- setRequestHeader: function( name, value ) {- if ( !state ) {- var lname = name.toLowerCase();- name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;- requestHeaders[ name ] = value;- }- return this;- },-- // Raw string- getAllResponseHeaders: function() {- return state === 2 ? responseHeadersString : null;- },-- // Builds headers hashtable if needed- getResponseHeader: function( key ) {- var match;- if ( state === 2 ) {- if ( !responseHeaders ) {- responseHeaders = {};- while( ( match = rheaders.exec( responseHeadersString ) ) ) {- responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];- }- }- match = responseHeaders[ key.toLowerCase() ];- }- return match === undefined ? null : match;- },-- // Overrides response content-type header- overrideMimeType: function( type ) {- if ( !state ) {- s.mimeType = type;- }- return this;- },-- // Cancel the request- abort: function( statusText ) {- statusText = statusText || strAbort;- if ( transport ) {- transport.abort( statusText );- }- done( 0, statusText );- return this;- }- };-- // Callback for when everything is done- // It is defined here because jslint complains if it is declared- // at the end of the function (which would be more logical and readable)- function done( status, nativeStatusText, responses, headers ) {- var isSuccess, success, error, response, modified,- statusText = nativeStatusText;-- // Called once- if ( state === 2 ) {- return;- }-- // State is "done" now- state = 2;-- // Clear timeout if it exists- if ( timeoutTimer ) {- clearTimeout( timeoutTimer );- }-- // Dereference transport for early garbage collection- // (no matter how long the jqXHR object will be used)- transport = undefined;-- // Cache response headers- responseHeadersString = headers || "";-- // Set readyState- jqXHR.readyState = status > 0 ? 4 : 0;-- // Get response data- if ( responses ) {- response = ajaxHandleResponses( s, jqXHR, responses );- }-- // If successful, handle type chaining- if ( status >= 200 && status < 300 || status === 304 ) {-- // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.- if ( s.ifModified ) {-- modified = jqXHR.getResponseHeader("Last-Modified");- if ( modified ) {- jQuery.lastModified[ ifModifiedKey ] = modified;- }- modified = jqXHR.getResponseHeader("Etag");- if ( modified ) {- jQuery.etag[ ifModifiedKey ] = modified;- }- }-- // If not modified- if ( status === 304 ) {-- statusText = "notmodified";- isSuccess = true;-- // If we have data- } else {-- isSuccess = ajaxConvert( s, response );- statusText = isSuccess.state;- success = isSuccess.data;- error = isSuccess.error;- isSuccess = !error;- }- } else {- // We extract error from statusText- // then normalize statusText and status for non-aborts- error = statusText;- if ( !statusText || status ) {- statusText = "error";- if ( status < 0 ) {- status = 0;- }- }- }-- // Set data for the fake xhr object- jqXHR.status = status;- jqXHR.statusText = ( nativeStatusText || statusText ) + "";-- // Success/Error- if ( isSuccess ) {- deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );- } else {- deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );- }-- // Status-dependent callbacks- jqXHR.statusCode( statusCode );- statusCode = undefined;-- if ( fireGlobals ) {- globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),- [ jqXHR, s, isSuccess ? success : error ] );- }-- // Complete- completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );-- if ( fireGlobals ) {- globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );- // Handle the global AJAX counter- if ( !( --jQuery.active ) ) {- jQuery.event.trigger( "ajaxStop" );- }- }- }-- // Attach deferreds- deferred.promise( jqXHR );- jqXHR.success = jqXHR.done;- jqXHR.error = jqXHR.fail;- jqXHR.complete = completeDeferred.add;-- // Status-dependent callbacks- jqXHR.statusCode = function( map ) {- if ( map ) {- var tmp;- if ( state < 2 ) {- for ( tmp in map ) {- statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];- }- } else {- tmp = map[ jqXHR.status ];- jqXHR.always( tmp );- }- }- return this;- };-- // Remove hash character (#7531: and string promotion)- // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)- // We also use the url parameter if available- s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );-- // Extract dataTypes list- s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );-- // A cross-domain request is in order when we have a protocol:host:port mismatch- if ( s.crossDomain == null ) {- parts = rurl.exec( s.url.toLowerCase() );- s.crossDomain = !!( parts &&- ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||- ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=- ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )- );- }-- // Convert data if not already a string- if ( s.data && s.processData && typeof s.data !== "string" ) {- s.data = jQuery.param( s.data, s.traditional );- }-- // Apply prefilters- inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );-- // If request was aborted inside a prefilter, stop there- if ( state === 2 ) {- return jqXHR;- }-- // We can fire global events as of now if asked to- fireGlobals = s.global;-- // Uppercase the type- s.type = s.type.toUpperCase();-- // Determine if request has content- s.hasContent = !rnoContent.test( s.type );-- // Watch for a new set of requests- if ( fireGlobals && jQuery.active++ === 0 ) {- jQuery.event.trigger( "ajaxStart" );- }-- // More options handling for requests with no content- if ( !s.hasContent ) {-- // If data is available, append data to url- if ( s.data ) {- s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;- // #9682: remove data so that it's not used in an eventual retry- delete s.data;- }-- // Get ifModifiedKey before adding the anti-cache parameter- ifModifiedKey = s.url;-- // Add anti-cache in url if needed- if ( s.cache === false ) {-- var ts = jQuery.now(),- // try replacing _= if it is there- ret = s.url.replace( rts, "$1_=" + ts );-- // if nothing was replaced, add timestamp to the end- s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );- }- }-- // Set the correct header, if data is being sent- if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {- jqXHR.setRequestHeader( "Content-Type", s.contentType );- }-- // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.- if ( s.ifModified ) {- ifModifiedKey = ifModifiedKey || s.url;- if ( jQuery.lastModified[ ifModifiedKey ] ) {- jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );- }- if ( jQuery.etag[ ifModifiedKey ] ) {- jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );- }- }-- // Set the Accepts header for the server, depending on the dataType- jqXHR.setRequestHeader(- "Accept",- s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?- s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :- s.accepts[ "*" ]- );-- // Check for headers option- for ( i in s.headers ) {- jqXHR.setRequestHeader( i, s.headers[ i ] );- }-- // Allow custom headers/mimetypes and early abort- if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {- // Abort if not done already and return- return jqXHR.abort();-- }-- // aborting is no longer a cancellation- strAbort = "abort";-- // Install callbacks on deferreds- for ( i in { success: 1, error: 1, complete: 1 } ) {- jqXHR[ i ]( s[ i ] );- }-- // Get transport- transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );-- // If no transport, we auto-abort- if ( !transport ) {- done( -1, "No Transport" );- } else {- jqXHR.readyState = 1;- // Send global event- if ( fireGlobals ) {- globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );- }- // Timeout- if ( s.async && s.timeout > 0 ) {- timeoutTimer = setTimeout( function(){- jqXHR.abort( "timeout" );- }, s.timeout );- }-- try {- state = 1;- transport.send( requestHeaders, done );- } catch (e) {- // Propagate exception as error if not done- if ( state < 2 ) {- done( -1, e );- // Simply rethrow otherwise- } else {- throw e;- }- }- }-- return jqXHR;- },-- // Counter for holding the number of active queries- active: 0,-- // Last-Modified header cache for next request- lastModified: {},- etag: {}--});--/* Handles responses to an ajax request:- * - sets all responseXXX fields accordingly- * - finds the right dataType (mediates between content-type and expected dataType)- * - returns the corresponding response- */-function ajaxHandleResponses( s, jqXHR, responses ) {-- var ct, type, finalDataType, firstDataType,- contents = s.contents,- dataTypes = s.dataTypes,- responseFields = s.responseFields;-- // Fill responseXXX fields- for ( type in responseFields ) {- if ( type in responses ) {- jqXHR[ responseFields[type] ] = responses[ type ];- }- }-- // Remove auto dataType and get content-type in the process- while( dataTypes[ 0 ] === "*" ) {- dataTypes.shift();- if ( ct === undefined ) {- ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );- }- }-- // Check if we're dealing with a known content-type- if ( ct ) {- for ( type in contents ) {- if ( contents[ type ] && contents[ type ].test( ct ) ) {- dataTypes.unshift( type );- break;- }- }- }-- // Check to see if we have a response for the expected dataType- if ( dataTypes[ 0 ] in responses ) {- finalDataType = dataTypes[ 0 ];- } else {- // Try convertible dataTypes- for ( type in responses ) {- if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {- finalDataType = type;- break;- }- if ( !firstDataType ) {- firstDataType = type;- }- }- // Or just use first one- finalDataType = finalDataType || firstDataType;- }-- // If we found a dataType- // We add the dataType to the list if needed- // and return the corresponding response- if ( finalDataType ) {- if ( finalDataType !== dataTypes[ 0 ] ) {- dataTypes.unshift( finalDataType );- }- return responses[ finalDataType ];- }-}--// Chain conversions given the request and the original response-function ajaxConvert( s, response ) {-- var conv, conv2, current, tmp,- // Work with a copy of dataTypes in case we need to modify it for conversion- dataTypes = s.dataTypes.slice(),- prev = dataTypes[ 0 ],- converters = {},- i = 0;-- // Apply the dataFilter if provided- if ( s.dataFilter ) {- response = s.dataFilter( response, s.dataType );- }-- // Create converters map with lowercased keys- if ( dataTypes[ 1 ] ) {- for ( conv in s.converters ) {- converters[ conv.toLowerCase() ] = s.converters[ conv ];- }- }-- // Convert to each sequential dataType, tolerating list modification- for ( ; (current = dataTypes[++i]); ) {-- // There's only work to do if current dataType is non-auto- if ( current !== "*" ) {-- // Convert response if prev dataType is non-auto and differs from current- if ( prev !== "*" && prev !== current ) {-- // Seek a direct converter- conv = converters[ prev + " " + current ] || converters[ "* " + current ];-- // If none found, seek a pair- if ( !conv ) {- for ( conv2 in converters ) {-- // If conv2 outputs current- tmp = conv2.split(" ");- if ( tmp[ 1 ] === current ) {-- // If prev can be converted to accepted input- conv = converters[ prev + " " + tmp[ 0 ] ] ||- converters[ "* " + tmp[ 0 ] ];- if ( conv ) {- // Condense equivalence converters- if ( conv === true ) {- conv = converters[ conv2 ];-- // Otherwise, insert the intermediate dataType- } else if ( converters[ conv2 ] !== true ) {- current = tmp[ 0 ];- dataTypes.splice( i--, 0, current );- }-- break;- }- }- }- }-- // Apply converter (if not an equivalence)- if ( conv !== true ) {-- // Unless errors are allowed to bubble, catch and return them- if ( conv && s["throws"] ) {- response = conv( response );- } else {- try {- response = conv( response );- } catch ( e ) {- return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };- }- }- }- }-- // Update prev for next iteration- prev = current;- }- }-- return { state: "success", data: response };-}-var oldCallbacks = [],- rquestion = /\?/,- rjsonp = /(=)\?(?=&|$)|\?\?/,- nonce = jQuery.now();--// Default jsonp settings-jQuery.ajaxSetup({- jsonp: "callback",- jsonpCallback: function() {- var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );- this[ callback ] = true;- return callback;- }-});--// Detect, normalize options and install callbacks for jsonp requests-jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {-- var callbackName, overwritten, responseContainer,- data = s.data,- url = s.url,- hasCallback = s.jsonp !== false,- replaceInUrl = hasCallback && rjsonp.test( url ),- replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&- !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&- rjsonp.test( data );-- // Handle iff the expected data type is "jsonp" or we have a parameter to set- if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {-- // Get callback name, remembering preexisting value associated with it- callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?- s.jsonpCallback() :- s.jsonpCallback;- overwritten = window[ callbackName ];-- // Insert callback into url or form data- if ( replaceInUrl ) {- s.url = url.replace( rjsonp, "$1" + callbackName );- } else if ( replaceInData ) {- s.data = data.replace( rjsonp, "$1" + callbackName );- } else if ( hasCallback ) {- s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;- }-- // Use data converter to retrieve json after script execution- s.converters["script json"] = function() {- if ( !responseContainer ) {- jQuery.error( callbackName + " was not called" );- }- return responseContainer[ 0 ];- };-- // force json dataType- s.dataTypes[ 0 ] = "json";-- // Install callback- window[ callbackName ] = function() {- responseContainer = arguments;- };-- // Clean-up function (fires after converters)- jqXHR.always(function() {- // Restore preexisting value- window[ callbackName ] = overwritten;-- // Save back as free- if ( s[ callbackName ] ) {- // make sure that re-using the options doesn't screw things around- s.jsonpCallback = originalSettings.jsonpCallback;-- // save the callback name for future use- oldCallbacks.push( callbackName );- }-- // Call if it was a function and we have a response- if ( responseContainer && jQuery.isFunction( overwritten ) ) {- overwritten( responseContainer[ 0 ] );- }-- responseContainer = overwritten = undefined;- });-- // Delegate to script- return "script";- }-});-// Install script dataType-jQuery.ajaxSetup({- accepts: {- script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"- },- contents: {- script: /javascript|ecmascript/- },- converters: {- "text script": function( text ) {- jQuery.globalEval( text );- return text;- }- }-});--// Handle cache's special case and global-jQuery.ajaxPrefilter( "script", function( s ) {- if ( s.cache === undefined ) {- s.cache = false;- }- if ( s.crossDomain ) {- s.type = "GET";- s.global = false;- }-});--// Bind script tag hack transport-jQuery.ajaxTransport( "script", function(s) {-- // This transport only deals with cross domain requests- if ( s.crossDomain ) {-- var script,- head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;-- return {-- send: function( _, callback ) {-- script = document.createElement( "script" );-- script.async = "async";-- if ( s.scriptCharset ) {- script.charset = s.scriptCharset;- }-- script.src = s.url;-- // Attach handlers for all browsers- script.onload = script.onreadystatechange = function( _, isAbort ) {-- if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {-- // Handle memory leak in IE- script.onload = script.onreadystatechange = null;-- // Remove the script- if ( head && script.parentNode ) {- head.removeChild( script );- }-- // Dereference the script- script = undefined;-- // Callback if not abort- if ( !isAbort ) {- callback( 200, "success" );- }- }- };- // Use insertBefore instead of appendChild to circumvent an IE6 bug.- // This arises when a base node is used (#2709 and #4378).- head.insertBefore( script, head.firstChild );- },-- abort: function() {- if ( script ) {- script.onload( 0, 1 );- }- }- };- }-});-var xhrCallbacks,- // #5280: Internet Explorer will keep connections alive if we don't abort on unload- xhrOnUnloadAbort = window.ActiveXObject ? function() {- // Abort all pending requests- for ( var key in xhrCallbacks ) {- xhrCallbacks[ key ]( 0, 1 );- }- } : false,- xhrId = 0;--// Functions to create xhrs-function createStandardXHR() {- try {- return new window.XMLHttpRequest();- } catch( e ) {}-}--function createActiveXHR() {- try {- return new window.ActiveXObject( "Microsoft.XMLHTTP" );- } catch( e ) {}-}--// Create the request object-// (This is still attached to ajaxSettings for backward compatibility)-jQuery.ajaxSettings.xhr = window.ActiveXObject ?- /* Microsoft failed to properly- * implement the XMLHttpRequest in IE7 (can't request local files),- * so we use the ActiveXObject when it is available- * Additionally XMLHttpRequest can be disabled in IE7/IE8 so- * we need a fallback.- */- function() {- return !this.isLocal && createStandardXHR() || createActiveXHR();- } :- // For all other browsers, use the standard XMLHttpRequest object- createStandardXHR;--// Determine support properties-(function( xhr ) {- jQuery.extend( jQuery.support, {- ajax: !!xhr,- cors: !!xhr && ( "withCredentials" in xhr )- });-})( jQuery.ajaxSettings.xhr() );--// Create transport if the browser can provide an xhr-if ( jQuery.support.ajax ) {-- jQuery.ajaxTransport(function( s ) {- // Cross domain only allowed if supported through XMLHttpRequest- if ( !s.crossDomain || jQuery.support.cors ) {-- var callback;-- return {- send: function( headers, complete ) {-- // Get a new xhr- var handle, i,- xhr = s.xhr();-- // Open the socket- // Passing null username, generates a login popup on Opera (#2865)- if ( s.username ) {- xhr.open( s.type, s.url, s.async, s.username, s.password );- } else {- xhr.open( s.type, s.url, s.async );- }-- // Apply custom fields if provided- if ( s.xhrFields ) {- for ( i in s.xhrFields ) {- xhr[ i ] = s.xhrFields[ i ];- }- }-- // Override mime type if needed- if ( s.mimeType && xhr.overrideMimeType ) {- xhr.overrideMimeType( s.mimeType );- }-- // X-Requested-With header- // For cross-domain requests, seeing as conditions for a preflight are- // akin to a jigsaw puzzle, we simply never set it to be sure.- // (it can always be set on a per-request basis or even using ajaxSetup)- // For same-domain requests, won't change header if already provided.- if ( !s.crossDomain && !headers["X-Requested-With"] ) {- headers[ "X-Requested-With" ] = "XMLHttpRequest";- }-- // Need an extra try/catch for cross domain requests in Firefox 3- try {- for ( i in headers ) {- xhr.setRequestHeader( i, headers[ i ] );- }- } catch( _ ) {}-- // Do send the request- // This may raise an exception which is actually- // handled in jQuery.ajax (so no try/catch here)- xhr.send( ( s.hasContent && s.data ) || null );-- // Listener- callback = function( _, isAbort ) {-- var status,- statusText,- responseHeaders,- responses,- xml;-- // Firefox throws exceptions when accessing properties- // of an xhr when a network error occurred- // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)- try {-- // Was never called and is aborted or complete- if ( callback && ( isAbort || xhr.readyState === 4 ) ) {-- // Only called once- callback = undefined;-- // Do not keep as active anymore- if ( handle ) {- xhr.onreadystatechange = jQuery.noop;- if ( xhrOnUnloadAbort ) {- delete xhrCallbacks[ handle ];- }- }-- // If it's an abort- if ( isAbort ) {- // Abort it manually if needed- if ( xhr.readyState !== 4 ) {- xhr.abort();- }- } else {- status = xhr.status;- responseHeaders = xhr.getAllResponseHeaders();- responses = {};- xml = xhr.responseXML;-- // Construct response list- if ( xml && xml.documentElement /* #4958 */ ) {- responses.xml = xml;- }-- // When requesting binary data, IE6-9 will throw an exception- // on any attempt to access responseText (#11426)- try {- responses.text = xhr.responseText;- } catch( e ) {- }-- // Firefox throws an exception when accessing- // statusText for faulty cross-domain requests- try {- statusText = xhr.statusText;- } catch( e ) {- // We normalize with Webkit giving an empty statusText- statusText = "";- }-- // Filter status for non standard behaviors-- // If the request is local and we have data: assume a success- // (success with no data won't get notified, that's the best we- // can do given current implementations)- if ( !status && s.isLocal && !s.crossDomain ) {- status = responses.text ? 200 : 404;- // IE - #1450: sometimes returns 1223 when it should be 204- } else if ( status === 1223 ) {- status = 204;- }- }- }- } catch( firefoxAccessException ) {- if ( !isAbort ) {- complete( -1, firefoxAccessException );- }- }-- // Call complete if needed- if ( responses ) {- complete( status, statusText, responses, responseHeaders );- }- };-- if ( !s.async ) {- // if we're in sync mode we fire the callback- callback();- } else if ( xhr.readyState === 4 ) {- // (IE6 & IE7) if it's in cache and has been- // retrieved directly we need to fire the callback- setTimeout( callback, 0 );- } else {- handle = ++xhrId;- if ( xhrOnUnloadAbort ) {- // Create the active xhrs callbacks list if needed- // and attach the unload handler- if ( !xhrCallbacks ) {- xhrCallbacks = {};- jQuery( window ).unload( xhrOnUnloadAbort );- }- // Add to list of active xhrs callbacks- xhrCallbacks[ handle ] = callback;- }- xhr.onreadystatechange = callback;- }- },-- abort: function() {- if ( callback ) {- callback(0,1);- }- }- };- }- });-}-var fxNow, timerId,- rfxtypes = /^(?:toggle|show|hide)$/,- rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),- rrun = /queueHooks$/,- animationPrefilters = [ defaultPrefilter ],- tweeners = {- "*": [function( prop, value ) {- var end, unit,- tween = this.createTween( prop, value ),- parts = rfxnum.exec( value ),- target = tween.cur(),- start = +target || 0,- scale = 1,- maxIterations = 20;-- if ( parts ) {- end = +parts[2];- unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );-- // We need to compute starting value- if ( unit !== "px" && start ) {- // Iteratively approximate from a nonzero starting point- // Prefer the current property, because this process will be trivial if it uses the same units- // Fallback to end or a simple constant- start = jQuery.css( tween.elem, prop, true ) || end || 1;-- do {- // If previous iteration zeroed out, double until we get *something*- // Use a string for doubling factor so we don't accidentally see scale as unchanged below- scale = scale || ".5";-- // Adjust and apply- start = start / scale;- jQuery.style( tween.elem, prop, start + unit );-- // Update scale, tolerating zero or NaN from tween.cur()- // And breaking the loop if scale is unchanged or perfect, or if we've just had enough- } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );- }-- tween.unit = unit;- tween.start = start;- // If a +=/-= token was provided, we're doing a relative animation- tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;- }- return tween;- }]- };--// Animations created synchronously will run synchronously-function createFxNow() {- setTimeout(function() {- fxNow = undefined;- }, 0 );- return ( fxNow = jQuery.now() );-}--function createTweens( animation, props ) {- jQuery.each( props, function( prop, value ) {- var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),- index = 0,- length = collection.length;- for ( ; index < length; index++ ) {- if ( collection[ index ].call( animation, prop, value ) ) {-- // we're done with this property- return;- }- }- });-}--function Animation( elem, properties, options ) {- var result,- index = 0,- tweenerIndex = 0,- length = animationPrefilters.length,- deferred = jQuery.Deferred().always( function() {- // don't match elem in the :animated selector- delete tick.elem;- }),- tick = function() {- var currentTime = fxNow || createFxNow(),- remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),- // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)- temp = remaining / animation.duration || 0,- percent = 1 - temp,- index = 0,- length = animation.tweens.length;-- for ( ; index < length ; index++ ) {- animation.tweens[ index ].run( percent );- }-- deferred.notifyWith( elem, [ animation, percent, remaining ]);-- if ( percent < 1 && length ) {- return remaining;- } else {- deferred.resolveWith( elem, [ animation ] );- return false;- }- },- animation = deferred.promise({- elem: elem,- props: jQuery.extend( {}, properties ),- opts: jQuery.extend( true, { specialEasing: {} }, options ),- originalProperties: properties,- originalOptions: options,- startTime: fxNow || createFxNow(),- duration: options.duration,- tweens: [],- createTween: function( prop, end, easing ) {- var tween = jQuery.Tween( elem, animation.opts, prop, end,- animation.opts.specialEasing[ prop ] || animation.opts.easing );- animation.tweens.push( tween );- return tween;- },- stop: function( gotoEnd ) {- var index = 0,- // if we are going to the end, we want to run all the tweens- // otherwise we skip this part- length = gotoEnd ? animation.tweens.length : 0;-- for ( ; index < length ; index++ ) {- animation.tweens[ index ].run( 1 );- }-- // resolve when we played the last frame- // otherwise, reject- if ( gotoEnd ) {- deferred.resolveWith( elem, [ animation, gotoEnd ] );- } else {- deferred.rejectWith( elem, [ animation, gotoEnd ] );- }- return this;- }- }),- props = animation.props;-- propFilter( props, animation.opts.specialEasing );-- for ( ; index < length ; index++ ) {- result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );- if ( result ) {- return result;- }- }-- createTweens( animation, props );-- if ( jQuery.isFunction( animation.opts.start ) ) {- animation.opts.start.call( elem, animation );- }-- jQuery.fx.timer(- jQuery.extend( tick, {- anim: animation,- queue: animation.opts.queue,- elem: elem- })- );-- // attach callbacks from options- return animation.progress( animation.opts.progress )- .done( animation.opts.done, animation.opts.complete )- .fail( animation.opts.fail )- .always( animation.opts.always );-}--function propFilter( props, specialEasing ) {- var index, name, easing, value, hooks;-- // camelCase, specialEasing and expand cssHook pass- for ( index in props ) {- name = jQuery.camelCase( index );- easing = specialEasing[ name ];- value = props[ index ];- if ( jQuery.isArray( value ) ) {- easing = value[ 1 ];- value = props[ index ] = value[ 0 ];- }-- if ( index !== name ) {- props[ name ] = value;- delete props[ index ];- }-- hooks = jQuery.cssHooks[ name ];- if ( hooks && "expand" in hooks ) {- value = hooks.expand( value );- delete props[ name ];-- // not quite $.extend, this wont overwrite keys already present.- // also - reusing 'index' from above because we have the correct "name"- for ( index in value ) {- if ( !( index in props ) ) {- props[ index ] = value[ index ];- specialEasing[ index ] = easing;- }- }- } else {- specialEasing[ name ] = easing;- }- }-}--jQuery.Animation = jQuery.extend( Animation, {-- tweener: function( props, callback ) {- if ( jQuery.isFunction( props ) ) {- callback = props;- props = [ "*" ];- } else {- props = props.split(" ");- }-- var prop,- index = 0,- length = props.length;-- for ( ; index < length ; index++ ) {- prop = props[ index ];- tweeners[ prop ] = tweeners[ prop ] || [];- tweeners[ prop ].unshift( callback );- }- },-- prefilter: function( callback, prepend ) {- if ( prepend ) {- animationPrefilters.unshift( callback );- } else {- animationPrefilters.push( callback );- }- }-});--function defaultPrefilter( elem, props, opts ) {- var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,- anim = this,- style = elem.style,- orig = {},- handled = [],- hidden = elem.nodeType && isHidden( elem );-- // handle queue: false promises- if ( !opts.queue ) {- hooks = jQuery._queueHooks( elem, "fx" );- if ( hooks.unqueued == null ) {- hooks.unqueued = 0;- oldfire = hooks.empty.fire;- hooks.empty.fire = function() {- if ( !hooks.unqueued ) {- oldfire();- }- };- }- hooks.unqueued++;-- anim.always(function() {- // doing this makes sure that the complete handler will be called- // before this completes- anim.always(function() {- hooks.unqueued--;- if ( !jQuery.queue( elem, "fx" ).length ) {- hooks.empty.fire();- }- });- });- }-- // height/width overflow pass- if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {- // Make sure that nothing sneaks out- // Record all 3 overflow attributes because IE does not- // change the overflow attribute when overflowX and- // overflowY are set to the same value- opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];-- // Set display property to inline-block for height/width- // animations on inline elements that are having width/height animated- if ( jQuery.css( elem, "display" ) === "inline" &&- jQuery.css( elem, "float" ) === "none" ) {-- // inline-level elements accept inline-block;- // block-level elements need to be inline with layout- if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {- style.display = "inline-block";-- } else {- style.zoom = 1;- }- }- }-- if ( opts.overflow ) {- style.overflow = "hidden";- if ( !jQuery.support.shrinkWrapBlocks ) {- anim.done(function() {- style.overflow = opts.overflow[ 0 ];- style.overflowX = opts.overflow[ 1 ];- style.overflowY = opts.overflow[ 2 ];- });- }- }--- // show/hide pass- for ( index in props ) {- value = props[ index ];- if ( rfxtypes.exec( value ) ) {- delete props[ index ];- toggle = toggle || value === "toggle";- if ( value === ( hidden ? "hide" : "show" ) ) {- continue;- }- handled.push( index );- }- }-- length = handled.length;- if ( length ) {- dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );- if ( "hidden" in dataShow ) {- hidden = dataShow.hidden;- }-- // store state if its toggle - enables .stop().toggle() to "reverse"- if ( toggle ) {- dataShow.hidden = !hidden;- }- if ( hidden ) {- jQuery( elem ).show();- } else {- anim.done(function() {- jQuery( elem ).hide();- });- }- anim.done(function() {- var prop;- jQuery.removeData( elem, "fxshow", true );- for ( prop in orig ) {- jQuery.style( elem, prop, orig[ prop ] );- }- });- for ( index = 0 ; index < length ; index++ ) {- prop = handled[ index ];- tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );- orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );-- if ( !( prop in dataShow ) ) {- dataShow[ prop ] = tween.start;- if ( hidden ) {- tween.end = tween.start;- tween.start = prop === "width" || prop === "height" ? 1 : 0;- }- }- }- }-}--function Tween( elem, options, prop, end, easing ) {- return new Tween.prototype.init( elem, options, prop, end, easing );-}-jQuery.Tween = Tween;--Tween.prototype = {- constructor: Tween,- init: function( elem, options, prop, end, easing, unit ) {- this.elem = elem;- this.prop = prop;- this.easing = easing || "swing";- this.options = options;- this.start = this.now = this.cur();- this.end = end;- this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );- },- cur: function() {- var hooks = Tween.propHooks[ this.prop ];-- return hooks && hooks.get ?- hooks.get( this ) :- Tween.propHooks._default.get( this );- },- run: function( percent ) {- var eased,- hooks = Tween.propHooks[ this.prop ];-- if ( this.options.duration ) {- this.pos = eased = jQuery.easing[ this.easing ](- percent, this.options.duration * percent, 0, 1, this.options.duration- );- } else {- this.pos = eased = percent;- }- this.now = ( this.end - this.start ) * eased + this.start;-- if ( this.options.step ) {- this.options.step.call( this.elem, this.now, this );- }-- if ( hooks && hooks.set ) {- hooks.set( this );- } else {- Tween.propHooks._default.set( this );- }- return this;- }-};--Tween.prototype.init.prototype = Tween.prototype;--Tween.propHooks = {- _default: {- get: function( tween ) {- var result;-- if ( tween.elem[ tween.prop ] != null &&- (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {- return tween.elem[ tween.prop ];- }-- // passing any value as a 4th parameter to .css will automatically- // attempt a parseFloat and fallback to a string if the parse fails- // so, simple values such as "10px" are parsed to Float.- // complex values such as "rotate(1rad)" are returned as is.- result = jQuery.css( tween.elem, tween.prop, false, "" );- // Empty strings, null, undefined and "auto" are converted to 0.- return !result || result === "auto" ? 0 : result;- },- set: function( tween ) {- // use step hook for back compat - use cssHook if its there - use .style if its- // available and use plain properties where available- if ( jQuery.fx.step[ tween.prop ] ) {- jQuery.fx.step[ tween.prop ]( tween );- } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {- jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );- } else {- tween.elem[ tween.prop ] = tween.now;- }- }- }-};--// Remove in 2.0 - this supports IE8's panic based approach-// to setting things on disconnected nodes--Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {- set: function( tween ) {- if ( tween.elem.nodeType && tween.elem.parentNode ) {- tween.elem[ tween.prop ] = tween.now;- }- }-};--jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {- var cssFn = jQuery.fn[ name ];- jQuery.fn[ name ] = function( speed, easing, callback ) {- return speed == null || typeof speed === "boolean" ||- // special check for .toggle( handler, handler, ... )- ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?- cssFn.apply( this, arguments ) :- this.animate( genFx( name, true ), speed, easing, callback );- };-});--jQuery.fn.extend({- fadeTo: function( speed, to, easing, callback ) {-- // show any hidden elements after setting opacity to 0- return this.filter( isHidden ).css( "opacity", 0 ).show()-- // animate to the value specified- .end().animate({ opacity: to }, speed, easing, callback );- },- animate: function( prop, speed, easing, callback ) {- var empty = jQuery.isEmptyObject( prop ),- optall = jQuery.speed( speed, easing, callback ),- doAnimation = function() {- // Operate on a copy of prop so per-property easing won't be lost- var anim = Animation( this, jQuery.extend( {}, prop ), optall );-- // Empty animations resolve immediately- if ( empty ) {- anim.stop( true );- }- };-- return empty || optall.queue === false ?- this.each( doAnimation ) :- this.queue( optall.queue, doAnimation );- },- stop: function( type, clearQueue, gotoEnd ) {- var stopQueue = function( hooks ) {- var stop = hooks.stop;- delete hooks.stop;- stop( gotoEnd );- };-- if ( typeof type !== "string" ) {- gotoEnd = clearQueue;- clearQueue = type;- type = undefined;- }- if ( clearQueue && type !== false ) {- this.queue( type || "fx", [] );- }-- return this.each(function() {- var dequeue = true,- index = type != null && type + "queueHooks",- timers = jQuery.timers,- data = jQuery._data( this );-- if ( index ) {- if ( data[ index ] && data[ index ].stop ) {- stopQueue( data[ index ] );- }- } else {- for ( index in data ) {- if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {- stopQueue( data[ index ] );- }- }- }-- for ( index = timers.length; index--; ) {- if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {- timers[ index ].anim.stop( gotoEnd );- dequeue = false;- timers.splice( index, 1 );- }- }-- // start the next in the queue if the last step wasn't forced- // timers currently will call their complete callbacks, which will dequeue- // but only if they were gotoEnd- if ( dequeue || !gotoEnd ) {- jQuery.dequeue( this, type );- }- });- }-});--// Generate parameters to create a standard animation-function genFx( type, includeWidth ) {- var which,- attrs = { height: type },- i = 0;-- // if we include width, step value is 1 to do all cssExpand values,- // if we don't include width, step value is 2 to skip over Left and Right- includeWidth = includeWidth? 1 : 0;- for( ; i < 4 ; i += 2 - includeWidth ) {- which = cssExpand[ i ];- attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;- }-- if ( includeWidth ) {- attrs.opacity = attrs.width = type;- }-- return attrs;-}--// Generate shortcuts for custom animations-jQuery.each({- slideDown: genFx("show"),- slideUp: genFx("hide"),- slideToggle: genFx("toggle"),- fadeIn: { opacity: "show" },- fadeOut: { opacity: "hide" },- fadeToggle: { opacity: "toggle" }-}, function( name, props ) {- jQuery.fn[ name ] = function( speed, easing, callback ) {- return this.animate( props, speed, easing, callback );- };-});--jQuery.speed = function( speed, easing, fn ) {- var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {- complete: fn || !fn && easing ||- jQuery.isFunction( speed ) && speed,- duration: speed,- easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing- };-- opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :- opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;-- // normalize opt.queue - true/undefined/null -> "fx"- if ( opt.queue == null || opt.queue === true ) {- opt.queue = "fx";- }-- // Queueing- opt.old = opt.complete;-- opt.complete = function() {- if ( jQuery.isFunction( opt.old ) ) {- opt.old.call( this );- }-- if ( opt.queue ) {- jQuery.dequeue( this, opt.queue );- }- };-- return opt;-};--jQuery.easing = {- linear: function( p ) {- return p;- },- swing: function( p ) {- return 0.5 - Math.cos( p*Math.PI ) / 2;- }-};--jQuery.timers = [];-jQuery.fx = Tween.prototype.init;-jQuery.fx.tick = function() {- var timer,- timers = jQuery.timers,- i = 0;-- fxNow = jQuery.now();-- for ( ; i < timers.length; i++ ) {- timer = timers[ i ];- // Checks the timer has not already been removed- if ( !timer() && timers[ i ] === timer ) {- timers.splice( i--, 1 );- }- }-- if ( !timers.length ) {- jQuery.fx.stop();- }- fxNow = undefined;-};--jQuery.fx.timer = function( timer ) {- if ( timer() && jQuery.timers.push( timer ) && !timerId ) {- timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );- }-};--jQuery.fx.interval = 13;--jQuery.fx.stop = function() {- clearInterval( timerId );- timerId = null;-};--jQuery.fx.speeds = {- slow: 600,- fast: 200,- // Default speed- _default: 400-};--// Back Compat <1.8 extension point-jQuery.fx.step = {};--if ( jQuery.expr && jQuery.expr.filters ) {- jQuery.expr.filters.animated = function( elem ) {- return jQuery.grep(jQuery.timers, function( fn ) {- return elem === fn.elem;- }).length;- };-}-var rroot = /^(?:body|html)$/i;--jQuery.fn.offset = function( options ) {- if ( arguments.length ) {- return options === undefined ?- this :- this.each(function( i ) {- jQuery.offset.setOffset( this, options, i );- });- }-- var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,- box = { top: 0, left: 0 },- elem = this[ 0 ],- doc = elem && elem.ownerDocument;-- if ( !doc ) {- return;- }-- if ( (body = doc.body) === elem ) {- return jQuery.offset.bodyOffset( elem );- }-- docElem = doc.documentElement;-- // Make sure it's not a disconnected DOM node- if ( !jQuery.contains( docElem, elem ) ) {- return box;- }-- // If we don't have gBCR, just use 0,0 rather than error- // BlackBerry 5, iOS 3 (original iPhone)- if ( typeof elem.getBoundingClientRect !== "undefined" ) {- box = elem.getBoundingClientRect();- }- win = getWindow( doc );- clientTop = docElem.clientTop || body.clientTop || 0;- clientLeft = docElem.clientLeft || body.clientLeft || 0;- scrollTop = win.pageYOffset || docElem.scrollTop;- scrollLeft = win.pageXOffset || docElem.scrollLeft;- return {- top: box.top + scrollTop - clientTop,- left: box.left + scrollLeft - clientLeft- };-};--jQuery.offset = {-- bodyOffset: function( body ) {- var top = body.offsetTop,- left = body.offsetLeft;-- if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {- top += parseFloat( jQuery.css(body, "marginTop") ) || 0;- left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;- }-- return { top: top, left: left };- },-- setOffset: function( elem, options, i ) {- var position = jQuery.css( elem, "position" );-- // set position first, in-case top/left are set even on static elem- if ( position === "static" ) {- elem.style.position = "relative";- }-- var curElem = jQuery( elem ),- curOffset = curElem.offset(),- curCSSTop = jQuery.css( elem, "top" ),- curCSSLeft = jQuery.css( elem, "left" ),- calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,- props = {}, curPosition = {}, curTop, curLeft;-- // need to be able to calculate position if either top or left is auto and position is either absolute or fixed- if ( calculatePosition ) {- curPosition = curElem.position();- curTop = curPosition.top;- curLeft = curPosition.left;- } else {- curTop = parseFloat( curCSSTop ) || 0;- curLeft = parseFloat( curCSSLeft ) || 0;- }-- if ( jQuery.isFunction( options ) ) {- options = options.call( elem, i, curOffset );- }-- if ( options.top != null ) {- props.top = ( options.top - curOffset.top ) + curTop;- }- if ( options.left != null ) {- props.left = ( options.left - curOffset.left ) + curLeft;- }-- if ( "using" in options ) {- options.using.call( elem, props );- } else {- curElem.css( props );- }- }-};---jQuery.fn.extend({-- position: function() {- if ( !this[0] ) {- return;- }-- var elem = this[0],-- // Get *real* offsetParent- offsetParent = this.offsetParent(),-- // Get correct offsets- offset = this.offset(),- parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();-- // Subtract element margins- // note: when an element has margin: auto the offsetLeft and marginLeft- // are the same in Safari causing offset.left to incorrectly be 0- offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;- offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;-- // Add offsetParent borders- parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;- parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;-- // Subtract the two offsets- return {- top: offset.top - parentOffset.top,- left: offset.left - parentOffset.left- };- },-- offsetParent: function() {- return this.map(function() {- var offsetParent = this.offsetParent || document.body;- while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {- offsetParent = offsetParent.offsetParent;- }- return offsetParent || document.body;- });- }-});---// Create scrollLeft and scrollTop methods-jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {- var top = /Y/.test( prop );-- jQuery.fn[ method ] = function( val ) {- return jQuery.access( this, function( elem, method, val ) {- var win = getWindow( elem );-- if ( val === undefined ) {- return win ? (prop in win) ? win[ prop ] :- win.document.documentElement[ method ] :- elem[ method ];- }-- if ( win ) {- win.scrollTo(- !top ? val : jQuery( win ).scrollLeft(),- top ? val : jQuery( win ).scrollTop()- );-- } else {- elem[ method ] = val;- }- }, method, val, arguments.length, null );- };-});--function getWindow( elem ) {- return jQuery.isWindow( elem ) ?- elem :- elem.nodeType === 9 ?- elem.defaultView || elem.parentWindow :- false;-}-// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods-jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {- jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {- // margin is only for outerHeight, outerWidth- jQuery.fn[ funcName ] = function( margin, value ) {- var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),- extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );-- return jQuery.access( this, function( elem, type, value ) {- var doc;-- if ( jQuery.isWindow( elem ) ) {- // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there- // isn't a whole lot we can do. See pull request at this URL for discussion:- // https://github.com/jquery/jquery/pull/764- return elem.document.documentElement[ "client" + name ];- }-- // Get document width or height- if ( elem.nodeType === 9 ) {- doc = elem.documentElement;-- // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest- // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.- return Math.max(- elem.body[ "scroll" + name ], doc[ "scroll" + name ],- elem.body[ "offset" + name ], doc[ "offset" + name ],- doc[ "client" + name ]- );- }-- return value === undefined ?- // Get width or height on the element, requesting but not forcing parseFloat- jQuery.css( elem, type, value, extra ) :-- // Set width or height on the element- jQuery.style( elem, type, value, extra );- }, type, chainable ? margin : undefined, chainable, null );- };- });-});-// Expose jQuery to the global object-window.jQuery = window.$ = jQuery;--// Expose jQuery as an AMD module, but only for AMD loaders that-// understand the issues with loading multiple versions of jQuery-// in a page that all might call define(). The loader will indicate-// they have special allowances for multiple jQuery versions by-// specifying define.amd.jQuery = true. Register as a named module,-// since jQuery can be concatenated with other files that may use define,-// but not use a proper concatenation script that understands anonymous-// AMD modules. A named AMD is safest and most robust way to register.-// Lowercase jquery is used because AMD module names are derived from-// file names, and jQuery is normally delivered in a lowercase file name.-// Do this after creating the global so that if an AMD module wants to call-// noConflict to hide this version of jQuery, it will work.-if ( typeof define === "function" && define.amd && define.amd.jQuery ) {- define( "jquery", [], function () { return jQuery; } );-}--})( window );
shake.cabal view
@@ -1,7 +1,7 @@ cabal-version: >= 1.10 build-type: Simple name: shake-version: 0.13.4+version: 0.14 license: BSD3 license-file: LICENSE category: Development@@ -31,33 +31,28 @@ (e.g. compiler version). homepage: https://github.com/ndmitchell/shake#readme bug-reports: https://github.com/ndmitchell/shake/issues-tested-with: GHC==7.8.2, GHC==7.6.3, GHC==7.4.2, GHC==7.2.2+tested-with: GHC==7.8.3, GHC==7.6.3, GHC==7.4.2, GHC==7.2.2 extra-source-files:- Test/C/constants.c- Test/C/constants.h- Test/C/main.c- Test/MakeTutor/Makefile- Test/MakeTutor/hellofunc.c- Test/MakeTutor/hellomake.c- Test/MakeTutor/hellomake.h- Test/Tar/list.txt- Test/Ninja/*.ninja- Test/Ninja/*.output- Test/Progress/*.prog- Paths.hs+ src/Test/C/constants.c+ src/Test/C/constants.h+ src/Test/C/main.c+ src/Test/MakeTutor/Makefile+ src/Test/MakeTutor/hellofunc.c+ src/Test/MakeTutor/hellomake.c+ src/Test/MakeTutor/hellomake.h+ src/Test/Tar/list.txt+ src/Test/Ninja/*.ninja+ src/Test/Ninja/*.output+ src/Test/Progress/*.prog+ src/Paths.hs CHANGES.txt README.md docs/Manual.md docs/Ninja.md docs/Why.md docs/shake-progress.png- js-src/jquery-1.8.3.js- js-src/flot-0.8.0.zip data-files:- html/jquery.flot.js- html/jquery.flot.stack.js- html/jquery.js html/viz.js html/profile.html html/progress.html@@ -82,6 +77,7 @@ library default-language: Haskell2010+ hs-source-dirs: src build-depends: base == 4.*, old-time,@@ -95,7 +91,10 @@ utf8-string >= 0.3, time, random,+ js-jquery,+ js-flot, transformers >= 0.2,+ extra >= 0.7, deepseq >= 1.1 if flag(portable)@@ -143,12 +142,13 @@ Development.Shake.Storage Development.Shake.Types Development.Shake.Value- General.Base General.Bilist General.Binary General.Cleanup General.Concurrent+ General.Extra General.Intern+ General.Prelude General.String General.Template General.Timing@@ -157,8 +157,15 @@ executable shake default-language: Haskell2010- main-is: Main.hs- ghc-options: -threaded -rtsopts "-with-rtsopts=-I0 -qg -qb"+ hs-source-dirs: src+ ghc-options: -main-is Run.main+ main-is: Run.hs+ ghc-options: -threaded -rtsopts+ if impl(ghc >= 7.4)+ ghc-options: "-with-rtsopts=-I0 -qg -qb"+ else+ -- -qg/-qb segfaults in GHC 7.2+ ghc-options: -with-rtsopts=-I0 build-depends: base == 4.*, old-time,@@ -172,7 +179,10 @@ utf8-string >= 0.3, time, random,+ js-jquery,+ js-flot, transformers >= 0.2,+ extra >= 0.7, deepseq >= 1.1 if flag(portable)@@ -188,14 +198,16 @@ Development.Make.Rules Development.Make.Type Development.Ninja.All- Start+ Run test-suite shake-test default-language: Haskell2010 type: exitcode-stdio-1.0+ ghc-options: -main-is Test.main main-is: Test.hs- ghc-options: -rtsopts+ hs-source-dirs: src+ ghc-options: -threaded -rtsopts build-depends: base == 4.*, old-time,@@ -209,8 +221,11 @@ utf8-string >= 0.3, time, random,+ js-jquery,+ js-flot, transformers >= 0.2, deepseq >= 1.1,+ extra >= 0.7, QuickCheck >= 2.0 if flag(portable)@@ -228,7 +243,7 @@ Development.Ninja.All Development.Ninja.Parse Development.Ninja.Type- Start+ Run Test.Type Test.Assume Test.Basic
+ src/Development/Make/All.hs view
@@ -0,0 +1,130 @@+{-# LANGUAGE RecordWildCards, PatternGuards #-}++module Development.Make.All(runMakefile) where++import Development.Shake hiding (addEnv)+import Development.Shake.FilePath+import Development.Make.Parse+import Development.Make.Env+import Development.Make.Rules+import Development.Make.Type+import qualified System.Directory as IO+import Data.List+import Data.Maybe+import Data.Tuple.Extra+import Control.Monad+import System.Process+import System.Exit+import System.Environment.Extra+import Control.Monad.Trans.State.Strict+++runMakefile :: FilePath -> [String] -> IO (Rules ())+runMakefile file args = do+ env <- defaultEnv+ mk <- parse file+ rs <- eval env mk+ return $ do+ defaultRuleFile_+ case filter (not . isPrefixOf "." . target) rs of+ Ruler x _ _ : _ | null args, '%' `notElem` x -> want_ [x]+ _ -> return ()+ mapM_ (want_ . return) args+ convert rs+++data Ruler = Ruler+ {target :: String+ ,prereq :: (Env, Expr) -- Env is the Env at this point+ ,cmds :: (Env, [Command]) -- Env is the Env at the end+ }+++eval :: Env -> Makefile -> IO [Ruler]+eval env (Makefile xs) = do+ (rs, env) <- runStateT (fmap concat $ mapM f xs) env+ return [r{cmds=(env,snd $ cmds r)} | r <- rs]+ where+ f :: Stmt -> StateT Env IO [Ruler]+ f Assign{..} = do+ e <- get+ e <- liftIO $ addEnv name assign expr e+ put e+ return []++ f Rule{..} = do+ e <- get+ target <- liftIO $ fmap words $ askEnv e targets+ return $ map (\t -> Ruler t (e, prerequisites) (undefined, commands)) target+++convert :: [Ruler] -> Rules ()+convert rs = match ??> run+ where+ match s = any (isJust . check s) rs+ check s r = makePattern (target r) s++ run target = do+ let phony = has False ".PHONY" target+ let silent = has True ".SILENT" target+ (deps, cmds) <- fmap (first concat . second concat . unzip) $ forM rs $ \r ->+ case check target r of+ Nothing -> return ([], [])+ Just op -> do+ let (preEnv,preExp) = prereq r+ env <- liftIO $ addEnv "@" Equals (Lit target) preEnv+ pre <- liftIO $ askEnv env preExp+ vp <- liftIO $ fmap splitSearchPath $ askEnv env $ Var "VPATH"+ pre <- mapM (vpath vp) $ words $ op pre+ return (pre, [cmds r])+ mapM_ (need_ . return) deps+ forM_ cmds $ \(env,cmd) -> do+ env <- liftIO $ addEnv "@" Equals (Lit target) env+ env <- liftIO $ addEnv "^" Equals (Lit $ unwords deps) env+ env <- liftIO $ addEnv "<" Equals (Lit $ head $ deps ++ [""]) env+ forM_ cmd $ \c ->+ case c of+ Expr c -> (if silent then quietly else id) $+ execCommand =<< liftIO (askEnv env c)+ return $ if phony then Phony else NotPhony++ has auto name target =+ or [(null ws && auto) || target `elem` ws | Ruler t (_,Lit s) _ <- rs, t == name, let ws = words s]+++execCommand :: String -> Action ()+execCommand x = do+ res <- if "@" `isPrefixOf` x then sys $ drop 1 x+ else putNormal x >> sys x+ when (res /= ExitSuccess) $+ error $ "System command failed: " ++ x+ where sys = quietly . traced (unwords $ take 1 $ words x) . system+++makePattern :: String -> FilePath -> Maybe (String -> String)+makePattern pat v = case break (== '%') pat of+ (pre,'%':post) -> if pre `isPrefixOf` v && post `isSuffixOf` v && rest >= 0+ then Just $ concatMap (\x -> if x == '%' then subs else [x])+ else Nothing+ where rest = length v - (length pre + length post)+ subs = take rest $ drop (length pre) v+ otherwise -> if pat == v then Just id else Nothing+++vpath :: [FilePath] -> FilePath -> Action FilePath+vpath [] y = return y+vpath (x:xs) y = do+ b <- doesFileExist $ x </> y+ if b then return $ x </> y else vpath xs y+++defaultEnv :: IO Env+defaultEnv = do+ exePath <- getExecutablePath+ env <- getEnvironment+ cur <- IO.getCurrentDirectory+ return $ newEnv $+ ("EXE",if null exe then "" else "." ++ exe) :+ ("MAKE",normaliseEx exePath) :+ ("CURDIR",normaliseEx cur) :+ env
+ src/Development/Make/Env.hs view
@@ -0,0 +1,40 @@+{-# LANGUAGE PatternGuards #-}++-- | The IO in this module is only to evaluate an envrionment variable,+-- the 'Env' itself it passed around purely.+module Development.Make.Env(Env, newEnv, addEnv, askEnv) where++import Development.Make.Type+import Data.Maybe+import qualified Data.HashMap.Strict as Map+++newtype Env = Env (Map.HashMap String (Assign,Expr))++newEnv :: [(String,String)] -> Env+newEnv xs = Env $ Map.fromList [(a,(Equals,Lit b)) | (a,b) <- xs]+++addEnv :: String -> Assign -> Expr -> Env -> IO Env+addEnv name ass val env@(Env e) = case ass of+ QuestionEquals -> if isJust $ Map.lookup name e then return env else addEnv name Equals val env+ Equals -> return $ Env $ Map.insert name (Equals,val) e+ ColonEquals -> do l <- askEnv env val; return $ Env $ Map.insert name (ColonEquals,Lit l) e+ PlusEquals -> case Map.lookup name e of+ Just (Equals,x) -> return $ Env $ Map.insert name (Equals,Concat [x,Lit " ",val]) e+ Just (ColonEquals,x) -> do l <- askEnv env val; return $ Env $ Map.insert name (ColonEquals,Concat [x,Lit " ",Lit l]) e+ _ -> addEnv name Equals val env+++askEnv :: Env -> Expr -> IO String+askEnv (Env e) x = do+ res <- f [] x+ case simplifyExpr res of+ Lit x -> return x+ x -> error $ "Internal error in askEnv, " ++ show x+ where+ f seen (Var x) | x `elem` seen = error $ "Recursion in variables, " ++ show seen+ | Just (_,y) <- Map.lookup x e = f (x:seen) y+ | otherwise = return $ Lit ""+ f seen x = descendExprM (f seen) x+
+ src/Development/Make/Parse.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE PatternGuards #-}++module Development.Make.Parse(parse) where++import Development.Make.Type+import Data.Char+import Data.List+import Data.Maybe+++trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse+++parse :: FilePath -> IO Makefile+parse file = do+ src <- if file == "-" then getContents else readFile file+ return $ parseMakefile src+++parseMakefile :: String -> Makefile+parseMakefile xs = Makefile $ rejoin $ concatMap parse $ map comments $ continuations $ lines xs+ where+ continuations (x:y:xs) | "\\" `isSuffixOf` x = continuations $ (init x ++ dropWhile isSpace y):xs+ continuations (x:xs) = x : continuations xs+ continuations [] = []++ comments = takeWhile (/= '#')++ parse x | all isSpace x = []+ | all isSpace $ take 1 x = [Right $ parseCommand $ trim x]+ | (a,b) <- break (== ';') x = Left (parseStmt a) : [Right $ parseCommand $ trim $ drop 1 b | b /= ""]++ rejoin (Left r@Rule{}:Right e:xs) = rejoin $ Left r{commands = commands r ++ [e]} : xs+ rejoin (Right e:xs) = error $ "Command must be under a rule: " ++ show e+ rejoin (Left r:xs) = r : rejoin xs+ rejoin [] = []+++parseStmt :: String -> Stmt+parseStmt x+ | (a,'=':b) <- break (== '=') x, ':' `notElem` a =+ if "+" `isSuffixOf` a then Assign (trim $ init a) PlusEquals (parseExpr $ trim b)+ else if "?" `isSuffixOf` a then Assign (trim $ init a) QuestionEquals (parseExpr $ trim b)+ else Assign (trim a) Equals (parseExpr $ trim b)+ | (a,':':b) <- break (== ':') x = case b of+ '=':b -> Assign (trim a) ColonEquals (parseExpr $ trim b)+ ':':'=':b -> Assign (trim a) ColonEquals (parseExpr $ trim b)+ _ -> Rule (parseExpr $ trim a) (parseExpr $ trim $ fromMaybe b $ stripPrefix ":" b) []+ | otherwise = error $ "Invalid statement: " ++ x+++parseExpr :: String -> Expr+parseExpr x = simplifyExpr $ Concat $ f x+ where+ f ('$':'$':x) = Lit "$" : f x+ f ('$':'(':xs) = case break (== ')') xs of+ (var,')':rest) -> parseVar var : f rest+ _ -> error $ "Couldn't find trailing `)' after " ++ xs+ f ('$':'{':xs) = case break (== '}') xs of+ (var,'}':rest) -> parseVar var : f rest+ _ -> error $ "Couldn't find trailing `}' after " ++ xs+ f ('$':x:xs) = Var [x] : f xs+ f (x:xs) = Lit [x] : f xs+ f [] = []+++parseVar :: String -> Expr+parseVar x = Var x+++parseCommand :: String -> Command+parseCommand = Expr . parseExpr
+ src/Development/Make/Rules.hs view
@@ -0,0 +1,62 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable #-}++-- | These are the additional rule types required by Makefile+module Development.Make.Rules(+ need_, want_,+ defaultRuleFile_,+ (??>), Phony(..)+ ) where++import Control.Monad.IO.Class+import System.Directory++import Development.Shake.Core+import General.String+import Development.Shake.Classes+import Development.Shake.FilePath+import Development.Shake.FileInfo++infix 1 ??>++---------------------------------------------------------------------+-- FILE_ RULES+-- These are like file rules, but a rule may not bother creating the result+-- Which matches the (insane) semantics of make+-- If a file is not produced, it will rebuild forever++newtype File_Q = File_Q BSU+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show File_Q where show (File_Q x) = unpackU x++newtype File_A = File_A (Maybe ModTime)+ deriving (Typeable,Eq,Hashable,Binary,Show,NFData)++instance Rule File_Q File_A where+ storedValue _ (File_Q x) = fmap (fmap (File_A . Just . fst)) $ getFileInfo x+++defaultRuleFile_ :: Rules ()+defaultRuleFile_ = priority 0 $ rule $ \(File_Q x) -> Just $ liftIO $ do+ res <- getFileInfo x+ case res of+ Nothing -> error $ "Error, file does not exist and no rule available:\n " ++ unpackU x+ Just (mt,_) -> return $ File_A $ Just mt+++need_ :: [FilePath] -> Action ()+need_ xs = (apply $ map (File_Q . packU) xs :: Action [File_A]) >> return ()++want_ :: [FilePath] -> Rules ()+want_ = action . need_++data Phony = Phony | NotPhony deriving Eq++(??>) :: (FilePath -> Bool) -> (FilePath -> Action Phony) -> Rules ()+(??>) test act = rule $ \(File_Q x_) -> let x = unpackU x_ in+ if not $ test x then Nothing else Just $ do+ liftIO $ createDirectoryIfMissing True $ takeDirectory x+ res <- act x+ liftIO $ fmap (File_A . fmap fst) $ if res == Phony+ then return Nothing+ else getFileInfo x_
+ src/Development/Make/Type.hs view
@@ -0,0 +1,57 @@++module Development.Make.Type where++import Control.Monad+++data Makefile = Makefile [Stmt] deriving Show++data Stmt+ = Rule+ {targets :: Expr+ ,prerequisites :: Expr+ ,commands :: [Command]+ }+ | Assign+ {name :: String+ ,assign :: Assign+ ,expr :: Expr+ }+ deriving Show++data Assign = Equals | ColonEquals | PlusEquals | QuestionEquals deriving Show++data Expr = Apply String [Expr]+ | Concat [Expr]+ | Var String+ | Lit String+ deriving Show++data Command = Expr Expr | String := Expr deriving Show++descendExpr :: (Expr -> Expr) -> Expr -> Expr+descendExpr f (Apply a b) = Apply a $ map f b+descendExpr f (Concat xs) = Concat $ map f xs+descendExpr f x = x++descendExprM :: Monad m => (Expr -> m Expr) -> Expr -> m Expr+descendExprM f (Apply a b) = Apply a `liftM` mapM f b+descendExprM f (Concat xs) = Concat `liftM` mapM f xs+descendExprM f x = return x++transformExpr :: (Expr -> Expr) -> Expr -> Expr+transformExpr f = f . descendExpr (transformExpr f)++simplifyExpr :: Expr -> Expr+simplifyExpr = transformExpr f+ where+ f (Concat xs) = case g xs of+ [] -> Lit ""+ [x] -> x+ xs -> Concat xs+ f x = x++ g (Concat x:xs) = g $ x ++ xs+ g (Lit x:Lit y:xs) = g $ Lit (x ++ y) : xs+ g (x:xs) = x : g xs+ g [] = []
+ src/Development/Ninja/All.hs view
@@ -0,0 +1,279 @@+{-# LANGUAGE RecordWildCards, ViewPatterns #-}++module Development.Ninja.All(runNinja) where++import Development.Ninja.Env+import Development.Ninja.Type+import Development.Ninja.Parse+import Development.Shake hiding (addEnv)+import Development.Shake.ByteString+import Development.Shake.Errors+import Development.Shake.Rules.File+import Development.Shake.Rules.OrderOnly+import General.Timing+import qualified Data.ByteString as BS8+import qualified Data.ByteString.Char8 as BS++import System.Directory+import qualified Data.HashMap.Strict as Map+import qualified Data.HashSet as Set+import Data.Tuple.Extra+import Control.Exception.Extra+import Control.Monad+import Data.Maybe+import Data.Char+import Data.List.Extra+import System.Info.Extra+++runNinja :: FilePath -> [String] -> Maybe String -> IO (Maybe (Rules ()))+runNinja file args (Just "compdb") = do+ dir <- getCurrentDirectory+ Ninja{..} <- parse file =<< newEnv+ rules <- return $ Map.fromList [r | r <- rules, BS.unpack (fst r) `elem` args]+ -- the build items are generated in reverse order, hence the reverse+ let xs = [(a,b,file,rule) | (a,b@Build{..}) <- reverse $ multiples ++ map (first return) singles+ , Just rule <- [Map.lookup ruleName rules], file:_ <- [depsNormal]]+ xs <- forM xs $ \(out,Build{..},file,Rule{..}) -> do+ -- the order of adding new environment variables matters+ env <- scopeEnv env+ addEnv env (BS.pack "out") (BS.unwords $ map quote out)+ addEnv env (BS.pack "in") (BS.unwords $ map quote depsNormal)+ addEnv env (BS.pack "in_newline") (BS.unlines depsNormal)+ addBinds env buildBind+ addBinds env ruleBind+ commandline <- fmap BS.unpack $ askVar env $ BS.pack "command"+ return $ CompDb dir commandline $ BS.unpack $ head depsNormal+ putStr $ printCompDb xs+ return Nothing++runNinja file args (Just x) = error $ "Unknown tool argument, expected 'compdb', got " ++ x++runNinja file args tool = do+ addTiming "Ninja parse"+ ninja@Ninja{..} <- parse file =<< newEnv+ return $ Just $ do+ needDeps <- return $ needDeps ninja -- partial application+ phonys <- return $ Map.fromList phonys+ singles <- return $ Map.fromList $ map (first filepathNormalise) singles+ multiples <- return $ Map.fromList [(x,(xs,b)) | (xs,b) <- map (first $ map filepathNormalise) multiples, x <- xs]+ rules <- return $ Map.fromList rules+ pools <- fmap Map.fromList $ forM ((BS.pack "console",1):pools) $ \(name,depth) ->+ fmap ((,) name) $ newResource (BS.unpack name) depth++ action $ needBS $ concatMap (resolvePhony phonys) $+ if not $ null args then map BS.pack args+ else if not $ null defaults then defaults+ else Map.keys singles ++ Map.keys multiples++ (\x -> fmap (map BS.unpack . fst) $ Map.lookup (BS.pack x) multiples) &?> \out -> let out2 = map BS.pack out in+ build needDeps phonys rules pools out2 $ snd $ multiples Map.! head out2++ (flip Map.member singles . BS.pack) ?> \out -> let out2 = BS.pack out in+ build needDeps phonys rules pools [out2] $ singles Map.! out2+++resolvePhony :: Map.HashMap Str [Str] -> Str -> [Str]+resolvePhony mp = f $ Left 100+ where+ f (Left 0) x = f (Right []) x+ f (Right xs) x | x `elem` xs = error $ "Recursive phony involving " ++ BS.unpack x+ f a x = case Map.lookup x mp of+ Nothing -> [x]+ Just xs -> concatMap (f $ either (Left . subtract 1) (Right . (x:)) a) xs+++quote :: Str -> Str+quote x | BS.any isSpace x = let q = BS.singleton '\"' in BS.concat [q,x,q]+ | otherwise = x+++build :: (Build -> [Str] -> Action ()) -> Map.HashMap Str [Str] -> Map.HashMap Str Rule -> Map.HashMap Str Resource -> [Str] -> Build -> Action ()+build needDeps phonys rules pools out build@Build{..} = do+ needBS $ concatMap (resolvePhony phonys) $ depsNormal ++ depsImplicit+ orderOnlyBS $ concatMap (resolvePhony phonys) depsOrderOnly+ case Map.lookup ruleName rules of+ Nothing -> error $ "Ninja rule named " ++ BS.unpack ruleName ++ " is missing, required to build " ++ BS.unpack (BS.unwords out)+ Just Rule{..} -> do+ env <- liftIO $ scopeEnv env+ liftIO $ do+ -- the order of adding new environment variables matters+ addEnv env (BS.pack "out") (BS.unwords $ map quote out)+ addEnv env (BS.pack "in") (BS.unwords $ map quote depsNormal)+ addEnv env (BS.pack "in_newline") (BS.unlines depsNormal)+ addBinds env buildBind+ addBinds env ruleBind++ applyRspfile env $ do+ commandline <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "command"+ depfile <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "depfile"+ deps <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "deps"+ description <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "description"+ pool <- liftIO $ askVar env $ BS.pack "pool"++ let withPool act = case Map.lookup pool pools of+ _ | BS.null pool -> act+ Nothing -> error $ "Ninja pool named " ++ BS.unpack pool ++ " not found, required to build " ++ BS.unpack (BS.unwords out)+ Just r -> withResource r 1 act++ when (description /= "") $ putNormal description+ let (cmdOpts, cmdProg, cmdArgs) = toCommand commandline+ if deps == "msvc" then do+ Stdout stdout <- withPool $ command cmdOpts cmdProg cmdArgs+ prefix <- liftIO $ fmap (fromMaybe $ BS.pack "Note: including file: ") $+ askEnv env $ BS.pack "msvc_deps_prefix"+ needDeps build $ parseShowIncludes prefix $ BS.pack stdout+ else+ withPool $ command_ cmdOpts cmdProg cmdArgs+ when (depfile /= "") $ do+ when (deps /= "gcc") $ need [depfile]+ depsrc <- liftIO $ BS.readFile depfile+ needDeps build $ concatMap snd $ parseMakefile depsrc+ -- correct as per the Ninja spec, but breaks --skip-commands+ -- when (deps == "gcc") $ liftIO $ removeFile depfile+++needDeps :: Ninja -> Build -> [Str] -> Action ()+needDeps Ninja{..} = \build xs -> do -- eta reduced so 'builds' is shared+ opts <- getShakeOptions+ if isNothing $ shakeLint opts then needBS xs else do+ neededBS xs+ -- now try and statically validate needed will never fail+ -- first find which dependencies are generated files+ xs <- return $ filter (`Map.member` builds) xs+ -- now try and find them as dependencies+ let bad = xs `difference` allDependencies build+ case bad of+ [] -> return ()+ x:_ -> errorStructured+ "Lint checking error - file in deps is generated and not a pre-dependency"+ [("File", Just $ BS.unpack x)]+ ""+ where+ builds :: Map.HashMap FileStr Build+ builds = Map.fromList $ singles ++ [(x,y) | (xs,y) <- multiples, x <- xs]++ -- do list difference, assuming a small initial set, most of which occurs early in the list+ difference :: [Str] -> [Str] -> [Str]+ difference [] ys = []+ difference xs ys = f (Set.fromList xs) ys+ where+ f xs [] = Set.toList xs+ f xs (y:ys) | y `Set.member` xs = if Set.null xs2 then [] else f xs2 ys+ where xs2 = Set.delete y xs+ f xs (y:ys) = f xs ys++ -- find all dependencies of a rule, no duplicates, with all dependencies of this rule listed first+ allDependencies :: Build -> [FileStr]+ allDependencies rule = f Set.empty [] [rule]+ where+ f seen [] [] = []+ f seen [] (x:xs) = f seen (map filepathNormalise $ depsNormal x ++ depsImplicit x ++ depsOrderOnly x) xs+ f seen (x:xs) rest | x `Set.member` seen = f seen xs rest+ | otherwise = x : f (Set.insert x seen) xs (maybeToList (Map.lookup x builds) ++ rest)+++applyRspfile :: Env Str Str -> Action a -> Action a+applyRspfile env act = do+ rspfile <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "rspfile"+ rspfile_content <- liftIO $ askVar env $ BS.pack "rspfile_content"+ if rspfile == "" then+ act+ else+ flip actionFinally (ignore $ removeFile rspfile) $ do+ liftIO $ BS.writeFile rspfile rspfile_content+ act+++parseShowIncludes :: Str -> Str -> [FileStr]+parseShowIncludes prefix out =+ [y | x <- BS.lines out, prefix `BS.isPrefixOf` x+ , let y = BS.dropWhile isSpace $ BS.drop (BS.length prefix) x+ , not $ isSystemInclude y]++-- Dodgy, but ported over from the original Ninja+isSystemInclude :: FileStr -> Bool+isSystemInclude x = bsProgFiles `BS.isInfixOf` tx || bsVisStudio `BS.isInfixOf` tx+ where tx = BS8.map (\c -> if c >= 97 then c - 32 else c) x+ -- optimised toUpper that only cares about letters and spaces++bsProgFiles = BS.pack "PROGRAM FILES"+bsVisStudio = BS.pack "MICROSOFT VISUAL STUDIO"+++data CompDb = CompDb+ {cdbDirectory :: String+ ,cdbCommand :: String+ ,cdbFile :: String+ }+ deriving Show++printCompDb :: [CompDb] -> String+printCompDb xs = unlines $ ["["] ++ concat (zipWith f [1..] xs) ++ ["]"]+ where+ n = length xs+ f i CompDb{..} =+ [" {"+ ," \"directory\": " ++ g cdbDirectory ++ ","+ ," \"command\": " ++ g cdbCommand ++ ","+ ," \"file\": " ++ g cdbFile+ ," }" ++ (if i == n then "" else ",")]+ g = show+++toCommand :: String -> ([CmdOption], String, [String])+toCommand s+ -- On POSIX, Ninja does a /bin/sh -c, and so does Haskell in Shell mode (easy).+ | not isWindows = ([Shell], s, [])+ -- On Windows, Ninja passes the string directly to CreateProcess,+ -- but Haskell applies some escaping first.+ -- We try and get back as close to the original as we can, but it's very hacky+ | length s < 8000 =+ -- Using the "cmd" program adds overhead (I measure 7ms), and a limit of 8191 characters,+ -- but is the most robust, requiring no additional escaping.+ ([Shell], s, [])+ | (cmd,s) <- word1 s, map toUpper cmd `elem` ["CMD","CMD.EXE"], ("/c",s) <- word1 s =+ -- Given "cmd.exe /c <something>" we translate to Shell, which adds cmd.exe+ -- (looked up on the current path) and /c to the front. CMake uses this rule a lot.+ -- Adding quotes around pieces are /c goes very wrong.+ ([Shell], s, [])+ | otherwise =+ -- It's a long command line which doesn't call "cmd /c". We reverse the escaping+ -- Haskell applies, but each argument will still gain quotes around it.+ let xs = splitArgs s in ([], head $ xs ++ [""], drop 1 xs)+++data State+ = Gap -- ^ Current in the gap between words+ | Word -- ^ Currently inside a space-separated argument+ | Quot -- ^ Currently inside a quote-surrounded argument++-- | The process package contains a translate function, reproduced below. The aim is that after command line+-- parsing we should get out mostly the same answer.+splitArgs :: String -> [String]+splitArgs = f Gap+ where+ f Gap (x:xs) | isSpace x = f Gap xs+ f Gap ('\"':xs) = f Quot xs+ f Gap [] = []+ f Gap xs = f Word xs+ f Word (x:xs) | isSpace x = [] : f Gap xs+ f Quot ('\"':xs) = [] : f Gap xs+ f s ('\\':xs) | (length -> a, b) <- span (== '\\') xs = case b of+ '\"':xs | even a -> add (replicate (a `div` 2) '\\' ++ "\"") $ f s xs+ | otherwise -> add (replicate ((a+1) `div` 2) '\\') $ f s ('\"':xs)+ xs -> add (replicate (a+1) '\\') $ f s xs+ f s (x:xs) = add [x] $ f s xs+ f s [] = [] : []++ add a (b:c) = (a++b):c+ add a [] = a:[]++{-+translate (cmd,args) = unwords $ f cmd : map f args+ where+ f x = '"' : snd (foldr escape (True,"\"") xs)+ escape '"' (_, str) = (True, '\\' : '"' : str)+ escape '\\' (True, str) = (True, '\\' : '\\' : str)+ escape c (_, str) = (False, c : str)+-}
+ src/Development/Ninja/Env.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE PatternGuards #-}++-- | A Ninja style environment, basically a linked-list of mutable hash tables.+module Development.Ninja.Env(+ Env, newEnv, scopeEnv, addEnv, askEnv, fromEnv+ ) where++import qualified Data.HashMap.Strict as Map+import Data.Hashable+import Data.IORef+++data Env k v = Env (IORef (Map.HashMap k v)) (Maybe (Env k v))++instance Show (Env k v) where show _ = "Env"+++newEnv :: IO (Env k v)+newEnv = do ref <- newIORef Map.empty; return $ Env ref Nothing+++scopeEnv :: Env k v -> IO (Env k v)+scopeEnv e = do ref <- newIORef Map.empty; return $ Env ref $ Just e+++addEnv :: (Eq k, Hashable k) => Env k v -> k -> v -> IO ()+addEnv (Env ref _) k v = modifyIORef ref $ Map.insert k v+++askEnv :: (Eq k, Hashable k) => Env k v -> k -> IO (Maybe v)+askEnv (Env ref e) k = do+ mp <- readIORef ref+ case Map.lookup k mp of+ Just v -> return $ Just v+ Nothing | Just e <- e -> askEnv e k+ _ -> return Nothing++fromEnv :: Env k v -> IO (Map.HashMap k v)+fromEnv (Env ref _) = readIORef ref
+ src/Development/Ninja/Lexer.hs view
@@ -0,0 +1,219 @@+{-# LANGUAGE PatternGuards #-}+{-# OPTIONS_GHC -O2 #-}+-- {-# OPTIONS_GHC -ddump-simpl #-}++-- | Lexing is a slow point, the code below is optimised+module Development.Ninja.Lexer(Lexeme(..), lexer, lexerFile) where++import Data.Tuple.Extra+import qualified Data.ByteString.Char8 as BS+import qualified Data.ByteString.Unsafe as BS+import Development.Ninja.Type+import qualified Data.ByteString.Internal as Internal+import Foreign+import GHC.Exts++---------------------------------------------------------------------+-- LIBRARY BITS++newtype Str0 = Str0 Str -- null terminated++type S = Ptr Word8++chr :: S -> Char+chr x = Internal.w2c $ Internal.inlinePerformIO $ peek x++inc :: S -> S+inc x = x `plusPtr` 1++{-# INLINE dropWhile0 #-}+dropWhile0 :: (Char -> Bool) -> Str0 -> Str0+dropWhile0 f x = snd $ span0 f x++{-# INLINE span0 #-}+span0 :: (Char -> Bool) -> Str0 -> (Str, Str0)+span0 f x = break0 (not . f) x++{-# INLINE break0 #-}+break0 :: (Char -> Bool) -> Str0 -> (Str, Str0)+break0 f (Str0 bs) = (BS.unsafeTake i bs, Str0 $ BS.unsafeDrop i bs)+ where+ i = Internal.inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> do+ let start = castPtr ptr :: S+ let end = go start+ return $! Ptr end `minusPtr` start++ go s@(Ptr a) | c == '\0' || f c = a+ | otherwise = go (inc s)+ where c = chr s++{-# INLINE break00 #-}+-- The predicate must return true for '\0'+break00 :: (Char -> Bool) -> Str0 -> (Str, Str0)+break00 f (Str0 bs) = (BS.unsafeTake i bs, Str0 $ BS.unsafeDrop i bs)+ where+ i = Internal.inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> do+ let start = castPtr ptr :: S+ let end = go start+ return $! Ptr end `minusPtr` start++ go s@(Ptr a) | f c = a+ | otherwise = go (inc s)+ where c = chr s++head0 :: Str0 -> Char+head0 (Str0 x) = Internal.w2c $ BS.unsafeHead x++tail0 :: Str0 -> Str0+tail0 (Str0 x) = Str0 $ BS.unsafeTail x++list0 :: Str0 -> (Char, Str0)+list0 x = (head0 x, tail0 x)++take0 :: Int -> Str0 -> Str+take0 i (Str0 x) = BS.takeWhile (/= '\0') $ BS.take i x+++---------------------------------------------------------------------+-- ACTUAL LEXER++-- Lex each line separately, rather than each lexeme+data Lexeme+ = LexBind Str Expr -- [indent]foo = bar+ | LexBuild [Expr] Str [Expr] -- build foo: bar | baz || qux (| and || are represented as Expr)+ | LexInclude Expr -- include file+ | LexSubninja Expr -- include file+ | LexRule Str -- rule name+ | LexPool Str -- pool name+ | LexDefault [Expr] -- default foo bar+ | LexDefine Str Expr -- foo = bar+ deriving Show++isVar, isVarDot :: Char -> Bool+isVar x = x == '-' || x == '_' || (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= '0' && x <= '9')+isVarDot x = x == '.' || isVar x++endsDollar :: Str -> Bool+endsDollar x = BS.isSuffixOf (BS.singleton '$') x++dropN :: Str0 -> Str0+dropN x = if head0 x == '\n' then tail0 x else x++dropSpace :: Str0 -> Str0+dropSpace x = dropWhile0 (== ' ') x+++lexerFile :: Maybe FilePath -> IO [Lexeme]+lexerFile file = fmap lexer $ maybe BS.getContents BS.readFile file++lexer :: Str -> [Lexeme]+lexer x = lexerLoop $ Str0 $ x `BS.append` BS.pack "\n\n\0"++lexerLoop :: Str0 -> [Lexeme]+lexerLoop c_x | (c,x) <- list0 c_x = case c of+ '\r' -> lexerLoop x+ '\n' -> lexerLoop x+ ' ' -> lexBind $ dropSpace x+ '#' -> lexerLoop $ dropWhile0 (/= '\n') x+ 'b' | Just x <- strip "uild " x -> lexBuild $ dropSpace x+ 'r' | Just x <- strip "ule " x -> lexRule $ dropSpace x+ 'd' | Just x <- strip "efault " x -> lexDefault $ dropSpace x+ 'p' | Just x <- strip "ool " x -> lexPool $ dropSpace x+ 'i' | Just x <- strip "nclude " x -> lexInclude $ dropSpace x+ 's' | Just x <- strip "ubninja " x -> lexSubninja $ dropSpace x+ '\0' -> []+ _ -> lexDefine c_x+ where+ strip str (Str0 x) = if b `BS.isPrefixOf` x then Just $ Str0 $ BS.drop (BS.length b) x else Nothing+ where b = BS.pack str++lexBind c_x | (c,x) <- list0 c_x = case c of+ '\r' -> lexerLoop x+ '\n' -> lexerLoop x+ '#' -> lexerLoop $ dropWhile0 (/= '\n') x+ '\0' -> []+ _ -> lexxBind LexBind c_x++lexBuild x+ | (outputs,x) <- lexxExprs True x+ , (rule,x) <- span0 isVar $ dropSpace x+ , (deps,x) <- lexxExprs False $ dropSpace x+ = LexBuild outputs rule deps : lexerLoop x++lexDefault x+ | (files,x) <- lexxExprs False x+ = LexDefault files : lexerLoop x++lexRule x = lexxName LexRule x+lexPool x = lexxName LexPool x+lexInclude x = lexxFile LexInclude x+lexSubninja x = lexxFile LexSubninja x+lexDefine x = lexxBind LexDefine x++lexxBind ctor x+ | (var,x) <- span0 isVarDot x+ , ('=',x) <- list0 $ dropSpace x+ , (exp,x) <- lexxExpr False False $ dropSpace x+ = ctor var exp : lexerLoop x+lexxBind _ x = error $ show ("parse failed when parsing binding", take0 100 x)++lexxFile ctor x+ | (exp,rest) <- lexxExpr False False $ dropSpace x+ = ctor exp : lexerLoop rest++lexxName ctor x+ | (name,rest) <- splitLineCont x+ = ctor name : lexerLoop rest+++lexxExprs :: Bool -> Str0 -> ([Expr], Str0)+lexxExprs stopColon x = case lexxExpr stopColon True x of+ (a,c_x) | c <- head0 c_x, x <- tail0 c_x -> case c of+ ' ' -> first (a:) $ lexxExprs stopColon $ dropSpace x+ ':' | stopColon -> ([a], x)+ _ | stopColon -> error "expected a colon"+ '\r' -> a $: dropN x+ '\n' -> a $: x+ '\0' -> a $: c_x+ where+ Exprs [] $: x = ([], x)+ a $: x = ([a], x)+++{-# NOINLINE lexxExpr #-}+lexxExpr :: Bool -> Bool -> Str0 -> (Expr, Str0) -- snd will start with one of " :\n\r" or be empty+lexxExpr stopColon stopSpace = first exprs . f+ where+ exprs [x] = x+ exprs xs = Exprs xs++ special = case (stopColon, stopSpace) of+ (True , True ) -> \x -> x <= ':' && (x == ':' || x == ' ' || x == '$' || x == '\r' || x == '\n' || x == '\0')+ (True , False) -> \x -> x <= ':' && (x == ':' || x == '$' || x == '\r' || x == '\n' || x == '\0')+ (False, True ) -> \x -> x <= '$' && ( x == ' ' || x == '$' || x == '\r' || x == '\n' || x == '\0')+ (False, False) -> \x -> x <= '$' && ( x == '$' || x == '\r' || x == '\n' || x == '\0')+ f x = case break00 special x of (a,x) -> if BS.null a then g x else Lit a $: g x++ x $: (xs,y) = (x:xs,y)++ g x | head0 x /= '$' = ([], x)+ g x | c_x <- tail0 x, (c,x) <- list0 c_x = case c of+ '$' -> Lit (BS.singleton '$') $: f x+ ' ' -> Lit (BS.singleton ' ') $: f x+ ':' -> Lit (BS.singleton ':') $: f x+ '\n' -> f $ dropSpace x+ '\r' -> f $ dropSpace $ dropN x+ '{' | (name,x) <- span0 isVarDot x, not $ BS.null name, ('}',x) <- list0 x -> Var name $: f x+ _ | (name,x) <- span0 isVar c_x, not $ BS.null name -> Var name $: f x+ _ -> error $ "Unexpect $ followed by unexpected stuff"+++splitLineCont :: Str0 -> (Str, Str0)+splitLineCont x = first BS.concat $ f x+ where+ f x = if not $ endsDollar a then ([a], b) else let (c,d) = f $ dropSpace b in (BS.init a : c, d)+ where (a,b) = splitLineCR x++splitLineCR :: Str0 -> (Str, Str0)+splitLineCR x = if BS.singleton '\r' `BS.isSuffixOf` a then (BS.init a, dropN b) else (a, dropN b)+ where (a,b) = break0 (== '\n') x
+ src/Development/Ninja/Parse.hs view
@@ -0,0 +1,78 @@+{-# LANGUAGE RecordWildCards #-}++module Development.Ninja.Parse(parse) where++import qualified Data.ByteString.Char8 as BS+import Development.Ninja.Env+import Development.Ninja.Type+import Development.Ninja.Lexer+import Control.Monad+++parse :: FilePath -> Env Str Str -> IO Ninja+parse file env = parseFile file env newNinja+++parseFile :: FilePath -> Env Str Str -> Ninja -> IO Ninja+parseFile file env ninja = do+ lexes <- lexerFile $ if file == "-" then Nothing else Just file+ foldM (applyStmt env) ninja $ withBinds lexes++withBinds :: [Lexeme] -> [(Lexeme, [(Str,Expr)])]+withBinds [] = []+withBinds (x:xs) = (x,a) : withBinds b+ where+ (a,b) = f xs+ f (LexBind a b : rest) = let (as,bs) = f rest in ((a,b):as, bs)+ f xs = ([], xs)+++applyStmt :: Env Str Str -> Ninja -> (Lexeme, [(Str,Expr)]) -> IO Ninja+applyStmt env ninja@Ninja{..} (key, binds) = case key of+ LexBuild outputs rule deps -> do+ outputs <- mapM (askExpr env) outputs+ deps <- mapM (askExpr env) deps+ let (normal,implicit,orderOnly) = splitDeps deps+ let build = Build rule env normal implicit orderOnly binds+ return $+ if rule == BS.pack "phony" then ninja{phonys = [(x, normal) | x <- outputs] ++ phonys}+ else if length outputs == 1 then ninja{singles = (head outputs, build) : singles}+ else ninja{multiples = (outputs, build) : multiples}+ LexRule name ->+ return ninja{rules = (name, Rule binds) : rules}+ LexDefault xs -> do+ xs <- mapM (askExpr env) xs+ return ninja{defaults = xs ++ defaults}+ LexPool name -> do+ depth <- getDepth env binds+ return ninja{pools = (name, depth) : pools}+ LexInclude expr -> do+ file <- askExpr env expr+ parseFile (BS.unpack file) env ninja+ LexSubninja expr -> do+ file <- askExpr env expr+ e <- scopeEnv env+ parseFile (BS.unpack file) e ninja+ LexDefine a b -> do+ addBind env a b+ return ninja+ LexBind a b ->+ error $ "Unexpected binding defining " ++ BS.unpack a+++splitDeps :: [Str] -> ([Str], [Str], [Str])+splitDeps (x:xs) | x == BS.pack "|" = ([],a++b,c)+ | x == BS.pack "||" = ([],b,a++c)+ | otherwise = (x:a,b,c)+ where (a,b,c) = splitDeps xs+splitDeps [] = ([], [], [])+++getDepth :: Env Str Str -> [(Str, Expr)] -> IO Int+getDepth env xs = case lookup (BS.pack "depth") xs of+ Nothing -> return 1+ Just x -> do+ x <- askExpr env x+ case BS.readInt x of+ Just (i, n) | BS.null n -> return i+ _ -> error $ "Could not parse depth field in pool, got: " ++ BS.unpack x
+ src/Development/Ninja/Type.hs view
@@ -0,0 +1,67 @@++-- | The IO in this module is only to evaluate an envrionment variable,+-- the 'Env' itself it passed around purely.+module Development.Ninja.Type(+ Str, FileStr,+ Expr(..), Env, newEnv, askVar, askExpr, addEnv, addBind, addBinds,+ Ninja(..), newNinja, Build(..), Rule(..),+ ) where++import Development.Ninja.Env+import qualified Data.ByteString.Char8 as BS+import Data.Maybe+++type Str = BS.ByteString+type FileStr = Str+++---------------------------------------------------------------------+-- EXPRESSIONS AND BINDINGS++data Expr = Exprs [Expr] | Lit Str | Var Str deriving (Show,Eq)++askExpr :: Env Str Str -> Expr -> IO Str+askExpr e = f+ where f (Exprs xs) = fmap BS.concat $ mapM f xs+ f (Lit x) = return x+ f (Var x) = askVar e x++askVar :: Env Str Str -> Str -> IO Str+askVar e x = fmap (fromMaybe BS.empty) $ askEnv e x++addBind :: Env Str Str -> Str -> Expr -> IO ()+addBind e k v = addEnv e k =<< askExpr e v++addBinds :: Env Str Str -> [(Str, Expr)] -> IO ()+addBinds e = mapM_ (uncurry $ addBind e)+++---------------------------------------------------------------------+-- STRUCTURE++data Ninja = Ninja+ {rules :: [(Str,Rule)]+ ,singles :: [(FileStr,Build)]+ ,multiples :: [([FileStr], Build)]+ ,phonys :: ([(Str, [FileStr])])+ ,defaults :: [FileStr]+ ,pools :: [(Str, Int)]+ }+ deriving Show++newNinja :: Ninja+newNinja = Ninja [] [] [] [] [] []++data Build = Build+ {ruleName :: Str+ ,env :: Env Str Str+ ,depsNormal :: [FileStr]+ ,depsImplicit :: [FileStr]+ ,depsOrderOnly :: [FileStr]+ ,buildBind :: [(Str,Expr)]+ } deriving Show++data Rule = Rule+ {ruleBind :: [(Str,Expr)]+ } deriving Show
+ src/Development/Shake.hs view
@@ -0,0 +1,199 @@++-- | This module is used for defining Shake build systems. As a simple example of a Shake build system,+-- let us build the file @result.tar@ from the files listed by @result.txt@:+--+-- @+--import "Development.Shake"+--import "Development.Shake.FilePath"+--+--main = 'shakeArgs' 'shakeOptions' $ do+-- 'want' [\"result.tar\"]+-- \"*.tar\" '%>' \\out -> do+-- contents \<- 'readFileLines' $ out 'Development.Shake.FilePath.-<.>' \"txt\"+-- 'need' contents+-- 'cmd' \"tar -cf\" [out] contents+-- @+--+-- We start by importing the modules defining both Shake and routines for manipulating 'FilePath' values.+-- We define @main@ to call 'shake' with the default 'shakeOptions'. As the second argument to+-- 'shake', we provide a set of rules. There are two common forms of rules, 'want' to specify target files,+-- and '%>' to define a rule which builds a 'FilePattern'. We use 'want' to require that after the build+-- completes the file @result.tar@ should be ready.+--+-- The @*.tar@ rule describes how to build files with the extension @.tar@, including @result.tar@.+-- We 'readFileLines' on @result.txt@, after changing the @.tar@ extension to @.txt@. We read each line+-- into the variable @contents@ -- being a list of the files that should go into @result.tar@. Next, we+-- depend ('need') all the files in @contents@. If any of these files change, the rule will be repeated.+-- Finally we call the @tar@ program. If either @result.txt@ changes, or any of the files listed by @result.txt@+-- change, then @result.tar@ will be rebuilt.+--+-- To find out more:+--+-- * The user manual contains a longer example and background information on how to use Shake+-- <https://github.com/ndmitchell/shake/blob/master/docs/Manual.md#readme>.+--+-- * The home page has links to additional information <https://github.com/ndmitchell/shake#readme>, including+-- a mailing list.+--+-- * The theory behind Shake is described in an ICFP 2012 paper, /Shake Before Building -- Replacing Make with Haskell/+-- <http://community.haskell.org/~ndm/downloads/paper-shake_before_building-10_sep_2012.pdf>. The associated talk+-- forms a short overview of Shake <http://www.youtube.com/watch?v=xYCPpXVlqFM>.+--+-- /== WRITING A BUILD SYSTEM ==============================/+--+-- When writing a Shake build system, start by defining what you 'want', then write rules+-- with '%>' to produce the results. Before calling 'cmd' you should ensure that any files the command+-- requires are demanded with calls to 'need'. We offer the following advice to Shake users:+--+-- * If @ghc --make@ or @cabal@ is capable of building your project, use that instead. Custom build systems are+-- necessary for many complex projects, but many projects are not complex.+--+-- * The 'shakeArgs' function automatically handles command line arguments. To define non-file targets use 'phony'.+--+-- * Put all result files in a distinguished directory, for example @_make@. You can implement a @clean@+-- command by removing that directory, using @'removeFilesAfter' \"_make\" [\"\/\/\*\"]@.+--+-- * To obtain parallel builds set 'shakeThreads' to a number greater than 1.+--+-- * Lots of compilers produce @.o@ files. To avoid overlapping rules, use @.c.o@ for C compilers,+-- @.hs.o@ for Haskell compilers etc.+--+-- * Do not be afraid to mix Shake rules, system commands and other Haskell libraries -- use each for what+-- it does best.+--+-- * The more accurate the dependencies are, the better. Use additional rules like 'doesFileExist' and+-- 'getDirectoryFiles' to track information other than just the contents of files. For information in the environment+-- that you suspect will change regularly (perhaps @ghc@ version number), either write the information to+-- a file with 'alwaysRerun' and 'writeFileChanged', or use 'addOracle'.+--+-- /== GHC BUILD FLAGS ==============================/+--+-- For large build systems the choice of GHC flags can have a significant impact. We recommend:+--+-- > ghc --make MyBuildSystem -rtsopts -with-rtsopts=-I0+--+-- * @-rtsopts@: Allow the setting of further GHC options at runtime.+--+-- * @-I0@: Disable idle garbage collection. In a build system regularly running many system+-- commands the program appears \"idle\" very often, triggering regular unnecessary garbage collection, stealing+-- resources from the program doing actual work.+--+-- * Omit @-threaded@: In GHC 7.6 and earlier bug 7646 <http://ghc.haskell.org/trac/ghc/ticket/7646>+-- can cause a race condition in build systems that write files then read them. Omitting @-threaded@ will+-- still allow your 'cmd' actions to run in parallel, so most build systems will still run in parallel.+--+-- * If you do compile with @-threaded@, pass the options @-qg -qb@ to @-with-rtsopts@+-- to disable parallel garbage collection. Parallel garbage collection in Shake+-- programs typically goes slower than sequential garbage collection, while occupying many cores that+-- could be used for running system commands.+--+-- /Acknowledgements/: Thanks to Austin Seipp for properly integrating the profiling code.+module Development.Shake(+ -- * Core+ shake,+ shakeOptions,+ Rules, action, withoutActions, alternatives, priority,+ Action, traced,+ liftIO, actionOnException, actionFinally,+ ShakeException(..),+ -- * Configuration+ ShakeOptions(..), Assume(..), Lint(..), Change(..), getShakeOptions,+ -- ** Command line+ shakeArgs, shakeArgsWith, shakeOptDescrs,+ -- ** Progress reporting+ Progress(..), progressSimple, progressDisplay, progressTitlebar, progressProgram,+ -- ** Verbosity+ Verbosity(..), getVerbosity, putLoud, putNormal, putQuiet, withVerbosity, quietly,+ -- * Running commands+ command, command_, cmd,+ Stdout(..), Stderr(..), Exit(..),+ CmdResult, CmdOption(..),+ addPath, addEnv,+ -- * Utility functions+ copyFile', copyFileChanged,+ readFile', readFileLines,+ writeFile', writeFileLines, writeFileChanged,+ removeFiles, removeFilesAfter,+ withTempFile, withTempDir,+ -- * File rules+ need, want, (%>), (|%>), (?>), phony, (~>),+ (&%>), (&?>),+ orderOnly,+ FilePattern, (?==),+ needed, trackRead, trackWrite, trackAllow,+ -- * Directory rules+ doesFileExist, doesDirectoryExist, getDirectoryContents, getDirectoryFiles, getDirectoryDirs,+ -- * Environment rules+ getEnv, getEnvWithDefault,+ -- * Oracle rules+ addOracle, askOracle, askOracleWith,+ -- * Special rules+ alwaysRerun,+ -- * Resources+ Resource, newResource, newResourceIO, withResource, withResources,+ newThrottle, newThrottleIO,+ unsafeExtraThread,+ -- * Cache+ newCache, newCacheIO,+ -- * Deprecated+ (*>), (|*>), (&*>),+ (**>), (*>>), (?>>),+ system', systemCwd, systemOutput+ ) where++-- I would love to use module export in the above export list, but alas Haddock+-- then shows all the things that are hidden in the docs, which is terrible.++import Control.Monad.IO.Class+import Development.Shake.Types+import Development.Shake.Core hiding (trackAllow)+import Development.Shake.Derived+import Development.Shake.Errors+import Development.Shake.Progress+import Development.Shake.Args+import Development.Shake.Shake++import Development.Shake.Command+import Development.Shake.Rules.Directory+import Development.Shake.Rules.File+import Development.Shake.FilePattern+import Development.Shake.Rules.Files+import Development.Shake.Rules.Oracle+import Development.Shake.Rules.OrderOnly+import Development.Shake.Rules.Rerun+++---------------------------------------------------------------------+-- DEPRECATED SINCE 0.13, MAY 2014++infix 1 **>, ?>>, *>>++-- | /Deprecated:/ Alias for '|%>'.+(**>) :: [FilePattern] -> (FilePath -> Action ()) -> Rules ()+(**>) = (|%>)++-- | /Deprecated:/ Alias for '&?>'.+(?>>) :: (FilePath -> Maybe [FilePath]) -> ([FilePath] -> Action ()) -> Rules ()+(?>>) = (&?>)++-- | /Deprecated:/ Alias for '&%>'.+(*>>) :: [FilePattern] -> ([FilePath] -> Action ()) -> Rules ()+(*>>) = (&%>)+++---------------------------------------------------------------------+-- DEPRECATED SINCE 0.14, MAY 2014++infix 1 *>, |*>, &*>++-- | /Deprecated:/ Alias for '%>'. Note that @*>@ clashes with a Prelude operator in GHC 7.10.+(*>) :: FilePattern -> (FilePath -> Action ()) -> Rules ()+(*>) = (%>)++-- | /Deprecated:/ Alias for '|%>'.+(|*>) :: [FilePattern] -> (FilePath -> Action ()) -> Rules ()+(|*>) = (|%>)++-- | /Deprecated:/ Alias for '&%>'.+(&*>) :: [FilePattern] -> ([FilePath] -> Action ()) -> Rules ()+(&*>) = (&%>)
+ src/Development/Shake/Args.hs view
@@ -0,0 +1,342 @@++-- | Command line parsing flags.+module Development.Shake.Args(shakeOptDescrs, shakeArgs, shakeArgsWith) where++import Paths_shake+import Development.Shake.Types+import Development.Shake.Core+import Development.Shake.Demo+import Development.Shake.Rules.File+import Development.Shake.Progress+import Development.Shake.Shake+import General.Timing++import Data.Tuple.Extra+import Control.Concurrent+import Control.Exception.Extra+import Control.Monad+import Data.Char+import Data.Either+import Data.List+import Data.Maybe+import Data.Time+import Data.Version(showVersion)+import System.Console.GetOpt+import System.Directory+import System.Environment+import System.Exit+import System.Time.Extra+++-- | Run a build system using command line arguments for configuration.+-- The available flags are those from 'shakeOptDescrs', along with a few additional+-- @make@ compatible flags that are not represented in 'ShakeOptions', such as @--print-directory@.+-- If there are no file arguments then the 'Rules' are used directly, otherwise the file arguments+-- are 'want'ed (after calling 'withoutActions'). As an example:+--+-- @+-- main = 'shakeArgs' 'shakeOptions'{'shakeFiles' = \"_make/\", 'shakeProgress' = 'progressSimple'} $ do+-- 'phony' \"clean\" $ 'Development.Shake.removeFilesAfter' \"_make\" [\"\/\/*\"]+-- 'want' [\"_make\/neil.txt\",\"_make\/emily.txt\"]+-- \"_make\/*.txt\" '%>' \\out ->+-- ... build action here ...+-- @+--+-- This build system will default to building @neil.txt@ and @emily.txt@, while showing progress messages,+-- and putting the Shake files in locations such as @_make\/.database@. Some example command line flags:+--+-- * @main --no-progress@ will turn off progress messages.+--+-- * @main -j6@ will build on 6 threads.+--+-- * @main --help@ will display a list of supported flags.+--+-- * @main clean@ will not build anything, but will remove the @_make@ directory, including the+-- any 'shakeFiles'.+--+-- * @main _make/henry.txt@ will not build @neil.txt@ or @emily.txt@, but will instead build @henry.txt@.+shakeArgs :: ShakeOptions -> Rules () -> IO ()+shakeArgs opts rules = shakeArgsWith opts [] f+ where f _ files = return $ Just $ if null files then rules else want files >> withoutActions rules+++-- | A version of 'shakeArgs' with more flexible handling of command line arguments.+-- The caller of 'shakeArgsWith' can add additional flags (the second argument) and chose how to convert+-- the flags/arguments into rules (the third argument). Given:+--+-- @+-- 'shakeArgsWith' opts flags (\\flagValues argValues -> result)+-- @+--+-- * @opts@ is the initial 'ShakeOptions' value, which may have some fields overriden by command line flags.+-- This argument is usually 'shakeOptions', perhaps with a few fields overriden.+--+-- * @flags@ is a list of flag descriptions, which either produce a 'String' containing an error+-- message (typically for flags with invalid arguments, .e.g. @'Left' \"could not parse as int\"@), or a value+-- that is passed as @flagValues@. If you have no custom flags, pass @[]@.+--+-- * @flagValues@ is a list of custom flags that the user supplied. If @flags == []@ then this list will+-- be @[]@.+--+-- * @argValues@ is a list of non-flag arguments, which are often treated as files and passed to 'want'.+--+-- * @result@ should produce a 'Nothing' to indicate that no building needs to take place, or a 'Just'+-- providing the rules that should be used.+--+-- As an example of a build system that can use either @gcc@ or @distcc@ for compiling:+--+-- @+--import System.Console.GetOpt+--+--data Flags = DistCC deriving Eq+--flags = [Option \"\" [\"distcc\"] (NoArg $ Right DistCC) \"Run distributed.\"]+--+--main = 'shakeArgsWith' 'shakeOptions' flags $ \\flags targets -> return $ Just $ do+-- if null targets then 'want' [\"result.exe\"] else 'want' targets+-- let compiler = if DistCC \`elem\` flags then \"distcc\" else \"gcc\"+-- \"*.o\" '%>' \\out -> do+-- 'need' ...+-- 'cmd' compiler ...+-- ...+-- @+--+-- Now you can pass @--distcc@ to use the @distcc@ compiler.+shakeArgsWith :: ShakeOptions -> [OptDescr (Either String a)] -> ([a] -> [String] -> IO (Maybe (Rules ()))) -> IO ()+shakeArgsWith baseOpts userOptions rules = do+ addTiming "shakeArgsWith"+ args <- getArgs+ let (flags,files,errs) = getOpt Permute opts args+ (flagsError,flag1) = partitionEithers flags+ (self,user) = partitionEithers flag1+ (flagsExtra,flagsShake) = first concat $ unzip self+ assumeNew = [x | AssumeNew x <- flagsExtra]+ assumeOld = [x | AssumeOld x <- flagsExtra]+ progressReplays = [x | ProgressReplay x <- flagsExtra]+ progressRecords = [x | ProgressRecord x <- flagsExtra]+ changeDirectory = listToMaybe [x | ChangeDirectory x <- flagsExtra]+ printDirectory = last $ False : [x | PrintDirectory x <- flagsExtra]+ shakeOpts = foldl' (flip ($)) baseOpts flagsShake++ -- error if you pass some clean and some dirty with specific flags+ errs <- return $ errs ++ flagsError ++ ["cannot mix " ++ a ++ " and " ++ b | a:b:_ <-+ [["`--assume-new'" | assumeNew/=[] ] ++ ["`--assume-old'" | assumeOld/=[] ] ++ ["explicit targets" | files/=[]]]]++ when (errs /= []) $ do+ putStr $ unlines $ map ("shake: " ++) $ filter (not . null) $ lines $ unlines errs+ showHelp+ exitFailure++ if Help `elem` flagsExtra then do+ showHelp+ else if Version `elem` flagsExtra then+ putStrLn $ "Shake build system, version " ++ showVersion version+ else if NumericVersion `elem` flagsExtra then+ putStrLn $ showVersion version+ else if Demo `elem` flagsExtra then+ demo $ shakeStaunch shakeOpts+ else if not $ null progressReplays then do+ dat <- forM progressReplays $ \file -> do+ src <- readFile file+ return (file, map read $ lines src)+ forM_ (if null $ shakeReport shakeOpts then ["-"] else shakeReport shakeOpts) $ \file -> do+ putStrLn $ "Writing report to " ++ file+ writeProgressReport file dat+ else do+ when (Sleep `elem` flagsExtra) $ threadDelay 1000000+ start <- getCurrentTime+ curdir <- getCurrentDirectory+ let redir = case changeDirectory of+ Nothing -> id+ -- get the "html" directory so it caches with the current directory+ -- required only for debug code+ Just d -> bracket_ (getDataFileName "html" >> setCurrentDirectory d) (setCurrentDirectory curdir)+ shakeOpts <- if null progressRecords then return shakeOpts else do+ t <- offsetTime+ return shakeOpts{shakeProgress = \p -> do+ bracket+ (forkIO $ shakeProgress shakeOpts p)+ killThread+ $ const $ progressDisplay 1 (const $ return ()) $ do+ p <- p+ t <- t+ forM_ progressRecords $ \file -> do+ appendFile file $ show (t,p) ++ "\n"+ return p+ }+ (ran,res) <- redir $ do+ when printDirectory $ putStrLn $ "shake: In directory `" ++ curdir ++ "'"+ rules <- rules user files+ case rules of+ Nothing -> return (False,Right ())+ Just rules -> do+ res <- try_ $ shake shakeOpts $+ if NoBuild `elem` flagsExtra then withoutActions rules else rules+ return (True, res)++ if not ran || shakeVerbosity shakeOpts < Normal || NoTime `elem` flagsExtra then+ either throwIO return res+ else+ let esc code = if Color `elem` flagsExtra then escape code else id+ in case res of+ Left err ->+ if Exception `elem` flagsExtra then+ throw err+ else do+ putStrLn $ esc "31" $ show err+ exitFailure+ Right () -> do+ stop <- getCurrentTime+ let tot = diffUTCTime stop start+ (mins,secs) = divMod (ceiling tot) (60 :: Int)+ time = show mins ++ ":" ++ ['0' | secs < 10] ++ show secs+ putStrLn $ esc "32" $ "Build completed in " ++ time ++ "m"+ where+ opts = map (wrap Left . snd) shakeOptsEx ++ map (wrap Right) userOptions+ showHelp = do+ progName <- getProgName+ putStr $ unlines $ ("Usage: " ++ progName ++ " [options] [target] ...") : "Options:" : showOptDescr opts++ wrap :: (a -> b) -> OptDescr (Either String a) -> OptDescr (Either String b)+ wrap f = fmapOptDescr (either Left (Right . f))+++showOptDescr :: [OptDescr a] -> [String]+showOptDescr xs = concat+ [ if nargs <= 26 then [" " ++ args ++ replicate (28 - nargs) ' ' ++ desc]+ else [" " ++ args, replicate 30 ' ' ++ desc]+ | Option s l arg desc <- xs+ , let args = intercalate ", " $ map (short arg) s ++ map (long arg) l+ , let nargs = length args]+ where short NoArg{} x = "-" ++ [x]+ short (ReqArg _ b) x = "-" ++ [x] ++ " " ++ b+ short (OptArg _ b) x = "-" ++ [x] ++ "[=" ++ b ++ "]"+ long NoArg{} x = "--" ++ x+ long (ReqArg _ b) x = "--" ++ x ++ "=" ++ b+ long (OptArg _ b) x = "--" ++ x ++ "[=" ++ b ++ "]"+++fmapOptDescr :: (a -> b) -> OptDescr a -> OptDescr b+fmapOptDescr f (Option a b c d) = Option a b (g c) d+ where g (NoArg a) = NoArg $ f a+ g (ReqArg a b) = ReqArg (f . a) b+ g (OptArg a b) = OptArg (f . a) b+++-- | A list of command line options that can be used to modify 'ShakeOptions'. Each option returns+-- either an error message (invalid argument to the flag) or a function that changes some fields+-- in 'ShakeOptions'. The command line flags are @make@ compatible where possbile, but additional+-- flags have been added for the extra options Shake supports.+shakeOptDescrs :: [OptDescr (Either String (ShakeOptions -> ShakeOptions))]+shakeOptDescrs = [fmapOptDescr (either Left (Right . snd)) o | (True, o) <- shakeOptsEx]++data Extra = ChangeDirectory FilePath+ | Version+ | NumericVersion+ | AssumeNew FilePath+ | AssumeOld FilePath+ | PrintDirectory Bool+ | Color+ | Help+ | Sleep+ | NoTime+ | Exception+ | NoBuild+ | ProgressRecord FilePath+ | ProgressReplay FilePath+ | Demo+ deriving Eq+++unescape :: String -> String+unescape ('\ESC':'[':xs) = unescape $ drop 1 $ dropWhile (not . isAlpha) xs+unescape (x:xs) = x : unescape xs+unescape [] = []++escape :: String -> String -> String+escape code x = "\ESC[" ++ code ++ "m" ++ x ++ "\ESC[0m"+++-- | True if it has a potential effect on ShakeOptions+shakeOptsEx :: [(Bool, OptDescr (Either String ([Extra], ShakeOptions -> ShakeOptions)))]+shakeOptsEx =+ [yes $ Option "a" ["abbrev"] (pairArg "abbrev" "FULL=SHORT" $ \a s -> s{shakeAbbreviations=shakeAbbreviations s ++ [a]}) "Use abbreviation in status messages."+ ,yes $ Option "B" ["always-make"] (noArg $ \s -> s{shakeAssume=Just AssumeDirty}) "Unconditionally make all targets."+ ,no $ Option "" ["no-build"] (NoArg $ Right ([NoBuild], id)) "Don't build anything."+ ,no $ Option "C" ["directory"] (ReqArg (\x -> Right ([ChangeDirectory x],id)) "DIRECTORY") "Change to DIRECTORY before doing anything."+ ,yes $ Option "" ["color","colour"] (NoArg $ Right ([Color], \s -> s{shakeOutput=outputColor (shakeOutput s)})) "Colorize the output."+ ,yes $ Option "d" ["debug"] (OptArg (\x -> Right ([], \s -> s{shakeVerbosity=Diagnostic, shakeOutput=outputDebug (shakeOutput s) x})) "FILE") "Print lots of debugging information."+ ,no $ Option "" ["demo"] (NoArg $ Right ([Demo], id)) "Run in demo mode."+ ,yes $ Option "" ["digest"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeDigest})) "Files change when digest changes."+ ,yes $ Option "" ["digest-and"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeModtimeAndDigest})) "Files change when modtime and digest change."+ ,yes $ Option "" ["digest-and-input"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeModtimeAndDigestInput})) "Files change on modtime (and digest for inputs)."+ ,yes $ Option "" ["digest-or"] (NoArg $ Right ([], \s -> s{shakeChange=ChangeModtimeOrDigest})) "Files change when modtime or digest change."+ ,no $ Option "" ["exception"] (NoArg $ Right ([Exception], id)) "Throw exceptions directly."+ ,yes $ Option "" ["flush"] (intArg 1 "flush" "N" (\i s -> s{shakeFlush=Just i})) "Flush metadata every N seconds."+ ,yes $ Option "" ["never-flush"] (noArg $ \s -> s{shakeFlush=Nothing}) "Never explicitly flush metadata."+ ,no $ Option "h" ["help"] (NoArg $ Right ([Help],id)) "Print this message and exit."+ ,yes $ Option "j" ["jobs"] (optIntArg 0 "jobs" "N" $ \i s -> s{shakeThreads=fromMaybe 0 i}) "Allow N jobs/threads at once [default CPUs]."+ ,yes $ Option "k" ["keep-going"] (noArg $ \s -> s{shakeStaunch=True}) "Keep going when some targets can't be made."+ ,yes $ Option "l" ["lint"] (noArg $ \s -> s{shakeLint=Just LintBasic}) "Perform limited validation after the run."+ ,yes $ Option "" ["lint-tracker"] (noArg $ \s -> s{shakeLint=Just LintTracker}) "Use tracker.exe to do validation."+ ,yes $ Option "" ["no-lint"] (noArg $ \s -> s{shakeLint=Nothing}) "Turn off --lint."+ ,yes $ Option "" ["live"] (OptArg (\x -> Right ([], \s -> s{shakeLiveFiles=shakeLiveFiles s ++ [fromMaybe "live.txt" x]})) "FILE") "List the files that are live [to live.txt]."+ ,yes $ Option "m" ["metadata"] (reqArg "PREFIX" $ \x s -> s{shakeFiles=x}) "Prefix for storing metadata files."+ ,no $ Option "" ["numeric-version"] (NoArg $ Right ([NumericVersion],id)) "Print just the version number and exit."+ ,no $ Option "o" ["old-file","assume-old"] (ReqArg (\x -> Right ([AssumeOld x],id)) "FILE") "Consider FILE to be very old and don't remake it."+ ,yes $ Option "" ["old-all"] (noArg $ \s -> s{shakeAssume=Just AssumeClean}) "Don't remake any files."+ ,yes $ Option "" ["assume-skip"] (noArg $ \s -> s{shakeAssume=Just AssumeSkip}) "Don't remake any files this run."+ ,yes $ Option "" ["skip-commands"] (noArg $ \s -> s{shakeRunCommands=False}) "Try and avoid running external programs."+ ,yes $ Option "r" ["report","profile"] (OptArg (\x -> Right ([], \s -> s{shakeReport=shakeReport s ++ [fromMaybe "report.html" x]})) "FILE") "Write out profiling information [to report.html]."+ ,yes $ Option "" ["no-reports"] (noArg $ \s -> s{shakeReport=[]}) "Turn off --report."+ ,yes $ Option "" ["rule-version"] (reqArg "VERSION" $ \x s -> s{shakeVersion=x}) "Version of the build rules."+ ,yes $ Option "s" ["silent"] (noArg $ \s -> s{shakeVerbosity=Silent}) "Don't print anything."+ ,no $ Option "" ["sleep"] (NoArg $ Right ([Sleep],id)) "Sleep for a second before building."+ ,yes $ Option "S" ["no-keep-going","stop"] (noArg $ \s -> s{shakeStaunch=False}) "Turns off -k."+ ,yes $ Option "" ["storage"] (noArg $ \s -> s{shakeStorageLog=True}) "Write a storage log."+ ,yes $ Option "p" ["progress"] (progress $ optIntArg 1 "progress" "N" $ \i s -> s{shakeProgress=prog $ fromMaybe 5 i}) "Show progress messages [every N secs, default 5]."+ ,yes $ Option "" ["no-progress"] (noArg $ \s -> s{shakeProgress=const $ return ()}) "Don't show progress messages."+ ,yes $ Option "q" ["quiet"] (noArg $ \s -> s{shakeVerbosity=move (shakeVerbosity s) pred}) "Don't print much."+ ,no $ Option "" ["no-time"] (NoArg $ Right ([NoTime],id)) "Don't print build time."+ ,yes $ Option "" ["timings"] (noArg $ \s -> s{shakeTimings=True}) "Print phase timings."+ ,yes $ Option "" ["touch"] (noArg $ \s -> s{shakeAssume=Just AssumeClean}) "Assume targets are clean."+ ,yes $ Option "V" ["verbose","trace"] (noArg $ \s -> s{shakeVerbosity=move (shakeVerbosity s) succ}) "Print tracing information."+ ,no $ Option "v" ["version"] (NoArg $ Right ([Version],id)) "Print the version number and exit."+ ,no $ Option "w" ["print-directory"] (NoArg $ Right ([PrintDirectory True],id)) "Print the current directory."+ ,no $ Option "" ["no-print-directory"] (NoArg $ Right ([PrintDirectory False],id)) "Turn off -w, even if it was turned on implicitly."+ ,no $ Option "W" ["what-if","new-file","assume-new"] (ReqArg (\x -> Right ([AssumeNew x],id)) "FILE") "Consider FILE to be infinitely new."+ ]+ where+ yes = (,) True+ no = (,) False++ move :: Verbosity -> (Int -> Int) -> Verbosity+ move x by = toEnum $ min (fromEnum mx) $ max (fromEnum mn) $ by $ fromEnum x+ where (mn,mx) = (asTypeOf minBound x, asTypeOf maxBound x)++ noArg f = NoArg $ Right ([], f)+ reqArg a f = ReqArg (\x -> Right ([], f x)) a+ intArg mn flag a f = flip ReqArg a $ \x -> case reads x of+ [(i,"")] | i >= mn -> Right ([],f i)+ _ -> Left $ "the `--" ++ flag ++ "' option requires a number, " ++ show mn ++ " or above"+ optIntArg mn flag a f = flip OptArg a $ maybe (Right ([], f Nothing)) $ \x -> case reads x of+ [(i,"")] | i >= mn -> Right ([],f $ Just i)+ _ -> Left $ "the `--" ++ flag ++ "' option requires a number, " ++ show mn ++ " or above"+ pairArg flag a f = flip ReqArg a $ \x -> case break (== '=') x of+ (a,'=':b) -> Right ([],f (a,b))+ _ -> Left $ "the `--" ++ flag ++ "' option requires an = in the argument"++ progress (OptArg func msg) = flip OptArg msg $ \x -> case break (== '=') `fmap` x of+ Just ("record",file) -> Right ([ProgressRecord $ if null file then "progress.txt" else tail file], id)+ Just ("replay",file) -> Right ([ProgressReplay $ if null file then "progress.txt" else tail file], id)+ _ -> func x++ outputDebug output Nothing = output+ outputDebug output (Just file) = \v msg -> do+ when (v /= Diagnostic) $ output v msg+ appendFile file $ unescape msg++ outputColor output v msg = output v $ escape "34" msg++ prog i p = do+ program <- progressProgram+ progressDisplay i (\s -> progressTitlebar s >> program s) p
+ src/Development/Shake/ByteString.hs view
@@ -0,0 +1,75 @@++module Development.Shake.ByteString(parseMakefile, filepathNormalise, linesCR) where++import qualified Data.ByteString.Char8 as BS+import qualified System.FilePath as Native+import System.Info.Extra+import Data.Char+import Data.List+++endsSlash :: BS.ByteString -> Bool+endsSlash = BS.isSuffixOf (BS.singleton '\\')++wordsMakefile :: BS.ByteString -> [BS.ByteString]+wordsMakefile = f . BS.splitWith isSpace+ where+ f (x:xs) | BS.null x = f xs+ f (x:y:xs) | endsSlash x = BS.concat [BS.init x, BS.singleton ' ', y] : f xs+ f (x:xs) = x : f xs+ f [] = []++parseMakefile :: BS.ByteString -> [(BS.ByteString, [BS.ByteString])]+parseMakefile = concatMap f . join . linesCR+ where+ join xs = case span endsSlash xs of+ ([], []) -> []+ (xs, []) -> [BS.unwords $ map BS.init xs]+ ([], y:ys) -> y : join ys+ (xs, y:ys) -> BS.unwords (map BS.init xs ++ [y]) : join ys++ f x = [(a, wordsMakefile $ BS.drop 1 b) | a <- wordsMakefile a]+ where (a,b) = BS.break (== ':') $ BS.takeWhile (/= '#') x+++-- | This is a hot-spot, so optimised+linesCR :: BS.ByteString -> [BS.ByteString]+linesCR x = case BS.split '\n' x of+ x:xs | Just ('\r',x) <- unsnoc x -> x : map (\x -> case unsnoc x of Just ('\r',x) -> x; _ -> x) xs+ xs -> xs+ where+ -- the ByteString unsnoc was introduced in a newer version+ unsnoc x | BS.null x = Nothing+ | otherwise = Just (BS.last x, BS.init x)+++filepathNormalise :: BS.ByteString -> BS.ByteString+filepathNormalise xs+ | isWindows, Just (a,xs) <- BS.uncons xs, sep a, Just (b,_) <- BS.uncons xs, sep b = '/' `BS.cons` f xs+ | otherwise = f xs+ where+ sep = Native.isPathSeparator+ f o = deslash o $ BS.concat $ (slash:) $ intersperse slash $ reverse $ (BS.empty:) $ g 0 $ reverse $ split $ o++ deslash o x+ | x == slash = case (pre,pos) of+ (True,True) -> slash+ (True,False) -> BS.pack "/."+ (False,True) -> BS.pack "./"+ (False,False) -> dot+ | otherwise = (if pre then id else BS.tail) $ (if pos then id else BS.init) x+ where pre = not (BS.null o) && sep (BS.head o)+ pos = not (BS.null o) && sep (BS.last o)++ g i [] = replicate i dotDot+ g i (x:xs) | BS.null x = g i xs+ g i (x:xs) | x == dotDot = g (i+1) xs+ g i (x:xs) | x == dot = g i xs+ g 0 (x:xs) = x : g 0 xs+ g i (x:xs) = g (i-1) xs++ split xs = BS.splitWith sep xs++dotDot = BS.pack ".."+dot = BS.singleton '.'+slash = BS.singleton '/'
+ src/Development/Shake/Classes.hs view
@@ -0,0 +1,11 @@++-- | This module reexports the six necessary type classes that every 'Rule' type must support.+-- You can use this module to define new rules without depending on the @binary@, @deepseq@ and @hashable@ packages.+module Development.Shake.Classes(+ Show(..), Typeable(..), Eq(..), Hashable(..), Binary(..), NFData(..)+ ) where++import Data.Hashable+import Data.Typeable+import Data.Binary+import Control.DeepSeq
+ src/Development/Shake/Command.hs view
@@ -0,0 +1,469 @@+{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, TypeOperators #-}++-- | This module provides functions for calling command line programs, primarily+-- 'command' and 'cmd'. As a simple example:+--+-- @+-- 'command' [] \"gcc\" [\"-c\",myfile]+-- @+--+-- The functions from this module are now available directly from "Development.Shake".+-- You should only need to import this module if you are using the 'cmd' function in the 'IO' monad.+module Development.Shake.Command(+ command, command_, cmd, CmdArguments,+ Stdout(..), Stderr(..), Exit(..),+ CmdResult, CmdOption(..),+ addPath, addEnv,+ ) where++import Data.Tuple.Extra+import Control.Concurrent+import Control.DeepSeq+import Control.Exception.Extra as C+import Control.Monad.Extra+import Control.Monad.IO.Class+import Data.Either+import Data.List.Extra+import Data.Maybe+import Foreign.C.Error+import System.Directory+import System.Environment.Extra+import System.Exit+import System.IO.Extra+import System.Process+import System.Info.Extra+import System.IO.Unsafe(unsafeInterleaveIO)++import Development.Shake.Core+import Development.Shake.FilePath+import Development.Shake.Types+import Development.Shake.Rules.File++import GHC.IO.Exception (IOErrorType(..), IOException(..))+++---------------------------------------------------------------------+-- ACTUAL EXECUTION++-- | Options passed to 'command' or 'cmd' to control how processes are executed.+data CmdOption+ = Cwd FilePath -- ^ Change the current directory in the spawned process. By default uses this processes current directory.+ | Env [(String,String)] -- ^ Change the environment variables in the spawned process. By default uses this processes environment.+ -- Use 'addPath' to modify the @$PATH@ variable, or 'addEnv' to modify other variables.+ | Stdin String -- ^ Given as the @stdin@ of the spawned process. By default the @stdin@ is inherited.+ | Shell -- ^ Pass the command to the shell without escaping - any arguments will be joined with spaces. By default arguments are escaped properly.+ | BinaryPipes -- ^ Treat the @stdin@\/@stdout@\/@stderr@ messages as binary. By default streams use text encoding.+ | Traced String -- ^ Name to use with 'traced', or @\"\"@ for no tracing. By default traces using the name of the executable.+ | WithStderr Bool -- ^ Should I include the @stderr@ in the exception if the command fails? Defaults to 'True'.+ | EchoStdout Bool -- ^ Should I echo the @stdout@? Defaults to 'True' unless a 'Stdout' result is required.+ | EchoStderr Bool -- ^ Should I echo the @stderr@? Defaults to 'True' unless a 'Stderr' result is required.+ deriving (Eq,Ord,Show)+++-- | Produce a 'CmdOption' of value 'Env' that is the current environment, plus a+-- prefix and suffix to the @$PATH@ environment variable. For example:+--+-- @+-- opt <- 'addPath' [\"\/usr\/special\"] []+-- 'cmd' opt \"userbinary --version\"+-- @+--+-- Would prepend @\/usr\/special@ to the current @$PATH@, and the command would pick+-- @\/usr\/special\/userbinary@, if it exists. To add other variables see 'addEnv'.+addPath :: MonadIO m => [String] -> [String] -> m CmdOption+addPath pre post = do+ args <- liftIO getEnvironment+ let (path,other) = partition ((== "PATH") . (if isWindows then upper else id) . fst) args+ return $ Env $+ [("PATH",intercalate [searchPathSeparator] $ pre ++ post) | null path] +++ [(a,intercalate [searchPathSeparator] $ pre ++ [b | b /= ""] ++ post) | (a,b) <- path] +++ other++-- | Produce a 'CmdOption' of value 'Env' that is the current environment, plus the argument+-- environment variables. For example:+--+-- @+-- opt <- 'addEnv' [(\"CFLAGS\",\"-O2\")]+-- 'cmd' opt \"gcc -c main.c\"+-- @+--+-- Would add the environment variable @$CFLAGS@ with value @-O2@. If the variable @$CFLAGS@+-- was already defined it would be overwritten. If you wish to modify @$PATH@ see 'addPath'.+addEnv :: MonadIO m => [(String, String)] -> m CmdOption+addEnv extra = do+ args <- liftIO getEnvironment+ return $ Env $ extra ++ filter (\(a,b) -> a `notElem` map fst extra) args+++data Result+ = ResultStdout String+ | ResultStderr String+ | ResultCode ExitCode+ deriving Eq+++commandExplicit :: String -> [CmdOption] -> [Result] -> String -> [String] -> Action [Result]+commandExplicit funcName copts results exe args = do+ opts <- getShakeOptions+ verb <- getVerbosity++ let skipper act = if null results && not (shakeRunCommands opts) then return [] else act++ let verboser act = do+ let cwd = listToMaybe $ reverse [x | Cwd x <- copts]+ putLoud $ maybe "" (\x -> "cd " ++ x ++ "; ") cwd ++ saneCommandForUser exe args+ (if verb >= Loud then quietly else id) act++ let tracer = case reverse [x | Traced x <- copts] of+ "":_ -> liftIO+ msg:_ -> traced msg+ [] -> traced (takeFileName exe)++ let tracker act = case shakeLint opts of+ Just LintTracker -> do+ dir <- liftIO $ getTemporaryDirectory+ (file, handle) <- liftIO $ openTempFile dir "shake.lint"+ liftIO $ hClose handle+ dir <- return $ file <.> "dir"+ liftIO $ createDirectory dir+ let cleanup = removeDirectoryRecursive dir >> removeFile file+ flip actionFinally cleanup $ do+ res <- act "tracker" $ "/if":dir:"/c":exe:args+ (read,write) <- liftIO $ trackerFiles dir+ trackRead read+ trackWrite write+ return res+ _ -> act exe args++ skipper $ tracker $ \exe args -> verboser $ tracer $ commandExplicitIO funcName copts results exe args+++-- | Given a directory (as passed to tracker /if) report on which files were used for reading/writing+trackerFiles :: FilePath -> IO ([FilePath], [FilePath])+trackerFiles dir = do+ curdir <- getCurrentDirectory+ let pre = upper curdir ++ "\\"+ files <- getDirectoryContents dir+ let f typ = do+ files <- forM [x | x <- files, takeExtension x == ".tlog", takeExtension (dropExtension $ dropExtension x) == '.':typ] $ \file -> do+ xs <- readFileEncoding utf16 $ dir </> file+ return $ filter (not . isPrefixOf "." . takeFileName) . mapMaybe (stripPrefix pre) $ lines xs+ fmap nub $ mapMaybeM correctCase $ nub $ concat files+ liftM2 (,) (f "read") (f "write")+++correctCase :: FilePath -> IO (Maybe FilePath)+correctCase x = f "" x+ where+ f pre "" = return $ Just pre+ f pre x = do+ let (a,b) = (takeDirectory1 x, dropDirectory1 x)+ dir <- getDirectoryContents pre+ case find ((==) a . upper) dir of+ Nothing -> return Nothing -- if it can't be found it probably doesn't exist, so assume a file that wasn't really read+ Just v -> f (pre +/+ v) b++ a +/+ b = if null a then b else a ++ "/" ++ b+++commandExplicitIO :: String -> [CmdOption] -> [Result] -> String -> [String] -> IO [Result]+commandExplicitIO funcName opts results exe args = do+-- BEGIN COPIED+-- Originally from readProcessWithExitCode with as few changes as possible+ cp <- resolvePath cp+ mask $ \restore -> do+ ans <- try_ $ createProcess cp+ (inh, outh, errh, pid) <- case ans of+ Right a -> return a+ Left err -> failure $ show err++ let close = maybe (return ()) hClose+ flip onException+ (do close inh; close outh; close errh+ terminateProcess pid; waitForProcess pid) $ restore $ do++ -- set pipes to binary if appropriate+ when (BinaryPipes `elem` opts) $ do+ let bin = maybe (return ()) (`hSetBinaryMode` True)+ bin inh; bin outh; bin errh++ -- fork off a thread to start consuming stdout+ (out,waitOut,waitOutEcho) <- case outh of+ Nothing -> return ("", return (), return ())+ Just outh -> do+ out <- hGetContents outh+ waitOut <- forkWait $ C.evaluate $ rnf out+ waitOutEcho <- if stdoutEcho+ then forkWait (hPutStr stdout out)+ else return (return ())+ return (out,waitOut,waitOutEcho)++ -- fork off a thread to start consuming stderr+ (err,waitErr,waitErrEcho) <- case errh of+ Nothing -> return ("", return (), return ())+ Just errh -> do+ err <- hGetContents errh+ waitErr <- forkWait $ C.evaluate $ rnf err+ waitErrEcho <- if stderrEcho+ then forkWait (hPutStr stderr err)+ else return (return ())+ return (err,waitErr,waitErrEcho)++ -- now write and flush any input+ let writeInput = do+ case inh of+ Nothing -> return ()+ Just inh -> do+ hPutStr inh input+ hFlush inh+ hClose inh++ C.catch writeInput $ \e -> case e of+ IOError { ioe_type = ResourceVanished+ , ioe_errno = Just ioe }+ | Errno ioe == ePIPE -> return ()+ _ -> throwIO e++ -- wait on the output+ waitOut+ waitErr++ waitOutEcho+ waitErrEcho++ close outh+ close errh++ -- wait on the process+ ex <- waitForProcess pid+-- END COPIED++ when (ResultCode ExitSuccess `notElem` results && ex /= ExitSuccess) $ do+ failure $+ "Exit code: " ++ show (case ex of ExitFailure i -> i; _ -> 0) ++ "\n" +++ (if not stderrThrow then "Stderr not captured because ErrorsWithoutStderr was used"+ else if null err then "Stderr was empty"+ else "Stderr:\n" ++ unlines (dropWhile null $ lines err))++ return $ flip map results $ \x -> case x of+ ResultStdout _ -> ResultStdout out+ ResultStderr _ -> ResultStderr err+ ResultCode _ -> ResultCode ex+ where+ failure extra = do+ cwd <- case cwd cp of+ Nothing -> return ""+ Just v -> do+ v <- canonicalizePath v `catch_` const (return v)+ return $ "Current directory: " ++ v ++ "\n"+ fail $+ "Development.Shake." ++ funcName ++ ", system command failed\n" +++ "Command: " ++ saneCommandForUser exe args ++ "\n" +++ cwd ++ extra++ input = last $ "" : [x | Stdin x <- opts]++ -- what should I do with these handles+ binary = BinaryPipes `elem` opts+ stdoutEcho = last $ (ResultStdout "" `notElem` results) : [b | EchoStdout b <- opts]+ stdoutCapture = ResultStdout "" `elem` results+ stderrEcho = last $ (ResultStderr "" `notElem` results) : [b | EchoStderr b <- opts]+ stderrThrow = last $ True : [b | WithStderr b <- opts]+ stderrCapture = ResultStderr "" `elem` results || (stderrThrow && ResultCode ExitSuccess `notElem` results)++ cp0 = (if Shell `elem` opts then shell $ unwords $ exe:args else proc exe args)+ {std_out = if binary || stdoutCapture || not stdoutEcho then CreatePipe else Inherit+ ,std_err = if binary || stderrCapture || not stderrEcho then CreatePipe else Inherit+ ,std_in = if null input then Inherit else CreatePipe+ }+ cp = foldl applyOpt cp0{std_out = CreatePipe, std_err = CreatePipe} opts+ applyOpt :: CreateProcess -> CmdOption -> CreateProcess+ applyOpt o (Cwd x) = o{cwd = if x == "" then Nothing else Just x}+ applyOpt o (Env x) = o{env = Just x}+ applyOpt o _ = o+++-- | If the user specifies a custom $PATH, and not Shell, then try and resolve their exe ourselves.+-- Tricky, because on Windows it doesn't look in the $PATH first.+resolvePath :: CreateProcess -> IO CreateProcess+resolvePath cp+ | Just e <- env cp+ , Just (_, path) <- find ((==) "PATH" . (if isWindows then upper else id) . fst) e+ , RawCommand prog args <- cmdspec cp+ = do+ let progExe = if prog == prog -<.> exe then prog else prog <.> exe+ -- use unsafeInterleaveIO to allow laziness to skip the queries we don't use+ pathOld <- unsafeInterleaveIO $ fmap (fromMaybe "") $ lookupEnv "PATH"+ old <- unsafeInterleaveIO $ findExecutable prog+ new <- unsafeInterleaveIO $ findExecutableWith (splitSearchPath path) progExe+ old2 <- unsafeInterleaveIO $ findExecutableWith (splitSearchPath pathOld) progExe++ switch <- return $ case () of+ _ | path == pathOld -> False -- The state I can see hasn't changed+ | Nothing <- new -> False -- I have nothing to offer+ | Nothing <- old -> True -- I failed last time, so this must be an improvement+ | Just old <- old, Just new <- new, equalFilePath old new -> False -- no different+ | Just old <- old, Just old2 <- old2, equalFilePath old old2 -> True -- I could predict last time+ | otherwise -> False+ return $ case new of+ Just new | switch -> cp{cmdspec = RawCommand new args}+ _ -> cp+resolvePath cp = do+ return cp+++findExecutableWith :: [FilePath] -> String -> IO (Maybe FilePath)+findExecutableWith path x = flip firstJustM (map (</> x) path) $ \s ->+ ifM (doesFileExist s) (return $ Just s) (return Nothing)+++-- Copied from System.Process+forkWait :: IO a -> IO (IO a)+forkWait a = do+ res <- newEmptyMVar+ _ <- mask $ \restore -> forkIO $ try_ (restore a) >>= putMVar res+ return (takeMVar res >>= either throwIO return)+++-- Like System.Process, but tweaked to show less escaping,+-- Relies on relatively detailed internals of showCommandForUser.+saneCommandForUser :: FilePath -> [String] -> String+saneCommandForUser cmd args = unwords $ map f $ cmd:args+ where+ f x = if take (length y - 2) (drop 1 y) == x then x else y+ where y = showCommandForUser x []+++---------------------------------------------------------------------+-- FIXED ARGUMENT WRAPPER++-- | Collect the @stdout@ of the process.+-- If you are collecting the @stdout@, it will not be echoed to the terminal, unless you include 'EchoStdout'.+newtype Stdout = Stdout {fromStdout :: String}++-- | Collect the @stderr@ of the process.+-- If you are collecting the @stderr@, it will not be echoed to the terminal, unless you include 'EchoStderr'.+newtype Stderr = Stderr {fromStderr :: String}++-- | Collect the 'ExitCode' of the process.+-- If you do not collect the exit code, any 'ExitFailure' will cause an exception.+newtype Exit = Exit {fromExit :: ExitCode}++-- | A class for specifying what results you want to collect from a process.+-- Values are formed of 'Stdout', 'Stderr', 'Exit' and tuples of those.+class CmdResult a where+ -- Return a list of results (with the right type but dummy data)+ -- and a function to transform a populated set of results into a value+ cmdResult :: ([Result], [Result] -> a)++instance CmdResult Exit where+ cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> Exit x)++instance CmdResult ExitCode where+ cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> x)++instance CmdResult Stdout where+ cmdResult = ([ResultStdout ""], \[ResultStdout x] -> Stdout x)++instance CmdResult Stderr where+ cmdResult = ([ResultStderr ""], \[ResultStderr x] -> Stderr x)++instance CmdResult () where+ cmdResult = ([], \[] -> ())++instance (CmdResult x1, CmdResult x2) => CmdResult (x1,x2) where+ cmdResult = (a1++a2, \rs -> let (r1,r2) = splitAt (length a1) rs in (b1 r1, b2 r2))+ where (a1,b1) = cmdResult+ (a2,b2) = cmdResult++cmdResultWith f = second (f .) cmdResult++instance (CmdResult x1, CmdResult x2, CmdResult x3) => CmdResult (x1,x2,x3) where+ cmdResult = cmdResultWith $ \(a,(b,c)) -> (a,b,c)+++-- | Execute a system command. Before running 'command' make sure you 'Development.Shake.need' any files+-- that are used by the command.+--+-- This function takes a list of options (often just @[]@, see 'CmdOption' for the available+-- options), the name of the executable (either a full name, or a program on the @$PATH@) and+-- a list of arguments. The result is often @()@, but can be a tuple containg any of 'Stdout',+-- 'Stderr' and 'Exit'. Some examples:+--+-- @+-- 'command_' [] \"gcc\" [\"-c\",\"myfile.c\"] -- compile a file, throwing an exception on failure+-- 'Exit' c <- 'command' [] \"gcc\" [\"-c\",myfile] -- run a command, recording the exit code+-- ('Exit' c, 'Stderr' err) <- 'command' [] \"gcc\" [\"-c\",\"myfile.c\"] -- run a command, recording the exit code and error output+-- 'Stdout' out <- 'command' [] \"gcc\" [\"-MM\",\"myfile.c\"] -- run a command, recording the output+-- 'command_' ['Cwd' \"generated\"] \"gcc\" [\"-c\",myfile] -- run a command in a directory+-- @+--+-- Unless you retrieve the 'ExitCode' using 'Exit', any 'ExitFailure' will throw an error, including+-- the 'Stderr' in the exception message. If you capture the 'Stdout' or 'Stderr', that stream will not be echoed to the console,+-- unless you use the option 'EchoStdout' or 'EchoStderr'.+--+-- If you use 'command' inside a @do@ block and do not use the result, you may get a compile-time error about being+-- unable to deduce 'CmdResult'. To avoid this error, use 'command_'.+command :: CmdResult r => [CmdOption] -> String -> [String] -> Action r+command opts x xs = fmap b $ commandExplicit "command" opts a x xs+ where (a,b) = cmdResult++-- | A version of 'command' where you do not require any results, used to avoid errors about being unable+-- to deduce 'CmdResult'.+command_ :: [CmdOption] -> String -> [String] -> Action ()+command_ opts x xs = void $ commandExplicit "command_" opts [] x xs+++---------------------------------------------------------------------+-- VARIABLE ARGUMENT WRAPPER++type a :-> t = a+++-- | Execute a system command. Before running 'cmd' make sure you 'Development.Shake.need' any files+-- that are used by the command.+--+-- * @String@ arguments are treated as whitespace separated arguments.+--+-- * @[String]@ arguments are treated as literal arguments.+--+-- * 'CmdOption' arguments are used as options.+--+-- To take the examples from 'command':+--+-- @+-- () <- 'cmd' \"gcc -c myfile.c\" -- compile a file, throwing an exception on failure+-- 'Exit' c <- 'cmd' \"gcc -c\" [myfile] -- run a command, recording the exit code+-- ('Exit' c, 'Stderr' err) <- 'cmd' \"gcc -c myfile.c\" -- run a command, recording the exit code and error output+-- 'Stdout' out <- 'cmd' \"gcc -MM myfile.c\" -- run a command, recording the output+-- 'cmd' ('Cwd' \"generated\") \"gcc -c\" [myfile] :: 'Action' () -- run a command in a directory+-- @+--+-- When passing file arguments we use @[myfile]@ so that if the @myfile@ variable contains spaces they are properly escaped.+--+-- If you use 'cmd' inside a @do@ block and do not use the result, you may get a compile-time error about being+-- unable to deduce 'CmdResult'. To avoid this error, bind the result to @()@, or include a type signature.+--+-- The 'cmd' command can also be run in the 'IO' monad, but then 'Traced' is ignored and command lines are not echoed.+cmd :: CmdArguments args => args :-> Action r+cmd = cmdArguments []++class CmdArguments t where cmdArguments :: [Either CmdOption String] -> t+instance (Arg a, CmdArguments r) => CmdArguments (a -> r) where+ cmdArguments xs x = cmdArguments $ xs ++ arg x+instance CmdResult r => CmdArguments (Action r) where+ cmdArguments x = case partitionEithers x of+ (opts, x:xs) -> let (a,b) = cmdResult in fmap b $ commandExplicit "cmd" opts a x xs+ _ -> error "Error, no executable or arguments given to Development.Shake.cmd"+instance CmdResult r => CmdArguments (IO r) where+ cmdArguments x = case partitionEithers x of+ (opts, x:xs) -> let (a,b) = cmdResult in fmap b $ commandExplicitIO "cmd" opts a x xs+ _ -> error "Error, no executable or arguments given to Development.Shake.cmd"++class Arg a where arg :: a -> [Either CmdOption String]+instance Arg String where arg = map Right . words+instance Arg [String] where arg = map Right+instance Arg (Maybe String) where arg = map Right . maybe [] words+instance Arg CmdOption where arg = return . Left+instance Arg [CmdOption] where arg = map Left+instance Arg (Maybe CmdOption) where arg = map Left . maybeToList
+ src/Development/Shake/Config.hs view
@@ -0,0 +1,107 @@+{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}++-- | A module for parsing and using config files in a Shake build system. Config files+-- consist of variable bindings, for example:+--+-- > # This is my Config file+-- > HEADERS_DIR = /path/to/dir+-- > CFLAGS = -g -I${HEADERS_DIR}+-- > CFLAGS = $CFLAGS -O2+-- > include extra/file.cfg+--+-- This defines the variable @HEADERS_DIR@ (equal to @\/path\/to\/dir@), and+-- @CFLAGS@ (equal to @-g -I\/path\/to\/dir -O2@), and also includes the configuration+-- statements in the file @extra/file.cfg@. The full lexical syntax for configuration+-- files is defined here: <http://martine.github.io/ninja/manual.html#_lexical_syntax>.+--+-- To use the configuration file either use 'readConfigFile' to parse the configuration file+-- and use the values directly, or 'usingConfigFile' and 'getConfig' to track the configuration+-- values, so they become build dependencies.+module Development.Shake.Config(+ readConfigFile, readConfigFileWithEnv,+ usingConfigFile, usingConfig,+ getConfig, getConfigKeys+ ) where++import Development.Shake+import Development.Shake.Classes+import qualified Development.Ninja.Parse as Ninja+import qualified Development.Ninja.Env as Ninja+import qualified Data.HashMap.Strict as Map+import qualified Data.ByteString.UTF8 as UTF8+import Control.Applicative+import Data.Tuple.Extra+import Data.List+++-- | Read a config file, returning a list of the variables and their bindings.+-- Config files use the Ninja lexical syntax:+-- <http://martine.github.io/ninja/manual.html#_lexical_syntax>+readConfigFile :: FilePath -> IO (Map.HashMap String String)+readConfigFile = readConfigFileWithEnv []+++-- | Read a config file with an initial environment, returning a list of the variables and their bindings.+-- Config files use the Ninja lexical syntax:+-- <http://martine.github.io/ninja/manual.html#_lexical_syntax>+readConfigFileWithEnv :: [(String, String)] -> FilePath -> IO (Map.HashMap String String)+readConfigFileWithEnv vars file = do+ env <- Ninja.newEnv+ mapM_ (uncurry (Ninja.addEnv env) . (UTF8.fromString *** UTF8.fromString)) vars+ Ninja.parse file env+ mp <- Ninja.fromEnv env+ return $ Map.fromList $ map (UTF8.toString *** UTF8.toString) $ Map.toList mp+++newtype Config = Config String deriving (Show,Typeable,Eq,Hashable,Binary,NFData)++newtype ConfigKeys = ConfigKeys () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+++-- | Specify the file to use with 'getConfig'.+usingConfigFile :: FilePath -> Rules ()+usingConfigFile file = do+ mp <- newCache $ \() -> liftIO $ readConfigFile file+ addOracle $ \(Config x) -> Map.lookup x <$> mp ()+ addOracle $ \(ConfigKeys x) -> sort . Map.keys <$> mp ()+ return ()+++-- | Specify the values to use with 'getConfig', generally prefer+-- 'usingConfigFile' unless you also need access to the values+-- of variables outside 'Action'.+usingConfig :: Map.HashMap String String -> Rules ()+usingConfig mp = do+ addOracle $ \(Config x) -> return $ Map.lookup x mp+ return ()+++-- | Obtain the value of a configuration variable, returns 'Nothing' to indicate the variable+-- has no binding. Any build system using 'getConfig' /must/ call either 'usingConfigFile'+-- or 'usingConfig'. The 'getConfig' function will introduce a dependency on the configuration+-- variable (but not the whole configuration file), and if the configuration variable changes, the rule will be rerun.+-- As an example:+--+-- @+-- 'usingConfigFile' \"myconfiguration.cfg\"+-- \"*.o\" '%>' \\out -> do+-- cflags <- 'getConfig' \"CFLAGS\"+-- 'cmd' \"gcc\" [out '-<.>' \"c\"] (fromMaybe \"\" cflags)+-- @+getConfig :: String -> Action (Maybe String)+getConfig = askOracle . Config+++-- | Obtain the configuration keys.+-- Any build system using 'getConfigKeys' /must/ call either 'usingConfigFile' or 'usingConfig'.+-- The 'getConfigKeys' function will introduce a dependency on the configuration keys+-- (but not the whole configuration file), and if the configuration keys change, the rule will be rerun.+-- Usually use as part of an action.+-- As an example:+--+-- @+-- 'usingConfigFile' \"myconfiguration.cfg\"+-- 'action' $ need =<< getConfigKeys+-- @+getConfigKeys :: Action [String]+getConfigKeys = askOracle $ ConfigKeys ()
+ src/Development/Shake/Core.hs view
@@ -0,0 +1,833 @@+{-# LANGUAGE RecordWildCards, GeneralizedNewtypeDeriving, ScopedTypeVariables, PatternGuards #-}+{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses #-}++{-# LANGUAGE CPP #-}+#if __GLASGOW_HASKELL__ >= 704+{-# LANGUAGE ConstraintKinds #-}+#endif++module Development.Shake.Core(+ run,+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue,+#endif+ Rule(..), Rules, rule, action, withoutActions, alternatives, priority,+ Action, actionOnException, actionFinally, apply, apply1, traced, getShakeOptions,+ trackUse, trackChange, trackAllow,+ getVerbosity, putLoud, putNormal, putQuiet, withVerbosity, quietly,+ Resource, newResource, newResourceIO, withResource, withResources, newThrottle, newThrottleIO,+ newCache, newCacheIO,+ unsafeExtraThread,+ -- Internal stuff+ rulesIO, runAfter+ ) where++import Prelude(); import General.Prelude++import Control.Exception.Extra+import Control.Applicative+import Data.Tuple.Extra+import Control.Concurrent.Extra+import Control.Monad.Extra+import Control.Monad.IO.Class+import Control.Monad.Trans.Writer.Strict+import Data.Typeable+import Data.Function+import Data.Either.Extra+import Numeric.Extra+import Data.List+import qualified Data.HashMap.Strict as Map+import Data.Maybe+import Data.IORef+import System.Directory+import System.IO.Extra+import System.Time.Extra++import Development.Shake.Classes+import Development.Shake.Pool+import Development.Shake.Database+import Development.Shake.Monad+import Development.Shake.Resource+import Development.Shake.Value+import Development.Shake.Profile+import Development.Shake.Types+import Development.Shake.Errors+import Development.Shake.Special+import General.Timing+import General.Extra+import General.Concurrent+import General.Cleanup+import General.String+++---------------------------------------------------------------------+-- RULES++#if __GLASGOW_HASKELL__ >= 704+-- | Define an alias for the six type classes required for things involved in Shake 'Development.Shake.Rule's.+-- This alias is only available in GHC 7.4 and above, and requires the @ConstraintKinds@ extension.+--+-- To define your own values meeting the necessary constraints it is convenient to use the extensions+-- @GeneralizedNewtypeDeriving@ and @DeriveDataTypeable@ to write:+--+-- > newtype MyType = MyType (String, Bool) deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+type ShakeValue a = (Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a)+#endif+++-- | Define a pair of types that can be used by Shake rules.+-- To import all the type classes required see "Development.Shake.Classes".+class (+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue key, ShakeValue value+#else+ Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key,+ Show value, Typeable value, Eq value, Hashable value, Binary value, NFData value+#endif+ ) => Rule key value where++ -- | /[Required]/ Retrieve the @value@ associated with a @key@, if available.+ --+ -- As an example for filenames/timestamps, if the file exists you should return 'Just'+ -- the timestamp, but otherwise return 'Nothing'. For rules whose values are not+ -- stored externally, 'storedValue' should return 'Nothing'.+ storedValue :: ShakeOptions -> key -> IO (Maybe value)++ -- | /[Optional]/ Equality check, with a notion of how expensive the check was.+ equalValue :: ShakeOptions -> key -> value -> value -> EqualCost+ equalValue _ _ v1 v2 = if v1 == v2 then EqualCheap else NotEqual+++data ARule m = forall key value . Rule key value => ARule (key -> Maybe (m value))++ruleKey :: Rule key value => (key -> Maybe (m value)) -> key+ruleKey = err "ruleKey"++ruleValue :: Rule key value => (key -> Maybe (m value)) -> value+ruleValue = err "ruleValue"+++-- | Define a set of rules. Rules can be created with calls to functions such as 'Development.Shake.%>' or 'action'. Rules are combined+-- with either the 'Monoid' instance, or (more commonly) the 'Monad' instance and @do@ notation. To define your own+-- custom types of rule, see "Development.Shake.Rule".+newtype Rules a = Rules (WriterT (SRules Action) IO a) -- All IO must be associative/commutative (e.g. creating IORef/MVars)+ deriving (Monad, Functor, Applicative)++rulesIO :: IO a -> Rules a+rulesIO = Rules . liftIO++newRules :: SRules Action -> Rules ()+newRules = Rules . tell++modifyRules :: (SRules Action -> SRules Action) -> Rules () -> Rules ()+modifyRules f (Rules r) = Rules $ censor f r++getRules :: Rules () -> IO (SRules Action)+getRules (Rules r) = execWriterT r+++data SRules m = SRules+ {actions :: [m ()]+ ,rules :: Map.HashMap TypeRep{-k-} (TypeRep{-k-},TypeRep{-v-},[(Double,ARule m)]) -- higher fst is higher priority+ }++instance Monoid (SRules m) where+ mempty = SRules [] (Map.fromList [])+ mappend (SRules x1 x2) (SRules y1 y2) = SRules (x1++y1) (Map.unionWith f x2 y2)+ where f (k, v1, xs) (_, v2, ys)+ | v1 == v2 = (k, v1, xs ++ ys)+ | otherwise = errorIncompatibleRules k v1 v2++instance Monoid a => Monoid (Rules a) where+ mempty = return mempty+ mappend = liftA2 mappend+++-- | Add a rule to build a key, returning an appropriate 'Action'. All rules at a given priority+-- must be disjoint. Rules have priority 1 by default, but can be modified with 'priority'.+rule :: Rule key value => (key -> Maybe (Action value)) -> Rules ()+rule r = newRules mempty{rules = Map.singleton k (k, v, [(1,ARule r)])}+ where k = typeOf $ ruleKey r; v = typeOf $ ruleValue r+++-- | Change the priority of a given set of rules, where higher priorities take precedence.+-- All matching rules at a given priority must be disjoint, or an error is raised.+-- All builtin Shake rules have priority between 0 and 1.+-- Excessive use of 'priority' is discouraged. As an example:+--+-- @+-- 'priority' 4 $ \"hello.*\" %> \\out -> 'writeFile'' out \"hello.*\"+-- 'priority' 8 $ \"*.txt\" %> \\out -> 'writeFile'' out \"*.txt\"+-- @+--+-- In this example @hello.txt@ will match the second rule, instead of raising an error about ambiguity.+priority :: Double -> Rules () -> Rules ()+priority i = modifyRules $ \s -> s{rules = Map.map (\(a,b,cs) -> (a,b,map (first $ const i) cs)) $ rules s}+++-- | Change the matching behaviour of rules so rules do not have to be disjoint, but are instead matched+-- in order. Only recommended for small blocks containing a handful of rules.+--+-- @+-- 'alternatives' $ do+-- \"hello.*\" %> \\out -> 'writeFile'' out \"hello.*\"+-- \"*.txt\" %> \\out -> 'writeFile'' out \"*.txt\"+-- @+--+-- In this example @hello.txt@ will match the first rule, instead of raising an error about ambiguity.+alternatives :: Rules () -> Rules ()+alternatives = modifyRules $ \r -> r{rules = Map.map f $ rules r}+ where+ f (k, v, []) = (k, v, [])+ f (k, v, xs) = let (is,rs) = unzip xs in (k, v, [(maximum is, foldl1' g rs)])++ g (ARule a) (ARule b) = ARule $ \x -> a x `mplus` b2 x+ where b2 = fmap (fmap (fromJust . cast)) . b . fromJust . cast+++-- | Run an action, usually used for specifying top-level requirements.+--+-- @+-- main = 'Development.Shake.shake' 'shakeOptions' $ do+-- 'action' $ do+-- b <- 'Development.Shake.doesFileExist' \"file.src\"+-- when b $ 'Development.Shake.need' [\"file.out\"]+-- @+--+-- This 'action' builds @file.out@, but only if @file.src@ exists. The 'action'+-- will be run in every build execution (unless 'withoutActions' is used), so only cheap+-- operations should be performed. All arguments to 'action' may be run in parallel, in any order.+--+-- For the standard requirement of only 'Development.Shake.need'ing a fixed list of files in the 'action',+-- see 'Development.Shake.want'.+action :: Action a -> Rules ()+action a = newRules mempty{actions=[void a]}+++-- | Remove all actions specified in a set of rules, usually used for implementing+-- command line specification of what to build.+withoutActions :: Rules () -> Rules ()+withoutActions = modifyRules $ \x -> x{actions=[]}+++registerWitnesses :: SRules m -> IO ()+registerWitnesses SRules{..} =+ forM_ (Map.elems rules) $ \(_, _, (_,ARule r):_) -> do+ registerWitness $ ruleKey r+ registerWitness $ ruleValue r+++data RuleInfo m = RuleInfo+ {stored :: Key -> IO (Maybe Value)+ ,equal :: Key -> Value -> Value -> EqualCost+ ,execute :: Key -> m Value+ ,resultType :: TypeRep+ }++createRuleinfo :: ShakeOptions -> SRules Action -> Map.HashMap TypeRep (RuleInfo Action)+createRuleinfo opt SRules{..} = flip Map.map rules $ \(_,tv,rs) -> RuleInfo (stored rs) (equal rs) (execute rs) tv+ where+ stored ((_,ARule r):_) = fmap (fmap newValue) . f r . fromKey+ where f :: Rule key value => (key -> Maybe (m value)) -> (key -> IO (Maybe value))+ f _ = storedValue opt++ equal ((_,ARule r):_) = \k v1 v2 -> f r (fromKey k) (fromValue v1) (fromValue v2)+ where f :: Rule key value => (key -> Maybe (m value)) -> key -> value -> value -> EqualCost+ f _ = equalValue opt++ execute rs = \k -> case filter (not . null) $ map (mapMaybe ($ k)) rs2 of+ [r]:_ -> r+ rs -> errorMultipleRulesMatch (typeKey k) (show k) (length rs)+ where rs2 = sets [(i, \k -> fmap (fmap newValue) $ r (fromKey k)) | (i,ARule r) <- rs] ++ sets :: Ord a => [(a, b)] -> [[b]] -- highest to lowest+ sets = map (map snd) . reverse . groupBy ((==) `on` fst) . sortBy (compare `on` fst)++runStored :: Map.HashMap TypeRep (RuleInfo m) -> Key -> IO (Maybe Value)+runStored mp k = case Map.lookup (typeKey k) mp of+ Nothing -> return Nothing+ Just RuleInfo{..} -> stored k++runEqual :: Map.HashMap TypeRep (RuleInfo m) -> Key -> Value -> Value -> EqualCost+runEqual mp k v1 v2 = case Map.lookup (typeKey k) mp of+ Nothing -> NotEqual+ Just RuleInfo{..} -> equal k v1 v2++runExecute :: Map.HashMap TypeRep (RuleInfo m) -> Key -> m Value+runExecute mp k = let tk = typeKey k in case Map.lookup tk mp of+ Nothing -> errorNoRuleToBuildType tk (Just $ show k) Nothing -- Not sure if this is even possible, but best be safe+ Just RuleInfo{..} -> execute k+++---------------------------------------------------------------------+-- MAKE++-- global constants of Action+data Global = Global+ {globalDatabase :: Database+ ,globalPool :: Pool+ ,globalCleanup :: Cleanup+ ,globalTimestamp :: IO Seconds+ ,globalRules :: Map.HashMap TypeRep (RuleInfo Action)+ ,globalOutput :: Verbosity -> String -> IO ()+ ,globalOptions :: ShakeOptions+ ,globalDiagnostic :: String -> IO ()+ ,globalLint :: String -> IO ()+ ,globalAfter :: IORef [IO ()]+ ,globalTrackAbsent :: IORef [(Key, Key)] -- in rule fst, snd must be absent+ }+++-- local variables of Action+data Local = Local+ -- constants+ {localStack :: Stack+ -- stack scoped local variables+ ,localVerbosity :: Verbosity+ ,localBlockApply :: Maybe String -- reason to block apply, or Nothing to allow+ -- mutable local variables+ ,localDepends :: [Depends] -- built up in reverse+ ,localDiscount :: !Seconds+ ,localTraces :: [Trace] -- in reverse+ ,localTrackAllows :: [Key -> Bool]+ ,localTrackUsed :: [Key]+ }++-- | The 'Action' monad, use 'liftIO' to raise 'IO' actions into it, and 'Development.Shake.need' to execute files.+-- Action values are used by 'rule' and 'action'. The 'Action' monad tracks the dependencies of a 'Rule'.+newtype Action a = Action {fromAction :: RAW Global Local a}+ deriving (Functor, Applicative, Monad, MonadIO)+++actionBoom :: Bool -> Action a -> IO b -> Action a+actionBoom runOnSuccess act clean = do+ cleanup <- Action $ getsRO globalCleanup+ clean <- liftIO $ addCleanup cleanup $ void clean+ res <- Action $ catchRAW (fromAction act) $ \e -> liftIO (clean True) >> throwRAW e+ liftIO $ clean runOnSuccess+ return res++-- | If an exception is raised by the 'Action', perform some 'IO'.+actionOnException :: Action a -> IO b -> Action a+actionOnException = actionBoom False++-- | After an 'Action', perform some 'IO', even if there is an exception.+actionFinally :: Action a -> IO b -> Action a+actionFinally = actionBoom True+++-- | Internal main function (not exported publicly)+run :: ShakeOptions -> Rules () -> IO ()+run opts@ShakeOptions{..} rs = (if shakeLineBuffering then lineBuffering else id) $ do+ start <- offsetTime+ rs <- getRules rs+ registerWitnesses rs++ outputLocked <- do+ lock <- newLock+ return $ \v msg -> withLock lock $ shakeOutput v msg++ let diagnostic = if shakeVerbosity >= Diagnostic then outputLocked Diagnostic . ("% "++) else const $ return ()+ let output v = outputLocked v . abbreviate shakeAbbreviations++ except <- newIORef (Nothing :: Maybe (String, SomeException))+ let staunch act | not shakeStaunch = void act+ | otherwise = do+ res <- try act+ case res of+ Left err -> do+ let named = maybe "" (abbreviate shakeAbbreviations . shakeExceptionTarget) . fromException+ atomicModifyIORef except $ \v -> (Just $ fromMaybe (named err, err) v, ())+ let msg = show err ++ "Continuing due to staunch mode, this error will be repeated later"+ when (shakeVerbosity >= Quiet) $ output Quiet msg+ Right _ -> return ()++ lint <- if isNothing shakeLint then return $ const $ return () else do+ dir <- getCurrentDirectory+ return $ \msg -> do+ now <- getCurrentDirectory+ when (dir /= now) $ errorStructured+ "Lint checking error - current directory has changed"+ [("When", Just msg)+ ,("Wanted",Just dir)+ ,("Got",Just now)]+ ""++ after <- newIORef []+ absent <- newIORef []+ shakeThreads <- if shakeThreads == 0 then getProcessorCount else return shakeThreads+ withCleanup $ \cleanup -> do+ _ <- addCleanup cleanup $ do+ when shakeTimings printTimings+ resetTimings -- so we don't leak memory+ withNumCapabilities shakeThreads $ do+ withDatabase opts diagnostic $ \database -> do+ wait <- newBarrier+ tid <- forkIO $ flip finally (signalBarrier wait ()) $+ shakeProgress $ do+ failure <- fmap (fmap fst) $ readIORef except+ stats <- progress database+ return stats{isFailure=failure}+ addCleanup cleanup $ do+ killThread tid+ void $ timeout 1000000 $ waitBarrier wait++ let ruleinfo = createRuleinfo opts rs+ addTiming "Running rules"+ runPool (shakeThreads == 1) shakeThreads $ \pool -> do+ let s0 = Global database pool cleanup start ruleinfo output opts diagnostic lint after absent+ let s1 = Local emptyStack shakeVerbosity Nothing [] 0 [] [] []+ forM_ (actions rs) $ \act -> do+ addPool pool $ runAction s0 s1 act $ \x -> staunch $ either throwIO return x++ when (isJust shakeLint) $ do+ addTiming "Lint checking"+ absent <- readIORef absent+ checkValid database (runStored ruleinfo) (runEqual ruleinfo) absent+ when (shakeVerbosity >= Loud) $ output Loud "Lint checking succeeded"+ when (shakeReport /= []) $ do+ addTiming "Profile report"+ report <- toReport database+ forM_ shakeReport $ \file -> do+ when (shakeVerbosity >= Normal) $+ output Normal $ "Writing report to " ++ file+ writeProfile file report+ when (shakeLiveFiles /= []) $ do+ addTiming "Listing live"+ live <- listLive database+ let liveFiles = [show k | k <- live, specialIsFileKey $ typeKey k]+ forM_ shakeLiveFiles $ \file -> do+ when (shakeVerbosity >= Normal) $+ output Normal $ "Writing live list to " ++ file+ (if file == "-" then putStr else writeFile file) $ unlines liveFiles+ maybe (return ()) (throwIO . snd) =<< readIORef except+ sequence_ . reverse =<< readIORef after+++lineBuffering :: IO a -> IO a+lineBuffering = withBuffering stdout LineBuffering . withBuffering stderr LineBuffering+++abbreviate :: [(String,String)] -> String -> String+abbreviate [] = id+abbreviate abbrev = f+ where+ -- order so longer appreviations are preferred+ ordAbbrev = sortBy (flip (compare `on` length . fst)) abbrev++ f [] = []+ f x | (to,rest):_ <- [(to,rest) | (from,to) <- ordAbbrev, Just rest <- [stripPrefix from x]] = to ++ f rest+ f (x:xs) = x : f xs+++wrapStack :: IO [String] -> IO a -> IO a+wrapStack stk act = catch_ act $ \(SomeException e) -> case cast e of+ Just s@ShakeException{} -> throwIO s+ Nothing -> do+ stk <- stk+ if null stk then throwIO e+ else throwIO $ ShakeException (last stk) stk $ SomeException e+++runAction :: Global -> Local -> Action a -> Capture (Either SomeException a)+runAction g l (Action x) k = runRAW g l x k+++runAfter :: IO () -> Action ()+runAfter op = do+ Global{..} <- Action getRO+ liftIO $ atomicModifyIORef globalAfter $ \ops -> (op:ops, ())+++-- | Execute a rule, returning the associated values. If possible, the rules will be run in parallel.+-- This function requires that appropriate rules have been added with 'rule'.+-- All @key@ values passed to 'apply' become dependencies of the 'Action'.+apply :: Rule key value => [key] -> Action [value]+apply = f -- Don't short-circuit [] as we still want error messages+ where+ -- We don't want the forall in the Haddock docs+ f :: forall key value . Rule key value => [key] -> Action [value]+ f ks = do+ let tk = typeOf (err "apply key" :: key)+ tv = typeOf (err "apply type" :: value)+ Global{..} <- Action getRO+ block <- Action $ getsRW localBlockApply+ whenJust block $ errorNoApply tk (fmap show $ listToMaybe ks)+ case Map.lookup tk globalRules of+ Nothing -> errorNoRuleToBuildType tk (fmap show $ listToMaybe ks) (Just tv)+ Just RuleInfo{resultType=tv2} | tv /= tv2 -> errorRuleTypeMismatch tk (fmap show $ listToMaybe ks) tv2 tv+ _ -> fmap (map fromValue) $ applyKeyValue $ map newKey ks+++applyKeyValue :: [Key] -> Action [Value]+applyKeyValue [] = return []+applyKeyValue ks = do+ global@Global{..} <- Action getRO+ let exec stack k continue = do+ let s = Local {localVerbosity=shakeVerbosity globalOptions, localDepends=[], localStack=stack, localBlockApply=Nothing+ ,localDiscount=0, localTraces=[], localTrackAllows=[], localTrackUsed=[]}+ let top = showTopStack stack+ time <- offsetTime+ runAction global s (do+ liftIO $ evaluate $ rnf k+ liftIO $ globalLint $ "before building " ++ top+ putWhen Chatty $ "# " ++ show k+ res <- runExecute globalRules k+ when (shakeLint globalOptions == Just LintTracker)+ trackCheckUsed+ Action $ fmap ((,) res) getRW) $ \x -> case x of+ Left e -> (continue =<<) $ try $ wrapStack (showStack globalDatabase stack) $ throwIO e+ Right (res, Local{..}) -> do+ dur <- time+ globalLint $ "after building " ++ top+ let ans = (res, reverse localDepends, dur - localDiscount, reverse localTraces)+ evaluate $ rnf ans+ continue $ Right ans+ stack <- Action $ getsRW localStack+ (dur, dep, vs) <- Action $ captureRAW $ build globalPool globalDatabase (Ops (runStored globalRules) (runEqual globalRules) exec) stack ks+ Action $ modifyRW $ \s -> s{localDiscount=localDiscount s + dur, localDepends=dep : localDepends s}+ return vs+++-- | Apply a single rule, equivalent to calling 'apply' with a singleton list. Where possible,+-- use 'apply' to allow parallelism.+apply1 :: Rule key value => key -> Action value+apply1 = fmap head . apply . return+++-- | Get the initial 'ShakeOptions', these will not change during the build process.+getShakeOptions :: Action ShakeOptions+getShakeOptions = Action $ getsRO globalOptions+++-- | Write an action to the trace list, along with the start/end time of running the IO action.+-- The 'Development.Shake.cmd' and 'Development.Shake.command' functions automatically call 'traced'.+-- The trace list is used for profile reports (see 'shakeReport').+traced :: String -> IO a -> Action a+traced msg act = do+ Global{..} <- Action getRO+ stack <- Action $ getsRW localStack+ start <- liftIO globalTimestamp+ putNormal $ "# " ++ msg ++ " (for " ++ showTopStack stack ++ ")"+ res <- liftIO act+ stop <- liftIO globalTimestamp+ Action $ modifyRW $ \s -> s{localTraces = Trace (pack msg) (doubleToFloat start) (doubleToFloat stop) : localTraces s}+ return res+++putWhen :: Verbosity -> String -> Action ()+putWhen v msg = do+ Global{..} <- Action getRO+ verb <- getVerbosity+ when (verb >= v) $+ liftIO $ globalOutput v msg+++-- | Write a message to the output when the verbosity ('shakeVerbosity') is appropriate.+-- The output will not be interleaved with any other Shake messages+-- (other than those generated by system commands).+putLoud, putNormal, putQuiet :: String -> Action ()+putLoud = putWhen Loud+putNormal = putWhen Normal+putQuiet = putWhen Quiet+++-- | Get the current verbosity level, originally set by 'shakeVerbosity'. If you+-- want to output information to the console, you are recommended to use+-- 'putLoud' \/ 'putNormal' \/ 'putQuiet', which ensures multiple messages are+-- not interleaved. The verbosity can be modified locally by 'withVerbosity'.+getVerbosity :: Action Verbosity+getVerbosity = Action $ getsRW localVerbosity+++-- | Run an action with a particular verbosity level.+-- Will not update the 'shakeVerbosity' returned by 'getShakeOptions' and will+-- not have any impact on 'Diagnostic' tracing.+withVerbosity :: Verbosity -> Action a -> Action a+withVerbosity new = Action . unmodifyRW f . fromAction+ where f s0 = (s0{localVerbosity=new}, \s -> s{localVerbosity=localVerbosity s0})+++-- | Run an action with 'Quiet' verbosity, in particular messages produced by 'traced'+-- (including from 'Development.Shake.cmd' or 'Development.Shake.command') will not be printed to the screen.+-- Will not update the 'shakeVerbosity' returned by 'getShakeOptions' and will+-- not turn off any 'Diagnostic' tracing.+quietly :: Action a -> Action a+quietly = withVerbosity Quiet+++---------------------------------------------------------------------+-- TRACKING++-- | Track that a key has been used by the action preceeding it.+trackUse ::+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue key+#else+ (Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key)+#endif+ => key -> Action ()+-- One of the following must be true:+-- 1) you are the one building this key (e.g. key == topStack)+-- 2) you have already been used by apply, and are on the dependency list+-- 3) someone explicitly gave you permission with trackAllow+-- 4) at the end of the rule, a) you are now on the dependency list, and b) this key itself has no dependencies (is source file)+trackUse key = do+ let k = newKey key+ Global{..} <- Action getRO+ l@Local{..} <- Action getRW+ deps <- liftIO $ concatMapM (listDepends globalDatabase) localDepends+ let top = topStack localStack+ if top == Just k then+ return () -- condition 1+ else if k `elem` deps then+ return () -- condition 2+ else if any ($ k) localTrackAllows then+ return () -- condition 3+ else+ Action $ putRW l{localTrackUsed = k : localTrackUsed} -- condition 4+++trackCheckUsed :: Action ()+trackCheckUsed = do+ Global{..} <- Action getRO+ Local{..} <- Action getRW+ liftIO $ do+ deps <- concatMapM (listDepends globalDatabase) localDepends++ -- check 3a+ bad <- return $ localTrackUsed \\ deps+ unless (null bad) $ do+ let n = length bad+ errorStructured+ ("Link checking error - " ++ (if n == 1 then "value was" else show n ++ " values were") ++ " used but not depended upon")+ [("Used", Just $ show x) | x <- bad]+ ""++ -- check 3b+ bad <- flip filterM localTrackUsed $ \k -> fmap (not . null) $ lookupDependencies globalDatabase k+ unless (null bad) $ do+ let n = length bad+ errorStructured+ ("Link checking error - " ++ (if n == 1 then "value was" else show n ++ " values were") ++ " depended upon after being used")+ [("Used", Just $ show x) | x <- bad]+ ""+++-- | Track that a key has been changed by the action preceeding it.+trackChange ::+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue key+#else+ (Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key)+#endif+ => key -> Action ()+-- One of the following must be true:+-- 1) you are the one building this key (e.g. key == topStack)+-- 2) someone explicitly gave you permission with trackAllow+-- 3) this file is never known to the build system, at the end it is not in the database+trackChange key = do+ let k = newKey key+ Global{..} <- Action getRO+ Local{..} <- Action getRW+ liftIO $ do+ let top = topStack localStack+ if top == Just k then+ return () -- condition 1+ else if any ($ k) localTrackAllows then+ return () -- condition 2+ else+ -- condition 3+ atomicModifyIORef globalTrackAbsent $ \ks -> ((fromMaybe k top, k):ks, ())+++-- | Allow any matching key to violate the tracking rules.+trackAllow ::+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue key+#else+ (Show key, Typeable key, Eq key, Hashable key, Binary key, NFData key)+#endif+ => (key -> Bool) -> Action ()+trackAllow test = Action $ modifyRW $ \s -> s{localTrackAllows = f : localTrackAllows s}+ where+ -- We don't want the forall in the Haddock docs+ arrow1Type :: forall a b . Typeable a => (a -> b) -> TypeRep+ arrow1Type _ = typeOf (err "trackAllow" :: a)++ ty = arrow1Type test+ f k = typeKey k == ty && test (fromKey k)+++---------------------------------------------------------------------+-- RESOURCES++-- | Create a finite resource, given a name (for error messages) and a quantity of the resource that exists.+-- Shake will ensure that actions using the same finite resource do not execute in parallel.+-- As an example, only one set of calls to the Excel API can occur at one time, therefore+-- Excel is a finite resource of quantity 1. You can write:+--+-- @+-- 'Development.Shake.shake' 'Development.Shake.shakeOptions'{'Development.Shake.shakeThreads'=2} $ do+-- 'Development.Shake.want' [\"a.xls\",\"b.xls\"]+-- excel <- 'Development.Shake.newResource' \"Excel\" 1+-- \"*.xls\" 'Development.Shake.%>' \\out ->+-- 'Development.Shake.withResource' excel 1 $+-- 'Development.Shake.cmd' \"excel\" out ...+-- @+--+-- Now the two calls to @excel@ will not happen in parallel.+--+-- As another example, calls to compilers are usually CPU bound but calls to linkers are usually+-- disk bound. Running 8 linkers will often cause an 8 CPU system to grid to a halt. We can limit+-- ourselves to 4 linkers with:+--+-- @+-- disk <- 'Development.Shake.newResource' \"Disk\" 4+-- 'Development.Shake.want' [show i 'Development.Shake.FilePath.<.>' \"exe\" | i <- [1..100]]+-- \"*.exe\" 'Development.Shake.%>' \\out ->+-- 'Development.Shake.withResource' disk 1 $+-- 'Development.Shake.cmd' \"ld -o\" [out] ...+-- \"*.o\" 'Development.Shake.%>' \\out ->+-- 'Development.Shake.cmd' \"cl -o\" [out] ...+-- @+newResource :: String -> Int -> Rules Resource+newResource name mx = rulesIO $ newResourceIO name mx+++-- | Create a throttled resource, given a name (for error messages) and a number of resources (the 'Int') that can be+-- used per time period (the 'Double' in seconds). Shake will ensure that actions using the same throttled resource+-- do not exceed the limits. As an example, let us assume that making more than 1 request every 5 seconds to+-- Google results in our client being blacklisted, we can write:+--+-- @+-- google <- 'Development.Shake.newThrottle' \"Google\" 1 5+-- \"*.url\" 'Development.Shake.%>' \\out -> do+-- 'Development.Shake.withResource' google 1 $+-- 'Development.Shake.cmd' \"wget\" [\"http:\/\/google.com?q=\" ++ 'Development.Shake.FilePath.takeBaseName' out] \"-O\" [out]+-- @+--+-- Now we will wait at least 5 seconds after querying Google before performing another query. If Google change the rules to+-- allow 12 requests per minute we can instead use @'Development.Shake.newThrottle' \"Google\" 12 60@, which would allow+-- greater parallelisation, and avoid throttling entirely if only a small number of requests are necessary.+--+-- In the original example we never make a fresh request until 5 seconds after the previous request has /completed/. If we instead+-- want to throttle requests since the previous request /started/ we can write:+--+-- @+-- google <- 'Development.Shake.newThrottle' \"Google\" 1 5+-- \"*.url\" 'Development.Shake.%>' \\out -> do+-- 'Development.Shake.withResource' google 1 $ return ()+-- 'Development.Shake.cmd' \"wget\" [\"http:\/\/google.com?q=\" ++ 'Development.Shake.FilePath.takeBaseName' out] \"-O\" [out]+-- @+--+-- However, the rule may not continue running immediately after 'Development.Shake.withResource' completes, so while+-- we will never exceed an average of 1 request every 5 seconds, we may end up running an unbounded number of+-- requests simultaneously. If this limitation causes a problem in practice it can be fixed.+newThrottle :: String -> Int -> Double -> Rules Resource+newThrottle name count period = rulesIO $ newThrottleIO name count period+++blockApply :: String -> Action a -> Action a+blockApply msg = Action . unmodifyRW f . fromAction+ where f s0 = (s0{localBlockApply=Just msg}, \s -> s{localBlockApply=localBlockApply s0})+++-- | Run an action which uses part of a finite resource. For more details see 'Resource'.+-- You cannot depend on a rule (e.g. 'need') while a resource is held.+withResource :: Resource -> Int -> Action a -> Action a+withResource r i act = do+ Global{..} <- Action getRO+ liftIO $ globalDiagnostic $ show r ++ " waiting to acquire " ++ show i+ Action $ captureRAW $ \continue -> acquireResource r globalPool i $ do+ globalDiagnostic $ show r ++ " acquired " ++ show i+ continue $ Right ()+ res <- Action $ tryRAW $ fromAction $ blockApply ("Within withResource using " ++ show r) act+ liftIO $ releaseResource r globalPool i+ liftIO $ globalDiagnostic $ show r ++ " released " ++ show i+ Action $ either throwRAW return res+++-- | Run an action which uses part of several finite resources. Acquires the resources in a stable+-- order, to prevent deadlock. If all rules requiring more than one resource acquire those+-- resources with a single call to 'withResources', resources will not deadlock.+withResources :: [(Resource, Int)] -> Action a -> Action a+withResources res act+ | (r,i):_ <- filter ((< 0) . snd) res = error $ "You cannot acquire a negative quantity of " ++ show r ++ ", requested " ++ show i+ | otherwise = f $ groupBy ((==) `on` fst) $ sortBy (compare `on` fst) res+ where+ f [] = act+ f (r:rs) = withResource (fst $ head r) (sum $ map snd r) $ f rs+++-- | A version of 'newCache' that runs in IO, and can be called before calling 'Development.Shake.shake'.+-- Most people should use 'newCache' instead.+newCacheIO :: (Eq k, Hashable k) => (k -> Action v) -> IO (k -> Action v)+newCacheIO act = do+ var {- :: Var (Map k (Fence (Either SomeException ([Depends],v)))) -} <- newVar Map.empty+ return $ \key -> do+ join $ liftIO $ modifyVar var $ \mp -> case Map.lookup key mp of+ Just bar -> return $ (,) mp $ do+ res <- liftIO $ testFence bar+ res <- case res of+ Just res -> return res+ Nothing -> do+ pool <- Action $ getsRO globalPool+ Action $ captureRAW $ \k -> waitFence bar $ \v ->+ addPool pool $ k $ Right v+ case res of+ Left err -> Action $ throwRAW err+ Right (deps,v) -> do+ Action $ modifyRW $ \s -> s{localDepends = deps ++ localDepends s}+ return v+ Nothing -> do+ bar <- newFence+ return $ (,) (Map.insert key bar mp) $ do+ pre <- Action $ getsRW localDepends+ res <- Action $ tryRAW $ fromAction $ act key+ case res of+ Left err -> do+ liftIO $ signalFence bar $ Left err+ Action $ throwRAW err+ Right v -> do+ post <- Action $ getsRW localDepends+ let deps = take (length post - length pre) post+ liftIO $ signalFence bar $ Right (deps, v)+ return v++-- | Given an action on a key, produce a cached version that will execute the action at most once per key.+-- Using the cached result will still result include any dependencies that the action requires.+-- Each call to 'newCache' creates a separate cache that is independent of all other calls to 'newCache'.+--+-- This function is useful when creating files that store intermediate values,+-- to avoid the overhead of repeatedly reading from disk, particularly if the file requires expensive parsing.+-- As an example:+--+-- @+-- digits \<- 'newCache' $ \\file -> do+-- src \<- readFile\' file+-- return $ length $ filter isDigit src+-- \"*.digits\" 'Development.Shake.%>' \\x -> do+-- v1 \<- digits ('dropExtension' x)+-- v2 \<- digits ('dropExtension' x)+-- 'Development.Shake.writeFile'' x $ show (v1,v2)+-- @+--+-- To create the result @MyFile.txt.digits@ the file @MyFile.txt@ will be read and counted, but only at most+-- once per execution.+newCache :: (Eq k, Hashable k) => (k -> Action v) -> Rules (k -> Action v)+newCache = rulesIO . newCacheIO+++-- | Run an action without counting to the thread limit, typically used for actions that execute+-- on remote machines using barely any local CPU resources. Unsafe as it allows the 'shakeThreads' limit to be exceeded.+-- You cannot depend on a rule (e.g. 'need') while the extra thread is executing.+-- If the rule blocks (e.g. calls 'withResource') then the extra thread may be used by some other action.+-- Only really suitable for calling 'cmd'/'command'.+unsafeExtraThread :: Action a -> Action a+unsafeExtraThread act = Action $ do+ global@Global{..} <- getRO+ stop <- liftIO $ increasePool globalPool+ res <- tryRAW $ fromAction $ blockApply "Within unsafeExtraThread" act+ liftIO stop+ captureRAW $ \continue -> (if isLeft res then addPoolPriority else addPool) globalPool $ continue res
+ src/Development/Shake/Database.hs view
@@ -0,0 +1,533 @@+{-# LANGUAGE RecordWildCards, PatternGuards, ViewPatterns #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}++module Development.Shake.Database(+ Trace(..),+ Database, withDatabase,+ listDepends, lookupDependencies,+ Ops(..), build, Depends,+ progress,+ Stack, emptyStack, topStack, showStack, showTopStack,+ toReport, checkValid, listLive+ ) where++import Prelude(); import General.Prelude++import Development.Shake.Classes+import General.Binary+import Development.Shake.Pool+import Development.Shake.Value+import Development.Shake.Errors+import Development.Shake.Storage+import Development.Shake.Types+import Development.Shake.Special+import Development.Shake.Profile+import Development.Shake.Monad+import General.String+import General.Intern as Intern++import Numeric.Extra+import Control.Applicative+import Control.Exception+import Control.Monad.Extra+import Control.Concurrent.Extra+import qualified Data.HashSet as Set+import qualified Data.HashMap.Strict as Map+import Data.IORef.Extra+import Data.Maybe+import Data.List+import System.Time.Extra++type Map = Map.HashMap+++---------------------------------------------------------------------+-- UTILITY TYPES++newtype Step = Step Word32 deriving (Eq,Ord,Show,Binary,NFData,Hashable,Typeable)++incStep (Step i) = Step $ i + 1+++---------------------------------------------------------------------+-- CALL STACK++data Stack = Stack (Maybe Key) [Id] !(Set.HashSet Id)++showStack :: Database -> Stack -> IO [String]+showStack Database{..} (Stack _ xs _) = do+ status <- withLock lock $ readIORef status+ return $ reverse $ map (maybe "<unknown>" (show . fst) . flip Map.lookup status) xs++addStack :: Id -> Key -> Stack -> Stack+addStack x key (Stack _ xs set) = Stack (Just key) (x:xs) (Set.insert x set)++showTopStack :: Stack -> String+showTopStack = maybe "<unknown>" show . topStack++topStack :: Stack -> Maybe Key+topStack (Stack key _ _) = key++checkStack :: [Id] -> Stack -> Maybe Id+checkStack new (Stack _ old set)+ | bad:_ <- filter (`Set.member` set) new = Just bad+ | otherwise = Nothing++emptyStack :: Stack+emptyStack = Stack Nothing [] Set.empty+++---------------------------------------------------------------------+-- CENTRAL TYPES++data Trace = Trace BS Float Float -- (message, start, end)+ deriving Show++instance NFData Trace where+ rnf (Trace a b c) = rnf a `seq` rnf b `seq` rnf c++-- | Invariant: The database does not have any cycles where a Key depends on itself+data Database = Database+ {lock :: Lock+ ,intern :: IORef (Intern Key)+ ,status :: IORef (Map Id (Key, Status))+ ,step :: Step+ ,journal :: Id -> (Key, Status {- Loaded or Missing -}) -> IO ()+ ,diagnostic :: String -> IO () -- logging function+ ,assume :: Maybe Assume+ }++data Status+ = Ready Result -- I have a value+ | Error SomeException -- I have been run and raised an error+ | Loaded Result -- Loaded from the database+ | Waiting Pending (Maybe Result) -- Currently checking if I am valid or building+ | Missing -- I am only here because I got into the Intern table+ deriving Show++data Result = Result+ {result :: Value -- the result associated with the Key+ ,built :: {-# UNPACK #-} !Step -- when it was actually run+ ,changed :: {-# UNPACK #-} !Step -- the step for deciding if it's valid+ ,depends :: [[Id]] -- dependencies+ ,execution :: {-# UNPACK #-} !Float -- how long it took when it was last run (seconds)+ ,traces :: [Trace] -- a trace of the expensive operations (start/end in seconds since beginning of run)+ } deriving Show+++newtype Pending = Pending (IORef (IO ()))+ -- you must run this action when you finish, while holding DB lock+ -- after you have set the result to Error or Ready++instance Show Pending where show _ = "Pending"+++statusType Ready{} = "Ready"+statusType Error{} = "Error"+statusType Loaded{} = "Loaded"+statusType Waiting{} = "Waiting"+statusType Missing{} = "Missing"++isError Error{} = True; isError _ = False+isWaiting Waiting{} = True; isWaiting _ = False+isReady Ready{} = True; isReady _ = False+++-- All the waiting operations are only valid when isWaiting+type Waiting = Status++afterWaiting :: Waiting -> IO () -> IO ()+afterWaiting (Waiting (Pending p) _) act = modifyIORef' p (>> act)++newWaiting :: Maybe Result -> IO Waiting+newWaiting r = do ref <- newIORef $ return (); return $ Waiting (Pending ref) r++runWaiting :: Waiting -> IO ()+runWaiting (Waiting (Pending p) _) = join $ readIORef p++-- Wait for a set of actions to complete+-- If the action returns True, the function will not be called again+-- If the first argument is True, the thing is ended+waitFor :: [(a, Waiting)] -> (Bool -> a -> IO Bool) -> IO ()+waitFor ws@(_:_) act = do+ todo <- newIORef $ length ws+ forM_ ws $ \(k,w) -> afterWaiting w $ do+ t <- readIORef todo+ when (t /= 0) $ do+ b <- act (t == 1) k+ writeIORef' todo $ if b then 0 else t - 1+++getResult :: Status -> Maybe Result+getResult (Ready r) = Just r+getResult (Loaded r) = Just r+getResult (Waiting _ r) = r+getResult _ = Nothing+++---------------------------------------------------------------------+-- OPERATIONS++newtype Depends = Depends {fromDepends :: [Id]}+ deriving (NFData)+++data Ops = Ops+ {stored :: Key -> IO (Maybe Value)+ -- ^ Given a Key, find the value stored on disk+ ,equal :: Key -> Value -> Value -> EqualCost+ -- ^ Given both Values, see if they are equal and how expensive that check was+ ,execute :: Stack -> Key -> Capture (Either SomeException (Value, [Depends], Seconds, [Trace]))+ -- ^ Given a stack and a key, either raise an exception or successfully build it+ }+++-- | Return either an exception (crash), or (how much time you spent waiting, the value)+build :: Pool -> Database -> Ops -> Stack -> [Key] -> Capture (Either SomeException (Seconds,Depends,[Value]))+build pool Database{..} Ops{..} stack ks continue = do+ join $ withLock lock $ do+ is <- forM ks $ \k -> do+ is <- readIORef intern+ case Intern.lookup k is of+ Just i -> return i+ Nothing -> do+ (is, i) <- return $ Intern.add k is+ writeIORef' intern is+ modifyIORef' status $ Map.insert i (k,Missing)+ return i++ whenJust (checkStack is stack) $ \bad -> do+ status <- readIORef status+ uncurry errorRuleRecursion $ case Map.lookup bad status of+ Nothing -> (Nothing, Nothing)+ Just (k,_) -> (Just $ typeKey k, Just $ show k)++ vs <- mapM (reduce stack) is+ let errs = [e | Error e <- vs]+ if all isReady vs then+ return $ continue $ Right (0, Depends is, [result r | Ready r <- vs])+ else if not $ null errs then+ return $ continue $ Left $ head errs+ else do+ time <- offsetTime+ let done x = do+ case x of+ Left e -> addPoolPriority pool $ continue $ Left e+ Right v -> addPool pool $ do dur <- time; continue $ Right (dur, Depends is, v)+ return True+ waitFor (filter (isWaiting . snd) $ zip is vs) $ \finish i -> do+ s <- readIORef status+ case Map.lookup i s of+ Just (_, Error e) -> done $ Left e -- on error make sure we immediately kick off our parent+ Just (_, Ready{}) | finish -> done $ Right [result r | i <- is, let Ready r = snd $ fromJust $ Map.lookup i s]+ | otherwise -> return False+ return $ return ()+ where+ (#=) :: Id -> (Key, Status) -> IO Status+ i #= (k,v) = do+ s <- readIORef status+ writeIORef' status $ Map.insert i (k,v) s+ diagnostic $ maybe "Missing" (statusType . snd) (Map.lookup i s) ++ " -> " ++ statusType v ++ ", " ++ maybe "<unknown>" (show . fst) (Map.lookup i s)+ return v++ atom x = let s = show x in if ' ' `elem` s then "(" ++ s ++ ")" else s++ -- Rules for each eval* function+ -- * Must NOT lock+ -- * Must have an equal return to what is stored in the db at that point+ -- * Must not return Loaded++ reduce :: Stack -> Id -> IO Status+ reduce stack i = do+ s <- readIORef status+ case Map.lookup i s of+ Nothing -> err $ "interned value missing from database, " ++ show i+ Just (k, Missing) -> run stack i k Nothing+ Just (k, Loaded r) -> do+ let out b = diagnostic $ "valid " ++ show b ++ " for " ++ atom k ++ " " ++ atom (result r)+ let continue r = out True >> check stack i k r (depends r)+ let rebuild = out False >> run stack i k (Just r)+ case assume of+ Just AssumeDirty -> rebuild+ Just AssumeSkip -> continue r+ _ -> do+ s <- stored k+ case s of+ Just s -> case equal k (result r) s of+ NotEqual -> rebuild+ EqualCheap -> continue r+ EqualExpensive -> do+ -- warning, have the db lock while appending (may harm performance)+ r <- return r{result=s}+ journal i (k, Loaded r)+ i #= (k, Loaded r)+ continue r+ _ -> rebuild+ Just (k, res) -> return res++ run :: Stack -> Id -> Key -> Maybe Result -> IO Waiting+ run stack i k r = do+ w <- newWaiting r+ addPool pool $ do+ let reply res = do+ ans <- withLock lock $ do+ ans <- i #= (k, res)+ runWaiting w+ return ans+ case ans of+ Ready r -> do+ diagnostic $ "result " ++ atom k ++ " = " ++ atom (result r)+ journal i (k, Loaded r) -- leave the DB lock before appending+ Error _ -> do+ diagnostic $ "result " ++ atom k ++ " = error"+ journal i (k, Missing)+ _ -> return ()+ let norm = execute (addStack i k stack) k $ \res ->+ reply $ case res of+ Left err -> Error err+ Right (v,deps,(doubleToFloat -> execution),traces) ->+ let c | Just r <- r, result r == v = changed r+ | otherwise = step+ in Ready Result{result=v,changed=c,built=step,depends=map fromDepends deps,..}++ case r of+ Just r | assume == Just AssumeClean -> do+ v <- stored k+ case v of+ Just v -> reply $ Ready r{result=v}+ Nothing -> norm+ _ -> norm+ i #= (k, w)++ check :: Stack -> Id -> Key -> Result -> [[Id]] -> IO Status+ check stack i k r [] =+ i #= (k, Ready r)+ check stack i k r (ds:rest) = do+ vs <- mapM (reduce (addStack i k stack)) ds+ let ws = filter (isWaiting . snd) $ zip ds vs+ if any isError vs || any (> built r) [changed | Ready Result{..} <- vs] then+ run stack i k $ Just r+ else if null ws then+ check stack i k r rest+ else do+ self <- newWaiting $ Just r+ waitFor ws $ \finish d -> do+ s <- readIORef status+ let buildIt = do+ b <- run stack i k $ Just r+ afterWaiting b $ runWaiting self+ return True+ case Map.lookup d s of+ Just (_, Error{}) -> buildIt+ Just (_, Ready r2)+ | changed r2 > built r -> buildIt+ | finish -> do+ res <- check stack i k r rest+ if not $ isWaiting res+ then runWaiting self+ else afterWaiting res $ runWaiting self+ return True+ | otherwise -> return False+ i #= (k, self)+++---------------------------------------------------------------------+-- PROGRESS++progress :: Database -> IO Progress+progress Database{..} = do+ s <- readIORef status+ return $ foldl' f mempty $ map snd $ Map.elems s+ where+ g = floatToDouble++ f s (Ready Result{..}) = if step == built+ then s{countBuilt = countBuilt s + 1, timeBuilt = timeBuilt s + g execution}+ else s{countSkipped = countSkipped s + 1, timeSkipped = timeSkipped s + g execution}+ f s (Loaded Result{..}) = s{countUnknown = countUnknown s + 1, timeUnknown = timeUnknown s + g execution}+ f s (Waiting _ r) =+ let (d,c) = timeTodo s+ t | Just Result{..} <- r = let d2 = d + g execution in d2 `seq` (d2,c)+ | otherwise = let c2 = c + 1 in c2 `seq` (d,c2)+ in s{countTodo = countTodo s + 1, timeTodo = t}+ f s _ = s+++---------------------------------------------------------------------+-- QUERY DATABASE++-- | Given a map of representing a dependency order (with a show for error messages), find an ordering for the items such+-- that no item points to an item before itself.+-- Raise an error if you end up with a cycle.+dependencyOrder :: (Eq a, Hashable a) => (a -> String) -> Map a [a] -> [a]+-- Algorithm:+-- Divide everyone up into those who have no dependencies [Id]+-- And those who depend on a particular Id, Dep :-> Maybe [(Key,[Dep])]+-- Where d :-> Just (k, ds), k depends on firstly d, then remaining on ds+-- For each with no dependencies, add to list, then take its dep hole and+-- promote them either to Nothing (if ds == []) or into a new slot.+-- k :-> Nothing means the key has already been freed+dependencyOrder shw status = f (map fst noDeps) $ Map.map Just $ Map.fromListWith (++) [(d, [(k,ds)]) | (k,d:ds) <- hasDeps]+ where+ (noDeps, hasDeps) = partition (null . snd) $ Map.toList status++ f [] mp | null bad = []+ | otherwise = error $ unlines $+ "Internal invariant broken, database seems to be cyclic" :+ map (" " ++) bad +++ ["... plus " ++ show (length badOverflow) ++ " more ..." | not $ null badOverflow]+ where (bad,badOverflow) = splitAt 10 $ [shw i | (i, Just _) <- Map.toList mp]++ f (x:xs) mp = x : f (now++xs) later+ where Just free = Map.lookupDefault (Just []) x mp+ (now,later) = foldl' g ([], Map.insert x Nothing mp) free++ g (free, mp) (k, []) = (k:free, mp)+ g (free, mp) (k, d:ds) = case Map.lookupDefault (Just []) d mp of+ Nothing -> g (free, mp) (k, ds)+ Just todo -> (free, Map.insert d (Just $ (k,ds) : todo) mp)+++-- | Eliminate all errors from the database, pretending they don't exist+resultsOnly :: Map Id (Key, Status) -> Map Id (Key, Result)+resultsOnly mp = Map.map (\(k, v) -> (k, let Just r = getResult v in r{depends = map (filter (isJust . flip Map.lookup keep)) $ depends r})) keep+ where keep = Map.filter (isJust . getResult . snd) mp++removeStep :: Map Id (Key, Result) -> Map Id (Key, Result)+removeStep = Map.filter (\(k,_) -> k /= stepKey)++toReport :: Database -> IO [ProfileEntry]+toReport Database{..} = do+ status <- fmap (removeStep . resultsOnly) $ readIORef status+ let order = let shw i = maybe "<unknown>" (show . fst) $ Map.lookup i status+ in dependencyOrder shw $ Map.map (concat . depends . snd) status+ ids = Map.fromList $ zip order [0..]++ steps = let xs = Set.toList $ Set.fromList $ concat [[changed, built] | (_,Result{..}) <- Map.elems status]+ in Map.fromList $ zip (sortBy (flip compare) xs) [0..]++ f (k, Result{..}) = ProfileEntry+ {prfName = show k+ ,prfBuilt = fromStep built+ ,prfChanged = fromStep changed+ ,prfDepends = mapMaybe (`Map.lookup` ids) (concat depends)+ ,prfExecution = floatToDouble execution+ ,prfTraces = map fromTrace traces+ }+ where fromStep i = fromJust $ Map.lookup i steps+ fromTrace (Trace a b c) = ProfileTrace (unpack a) (floatToDouble b) (floatToDouble c)+ return [maybe (err "toReport") f $ Map.lookup i status | i <- order]+++checkValid :: Database -> (Key -> IO (Maybe Value)) -> (Key -> Value -> Value -> EqualCost) -> [(Key, Key)] -> IO ()+checkValid Database{..} stored equal missing = do+ status <- readIORef status+ intern <- readIORef intern+ diagnostic "Starting validity/lint checking"++ -- Do not use a forM here as you use too much stack space+ bad <- (\f -> foldM f [] (Map.toList status)) $ \seen (i,v) -> case v of+ (key, Ready Result{..}) -> do+ now <- stored key+ let good = maybe False ((==) EqualCheap . equal key result) now+ diagnostic $ "Checking if " ++ show key ++ " is " ++ show result ++ ", " ++ if good then "passed" else "FAILED"+ return $ [(key, result, now) | not good && not (specialAlwaysRebuilds result)] ++ seen+ _ -> return seen+ unless (null bad) $ do+ let n = length bad+ errorStructured+ ("Lint checking error - " ++ (if n == 1 then "value has" else show n ++ " values have") ++ " changed since being depended upon")+ (intercalate [("",Just "")] [ [("Key", Just $ show key),("Old", Just $ show result),("New", Just $ maybe "<missing>" show now)]+ | (key, result, now) <- bad])+ ""++ bad <- return [(parent,key) | (parent, key) <- missing, isJust $ Intern.lookup key intern]+ unless (null bad) $ do+ let n = length bad+ errorStructured+ ("Link checking error - " ++ (if n == 1 then "value" else show n ++ " values") ++ " did not have " ++ (if n == 1 then "its" else "their") ++ " creation tracked")+ (intercalate [("",Just "")] [ [("Rule", Just $ show parent), ("Created", Just $ show key)] | (parent,key) <- bad])+ ""++ diagnostic "Validity/lint check passed"+++listLive :: Database -> IO [Key]+listLive Database{..} = do+ diagnostic "Listing live keys"+ status <- readIORef status+ return [k | (k, Ready{}) <- Map.elems status]+++listDepends :: Database -> Depends -> IO [Key]+listDepends Database{..} (Depends xs) =+ withLock lock $ do+ status <- readIORef status+ return $ map (fst . fromJust . flip Map.lookup status) xs++lookupDependencies :: Database -> Key -> IO [Key]+lookupDependencies Database{..} k = do+ withLock lock $ do+ intern <- readIORef intern+ status <- readIORef status+ let Just i = Intern.lookup k intern+ let Just (_, Ready r) = Map.lookup i status+ return $ map (fst . fromJust . flip Map.lookup status) $ concat $ depends r+++---------------------------------------------------------------------+-- STORAGE++-- To simplify journaling etc we smuggle the Step in the database, with a special StepKey+newtype StepKey = StepKey ()+ deriving (Show,Eq,Typeable,Hashable,Binary,NFData)++stepKey :: Key+stepKey = newKey $ StepKey ()++toStepResult :: Step -> Result+toStepResult i = Result (newValue i) i i [] 0 []++fromStepResult :: Result -> Step+fromStepResult = fromValue . result+++withDatabase :: ShakeOptions -> (String -> IO ()) -> (Database -> IO a) -> IO a+withDatabase opts diagnostic act = do+ registerWitness $ StepKey ()+ registerWitness $ Step 0+ witness <- currentWitness+ withStorage opts diagnostic witness $ \mp2 journal -> do+ let mp1 = Intern.fromList [(k, i) | (i, (k,_)) <- Map.toList mp2]++ (mp1, stepId) <- case Intern.lookup stepKey mp1 of+ Just stepId -> return (mp1, stepId)+ Nothing -> do+ (mp1, stepId) <- return $ Intern.add stepKey mp1+ return (mp1, stepId)++ intern <- newIORef mp1+ status <- newIORef mp2+ let step = case Map.lookup stepId mp2 of+ Just (_, Loaded r) -> incStep $ fromStepResult r+ _ -> Step 1+ journal stepId (stepKey, Loaded $ toStepResult step)+ lock <- newLock+ act Database{assume=shakeAssume opts,..}+++instance BinaryWith Witness Result where+ putWith ws (Result x1 x2 x3 x4 x5 x6) = putWith ws x1 >> put x2 >> put x3 >> put (BinList $ map BinList x4) >> put (BinFloat x5) >> put (BinList x6)+ getWith ws = (\x1 x2 x3 (BinList x4) (BinFloat x5) (BinList x6) -> Result x1 x2 x3 (map fromBinList x4) x5 x6) <$>+ getWith ws <*> get <*> get <*> get <*> get <*> get++instance Binary Trace where+ put (Trace a b c) = put a >> put (BinFloat b) >> put (BinFloat c)+ get = (\a (BinFloat b) (BinFloat c) -> Trace a b c) <$> get <*> get <*> get++instance BinaryWith Witness Status where+ putWith ctx Missing = putWord8 0+ putWith ctx (Loaded x) = putWord8 1 >> putWith ctx x+ putWith ctx x = err $ "putWith, Cannot write Status with constructor " ++ statusType x+ getWith ctx = do i <- getWord8; if i == 0 then return Missing else fmap Loaded $ getWith ctx
+ src/Development/Shake/Demo.hs view
@@ -0,0 +1,134 @@++-- | Demo tutorial, accessed with --demo+module Development.Shake.Demo(demo) where++import Paths_shake+import Development.Shake.Command++import Control.Exception.Extra+import Control.Monad+import Data.Char+import Data.List+import Data.Maybe+import Data.Version(showVersion)+import System.Directory+import System.Exit+import System.FilePath+import Development.Shake.FilePath(exe)+import System.IO+import System.Info.Extra+++demo :: Bool -> IO ()+demo auto = do+ hSetBuffering stdout NoBuffering+ putStrLn $ "% Welcome to the Shake v" ++ showVersion version ++ " demo mode!"+ putStr $ "% Detecting machine configuration... "++ -- CONFIGURE++ manual <- getDataFileName "docs/manual"+ hasManual <- wrap $ doesDirectoryExist manual+ ghc <- findExecutable "ghc"+ gcc <- do+ v <- findExecutable "gcc"+ case v of+ Nothing | isWindows, Just ghc <- ghc -> do+ let dir = takeDirectory (takeDirectory ghc) </> "bin/mingw/gcc.exe"+ b <- wrap $ doesFileExist dir+ return $ if b then Just dir else Nothing+ _ -> return v+ shakeLib <- wrap $ fmap (not . null . words . fromStdout) (cmd "ghc-pkg list --simple-output shake")+ ninja <- findExecutable "ninja"+ putStrLn "done\n"++ let path = if isWindows then "%PATH%" else "$PATH"+ require (isJust ghc) $ "% You don't have 'ghc' on your " ++ path ++ ", which is required to run the demo."+ require (isJust gcc) $ "% You don't have 'gcc' on your " ++ path ++ ", which is required to run the demo."+ require shakeLib "% You don't have the 'shake' library installed with GHC, which is required to run the demo."+ require hasManual "% You don't have the Shake data files installed, which are required to run the demo."++ empty <- fmap (null . filter (not . all (== '.'))) $ getDirectoryContents "."+ dir <- if empty then getCurrentDirectory else do+ home <- getHomeDirectory+ dir <- getDirectoryContents home+ return $ home </> head (map ("shake-demo" ++) ("":map show [2..]) \\ dir)++ putStrLn $ "% The Shake demo uses an empty directory, OK to use:"+ putStrLn $ "% " ++ dir+ b <- yesNo auto+ require b "% Please create an empty directory to run the demo from, then run 'shake --demo' again."++ putStr "% Copying files... "+ createDirectoryIfMissing True dir+ forM_ ["Build.hs","main.c","constants.c","constants.h","build" <.> if isWindows then "bat" else "sh"] $ \file ->+ copyFile (manual </> file) (dir </> file)+ when (not isWindows) $ do+ p <- getPermissions $ dir </> "build.sh"+ setPermissions (dir </> "build.sh") p{executable=True}+ putStrLn "done"++ let pause = do+ putStr "% Press ENTER to continue: "+ if auto then putLine "" else getLine+ let execute x = do+ putStrLn $ "% RUNNING: " ++ x+ cmd (Cwd dir) Shell x :: IO ()+ let build = if isWindows then "build" else "./build.sh"++ putStrLn "\n% [1/5] Building an example project with Shake."+ pause+ putStrLn $ "% RUNNING: cd " ++ dir+ execute build++ putStrLn "\n% [2/5] Running the produced example."+ pause+ execute $ "_build" </> "run" <.> exe++ putStrLn "\n% [3/5] Rebuilding an example project with Shake (nothing should change)."+ pause+ execute build++ putStrLn "\n% [4/5] Cleaning the build."+ pause+ execute $ build ++ " clean"++ putStrLn "\n% [5/5] Rebuilding with 2 threads and profiling."+ pause+ execute $ build ++ " -j2 --report --report=-"+ putStrLn "\n% See the profiling summary above, or look at the HTML profile report in"+ putStrLn $ "% " ++ dir </> "report.html"++ putStrLn "\n% Demo complete - all the examples can be run from:"+ putStrLn $ "% " ++ dir+ putStrLn "% For more info see http://www.shakebuild.com/"+ when (isJust ninja) $ do+ putStrLn "\n% PS. Shake can also execute Ninja build files"+ putStrLn "% For more info see http://www.shakebuild.com/ninja"++++-- | Require the user to press @y@ before continuing.+yesNo :: Bool -> IO Bool+yesNo auto = do+ putStr $ "% [Y/N] (then ENTER): "+ x <- if auto then putLine "y" else fmap (map toLower) getLine+ if "y" `isPrefixOf` x then+ return True+ else if "n" `isPrefixOf` x then+ return False+ else+ yesNo auto++putLine :: String -> IO String+putLine x = putStrLn x >> return x+++-- | Replace exceptions with 'False'.+wrap :: IO Bool -> IO Bool+wrap act = act `catch_` const (return False)+++-- | Require a condition to be true, or exit with a message.+require :: Bool -> String -> IO ()+require b msg = unless b $ putStrLn msg >> exitFailure
+ src/Development/Shake/Derived.hs view
@@ -0,0 +1,157 @@++module Development.Shake.Derived(+ system', systemCwd, systemOutput,+ copyFile', copyFileChanged,+ readFile', readFileLines,+ writeFile', writeFileLines, writeFileChanged,+ withTempFile, withTempDir+ ) where++import Control.Monad.Extra+import Control.Monad.IO.Class+import System.Process+import System.Directory+import System.Exit+import System.IO.Extra hiding (withTempFile, withTempDir, readFile')++import Development.Shake.Core+import Development.Shake.Rules.File+import Development.Shake.FilePath+import Development.Shake.Types+import qualified Data.ByteString as BS+++checkExitCode :: String -> ExitCode -> Action ()+checkExitCode cmd ExitSuccess = return ()+checkExitCode cmd (ExitFailure i) = error $ "System command failed (code " ++ show i ++ "):\n" ++ cmd++{-# DEPRECATED system' "Use 'command' or 'cmd'" #-}+{-# DEPRECATED systemCwd "Use 'command' or 'cmd' with 'Cwd'" #-}+{-# DEPRECATED systemOutput "Use 'command' or 'cmd' with 'Stdout' or 'Stderr'" #-}++-- | /Deprecated:/ Please use 'command' or 'cmd' instead.+-- This function will be removed in a future version.+--+-- Execute a system command. This function will raise an error if the exit code is non-zero.+-- Before running 'system'' make sure you 'need' any required files.+system' :: FilePath -> [String] -> Action ()+system' path args = do+ let path2 = toNative path+ let cmd = unwords $ path2 : args+ v <- getVerbosity+ putLoud cmd+ res <- (if v >= Loud then quietly else id) $ traced (takeBaseName path) $ rawSystem path2 args+ checkExitCode cmd res+++-- | /Deprecated:/ Please use 'command' or 'cmd' instead, with 'Cwd'.+-- This function will be removed in a future version.+--+-- Execute a system command with a specified current working directory (first argument).+-- This function will raise an error if the exit code is non-zero.+-- Before running 'systemCwd' make sure you 'need' any required files.+--+-- @+-- 'systemCwd' \"\/usr\/MyDirectory\" \"pwd\" []+-- @+systemCwd :: FilePath -> FilePath -> [String] -> Action ()+systemCwd cwd path args = do+ let path2 = toNative path+ let cmd = unwords $ path2 : args+ putLoud cmd+ res <- traced (takeBaseName path) $ do+ -- FIXME: Should I be using the non-exported System.Process.syncProcess?+ -- That installs/removes signal handlers.+ hdl <- runProcess path2 args (Just cwd) Nothing Nothing Nothing Nothing+ waitForProcess hdl+ checkExitCode cmd res+++-- | /Deprecated:/ Please use 'command' or 'cmd' instead, with 'Stdout' or 'Stderr'.+-- This function will be removed in a future version.+--+-- Execute a system command, returning @(stdout,stderr)@.+-- This function will raise an error if the exit code is non-zero.+-- Before running 'systemOutput' make sure you 'need' any required files.+systemOutput :: FilePath -> [String] -> Action (String, String)+systemOutput path args = do+ let path2 = toNative path+ let cmd = unwords $ path2 : args+ putLoud cmd+ (res,stdout,stderr) <- traced (takeBaseName path) $ readProcessWithExitCode path2 args ""+ checkExitCode cmd res+ return (stdout, stderr)+++-- | @copyFile' old new@ copies the existing file from @old@ to @new@.+-- The @old@ file will be tracked as a dependency.+copyFile' :: FilePath -> FilePath -> Action ()+copyFile' old new = do+ need [old]+ putLoud $ "Copying from " ++ old ++ " to " ++ new+ liftIO $ copyFile old new+++-- | @copyFile' old new@ copies the existing file from @old@ to @new@, if the contents have changed.+-- The @old@ file will be tracked as a dependency.+copyFileChanged :: FilePath -> FilePath -> Action ()+copyFileChanged old new = do+ need [old]+ eq <- liftIO $ doesFileExist new &&^ do+ withBinaryFile old ReadMode $ \h1 -> withBinaryFile new ReadMode $ \h2 ->+ liftM2 (==) (hFileSize h1) (hFileSize h2) &&^+ liftM2 (==) (BS.hGetContents h1) (BS.hGetContents h2)+ when (not eq) $ do+ putLoud $ "Copying from " ++ old ++ " to " ++ new+ -- copyFile does a lot of clever stuff with permissions etc, so make sure we just reuse it+ liftIO $ copyFile old new+++-- | Read a file, after calling 'need'. The argument file will be tracked as a dependency.+readFile' :: FilePath -> Action String+readFile' x = need [x] >> liftIO (readFile x)++-- | Write a file, lifted to the 'Action' monad.+writeFile' :: FilePath -> String -> Action ()+writeFile' name x = liftIO $ writeFile name x+++-- | A version of 'readFile'' which also splits the result into lines.+-- The argument file will be tracked as a dependency.+readFileLines :: FilePath -> Action [String]+readFileLines = fmap lines . readFile'++-- | A version of 'writeFile'' which writes out a list of lines.+writeFileLines :: FilePath -> [String] -> Action ()+writeFileLines name = writeFile' name . unlines+++-- | Write a file, but only if the contents would change.+writeFileChanged :: FilePath -> String -> Action ()+writeFileChanged name x = liftIO $ do+ b <- doesFileExist name+ if not b then writeFile name x else do+ -- Cannot use ByteString here, since it has different line handling+ -- semantics on Windows+ b <- withFile name ReadMode $ \h -> do+ src <- hGetContents h+ return $! src /= x+ when b $ writeFile name x+++-- | Create a temporary file in the temporary directory. The file will be deleted+-- after the action completes (provided the file is not still open).+-- The 'FilePath' will not have any file extension, will exist, and will be zero bytes long.+-- If you require a file with a specific name, use 'withTempDir'.+withTempFile :: (FilePath -> Action a) -> Action a+withTempFile act = do+ (file, del) <- liftIO newTempFile+ act file `actionFinally` del+++-- | Create a temporary directory inside the system temporary directory.+-- The directory will be deleted after the action completes.+withTempDir :: (FilePath -> Action a) -> Action a+withTempDir act = do+ (dir,del) <- liftIO newTempDir+ act dir `actionFinally` del
+ src/Development/Shake/Errors.hs view
@@ -0,0 +1,132 @@+{-# LANGUAGE DeriveDataTypeable, PatternGuards, RecordWildCards #-}++-- | Errors seen by the user+module Development.Shake.Errors(+ ShakeException(..),+ errorStructured, err,+ errorNoRuleToBuildType, errorRuleTypeMismatch, errorIncompatibleRules,+ errorMultipleRulesMatch, errorRuleRecursion, errorNoApply,+ ) where++import Data.Tuple.Extra+import Control.Exception+import Data.Typeable+import Data.List+++err :: String -> a+err msg = error $ "Development.Shake: Internal error, please report to Neil Mitchell (" ++ msg ++ ")"++alternatives = let (*) = (,) in+ ["_rule_" * "oracle"+ ,"_Rule_" * "Oracle"+ ,"_key_" * "question"+ ,"_Key_" * "Question"+ ,"_result_" * "answer"+ ,"_Result_" * "Answer"+ ,"_rule/defaultRule_" * "addOracle"+ ,"_apply_" * "askOracle"]+++errorStructured :: String -> [(String, Maybe String)] -> String -> a+errorStructured msg args hint = error $ unlines $+ [msg ++ ":"] +++ [" " ++ a ++ [':' | a /= ""] ++ replicate (as - length a + 2) ' ' ++ b | (a,b) <- args2] +++ [hint | hint /= ""]+ where+ as = maximum $ 0 : map (length . fst) args2+ args2 = [(a,b) | (a,Just b) <- args]++++structured :: Bool -> String -> [(String, Maybe String)] -> String -> a+structured alt msg args hint = errorStructured (f msg) (map (first f) args) (f hint)+ where+ f = filter (/= '_') . (if alt then g else id)+ g xs | (a,b):_ <- filter (\(a,b) -> a `isPrefixOf` xs) alternatives = b ++ g (drop (length a) xs)+ g (x:xs) = x : g xs+ g [] = []+++errorNoRuleToBuildType :: TypeRep -> Maybe String -> Maybe TypeRep -> a+errorNoRuleToBuildType tk k tv = structured (specialIsOracleKey tk)+ "Build system error - no _rule_ matches the _key_ type"+ [("_Key_ type", Just $ show tk)+ ,("_Key_ value", k)+ ,("_Result_ type", fmap show tv)]+ "Either you are missing a call to _rule/defaultRule_, or your call to _apply_ has the wrong _key_ type"++errorRuleTypeMismatch :: TypeRep -> Maybe String -> TypeRep -> TypeRep -> a+errorRuleTypeMismatch tk k tvReal tvWant = structured (specialIsOracleKey tk)+ "Build system error - _rule_ used at the wrong _result_ type"+ [("_Key_ type", Just $ show tk)+ ,("_Key_ value", k)+ ,("_Rule_ _result_ type", Just $ show tvReal)+ ,("Requested _result_ type", Just $ show tvWant)]+ "Either the function passed to _rule/defaultRule_ has the wrong _result_ type, or the result of _apply_ is used at the wrong type"++errorIncompatibleRules :: TypeRep -> TypeRep -> TypeRep -> a+errorIncompatibleRules tk tv1 tv2 = if specialIsOracleKey tk then errorDuplicateOracle tk Nothing [tv1,tv2] else errorStructured+ "Build system error - rule has multiple result types"+ [("Key type", Just $ show tk)+ ,("First result type", Just $ show tv1)+ ,("Second result type", Just $ show tv2)]+ "A function passed to rule/defaultRule has the wrong result type"++errorMultipleRulesMatch :: TypeRep -> String -> Int -> a+errorMultipleRulesMatch tk k count+ | specialIsOracleKey tk = if count == 0 then err $ "no oracle match for " ++ show tk else errorDuplicateOracle tk (Just k) []+ | otherwise = errorStructured+ ("Build system error - key matches " ++ (if count == 0 then "no" else "multiple") ++ " rules")+ [("Key type",Just $ show tk)+ ,("Key value",Just k)+ ,("Rules matched",Just $ show count)]+ (if count == 0 then "Either add a rule that produces the above key, or stop requiring the above key"+ else "Modify your rules/defaultRules so only one can produce the above key")++errorRuleRecursion :: Maybe TypeRep -> Maybe String -> a+errorRuleRecursion tk k = errorStructured -- may involve both rules and oracle, so report as a rule+ "Build system error - recursion detected"+ [("Key type",fmap show tk)+ ,("Key value",k)]+ "Rules may not be recursive"++errorDuplicateOracle :: TypeRep -> Maybe String -> [TypeRep] -> a+errorDuplicateOracle tk k tvs = errorStructured+ "Build system error - duplicate oracles for the same question type"+ ([("Question type",Just $ show tk)+ ,("Question value",k)] +++ [("Answer type " ++ show i, Just $ show tv) | (i,tv) <- zip [1..] tvs])+ "Only one call to addOracle is allowed per question type"++errorNoApply :: TypeRep -> Maybe String -> String -> a+errorNoApply tk k msg = structured (specialIsOracleKey tk)+ "Build system error - cannot currently call _apply_"+ [("Reason", Just msg)+ ,("_Key_ type", Just $ show tk)+ ,("_Key_ value", k)]+ "Move the _apply_ call earlier/later"+++-- Should be in Special, but then we get an import cycle+specialIsOracleKey :: TypeRep -> Bool+specialIsOracleKey t = con == "OracleQ"+ where con = show $ fst $ splitTyConApp t+++-- | Error representing all expected exceptions thrown by Shake.+-- Problems when executing rules will be raising using this exception type.+data ShakeException = ShakeException+ {shakeExceptionTarget :: String -- ^ The target that was being built when the exception occured.+ ,shakeExceptionStack :: [String] -- ^ The stack of targets, where the 'shakeExceptionTarget' is last.+ ,shakeExceptionInner :: SomeException -- ^ The underlying exception that was raised.+ }+ deriving Typeable++instance Exception ShakeException++instance Show ShakeException where+ show ShakeException{..} = unlines $+ "Error when running Shake build system:" :+ map ("* " ++) shakeExceptionStack +++ [show shakeExceptionInner]
+ src/Development/Shake/FileInfo.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, CPP, ForeignFunctionInterface #-}++module Development.Shake.FileInfo(+ FileInfo, fileInfoEq, fileInfoNeq, fileInfoVal,+ FileSize, ModTime, FileHash,+ getFileHash, getFileInfo+ ) where++import Control.Exception+import Development.Shake.Classes+import General.String+import qualified Data.ByteString.Lazy as LBS+import Data.Char+import Data.Word+import Numeric+import System.IO++#if __GLASGOW_HASKELL__ < 704+#define PORTABLE 1+#endif++#if defined(PORTABLE)+import System.IO.Error+import System.Directory+import Data.Time+import System.Time++#elif defined(mingw32_HOST_OS)+import qualified Data.ByteString.Char8 as BS+import Foreign+import Foreign.C.Types+import Foreign.C.String++#else+import System.IO.Error+import System.Posix.Files.ByteString+#endif++-- A piece of file information, where 0 = Eq to everything, 1 = Eq to nothing, 2+ = normal values+newtype FileInfo a = FileInfo Word32+ deriving (Typeable,Hashable,Binary,NFData)++instance Show (FileInfo a) where+ show (FileInfo x)+ | x == 0 = "EQ"+ | x == 1 = "NEQ"+ | x == 2 = "VAL"+ | otherwise = "0x" ++ map toUpper (showHex (x-2) "")++instance Eq (FileInfo a) where+ FileInfo a == FileInfo b+ | a == 0 || b == 0 = True+ | a == 1 || b == 1 = False+ | otherwise = a == b++fileInfoEq, fileInfoNeq, fileInfoVal :: FileInfo a+fileInfoEq = FileInfo 0+fileInfoNeq = FileInfo 1+fileInfoVal = FileInfo 2++fileInfo :: Word32 -> FileInfo a+fileInfo a = FileInfo $ if a > maxBound - 3 then a else a + 3++data FileInfoHash; type FileHash = FileInfo FileInfoHash+data FileInfoMod ; type ModTime = FileInfo FileInfoMod+data FileInfoSize; type FileSize = FileInfo FileInfoSize+++getFileHash :: BSU -> IO FileHash+getFileHash x = withFile (unpackU x) ReadMode $ \h -> do+ s <- LBS.hGetContents h+ let res = fileInfo $ fromIntegral $ hash s+ evaluate res+ return res+++getFileInfo :: BSU -> IO (Maybe (ModTime, FileSize))++#if defined(PORTABLE)+-- Portable fallback+getFileInfo x = handleJust (\e -> if isDoesNotExistError e then Just () else Nothing) (const $ return Nothing) $ do+ let file = unpackU x+ time <- getModificationTime file+ size <- withFile file ReadMode hFileSize+ return $ Just (fileInfo $ extractFileTime time, fileInfo $ fromIntegral size)++-- deal with difference in return type of getModificationTime between directory versions+class ExtractFileTime a where extractFileTime :: a -> Word32+instance ExtractFileTime ClockTime where extractFileTime (TOD t _) = fromIntegral t+instance ExtractFileTime UTCTime where extractFileTime = floor . fromRational . toRational . utctDayTime+++#elif defined(mingw32_HOST_OS)+-- Directly against the Win32 API, twice as fast as the portable version+getFileInfo x = BS.useAsCString (unpackU_ x) $ \file ->+ alloca_WIN32_FILE_ATTRIBUTE_DATA $ \fad -> do+ res <- c_getFileAttributesExA file 0 fad+ let peek = do mt <- peekLastWriteTimeLow fad; sz <- peekFileSizeLow fad; return $ Just (fileInfo mt, fileInfo sz)+ if res then+ peek+ else if requireU x then withCWString (unpackU x) $ \file -> do+ res <- c_getFileAttributesExW file 0 fad+ if res then peek else return Nothing+ else+ return Nothing++foreign import stdcall unsafe "Windows.h GetFileAttributesExA" c_getFileAttributesExA :: Ptr CChar -> Int32 -> Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Bool+foreign import stdcall unsafe "Windows.h GetFileAttributesExW" c_getFileAttributesExW :: Ptr CWchar -> Int32 -> Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Bool++data WIN32_FILE_ATTRIBUTE_DATA++alloca_WIN32_FILE_ATTRIBUTE_DATA :: (Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO a) -> IO a+alloca_WIN32_FILE_ATTRIBUTE_DATA act = allocaBytes size_WIN32_FILE_ATTRIBUTE_DATA act+ where size_WIN32_FILE_ATTRIBUTE_DATA = 36++peekLastWriteTimeLow :: Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Word32+peekLastWriteTimeLow p = peekByteOff p index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime+ where index_WIN32_FILE_ATTRIBUTE_DATA_ftLastWriteTime_dwLowDateTime = 20++peekFileSizeLow :: Ptr WIN32_FILE_ATTRIBUTE_DATA -> IO Word32+peekFileSizeLow p = peekByteOff p index_WIN32_FILE_ATTRIBUTE_DATA_nFileSizeLow+ where index_WIN32_FILE_ATTRIBUTE_DATA_nFileSizeLow = 32+++#else+-- Unix version+getFileInfo x = handleJust (\e -> if isDoesNotExistError e then Just () else Nothing) (const $ return Nothing) $ do+ s <- getFileStatus $ unpackU_ x+ return $ Just (fileInfo $ extractFileTime s, fileInfo $ fromIntegral $ fileSize s)++extractFileTime :: FileStatus -> Word32+#ifndef MIN_VERSION_unix+#define MIN_VERSION_unix(a,b,c) 0+#endif+#if MIN_VERSION_unix(2,6,0)+extractFileTime x = ceiling $ modificationTimeHiRes x * 1e4 -- precision of 0.1ms+#else+extractFileTime x = fromIntegral $ fromEnum $ modificationTime x+#endif++#endif
+ src/Development/Shake/FilePath.hs view
@@ -0,0 +1,95 @@++-- | A module for 'FilePath' operations exposing "System.FilePath" plus some additional operations.+module Development.Shake.FilePath(+ module System.FilePath,+ dropDirectory1, takeDirectory1, normaliseEx,+ (-<.>),+ toNative, toStandard,+ exe+ ) where++import System.FilePath+import System.Info.Extra+import qualified System.FilePath as Native++infixr 7 -<.>+++-- | Drop the first directory from a 'FilePath'. Should only be used on+-- relative paths.+--+-- > dropDirectory1 "aaa/bbb" == "bbb"+-- > dropDirectory1 "aaa/" == ""+-- > dropDirectory1 "aaa" == ""+-- > dropDirectory1 "" == ""+dropDirectory1 :: FilePath -> FilePath+dropDirectory1 = drop 1 . dropWhile (not . isPathSeparator)+++-- | Take the first component of a 'FilePath'. Should only be used on+-- relative paths.+--+-- > takeDirectory1 "aaa/bbb" == "aaa"+-- > takeDirectory1 "aaa/" == "aaa"+-- > takeDirectory1 "aaa" == "aaa"+takeDirectory1 :: FilePath -> FilePath+takeDirectory1 = takeWhile (not . isPathSeparator)+++-- | Normalise a 'FilePath', trying to do:+--+-- * All 'pathSeparators' become @\/@+--+-- * @foo\/bar\/..\/baz@ becomes @foo\/baz@+--+-- * @foo\/.\/bar@ becomes @foo\/bar@+--+-- * @foo\/\/bar@ becomes @foo\/bar@+--+-- This function is not based on the normalise function from the filepath library, as that function+-- is quite broken.+normaliseEx :: FilePath -> FilePath+normaliseEx xs | a:b:xs <- xs, isWindows && sep a && sep b = '/' : f ('/':xs) -- account for UNC paths being double //+ | otherwise = f xs+ where+ sep = Native.isPathSeparator+ f o = toNative $ deslash o $ (++"/") $ concatMap ('/':) $ reverse $ g 0 $ reverse $ split o++ deslash o x+ | x == "/" = case (pre,pos) of+ (True,True) -> "/"+ (True,False) -> "/."+ (False,True) -> "./"+ (False,False) -> "."+ | otherwise = (if pre then id else tail) $ (if pos then id else init) x+ where pre = sep $ head $ o ++ " "+ pos = sep $ last $ " " ++ o++ g i [] = replicate i ".."+ g i ("..":xs) = g (i+1) xs+ g i (".":xs) = g i xs+ g 0 (x:xs) = x : g 0 xs+ g i (x:xs) = g (i-1) xs++ split xs = if null ys then [] else a : split b+ where (a,b) = break sep $ ys+ ys = dropWhile sep xs+++-- | Convert to native path separators, namely @\\@ on Windows. +toNative :: FilePath -> FilePath+toNative = if isWindows then map (\x -> if x == '/' then '\\' else x) else id++-- | Convert all path separators to @/@, even on Windows.+toStandard :: FilePath -> FilePath+toStandard = if isWindows then map (\x -> if x == '\\' then '/' else x) else id+++-- | Remove the current extension and add another, an alias for 'replaceExtension'.+(-<.>) :: FilePath -> String -> FilePath+(-<.>) = replaceExtension+++-- | The extension of executables, @\"exe\"@ on Windows and @\"\"@ otherwise.+exe :: String+exe = if isWindows then "exe" else ""
+ src/Development/Shake/FilePattern.hs view
@@ -0,0 +1,174 @@+{-# LANGUAGE PatternGuards, ViewPatterns #-}++module Development.Shake.FilePattern(+ FilePattern, (?==),+ compatible, simple, extract, substitute,+ directories, directories1+ ) where++import System.FilePath(isPathSeparator, pathSeparators, pathSeparator)+import Data.List+import Data.Tuple.Extra+import General.Extra+++---------------------------------------------------------------------+-- BASIC FILE PATTERN MATCHING++-- | A type synonym for file patterns, containing @\/\/@ and @*@. For the syntax+-- and semantics of 'FilePattern' see '?=='.+--+-- Most 'normaliseEx'd 'FilePath' values are suitable as 'FilePattern' values which match+-- only that specific file. On Windows @\\@ is treated as equivalent to @\/@.+type FilePattern = String+++data Lexeme = Star | SlashSlash | Char Char deriving (Show, Eq)++isChar (Char _) = True; isChar _ = False+isDull (Char x) = not $ isPathSeparator x; isDull _ = False+fromChar (Char x) = x+++data Regex = Lit [Char] | Not [Char] | Any+ | Start | End+ | Bracket Regex+ | Or Regex Regex | Concat Regex Regex+ | Repeat Regex | Empty+ deriving Show++type SString = (Bool, String) -- fst is True if at the start of the string+++lexer :: FilePattern -> [Lexeme]+lexer ('*':xs) = Star : lexer xs+lexer (s1:s2:xs) | isPathSeparator s1 && isPathSeparator s2 = SlashSlash : lexer xs+lexer (x:xs) = Char x : lexer xs+lexer [] = []+++pattern :: [Lexeme] -> Regex+pattern = Concat Start . foldr Concat End . map f+ where+ f Star = Bracket $ Repeat $ Not pathSeparators+ f SlashSlash = let s = Start `Or` End `Or` Lit pathSeparators in Bracket $+ Or (s `Concat` Repeat Any `Concat` s) (Lit pathSeparators)+ f (Char x) = Lit $ if isPathSeparator x then pathSeparators else [x]+++-- | Return is (brackets, matched, rest)+match :: Regex -> SString -> [([String], String, SString)]+match (Lit l) (_, x:xs) | x `elem` l = [([], [x], (False, xs))]+match (Not l) (_, x:xs) | x `notElem` l = [([], [x], (False, xs))]+match Any (_, x:xs) = [([], [x], (False, xs))]+match Start (True, xs) = [([], [], (True, xs))]+match End (s, []) = [([], [], (s, []))]+match (Bracket r) xs = [(a ++ [b], b, c) | (a,b,c) <- match r xs]+match (Or r1 r2) xs = match r1 xs ++ match r2 xs+match (Concat r1 r2) xs = [(a1++a2,b1++b2,c2) | (a1,b1,c1) <- match r1 xs, (a2,b2,c2) <- match r2 c1]+match (Repeat r) xs = match (Empty `Or` Concat r (Repeat r)) xs+match Empty xs = [([], "", xs)]+match _ _ = []+++++-- | Match a 'FilePattern' against a 'FilePath', There are only two special forms:+--+-- * @*@ matches an entire path component, excluding any separators.+--+-- * @\/\/@ matches an arbitrary number of path components.+--+-- Some examples:+--+-- * @test.c@ matches @test.c@ and nothing else.+--+-- * @*.c@ matches all @.c@ files in the current directory, so @file.c@ matches,+-- but @file.h@ and @dir\/file.c@ don't.+--+-- * @\/\/*.c@ matches all @.c@ files in the current directory or its subdirectories,+-- so @file.c@, @dir\/file.c@ and @dir1\/dir2\/file.c@ all match, but @file.h@ and+-- @dir\/file.h@ don't.+--+-- * @dir\/*\/*@ matches all files one level below @dir@, so @dir\/one\/file.c@ and+-- @dir\/two\/file.h@ match, but @file.c@, @one\/dir\/file.c@, @dir\/file.h@+-- and @dir\/one\/two\/file.c@ don't.+--+-- Patterns with constructs such as @foo\/..\/bar@ will never match+-- normalised 'FilePath' values, so are unlikely to be correct.+(?==) :: FilePattern -> FilePath -> Bool+(?==) [s1,s2,'*'] | isPathSeparator s1 && isPathSeparator s2 = const True+(?==) p = \x -> not $ null $ match pat (True, x)+ where pat = pattern $ lexer p++---------------------------------------------------------------------+-- DIRECTORY PATTERNS++-- | Given a pattern, return the directory that requires searching,+-- with 'True' if it requires a recursive search. Must be conservative.+-- Examples:+--+-- > directories1 "*.xml" == ("",False)+-- > directories1 "//*.xml" == ("",True)+-- > directories1 "foo//*.xml" == ("foo",True)+-- > directories1 "foo/bar/*.xml" == ("foo/bar",False)+-- > directories1 "*/bar/*.xml" == ("",True)+directories1 :: FilePattern -> (FilePath, Bool)+directories1 = first (intercalate [pathSeparator]) . f . lexer+ where+ f xs | (a@(_:_),b:bs) <- span isDull xs, b `elem` (SlashSlash:map Char pathSeparators) =+ if b == SlashSlash then ([map fromChar a],True) else first (map fromChar a:) $ f bs+ | all (\x -> isDull x || x == Star) xs = ([],False)+ | otherwise = ([], True)+++-- | Given a set of patterns, produce a set of directories that require searching,+-- with 'True' if it requires a recursive search. Must be conservative. Examples:+--+-- > directories ["*.xml","//*.c"] == [("",True)]+-- > directories ["bar/*.xml","baz//*.c"] == [("bar",False),("baz",True)]+-- > directories ["bar/*.xml","baz//*.c"] == [("bar",False),("baz",True)]+directories :: [FilePattern] -> [(FilePath,Bool)]+directories ps = foldl f xs xs+ where+ xs = fastNub $ map directories1 ps++ -- Eliminate anything which is a strict subset+ f xs (x,True) = filter (\y -> not $ (x,False) == y || x `isPrefixSlashOf` fst y) xs+ f xs _ = xs++ isPrefixSlashOf x (stripPrefix x -> Just (s1:_)) = isPathSeparator s1+ isPrefixSlashOf _ _ = False+++---------------------------------------------------------------------+-- MULTIPATTERN COMPATIBLE SUBSTITUTIONS++-- | Is the pattern free from any * and //.+simple :: FilePattern -> Bool+simple = all isChar . lexer+++-- | Do they have the same * and // counts in the same order+compatible :: [FilePattern] -> Bool+compatible [] = True+compatible (x:xs) = all ((==) (f x) . f) xs+ where f = filter (not . isChar) . lexer+++-- | Extract the items that match the wildcards. The pair must match with '?=='.+extract :: FilePattern -> FilePath -> [String]+extract p x = ms+ where (ms,_,_):_ = match (pattern $ lexer p) (True,x)+++-- | Given the result of 'extract', substitute it back in to a 'compatible' pattern.+--+-- > p '?==' x ==> substitute (extract p x) p == x+substitute :: [String] -> FilePattern -> FilePath+substitute ms p = f ms (lexer p)+ where+ f ms (Char p:ps) = p : f ms ps+ f (m:ms) (_:ps) = m ++ f ms ps+ f [] [] = []+ f _ _ = error $ "Substitution failed into pattern " ++ show p ++ " with " ++ show (length ms) ++ " matches, namely " ++ show ms
+ src/Development/Shake/Monad.hs view
@@ -0,0 +1,122 @@+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++module Development.Shake.Monad(+ RAW, Capture, runRAW,+ getRO, getRW, getsRO, getsRW, putRW, modifyRW,+ withRO, withRW,+ catchRAW, tryRAW, throwRAW,+ unmodifyRW, captureRAW,+ ) where++import Prelude(); import General.Prelude++import Control.Exception.Extra+import Control.Monad.IO.Class+import Control.Monad.Trans.Cont+import Control.Monad.Trans.Reader+import Data.IORef+++data S ro rw = S+ {handler :: IORef (SomeException -> IO ())+ ,ro :: ro+ ,rww :: IORef rw -- Read/Write Writeable var (rww)+ }++newtype RAW ro rw a = RAW {fromRAW :: ReaderT (S ro rw) (ContT () IO) a}+ deriving (Functor, Applicative, Monad, MonadIO)++type Capture a = (a -> IO ()) -> IO ()+++-- | Run and then call a continuation.+runRAW :: ro -> rw -> RAW ro rw a -> Capture (Either SomeException a)+runRAW ro rw m k = do+ rww <- newIORef rw+ handler <- newIORef $ k . Left+ fromRAW m `runReaderT` S handler ro rww `runContT` (k . Right)+ `catch_` \e -> ($ e) =<< readIORef handler+++---------------------------------------------------------------------+-- STANDARD++getRO :: RAW ro rw ro+getRO = RAW $ asks ro++getRW :: RAW ro rw rw+getRW = RAW $ liftIO . readIORef =<< asks rww++getsRO :: (ro -> a) -> RAW ro rw a+getsRO f = fmap f getRO++getsRW :: (rw -> a) -> RAW ro rw a+getsRW f = fmap f getRW++-- | Strict version+putRW :: rw -> RAW ro rw ()+putRW rw = rw `seq` RAW $ liftIO . flip writeIORef rw =<< asks rww++withRAW :: (S ro rw -> S ro2 rw2) -> RAW ro2 rw2 a -> RAW ro rw a+withRAW f m = RAW $ withReaderT f $ fromRAW m++modifyRW :: (rw -> rw) -> RAW ro rw ()+modifyRW f = do x <- getRW; putRW $ f x++withRO :: (ro -> ro2) -> RAW ro2 rw a -> RAW ro rw a+withRO f = withRAW $ \s -> s{ro=f $ ro s}++withRW :: (rw -> rw2) -> RAW ro rw2 a -> RAW ro rw a+withRW f m = do+ rw <- getRW+ rww <- liftIO $ newIORef $ f rw+ withRAW (\s -> s{rww=rww}) m+++---------------------------------------------------------------------+-- EXCEPTIONS++catchRAW :: RAW ro rw a -> (SomeException -> RAW ro rw a) -> RAW ro rw a+catchRAW m hdl = RAW $ ReaderT $ \s -> ContT $ \k -> do+ old <- readIORef $ handler s+ writeIORef (handler s) $ \e -> do+ writeIORef (handler s) old+ fromRAW (hdl e) `runReaderT` s `runContT` k `catch_`+ \e -> ($ e) =<< readIORef (handler s)+ fromRAW m `runReaderT` s `runContT` \v -> do+ writeIORef (handler s) old+ k v+++tryRAW :: RAW ro rw a -> RAW ro rw (Either SomeException a)+tryRAW m = catchRAW (fmap Right m) (return . Left)++throwRAW :: Exception e => e -> RAW ro rw a+throwRAW = liftIO . throwIO+++---------------------------------------------------------------------+-- WEIRD STUFF++-- | Apply a modification, run an action, then undo the changes after.+unmodifyRW :: (rw -> (rw, rw -> rw)) -> RAW ro rw a -> RAW ro rw a+unmodifyRW f m = do+ (s2,undo) <- fmap f getRW+ putRW s2+ res <- m+ modifyRW undo+ return res+++-- | Capture a continuation. The continuation should be called at most once.+-- Calling the same continuation, multiple times, in parallel, results in incorrect behaviour.+captureRAW :: Capture (Either SomeException a) -> RAW ro rw a+captureRAW f = RAW $ ReaderT $ \s -> ContT $ \k -> do+ old <- readIORef (handler s)+ writeIORef (handler s) throwIO+ f $ \x -> case x of+ Left e -> old e+ Right v -> do+ writeIORef (handler s) old+ k v `catch_` \e -> ($ e) =<< readIORef (handler s)+ writeIORef (handler s) throwIO
+ src/Development/Shake/Pool.hs view
@@ -0,0 +1,164 @@++-- | Thread pool implementation.+module Development.Shake.Pool(+ Pool, runPool,+ addPool, addPoolPriority,+ increasePool+ ) where++import Control.Concurrent.Extra+import Control.Exception+import Control.Monad+import General.Timing+import qualified Data.HashSet as Set+import System.IO.Unsafe+import System.Random+++---------------------------------------------------------------------+-- UNFAIR/RANDOM QUEUE++-- Monad for non-deterministic (but otherwise pure) computations+type NonDet a = IO a++nonDet :: NonDet [Bool]+nonDet = do bs <- unsafeInterleaveIO nonDet+ b <- randomIO+ return $ b:bs++-- Left = deterministic list, Right = non-deterministic tree+data Queue a = Queue [a] (Either [a] (Maybe (Tree a)))++newQueue :: Bool -> Queue a+newQueue deterministic = Queue [] $ if deterministic then Left [] else Right Nothing++enqueuePriority :: a -> Queue a -> Queue a+enqueuePriority x (Queue p t) = Queue (x:p) t++enqueue :: a -> Queue a -> NonDet (Queue a)+enqueue x (Queue p (Left xs)) = return $ Queue p $ Left $ x:xs+enqueue x (Queue p (Right Nothing)) = return $ Queue p $ Right $ Just $ Leaf x+enqueue x (Queue p (Right (Just t))) = do bs <- nonDet; return $ Queue p $ Right $ Just $ insertTree bs x t++dequeue :: Queue a -> Maybe (NonDet (a, Queue a))+dequeue (Queue (p:ps) t) = Just $ return (p, Queue ps t)+dequeue (Queue [] (Left (x:xs))) = Just $ return (x, Queue [] $ Left xs)+dequeue (Queue [] (Left [])) = Nothing+dequeue (Queue [] (Right (Just t))) = Just $ do bs <- nonDet; (x,t) <- return $ removeTree bs t; return (x, Queue [] $ Right t)+dequeue (Queue [] (Right Nothing)) = Nothing+++---------------------------------------------------------------------+-- TREE++-- Note that for a Random tree, since everything is Random, Branch x y =~= Branch y x+data Tree a = Leaf a | Branch (Tree a) (Tree a)++insertTree :: [Bool] -> a -> Tree a -> Tree a+insertTree _ x (Leaf y) = Branch (Leaf x) (Leaf y)+insertTree (b:bs) x (Branch y z) = if b then f y z else f z y+ where f y z = Branch y (insertTree bs x z)++removeTree :: [Bool] -> Tree a -> (a, Maybe (Tree a))+removeTree _ (Leaf x) = (x, Nothing)+removeTree (b:bs) (Branch y z) = if b then f y z else f z y+ where+ f y z = case removeTree bs z of+ (x, Nothing) -> (x, Just y)+ (x, Just z) -> (x, Just $ Branch y z)++---------------------------------------------------------------------+-- THREAD POOL++{-+Must keep a list of active threads, so can raise exceptions in a timely manner+If any worker throws an exception, must signal to all the other workers+-}++data Pool = Pool+ !(Var (Maybe S)) -- Current state, 'Nothing' to say we are aborting+ !(Barrier (Either SomeException S)) -- Barrier to signal that we are++data S = S+ {threads :: !(Set.HashSet ThreadId) -- IMPORTANT: Must be strict or we leak thread stacks+ ,threadsLimit :: {-# UNPACK #-} !Int -- user supplied thread limit, Set.size threads <= threadsLimit+ ,threadsMax :: {-# UNPACK #-} !Int -- high water mark of Set.size threads (accounting only)+ ,threadsSum :: {-# UNPACK #-} !Int -- number of threads we have been through (accounting only)+ ,todo :: !(Queue (IO ())) -- operations waiting a thread+ }+++emptyS :: Int -> Bool -> S+emptyS n deterministic = S Set.empty n 0 0 $ newQueue deterministic+++-- | Given a pool, and a function that breaks the S invariants, restore them+-- They are only allowed to touch threadsLimit or todo+step :: Pool -> (S -> NonDet S) -> IO ()+step pool@(Pool var done) op = do+ let onVar act = modifyVar_ var $ maybe (return Nothing) act+ onVar $ \s -> do+ s <- op s+ res <- maybe (return Nothing) (fmap Just) $ dequeue $ todo s+ case res of+ Just (now, todo2) | Set.size (threads s) < threadsLimit s -> do+ -- spawn a new worker+ t <- forkIO $ do+ t <- myThreadId+ res <- try now+ case res of+ Left e -> onVar $ \s -> do+ mapM_ killThread $ Set.toList $ Set.delete t $ threads s+ signalBarrier done $ Left e+ return Nothing+ Right _ -> step pool $ \s -> return s{threads = Set.delete t $ threads s}+ let threads2 = Set.insert t $ threads s+ return $ Just s{todo = todo2, threads = threads2+ ,threadsSum = threadsSum s + 1, threadsMax = threadsMax s `max` Set.size threads2}+ Nothing | Set.null $ threads s -> do+ signalBarrier done $ Right s+ return Nothing+ _ -> return $ Just s+++-- | Add a new task to the pool, may be cancelled by sending it an exception+addPool :: Pool -> IO a -> IO ()+addPool pool act = step pool $ \s -> do+ todo <- enqueue (void act) (todo s)+ return s{todo = todo}++-- | Add a new task to the pool, may be cancelled by sending it an exception.+-- Takes priority over everything else.+addPoolPriority :: Pool -> IO a -> IO ()+addPoolPriority pool act = step pool $ \s -> do+ todo <- return $ enqueuePriority (void act) (todo s)+ return s{todo = todo}+++-- | Temporarily increase the pool by 1 thread. Call the cleanup action to restore the value.+-- After calling cleanup you should requeue onto a new thread.+increasePool :: Pool -> IO (IO ())+increasePool pool = do+ step pool $ \s -> return s{threadsLimit = threadsLimit s + 1}+ return $ step pool $ \s -> return s{threadsLimit = threadsLimit s - 1}+++-- | Run all the tasks in the pool on the given number of works.+-- If any thread throws an exception, the exception will be reraised.+runPool :: Bool -> Int -> (Pool -> IO ()) -> IO () -- run all tasks in the pool+runPool deterministic n act = do+ s <- newVar $ Just $ emptyS n deterministic+ let cleanup = modifyVar_ s $ \s -> do+ -- if someone kills our thread, make sure we kill our child threads+ case s of+ Just s -> mapM_ killThread $ Set.toList $ threads s+ Nothing -> return ()+ return Nothing+ flip onException cleanup $ do+ res <- newBarrier+ let pool = Pool s res+ addPool pool $ act pool+ res <- waitBarrier res+ case res of+ Left e -> throw e+ Right s -> addTiming $ "Pool finished (" ++ show (threadsSum s) ++ " threads, " ++ show (threadsMax s) ++ " max)"
+ src/Development/Shake/Profile.hs view
@@ -0,0 +1,91 @@+{-# LANGUAGE PatternGuards, RecordWildCards #-}++module Development.Shake.Profile(ProfileEntry(..), ProfileTrace(..), writeProfile) where++import General.Template+import Data.Tuple.Extra+import Data.Function+import Data.List+import Data.Version+import System.FilePath+import Numeric.Extra+import Paths_shake+import System.Time.Extra+import qualified Data.ByteString.Lazy.Char8 as LBS+++data ProfileEntry = ProfileEntry+ {prfName :: String, prfBuilt :: Int, prfChanged :: Int, prfDepends :: [Int], prfExecution :: Double, prfTraces :: [ProfileTrace]}+data ProfileTrace = ProfileTrace+ {prfCommand :: String, prfStart :: Double, prfStop :: Double}+prfTime ProfileTrace{..} = prfStop - prfStart+++-- | Generates an report given some build system profiling data.+writeProfile :: FilePath -> [ProfileEntry] -> IO ()+writeProfile out xs+ | takeExtension out == ".js" = writeFile out $ "var shake = \n" ++ generateJSON xs+ | takeExtension out == ".json" = writeFile out $ generateJSON xs+ | takeExtension out == ".trace" = writeFile out $ generateTrace xs+ | out == "-" = putStr $ unlines $ generateSummary xs+ | otherwise = LBS.writeFile out =<< generateHTML xs+++generateSummary :: [ProfileEntry] -> [String]+generateSummary xs =+ ["* This database has tracked " ++ show (maximum (0 : map prfChanged xs) + 1) ++ " runs."+ ,let f = show . length in "* There are " ++ f xs ++ " rules (" ++ f ls ++ " rebuilt in the last run)."+ ,let f = show . sum . map (length . prfTraces) in "* Building required " ++ f xs ++ " traced commands (" ++ f ls ++ " in the last run)."+ ,"* The total (unparallelised) time is " ++ showDuration (sum $ map prfExecution xs) +++ " of which " ++ showDuration (sum $ map prfTime $ concatMap prfTraces xs) ++ " is traced commands."+ ,let f xs = if null xs then "0s" else (\(a,b) -> showDuration a ++ " (" ++ b ++ ")") $ maximumBy (compare `on` fst) xs in+ "* The longest rule takes " ++ f (map (prfExecution &&& prfName) xs) +++ ", and the longest traced command takes " ++ f (map (prfTime &&& prfCommand) $ concatMap prfTraces xs) ++ "."+ ,let sumLast = sum $ map prfTime $ concatMap prfTraces ls+ maxStop = maximum $ 0 : map prfStop (concatMap prfTraces ls) in+ "* Last run gave an average parallelism of " ++ showDP 2 (if maxStop == 0 then 0 else sumLast / maxStop) +++ " times over " ++ showDuration(maxStop) ++ "."+ ]+ where ls = filter ((==) 0 . prfBuilt) xs+++generateHTML :: [ProfileEntry] -> IO LBS.ByteString+generateHTML xs = do+ htmlDir <- getDataFileName "html"+ report <- LBS.readFile $ htmlDir </> "profile.html"+ let f name | name == "profile-data.js" = return $ LBS.pack $ "var shake =\n" ++ generateJSON xs+ | name == "version.js" = return $ LBS.pack $ "var version = " ++ show (showVersion version)+ | otherwise = LBS.readFile $ htmlDir </> name+ runTemplate f report+++generateTrace :: [ProfileEntry] -> String+generateTrace xs = jsonListLines $+ showEntries 0 [y{prfCommand=prfName x} | x <- xs, y <- prfTraces x] +++ showEntries 1 (concatMap prfTraces xs)+ where+ showEntries pid xs = map (showEntry pid) $ snd $ mapAccumL alloc [] $ sortBy (compare `on` prfStart) xs+ alloc as r | (a1,an:a2) <- break (\a -> prfStop a <= prfStart r) as = (a1++r:a2, (length a1,r))+ | otherwise = (as++[r], (length as,r))+ showEntry pid (tid, ProfileTrace{..}) = jsonObject+ [("args","{}"), ("ph",show "X"), ("cat",show "target")+ ,("name",show prfCommand), ("tid",show tid), ("pid",show pid)+ ,("ts",show $ 1000000*prfStart), ("dur",show $ 1000000*(prfStop-prfStart))]+++generateJSON :: [ProfileEntry] -> String+generateJSON = jsonListLines . map showEntry+ where+ showEntry ProfileEntry{..} = jsonObject $+ [("name", show prfName)+ ,("built", show prfBuilt)+ ,("changed", show prfChanged)+ ,("depends", show prfDepends)+ ,("execution", show prfExecution)] +++ [("traces", jsonList $ map showTrace prfTraces) | not $ null prfTraces]+ showTrace ProfileTrace{..} = jsonObject+ [("command",show prfCommand), ("start",show prfStart), ("stop",show prfStop)]++jsonListLines xs = "[" ++ intercalate "\n," xs ++ "\n]"+jsonList xs = "[" ++ intercalate "," xs ++ "]"+jsonObject xs = "{" ++ intercalate ", " [show a ++ ":" ++ b | (a,b) <- xs] ++ "}"
+ src/Development/Shake/Progress.hs view
@@ -0,0 +1,353 @@+{-# LANGUAGE DeriveDataTypeable, RecordWildCards, CPP, ForeignFunctionInterface #-}+{-# LANGUAGE ViewPatterns #-}++-- | Progress tracking+module Development.Shake.Progress(+ Progress(..),+ progressSimple, progressDisplay, progressTitlebar, progressProgram,+ ProgressEntry(..), progressReplay, writeProgressReport -- INTERNAL USE ONLY+ ) where++import Prelude(); import General.Prelude++import Control.Applicative+import Data.Tuple.Extra+import Control.Exception.Extra+import Control.Monad+import System.Environment+import System.Directory+import System.Process+import System.FilePath+import Data.Char+import Data.Data+import Data.IORef+import Data.List+import Data.Maybe+import Data.Version+import qualified Data.ByteString.Char8 as BS+import qualified Data.ByteString.Lazy.Char8 as LBS+import Numeric.Extra+import General.Template+import System.IO.Unsafe+import Paths_shake+import System.Time.Extra++#ifdef mingw32_HOST_OS++import Foreign+import Foreign.C.Types++type LPCSTR = Ptr CChar++foreign import stdcall "Windows.h SetConsoleTitleA" c_setConsoleTitle :: LPCSTR -> IO Bool++#endif+++---------------------------------------------------------------------+-- PROGRESS TYPES - exposed to the user++-- | Information about the current state of the build, obtained by passing a callback function+-- to 'Development.Shake.shakeProgress'. Typically a program will use 'progressDisplay' to poll this value and produce+-- status messages, which is implemented using this data type.+data Progress = Progress+ {isFailure :: !(Maybe String) -- ^ Starts out 'Nothing', becomes 'Just' a target name if a rule fails.+ ,countSkipped :: {-# UNPACK #-} !Int -- ^ Number of rules which were required, but were already in a valid state.+ ,countBuilt :: {-# UNPACK #-} !Int -- ^ Number of rules which were have been built in this run.+ ,countUnknown :: {-# UNPACK #-} !Int -- ^ Number of rules which have been built previously, but are not yet known to be required.+ ,countTodo :: {-# UNPACK #-} !Int -- ^ Number of rules which are currently required (ignoring dependencies that do not change), but not built.+ ,timeSkipped :: {-# UNPACK #-} !Double -- ^ Time spent building 'countSkipped' rules in previous runs.+ ,timeBuilt :: {-# UNPACK #-} !Double -- ^ Time spent building 'countBuilt' rules.+ ,timeUnknown :: {-# UNPACK #-} !Double -- ^ Time spent building 'countUnknown' rules in previous runs.+ ,timeTodo :: {-# UNPACK #-} !(Double,Int) -- ^ Time spent building 'countTodo' rules in previous runs, plus the number which have no known time (have never been built before).+ }+ deriving (Eq,Ord,Show,Read,Data,Typeable)++instance Monoid Progress where+ mempty = Progress Nothing 0 0 0 0 0 0 0 (0,0)+ mappend a b = Progress+ {isFailure = isFailure a `mplus` isFailure b+ ,countSkipped = countSkipped a + countSkipped b+ ,countBuilt = countBuilt a + countBuilt b+ ,countUnknown = countUnknown a + countUnknown b+ ,countTodo = countTodo a + countTodo b+ ,timeSkipped = timeSkipped a + timeSkipped b+ ,timeBuilt = timeBuilt a + timeBuilt b+ ,timeUnknown = timeUnknown a + timeUnknown b+ ,timeTodo = let (a1,a2) = timeTodo a; (b1,b2) = timeTodo b+ x1 = a1 + b1; x2 = a2 + b2+ in x1 `seq` x2 `seq` (x1,x2)+ }+++---------------------------------------------------------------------+-- MEALY TYPE - for writing the progress functions+-- See <http://hackage.haskell.org/package/machines-0.2.3.1/docs/Data-Machine-Mealy.html>++-- | A machine that takes inputs and produces outputs+newtype Mealy i a = Mealy {runMealy :: i -> (a, Mealy i a)}++instance Functor (Mealy i) where+ fmap f (Mealy m) = Mealy $ \i -> case m i of+ (x, m) -> (f x, fmap f m)++instance Applicative (Mealy i) where+ pure x = let r = Mealy (const (x, r)) in r+ Mealy mf <*> Mealy mx = Mealy $ \i -> case mf i of+ (f, mf) -> case mx i of+ (x, mx) -> (f x, mf <*> mx)++echoMealy :: Mealy i i+echoMealy = Mealy $ \i -> (i, echoMealy)++scanMealy :: (a -> b -> a) -> a -> Mealy i b -> Mealy i a+scanMealy f z (Mealy m) = Mealy $ \i -> case m i of+ (x, m) -> let z2 = f z x in (z2, scanMealy f z2 m)+++---------------------------------------------------------------------+-- MEALY UTILITIES++oldMealy :: a -> Mealy i a -> Mealy i (a,a)+oldMealy old = scanMealy (\(_,old) new -> (old,new)) (old,old)++latch :: Mealy i (Bool, a) -> Mealy i a+latch s = fromJust <$> scanMealy f Nothing s+ where f old (b,v) = Just $ if b then fromMaybe v old else v++iff :: Mealy i Bool -> Mealy i a -> Mealy i a -> Mealy i a+iff c t f = (\c t f -> if c then t else f) <$> c <*> t <*> f++-- decay'd division, compute a/b, with a decay of f+-- r' is the new result, r is the last result+-- r ~= a / b+-- r' = r*b + f*(a'-a)+-- -------------+-- b + f*(b'-b)+-- when f == 1, r == r'+--+-- both streams must only ever increase+decay :: Double -> Mealy i Double -> Mealy i Double -> Mealy i Double+decay f a b = scanMealy step 0 $ (,) <$> oldMealy 0 a <*> oldMealy 0 b+ where step r ((a,a'),(b,b')) =((r*b) + f*(a'-a)) / (b + f*(b'-b))+++---------------------------------------------------------------------+-- MESSAGE GENERATOR++formatMessage :: Double -> Double -> String+formatMessage secs perc =+ (if isNaN secs || secs < 0 then "??s" else showMinSec $ ceiling secs) ++ " (" +++ (if isNaN perc || perc < 0 || perc > 100 then "??" else show $ floor perc) ++ "%)"++showMinSec :: Int -> String+showMinSec secs = (if m == 0 then "" else show m ++ "m" ++ ['0' | s < 10]) ++ show s ++ "s"+ where (m,s) = divMod secs 60++liftA2' :: Applicative m => m a -> m b -> (a -> b -> c) -> m c+liftA2' a b f = liftA2 f a b+++-- | return (number of seconds, percentage, explanation)+message :: Mealy (Double, Progress) (Double, Progress) -> Mealy (Double, Progress) (Double, Double, String)+message input = liftA3 (,,) time perc debug+ where+ progress = snd <$> input+ secs = fst <$> input+ debug = (\donePerSec ruleTime (todoKnown,todoUnknown) ->+ "Progress: " +++ "((known=" ++ showDP 2 todoKnown ++ "s) + " +++ "(unknown=" ++ show todoUnknown ++ " * time=" ++ showDP 2 ruleTime ++ "s)) " +++ "(rate=" ++ showDP 2 donePerSec ++ "))")+ <$> donePerSec <*> ruleTime <*> (timeTodo <$> progress)++ -- Number of seconds work completed in this build run+ -- Ignores timeSkipped which would be more truthful, but it makes the % drop sharply+ -- which isn't what users want+ done = timeBuilt <$> progress++ -- Work done per second, don't divide by 0 and don't update if 'done' doesn't change+ donePerSec = iff ((==) 0 <$> done) (pure 1) perSecStable+ where perSecStable = latch $ liftA2 (,) (uncurry (==) <$> oldMealy 0 done) perSecRaw+ perSecRaw = decay 1.2 done secs++ -- Predicted build time for a rule that has never been built before+ -- The high decay means if a build goes in "phases" - lots of source files, then lots of compiling+ -- we reach a reasonable number fairly quickly, without bouncing too much+ ruleTime = liftA2 weightedAverage+ (f (decay 10) timeBuilt countBuilt)+ (f (liftA2 (/)) (fst . timeTodo) (\Progress{..} -> countTodo - snd timeTodo))+ -- don't call decay on todo, since it goes up and down (as things get done)+ where+ weightedAverage (w1,x1) (w2,x2)+ | w1 == 0 && w2 == 0 = 0+ | otherwise = ((w1 *. x1) + (w2 *. x2)) / intToDouble (w1+w2)+ where i *. d = if i == 0 then 0 else intToDouble i * d -- since d might be NaN++ f divide time count = let xs = count <$> progress in liftA2 (,) xs $ divide (time <$> progress) (intToDouble <$> xs)++ -- Number of seconds work remaining, ignoring multiple threads+ todo = f <$> progress <*> ruleTime+ where f Progress{..} ruleTime = fst timeTodo + (fromIntegral (snd timeTodo) * ruleTime)++ -- Display information+ time = liftA2 (/) todo donePerSec+ perc = iff ((==) 0 <$> done) (pure 0) $+ liftA2' done todo $ \done todo -> 100 * done / (done + todo)+++---------------------------------------------------------------------+-- EXPOSED FUNCTIONS++-- | Given a sampling interval (in seconds) and a way to display the status message,+-- produce a function suitable for using as 'Development.Shake.shakeProgress'.+-- This function polls the progress information every /n/ seconds, produces a status+-- message and displays it using the display function.+--+-- Typical status messages will take the form of @1m25s (15%)@, indicating that the build+-- is predicted to complete in 1 minute 25 seconds (85 seconds total), and 15% of the necessary build time has elapsed.+-- This function uses past observations to predict future behaviour, and as such, is only+-- guessing. The time is likely to go up as well as down, and will be less accurate from a+-- clean build (as the system has fewer past observations).+--+-- The current implementation is to predict the time remaining (based on 'timeTodo') and the+-- work already done ('timeBuilt'). The percentage is then calculated as @remaining / (done + remaining)@,+-- while time left is calculated by scaling @remaining@ by the observed work rate in this build,+-- roughly @done / time_elapsed@.+progressDisplay :: Double -> (String -> IO ()) -> IO Progress -> IO ()+progressDisplay sample disp prog = do+ disp "Starting..." -- no useful info at this stage+ time <- offsetTime+ catchJust (\x -> if x == ThreadKilled then Just () else Nothing) (loop time $ message echoMealy) (const $ disp "Finished")+ where+ loop :: IO Double -> Mealy (Double, Progress) (Double, Double, String) -> IO ()+ loop time mealy = do+ sleep sample+ p <- prog+ t <- time+ ((secs,perc,debug), mealy) <- return $ runMealy mealy (t, p)+ -- putStrLn debug+ disp $ formatMessage secs perc ++ maybe "" (\err -> ", Failure! " ++ err) (isFailure p)+ loop time mealy+++data ProgressEntry = ProgressEntry+ {idealSecs :: Double, idealPerc :: Double+ ,actualSecs :: Double, actualPerc :: Double+ }++-- | Given a list of progress inputs, what would you have suggested (seconds, percentage)+progressReplay :: [(Double, Progress)] -> [ProgressEntry]+progressReplay [] = []+progressReplay ps = snd $ mapAccumL f (message echoMealy) ps+ where+ end = fst $ last ps+ f a (time,p) = (a2, ProgressEntry (end - time) (time * 100 / end) secs perc)+ where ((secs,perc,_),a2) = runMealy a (time,p)+++-- | Given a trace, display information about how well we did+writeProgressReport :: FilePath -> [(FilePath, [(Double, Progress)])] -> IO ()+writeProgressReport out (map (second progressReplay) -> xs)+ | takeExtension out == ".js" = writeFile out $ "var shake = \n" ++ generateJSON xs+ | takeExtension out == ".json" = writeFile out $ generateJSON xs+ | out == "-" = putStr $ unlines $ generateSummary xs+ | otherwise = LBS.writeFile out =<< generateHTML xs+++generateSummary :: [(FilePath, [ProgressEntry])] -> [String]+generateSummary xs = flip concatMap xs $ \(file,xs) ->+ ["# " ++ file, f xs "Seconds" idealSecs actualSecs, f xs "Percent" idealPerc actualPerc]+ where+ levels = [100,90,80,50]+ f xs lbl ideal actual = lbl ++ ": " ++ intercalate ", "+ [show l ++ "% within " ++ show (ceiling $ maximum $ 0 : take ((length xs * l) `div` 100) diff) | l <- levels]+ where diff = sort [abs $ ideal x - actual x | x <- xs]+++generateHTML :: [(FilePath, [ProgressEntry])] -> IO LBS.ByteString+generateHTML xs = do+ htmlDir <- getDataFileName "html"+ report <- LBS.readFile $ htmlDir </> "progress.html"+ let f name | name == "progress-data.js" = return $ LBS.pack $ "var shake =\n" ++ generateJSON xs+ | name == "version.js" = return $ LBS.pack $ "var version = " ++ show (showVersion version)+ | otherwise = LBS.readFile $ htmlDir </> name+ runTemplate f report++generateJSON :: [(FilePath, [ProgressEntry])] -> String+generateJSON = concat . jsonList . map ((++"}") . unlines . f)+ where+ f (file,ps) =+ ("{\"name\":" ++ show (takeFileName file) ++ ", \"values\":") :+ indent (jsonList $ map g ps)++ shw = showDP 1+ g ProgressEntry{..} = jsonObject+ [("idealSecs",shw idealSecs),("idealPerc",shw idealPerc)+ ,("actualSecs",shw actualSecs),("actualPerc",shw actualPerc)]++indent = map (" "++)+jsonList xs = zipWith (:) ('[':repeat ',') xs ++ ["]"]+jsonObject xs = "{" ++ intercalate ", " [show a ++ ":" ++ b | (a,b) <- xs] ++ "}"+++{-# NOINLINE xterm #-}+xterm :: Bool+xterm = System.IO.Unsafe.unsafePerformIO $+ -- Terminal.app uses "xterm-256color" as its env variable+ catch_ (fmap ("xterm" `isPrefixOf`) $ getEnv "TERM") $+ \e -> return False+++-- | Set the title of the current console window to the given text. If the+-- environment variable @$TERM@ is set to @xterm@ this uses xterm escape sequences.+-- On Windows, if not detected as an xterm, this function uses the @SetConsoleTitle@ API.+progressTitlebar :: String -> IO ()+progressTitlebar x+ | xterm = BS.putStr $ BS.pack $ "\ESC]0;" ++ x ++ "\BEL"+#ifdef mingw32_HOST_OS+ | otherwise = BS.useAsCString (BS.pack x) $ \x -> c_setConsoleTitle x >> return ()+#else+ | otherwise = return ()+#endif+++-- | Call the program @shake-progress@ if it is on the @$PATH@. The program is called with+-- the following arguments:+--+-- * @--title=string@ - the string passed to @progressProgram@.+--+-- * @--state=Normal@, or one of @NoProgress@, @Normal@, or @Error@ to indicate+-- what state the progress bar should be in.+--+-- * @--value=25@ - the percent of the build that has completed, if not in @NoProgress@ state.+--+-- The program will not be called consecutively with the same @--state@ and @--value@ options.+--+-- Windows 7 or higher users can get taskbar progress notifications by placing the following+-- program in their @$PATH@: <https://github.com/ndmitchell/shake/releases>.+progressProgram :: IO (String -> IO ())+progressProgram = do+ exe <- findExecutable "shake-progress"+ case exe of+ Nothing -> return $ const $ return ()+ Just exe -> do+ ref <- newIORef Nothing+ return $ \msg -> do+ let failure = " Failure! " `isInfixOf` msg+ let perc = let (a,b) = break (== '%') msg+ in if null b then "" else reverse $ takeWhile isDigit $ reverse a+ let key = (failure, perc)+ same <- atomicModifyIORef ref $ \old -> (Just key, old == Just key)+ let state = if perc == "" then "NoProgress" else if failure then "Error" else "Normal"+ rawSystem exe $ ["--title=" ++ msg, "--state=" ++ state] ++ ["--value=" ++ perc | perc /= ""]+ return ()+++-- | A simple method for displaying progress messages, suitable for using as 'Development.Shake.shakeProgress'.+-- This function writes the current progress to the titlebar every five seconds using 'progressTitlebar',+-- and calls any @shake-progress@ program on the @$PATH@ using 'progressProgram'.+progressSimple :: IO Progress -> IO ()+progressSimple p = do+ program <- progressProgram+ progressDisplay 5 (\s -> progressTitlebar s >> program s) p
+ src/Development/Shake/Resource.hs view
@@ -0,0 +1,162 @@+{-# LANGUAGE RecordWildCards, ViewPatterns #-}++module Development.Shake.Resource(+ Resource, newResourceIO, newThrottleIO, acquireResource, releaseResource+ ) where++import Prelude(); import General.Prelude++import Data.Function+import System.IO.Unsafe+import Control.Concurrent.Extra+import Data.Tuple.Extra+import Control.Monad+import General.Bilist+import Development.Shake.Pool+import System.Time.Extra+++{-# NOINLINE resourceIds #-}+resourceIds :: Var Int+resourceIds = unsafePerformIO $ newVar 0++resourceId :: IO Int+resourceId = modifyVar resourceIds $ \i -> let j = i + 1 in j `seq` return (j, j)+++-- | A type representing an external resource which the build system should respect. There+-- are two ways to create 'Resource's in Shake:+--+-- * 'Development.Shake.newResource' creates a finite resource, stopping too many actions running+-- simultaneously.+--+-- * 'Development.Shake.newThrottle' creates a throttled resource, stopping too many actions running+-- over a short time period.+--+-- These resources are used with 'Development.Shake.withResource' when defining rules. Typically only+-- system commands (such as 'Development.Shake.cmd') should be run inside 'Development.Shake.withResource',+-- not commands such as 'Development.Shake.need'.+--+-- Be careful that the actions run within 'Development.Shake.withResource' do not themselves require further+-- resources, or you may get a \"thread blocked indefinitely in an MVar operation\" exception.+-- If an action requires multiple resources, use 'Development.Shake.withResources' to avoid deadlock.+data Resource = Resource+ {resourceOrd :: Int+ -- ^ Key used for Eq/Ord operations. To make withResources work, we require newResourceIO < newThrottleIO+ ,resourceShow :: String+ -- ^ String used for Show+ ,acquireResource :: Pool -> Int -> IO () -> IO ()+ -- ^ Acquire the resource and call the function. Passes 'False' to indicate you have acquired with no blocking,+ -- or 'True' to say there was waiting and you must not do significant computation on that thread.+ ,releaseResource :: Pool -> Int -> IO ()+ -- ^ You should only ever releaseResource that you obtained with acquireResource.+ }++instance Show Resource where show = resourceShow+instance Eq Resource where (==) = (==) `on` resourceOrd+instance Ord Resource where compare = compare `on` resourceOrd+++---------------------------------------------------------------------+-- FINITE RESOURCES++data Finite = Finite+ {finiteAvailable :: !Int+ -- ^ number of currently available resources+ ,finiteWaiting :: Bilist (Int, IO ())+ -- ^ queue of people with how much they want and the action when it is allocated to them+ }++-- | A version of 'Development.Shake.newResource' that runs in IO, and can be called before calling 'Development.Shake.shake'.+-- Most people should use 'Development.Shake.newResource' instead.+newResourceIO :: String -> Int -> IO Resource+newResourceIO name mx = do+ when (mx < 0) $+ error $ "You cannot create a resource named " ++ name ++ " with a negative quantity, you used " ++ show mx+ key <- resourceId+ var <- newVar $ Finite mx mempty+ return $ Resource (negate key) shw (acquire var) (release var)+ where+ shw = "Resource " ++ name++ acquire :: Var Finite -> Pool -> Int -> IO () -> IO ()+ acquire var pool want continue+ | want < 0 = error $ "You cannot acquire a negative quantity of " ++ shw ++ ", requested " ++ show want+ | want > mx = error $ "You cannot acquire more than " ++ show mx ++ " of " ++ shw ++ ", requested " ++ show want+ | otherwise = join $ modifyVar var $ \x@Finite{..} -> return $+ if want <= finiteAvailable then+ (x{finiteAvailable = finiteAvailable - want}, continue)+ else+ (x{finiteWaiting = finiteWaiting `snoc` (want, addPool pool continue)}, return ())++ release :: Var Finite -> Pool -> Int -> IO ()+ release var _ i = join $ modifyVar var $ \x -> return $ f x{finiteAvailable = finiteAvailable x + i}+ where+ f (Finite i (uncons -> Just ((wi,wa),ws)))+ | wi <= i = second (wa >>) $ f $ Finite (i-wi) ws+ | otherwise = first (add (wi,wa)) $ f $ Finite i ws+ f (Finite i _) = (Finite i mempty, return ())+ add a s = s{finiteWaiting = a `cons` finiteWaiting s}+++---------------------------------------------------------------------+-- THROTTLE RESOURCES+++-- call a function after a certain delay+waiter :: Seconds -> IO () -> IO ()+waiter period act = void $ forkIO $ do+ sleep period+ act++-- Make sure the pool cannot run try until after you have finished with it+blockPool :: Pool -> IO (IO ())+blockPool pool = do+ bar <- newBarrier+ addPool pool $ do+ cancel <- increasePool pool+ waitBarrier bar+ cancel+ return $ signalBarrier bar ()+++data Throttle+ -- | Some number of resources are available+ = ThrottleAvailable !Int+ -- | Some users are blocked (non-empty), plus an action to call once we go back to Available+ | ThrottleWaiting (IO ()) (Bilist (Int, IO ()))+++-- | A version of 'Development.Shake.newThrottle' that runs in IO, and can be called before calling 'Development.Shake.shake'.+-- Most people should use 'Development.Shake.newThrottle' instead.+newThrottleIO :: String -> Int -> Double -> IO Resource+newThrottleIO name count period = do+ when (count < 0) $+ error $ "You cannot create a throttle named " ++ name ++ " with a negative quantity, you used " ++ show count+ key <- resourceId+ var <- newVar $ ThrottleAvailable count+ return $ Resource key shw (acquire var) (release var)+ where+ shw = "Throttle " ++ name++ acquire :: Var Throttle -> Pool -> Int -> IO () -> IO ()+ acquire var pool want continue+ | want < 0 = error $ "You cannot acquire a negative quantity of " ++ shw ++ ", requested " ++ show want+ | want > count = error $ "You cannot acquire more than " ++ show count ++ " of " ++ shw ++ ", requested " ++ show want+ | otherwise = join $ modifyVar var $ \x -> case x of+ ThrottleAvailable i+ | i >= want -> return (ThrottleAvailable $ i - want, continue)+ | otherwise -> do+ stop <- blockPool pool+ return (ThrottleWaiting stop $ (want - i, addPool pool continue) `cons` mempty, return ())+ ThrottleWaiting stop xs -> return (ThrottleWaiting stop $ xs `snoc` (want, addPool pool continue), return ())++ release :: Var Throttle -> Pool -> Int -> IO ()+ release var pool n = waiter period $ join $ modifyVar var $ \x -> return $ case x of+ ThrottleAvailable i -> (ThrottleAvailable $ i+n, return ())+ ThrottleWaiting stop xs -> f stop n xs+ where+ f stop i (uncons -> Just ((wi,wa),ws))+ | i >= wi = second (wa >>) $ f stop (i-wi) ws+ | otherwise = (ThrottleWaiting stop $ (wi-i,wa) `cons` ws, return ())+ f stop i _ = (ThrottleAvailable i, stop)
+ src/Development/Shake/Rule.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE CPP #-}++-- | This module is used for defining new types of rules for Shake build systems.+-- Most users will find the built-in set of rules sufficient.+module Development.Shake.Rule(+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue,+#endif+ Rule(..), EqualCost(..), rule, apply, apply1,+ trackUse, trackChange, trackAllow,+ -- * Deprecated+ defaultRule+ ) where++import Development.Shake.Core+import Development.Shake.Types++{-# DEPRECATED defaultRule "Use 'rule' with 'priority' 0" #-}++-- | A deprecated way of defining a low priority rule. Defined as:+--+-- @+-- defaultRule = 'priority' 0 . 'rule'+-- @+defaultRule :: Rule key value => (key -> Maybe (Action value)) -> Rules ()+defaultRule = priority 0 . rule
+ src/Development/Shake/Rules/Directory.hs view
@@ -0,0 +1,280 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, ScopedTypeVariables, DeriveDataTypeable, RecordWildCards, FlexibleContexts #-}++-- | Both System.Directory and System.Environment wrappers+module Development.Shake.Rules.Directory(+ doesFileExist, doesDirectoryExist,+ getDirectoryContents, getDirectoryFiles, getDirectoryDirs,+ getEnv, getEnvWithDefault,+ removeFiles, removeFilesAfter,+ defaultRuleDirectory+ ) where++import Control.Applicative+import Control.Monad.Extra+import Control.Monad.IO.Class+import Data.Maybe+import Data.Binary+import Data.List+import qualified System.Directory as IO+import qualified System.Environment.Extra as IO++import Development.Shake.Core+import Development.Shake.Classes+import Development.Shake.FilePath+import Development.Shake.FilePattern+import General.Extra+++newtype DoesFileExistQ = DoesFileExistQ FilePath+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show DoesFileExistQ where+ show (DoesFileExistQ a) = "doesFileExist " ++ showQuote a++newtype DoesFileExistA = DoesFileExistA Bool+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show DoesFileExistA where+ show (DoesFileExistA a) = show a+++newtype DoesDirectoryExistQ = DoesDirectoryExistQ FilePath+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show DoesDirectoryExistQ where+ show (DoesDirectoryExistQ a) = "doesDirectoryExist " ++ showQuote a++newtype DoesDirectoryExistA = DoesDirectoryExistA Bool+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show DoesDirectoryExistA where+ show (DoesDirectoryExistA a) = show a+++newtype GetEnvQ = GetEnvQ String+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show GetEnvQ where+ show (GetEnvQ a) = "getEnv " ++ showQuote a++newtype GetEnvA = GetEnvA (Maybe String)+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show GetEnvA where+ show (GetEnvA a) = maybe "<unset>" showQuote a+++data GetDirectoryQ+ = GetDir {dir :: FilePath}+ | GetDirFiles {dir :: FilePath, pat :: [FilePattern]}+ | GetDirDirs {dir :: FilePath}+ deriving (Typeable,Eq)++newtype GetDirectoryA = GetDirectoryA [FilePath]+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show GetDirectoryQ where+ show (GetDir x) = "getDirectoryContents " ++ showQuote x+ show (GetDirFiles a b) = "getDirectoryFiles " ++ showQuote a ++ " [" ++ unwords (map showQuote b) ++ "]"+ show (GetDirDirs x) = "getDirectoryDirs " ++ showQuote x++instance Show GetDirectoryA where+ show (GetDirectoryA xs) = unwords $ map showQuote xs++instance NFData GetDirectoryQ where+ rnf (GetDir a) = rnf a+ rnf (GetDirFiles a b) = rnf a `seq` rnf b+ rnf (GetDirDirs a) = rnf a++instance Hashable GetDirectoryQ where+ hashWithSalt salt = hashWithSalt salt . f+ where f (GetDir x) = (0 :: Int, x, [])+ f (GetDirFiles x y) = (1, x, y)+ f (GetDirDirs x) = (2, x, [])++instance Binary GetDirectoryQ where+ get = do+ i <- getWord8+ case i of+ 0 -> liftM GetDir get+ 1 -> liftM2 GetDirFiles get get+ 2 -> liftM GetDirDirs get++ put (GetDir x) = putWord8 0 >> put x+ put (GetDirFiles x y) = putWord8 1 >> put x >> put y+ put (GetDirDirs x) = putWord8 2 >> put x+++instance Rule DoesFileExistQ DoesFileExistA where+ storedValue _ (DoesFileExistQ x) = fmap (Just . DoesFileExistA) $ IO.doesFileExist x++instance Rule DoesDirectoryExistQ DoesDirectoryExistA where+ storedValue _ (DoesDirectoryExistQ x) = fmap (Just . DoesDirectoryExistA) $ IO.doesDirectoryExist x++instance Rule GetEnvQ GetEnvA where+ storedValue _ (GetEnvQ x) = fmap (Just . GetEnvA) $ IO.lookupEnv x++instance Rule GetDirectoryQ GetDirectoryA where+ storedValue _ x = fmap Just $ getDir x+++-- | This function is not actually exported, but Haddock is buggy. Please ignore.+defaultRuleDirectory :: Rules ()+defaultRuleDirectory = do+ rule $ \(DoesFileExistQ x) -> Just $+ liftIO $ fmap DoesFileExistA $ IO.doesFileExist x+ rule $ \(DoesDirectoryExistQ x) -> Just $+ liftIO $ fmap DoesDirectoryExistA $ IO.doesDirectoryExist x+ rule $ \(x :: GetDirectoryQ) -> Just $+ liftIO $ getDir x+ rule $ \(GetEnvQ x) -> Just $+ liftIO $ fmap GetEnvA $ IO.lookupEnv x+++-- | Returns 'True' if the file exists. The existence of the file is tracked as a+-- dependency, and if the file is created or deleted the rule will rerun in subsequent builds.+--+-- You should not call 'doesFileExist' on files which can be created by the build system.+doesFileExist :: FilePath -> Action Bool+doesFileExist file = do+ DoesFileExistA res <- apply1 $ DoesFileExistQ file+ return res++-- | Returns 'True' if the directory exists. The existence of the directory is tracked as a+-- dependency, and if the directory is created or delete the rule will rerun in subsequent builds.+--+-- You should not call 'doesDirectoryExist' on directories which can be created by the build system.+doesDirectoryExist :: FilePath -> Action Bool+doesDirectoryExist file = do+ DoesDirectoryExistA res <- apply1 $ DoesDirectoryExistQ file+ return res++-- | Return 'Just' the value of the environment variable, or 'Nothing'+-- if the variable is not set. The environment variable is tracked as a+-- dependency, and if it changes the rule will rerun in subsequent builds.+getEnv :: String -> Action (Maybe String)+getEnv var = do+ GetEnvA res <- apply1 $ GetEnvQ var+ return res++-- | Return the value of the environment variable, or the default value if it+-- not set. Similar to 'getEnv'.+getEnvWithDefault :: String -> String -> Action String+getEnvWithDefault def var = fromMaybe def <$> getEnv var++-- | Get the contents of a directory. The result will be sorted, and will not contain+-- the entries @.@ or @..@ (unlike the standard Haskell version). The resulting paths will be relative+-- to the first argument. The result is tracked as a+-- dependency, and if it changes the rule will rerun in subsequent builds.+--+-- It is usually simpler to call either 'getDirectoryFiles' or 'getDirectoryDirs'.+getDirectoryContents :: FilePath -> Action [FilePath]+getDirectoryContents x = getDirAction $ GetDir x++-- | Get the files anywhere under a directory that match any of a set of patterns.+-- For the interpretation of the patterns see '?=='. All results will be+-- relative to the 'FilePath' argument. The result is tracked as a+-- dependency, and if it changes the rule will rerun in subsequent builds.+-- Some examples:+--+-- > getDirectoryFiles "Config" ["//*.xml"]+-- > -- All .xml files anywhere under the Config directory+-- > -- If Config/foo/bar.xml exists it will return ["foo/bar.xml"]+-- > getDirectoryFiles "Modules" ["*.hs","*.lhs"]+-- > -- All .hs or .lhs in the Modules directory+-- > -- If Modules/foo.hs and Modules/foo.lhs exist, it will return ["foo.hs","foo.lhs"]+--+-- If you require a qualified file name it is often easier to use @\"\"@ as 'FilePath' argument,+-- for example the following two expressions are equivalent:+--+-- > fmap (map ("Config" </>)) (getDirectoryFiles "Config" ["//*.xml"])+-- > getDirectoryFiles "" ["Config//*.xml"]+getDirectoryFiles :: FilePath -> [FilePattern] -> Action [FilePath]+getDirectoryFiles x f = getDirAction $ GetDirFiles x f++-- | Get the directories in a directory, not including @.@ or @..@.+-- All directories are relative to the argument directory. The result is tracked as a+-- dependency, and if it changes the rule will rerun in subsequent builds.+--+--+-- > getDirectoryDirs "/Users"+-- > -- Return all directories in the /Users directory+-- > -- e.g. ["Emily","Henry","Neil"]+getDirectoryDirs :: FilePath -> Action [FilePath]+getDirectoryDirs x = getDirAction $ GetDirDirs x++getDirAction x = do GetDirectoryA y <- apply1 x; return y++contents :: FilePath -> IO [FilePath]+-- getDirectoryContents "" is equivalent to getDirectoryContents "." on Windows,+-- but raises an error on Linux. We smooth out the difference.+contents x = fmap (filter $ not . all (== '.')) $ IO.getDirectoryContents $ if x == "" then "." else x+++answer :: [FilePath] -> GetDirectoryA+answer = GetDirectoryA . sort++getDir :: GetDirectoryQ -> IO GetDirectoryA+getDir GetDir{..} = fmap answer $ contents dir++getDir GetDirDirs{..} = fmap answer $ filterM f =<< contents dir+ where f x = IO.doesDirectoryExist $ dir </> x++getDir GetDirFiles{..} = fmap answer $ concatMapM f $ directories pat+ where+ test = let ps = map (?==) pat in \x -> any ($ x) ps++ f (dir2,False) = do+ xs <- fmap (map (dir2 </>)) $ contents $ dir </> dir2+ flip filterM xs $ \x -> if not $ test x then return False else fmap not $ IO.doesDirectoryExist $ dir </> x++ f (dir2,True) = do+ xs <- fmap (map (dir2 </>)) $ contents $ dir </> dir2+ (dirs,files) <- partitionM (\x -> IO.doesDirectoryExist $ dir </> x) xs+ rest <- concatMapM (\d -> f (d, True)) dirs+ return $ filter test files ++ rest+++-- | Remove all files and directories that match any of the patterns within a directory.+-- Some examples:+--+-- @+-- 'removeFiles' \"output\" [\"\/\/*\"]+-- 'removeFiles' \".\" [\"\/\/*.hi\",\"\/\/*.o\"]+-- @+--+-- Any directories that become empty after deleting items from within them will themselves be deleted,+-- up to (and including) the containing directory.+-- This function is often useful when writing a @clean@ action for your build system,+-- often as a 'phony' rule.+removeFiles :: FilePath -> [FilePattern] -> IO ()+removeFiles dir pat = do+ b <- IO.doesDirectoryExist dir+ when b $ void $ f ""+ where+ -- because it is generate and match anything like ../ will be ignored, since we never generate ..+ -- therefore we can safely know we never escape the containing directory+ test = let ps = map (?==) pat in \x -> any ($ x) ps++ -- dir </> dir2 is the part to operate on, return True if you deleted the directory+ f :: FilePath -> IO Bool+ f dir2 | test dir2 = do+ IO.removeDirectoryRecursive $ dir </> dir2+ return True+ f dir2 = do+ xs <- fmap (map (dir2 </>)) $ contents $ dir </> dir2+ (dirs,files) <- partitionM (\x -> IO.doesDirectoryExist $ dir </> x) xs+ noDirs <- fmap and $ mapM f dirs+ let (del,keep) = partition test files+ forM del $ \d -> IO.removeFile $ dir </> d+ let die = noDirs && null keep && not (null xs)+ when die $ IO.removeDirectory $ dir </> dir2+ return die+++-- | Remove files, like 'removeFiles', but executed after the build completes successfully.+-- Useful for implementing @clean@ actions that delete files Shake may have open for building.+removeFilesAfter :: FilePath -> [FilePattern] -> Action ()+removeFilesAfter a b = do+ putLoud $ "Will remove " ++ unwords b ++ " from " ++ a+ runAfter $ removeFiles a b
+ src/Development/Shake/Rules/File.hs view
@@ -0,0 +1,256 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}+{-# LANGUAGE ViewPatterns #-}++module Development.Shake.Rules.File(+ need, needBS, needed, neededBS, want,+ trackRead, trackWrite, trackAllow,+ defaultRuleFile,+ (%>), (|%>), (?>), phony, (~>),+ -- * Internal only+ FileQ(..), FileA+ ) where++import Control.Applicative+import Control.Monad+import Control.Monad.IO.Class+import System.Directory+import qualified Data.ByteString.Char8 as BS+import qualified Data.HashSet as Set++import Development.Shake.Core hiding (trackAllow)+import qualified Development.Shake.Core as S+import General.String+import Development.Shake.ByteString+import Development.Shake.Classes+import Development.Shake.FilePath(toStandard)+import Development.Shake.FilePattern+import Development.Shake.FileInfo+import Development.Shake.Types+import Development.Shake.Errors++import Data.Bits+import Data.List+import Data.Maybe+import System.FilePath(takeDirectory) -- important that this is the system local filepath, or wrong slashes go wrong+import System.IO.Unsafe(unsafeInterleaveIO)+++infix 1 %>, ?>, |%>, ~>+++newtype FileQ = FileQ {fromFileQ :: BSU}+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show FileQ where show (FileQ x) = unpackU x++data FileA = FileA {-# UNPACK #-} !ModTime {-# UNPACK #-} !FileSize FileHash+ deriving (Typeable,Eq)++instance Hashable FileA where+ hashWithSalt salt (FileA a b c) = hashWithSalt salt a `xor` hashWithSalt salt b `xor` hashWithSalt salt c++instance NFData FileA where+ rnf (FileA a b c) = rnf a `seq` rnf b `seq` rnf c++instance Binary FileA where+ put (FileA a b c) = put a >> put b >> put c+ get = liftA3 FileA get get get++instance Show FileA where+ show (FileA m s h) = "File {mod=" ++ show m ++ ",size=" ++ show s ++ ",digest=" ++ show h ++ "}"++instance Rule FileQ FileA where+ storedValue ShakeOptions{shakeChange=c} (FileQ x) = do+ res <- getFileInfo x+ case res of+ Nothing -> return Nothing+ Just (time,size) | c == ChangeModtime -> return $ Just $ FileA time size fileInfoVal+ Just (time,size) -> do+ hash <- unsafeInterleaveIO $ getFileHash x+ return $ Just $ FileA (if c == ChangeDigest then fileInfoVal else time) size hash++ equalValue ShakeOptions{shakeChange=c} q (FileA x1 x2 x3) (FileA y1 y2 y3) = case c of+ ChangeModtime -> bool $ x1 == y1+ ChangeDigest -> bool $ x2 == y2 && x3 == y3+ ChangeModtimeOrDigest -> bool $ x1 == y1 && x2 == y2 && x3 == y3+ _ -> if x1 == y1 then EqualCheap+ else if x2 == y2 && x3 == y3 then EqualExpensive+ else NotEqual+ where bool b = if b then EqualCheap else NotEqual++storedValueError :: ShakeOptions -> Bool -> String -> FileQ -> IO FileA+storedValueError opts input msg x = fromMaybe def <$> storedValue opts2 x+ where def = if shakeCreationCheck opts || input then error err else FileA fileInfoNeq fileInfoNeq fileInfoNeq+ err = msg ++ "\n " ++ unpackU (fromFileQ x)+ opts2 = if not input && shakeChange opts == ChangeModtimeAndDigestInput then opts{shakeChange=ChangeModtime} else opts+++-- | This function is not actually exported, but Haddock is buggy. Please ignore.+defaultRuleFile :: Rules ()+defaultRuleFile = priority 0 $ rule $ \x -> Just $ do+ opts <- getShakeOptions+ liftIO $ storedValueError opts True "Error, file does not exist and no rule available:" x+++-- | Add a dependency on the file arguments, ensuring they are built before continuing.+-- The file arguments may be built in parallel, in any order. This function is particularly+-- necessary when calling 'Development.Shake.cmd' or 'Development.Shake.command'. As an example:+--+-- @+-- \"\/\/*.rot13\" '%>' \\out -> do+-- let src = 'Development.Shake.FilePath.dropExtension' out+-- 'need' [src]+-- 'Development.Shake.cmd' \"rot13\" [src] \"-o\" [out]+-- @+--+-- Usually @need [foo,bar]@ is preferable to @need [foo] >> need [bar]@ as the former allows greater+-- parallelism, while the latter requires @foo@ to finish building before starting to build @bar@.+need :: [FilePath] -> Action ()+need xs = (apply $ map (FileQ . packU_ . filepathNormalise . unpackU_ . packU) xs :: Action [FileA]) >> return ()++needBS :: [BS.ByteString] -> Action ()+needBS xs = (apply $ map (FileQ . packU_ . filepathNormalise) xs :: Action [FileA]) >> return ()+++-- | Like 'need', but if 'shakeLint' is set, check that the file does not rebuild.+-- Used for adding dependencies on files that have already been used in this rule.+needed :: [FilePath] -> Action ()+needed xs = do+ opts <- getShakeOptions+ if isNothing $ shakeLint opts then need xs else neededCheck $ map packU xs+++neededBS :: [BS.ByteString] -> Action ()+neededBS xs = do+ opts <- getShakeOptions+ if isNothing $ shakeLint opts then needBS xs else neededCheck $ map packU_ xs+++neededCheck :: [BSU] -> Action ()+neededCheck (map (packU_ . filepathNormalise . unpackU_) -> xs) = do+ opts <- getShakeOptions+ pre <- liftIO $ mapM (storedValue opts . FileQ) xs+ post <- apply $ map FileQ xs :: Action [FileA]+ let bad = [ (x, if isJust a then "File change" else "File created")+ | (x, a, b) <- zip3 xs pre post, Just b /= a]+ case bad of+ [] -> return ()+ (file,msg):_ -> errorStructured+ "Lint checking error - 'needed' file required rebuilding"+ [("File", Just $ unpackU file)+ ,("Error",Just msg)]+ ""+++-- | Track that a file was read by the action preceeding it. If 'shakeLint' is activated+-- then these files must be dependencies of this rule. Calls to 'trackRead' are+-- automatically inserted in 'LintTracker' mode.+trackRead :: [FilePath] -> Action ()+trackRead = mapM_ (trackUse . FileQ . packU)++-- | Track that a file was written by the action preceeding it. If 'shakeLint' is activated+-- then these files must either be the target of this rule, or never referred to by the build system.+-- Calls to 'trackWrite' are automatically inserted in 'LintTracker' mode.+trackWrite :: [FilePath] -> Action ()+trackWrite = mapM_ (trackChange . FileQ . packU)++-- | Allow accessing a file in this rule, ignoring any 'trackRead'\/'trackWrite' calls matching+-- the pattern.+trackAllow :: [FilePattern] -> Action ()+trackAllow ps = do+ opts <- getShakeOptions+ when (isJust $ shakeLint opts) $+ S.trackAllow $ \(FileQ x) -> any (?== unpackU x) ps+++-- | Require that the argument files are built by the rules, used to specify the target.+--+-- @+-- main = 'Development.Shake.shake' 'shakeOptions' $ do+-- 'want' [\"Main.exe\"]+-- ...+-- @+--+-- This program will build @Main.exe@, given sufficient rules. All arguments to all 'want' calls+-- may be built in parallel, in any order.+--+-- This function is defined in terms of 'action' and 'need', use 'action' if you need more complex+-- targets than 'want' allows.+want :: [FilePath] -> Rules ()+want = action . need+++root :: String -> (FilePath -> Bool) -> (FilePath -> Action ()) -> Rules ()+root help test act = rule $ \(FileQ x_) -> let x = unpackU x_ in+ if not $ test x then Nothing else Just $ do+ liftIO $ createDirectoryIfMissing True $ takeDirectory x+ act x+ opts <- getShakeOptions+ liftIO $ storedValueError opts False ("Error, rule " ++ help ++ " failed to build file:") $ FileQ x_+++-- | Declare a phony action -- an action that does not produce a file, and will be rerun+-- in every execution that requires it. You can demand 'phony' rules using 'want' \/ 'need'.+-- Phony actions are never executed more than once in a single build run.+--+-- Phony actions are intended to define command-line abbreviations. If you 'need' a phony action+-- in a rule then every execution where that rule is required will rerun both the rule and the phony+-- action.+phony :: String -> Action () -> Rules ()+phony name act = rule $ \(FileQ x_) -> let x = unpackU x_ in+ if name /= x then Nothing else Just $ do+ act+ return $ FileA fileInfoNeq fileInfoNeq fileInfoNeq++-- | Infix operator alias for 'phony', for sake of consistency with normal+-- rules.+(~>) :: String -> Action () -> Rules ()+(~>) = phony +++-- | Define a rule to build files. If the first argument returns 'True' for a given file,+-- the second argument will be used to build it. Usually '%>' is sufficient, but '?>' gives+-- additional power. For any file used by the build system, only one rule should return 'True'.+-- This function will create the directory for the result file, if necessary.+--+-- @+-- (all isUpper . 'Development.Shake.FilePath.takeBaseName') '?>' \\out -> do+-- let src = 'Development.Shake.FilePath.replaceBaseName' out $ map toLower $ takeBaseName out+-- 'Development.Shake.writeFile'' out . map toUpper =<< 'Development.Shake.readFile'' src+-- @+(?>) :: (FilePath -> Bool) -> (FilePath -> Action ()) -> Rules ()+(?>) test act = priority 0.5 $ root "with ?>" test act+++-- | Define a set of patterns, and if any of them match, run the associated rule. Defined in terms of '%>'.+-- Think of it as the OR (@||@) equivalent of '%>'.+(|%>) :: [FilePattern] -> (FilePath -> Action ()) -> Rules ()+(|%>) pats act = do+ let (simp,other) = partition simple pats+ case simp of+ [] -> return ()+ [p] -> root "with |%>" (\x -> toStandard x == p) act+ ps -> let ps = Set.fromList pats in root "with |%>" (flip Set.member ps . toStandard) act+ unless (null other) $+ let ps = map (?==) other in priority 0.5 $ root "with |%>" (\x -> any ($ x) ps) act++-- | Define a rule that matches a 'FilePattern', see '?==' for the pattern rules.+-- Patterns with no wildcards have higher priority than those with wildcards, and no file+-- required by the system may be matched by more than one pattern at the same priority+-- (see 'priority' and 'alternatives' to modify this behaviour).+-- This function will create the directory for the result file, if necessary.+--+-- @+-- \"*.asm.o\" '%>' \\out -> do+-- let src = 'Development.Shake.FilePath.dropExtension' out+-- 'need' [src]+-- 'Development.Shake.cmd' \"as\" [src] \"-o\" [out]+-- @+--+-- To define a build system for multiple compiled languages, we recommend using @.asm.o@,+-- @.cpp.o@, @.hs.o@, to indicate which language produces an object file.+-- I.e., the file @foo.cpp@ produces object file @foo.cpp.o@.+--+-- Note that matching is case-sensitive, even on Windows.+(%>) :: FilePattern -> (FilePath -> Action ()) -> Rules ()+(%>) test act = (if simple test then id else priority 0.5) $ root (show test) (test ?==) act
+ src/Development/Shake/Rules/Files.hs view
@@ -0,0 +1,136 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}++module Development.Shake.Rules.Files(+ (&?>), (&%>)+ ) where++import Control.Monad+import Control.Monad.IO.Class+import Data.Maybe+import System.Directory++import Development.Shake.Core hiding (trackAllow)+import General.Extra+import General.String+import Development.Shake.Classes+import Development.Shake.Rules.File+import Development.Shake.FilePattern+import Development.Shake.Types++import System.FilePath(takeDirectory) -- important that this is the system local filepath, or wrong slashes go wrong+++infix 1 &?>, &%>+++newtype FilesQ = FilesQ [FileQ]+ deriving (Typeable,Eq,Hashable,Binary,NFData)++++newtype FilesA = FilesA [FileA]+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show FilesA where show (FilesA xs) = unwords $ "Files" : map (drop 5 . show) xs++instance Show FilesQ where show (FilesQ xs) = unwords $ map (showQuote . show) xs+++instance Rule FilesQ FilesA where+ storedValue opts (FilesQ xs) = fmap (fmap FilesA . sequence) $ mapM (storedValue opts) xs+ equalValue opts (FilesQ qs) (FilesA xs) (FilesA ys)+ | let n = length qs in n /= length xs || n /= length ys = NotEqual+ | otherwise = foldr and_ EqualCheap (zipWith3 (equalValue opts) qs xs ys)+ where and_ NotEqual x = NotEqual+ and_ EqualCheap x = x+ and_ EqualExpensive x = if x == NotEqual then NotEqual else EqualExpensive+++-- | Define a rule for building multiple files at the same time.+-- Think of it as the AND (@&&@) equivalent of '%>'.+-- As an example, a single invocation of GHC produces both @.hi@ and @.o@ files:+--+-- @+-- [\"*.o\",\"*.hi\"] '&%>' \\[o,hi] -> do+-- let hs = o 'Development.Shake.FilePath.-<.>' \"hs\"+-- 'Development.Shake.need' ... -- all files the .hs import+-- 'Development.Shake.cmd' \"ghc -c\" [hs]+-- @+--+-- However, in practice, it's usually easier to define rules with '%>' and make the @.hi@ depend+-- on the @.o@. When defining rules that build multiple files, all the 'FilePattern' values must+-- have the same sequence of @\/\/@ and @*@ wildcards in the same order.+-- This function will create directories for the result files, if necessary.+-- Think of it as the OR (@||@) equivalent of '%>'.+(&%>) :: [FilePattern] -> ([FilePath] -> Action ()) -> Rules ()+ps &%> act+ | not $ compatible ps = error $+ "All patterns to &%> must have the same number and position of // and * wildcards\n" +++ unwords ps+ | otherwise = do+ forM_ ps $ \p ->+ p %> \file -> do+ _ :: FilesA <- apply1 $ FilesQ $ map (FileQ . packU . substitute (extract p file)) ps+ return ()+ (if all simple ps then id else priority 0.5) $+ rule $ \(FilesQ xs_) -> let xs = map (unpackU . fromFileQ) xs_ in+ if not $ length xs == length ps && and (zipWith (?==) ps xs) then Nothing else Just $ do+ liftIO $ mapM_ (createDirectoryIfMissing True) $ fastNub $ map takeDirectory xs+ trackAllow xs+ act xs+ getFileTimes "&%>" xs_+++-- | Define a rule for building multiple files at the same time, a more powerful+-- and more dangerous version of '&%>'. Think of it as the AND (@&&@) equivalent of '?>'.+--+-- Given an application @test &?> ...@, @test@ should return @Just@ if the rule applies, and should+-- return the list of files that will be produced. This list /must/ include the file passed as an argument and should+-- obey the invariant:+--+-- > forAll $ \x ys -> test x == Just ys ==> x `elem` ys && all ((== Just ys) . test) ys+--+-- As an example of a function satisfying the invariaint:+--+-- @+--test x | 'Development.Shake.FilePath.takeExtension' x \`elem\` [\".hi\",\".o\"]+-- = Just ['Development.Shake.FilePath.dropExtension' x 'Development.Shake.FilePath.<.>' \"hi\", 'Development.Shake.FilePath.dropExtension' x 'Development.Shake.FilePath.<.>' \"o\"]+--test _ = Nothing+-- @+--+-- Regardless of whether @Foo.hi@ or @Foo.o@ is passed, the function always returns @[Foo.hi, Foo.o]@.+(&?>) :: (FilePath -> Maybe [FilePath]) -> ([FilePath] -> Action ()) -> Rules ()+(&?>) test act = priority 0.5 $ do+ let checkedTest x = case test x of+ Nothing -> Nothing+ Just ys | x `elem` ys && all ((== Just ys) . test) ys -> Just ys+ | otherwise -> error $ "Invariant broken in &?> when trying on " ++ x++ isJust . checkedTest ?> \x -> do+ -- FIXME: Could optimise this test by calling rule directly and returning FileA Eq Eq Eq+ -- But only saves noticable time on uncommon Change modes+ _ :: FilesA <- apply1 $ FilesQ $ map (FileQ . packU) $ fromJust $ test x+ return ()++ rule $ \(FilesQ xs_) -> let xs@(x:_) = map (unpackU . fromFileQ) xs_ in+ case checkedTest x of+ Just ys | ys == xs -> Just $ do+ liftIO $ mapM_ (createDirectoryIfMissing True) $ fastNub $ map takeDirectory xs+ act xs+ getFileTimes "&?>" xs_+ Just ys -> error $ "Error, &?> is incompatible with " ++ show xs ++ " vs " ++ show ys+ Nothing -> Nothing+++getFileTimes :: String -> [FileQ] -> Action FilesA+getFileTimes name xs = do+ opts <- getShakeOptions+ ys <- liftIO $ mapM (storedValue opts) xs+ case sequence ys of+ Just ys -> return $ FilesA ys+ Nothing | not $ shakeCreationCheck opts -> return $ FilesA []+ Nothing -> do+ let missing = length $ filter isNothing ys+ error $ "Error, " ++ name ++ " rule failed to build " ++ show missing +++ " file" ++ (if missing == 1 then "" else "s") ++ " (out of " ++ show (length xs) ++ ")" +++ concat ["\n " ++ unpackU x ++ if isNothing y then " - MISSING" else "" | (FileQ x,y) <- zip xs ys]
+ src/Development/Shake/Rules/Oracle.hs view
@@ -0,0 +1,118 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}+-- Allows the user to violate the functional dependency, but it has a runtime check so still safe+{-# LANGUAGE UndecidableInstances #-}++{-# LANGUAGE CPP #-}+#if __GLASGOW_HASKELL__ >= 704+{-# LANGUAGE ConstraintKinds #-}+#endif++module Development.Shake.Rules.Oracle(+ addOracle, askOracle, askOracleWith+ ) where++import Development.Shake.Core+import Development.Shake.Classes+++-- Use should type names, since the names appear in the Haddock, and are too long if they are in full+newtype OracleQ question = OracleQ question+ deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+newtype OracleA answer = OracleA answer+ deriving (Show,Typeable,Eq,Hashable,Binary,NFData)++instance (+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue q, ShakeValue a+#else+ Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,+ Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a+#endif+ ) => Rule (OracleQ q) (OracleA a) where+ storedValue _ _ = return Nothing+++-- | Add extra information which rules can depend on.+-- An oracle is a function from a question type @q@, to an answer type @a@.+-- As an example, we can define an oracle allowing you to depend on the current version of GHC:+--+-- @+-- newtype GhcVersion = GhcVersion () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+-- rules = do+-- 'addOracle' $ \\(GhcVersion _) -> fmap 'Development.Shake.fromStdout' $ 'Development.Shake.cmd' \"ghc --numeric-version\"+-- ... rules ...+-- @+--+-- If a rule calls @'askOracle' (GhcVersion ())@, that rule will be rerun whenever the GHC version changes.+-- Some notes:+--+-- * We define @GhcVersion@ with a @newtype@ around @()@, allowing the use of @GeneralizedNewtypeDeriving@.+-- All the necessary type classes are exported from "Development.Shake.Classes".+--+-- * Each call to 'addOracle' must use a different type of question.+--+-- * Actions passed to 'addOracle' will be run in every build they are required,+-- but if their value does not change they will not invalidate any rules depending on them.+-- To get a similar behaviour using data stored in files, see 'Development.Shake.alwaysRerun'.+--+-- * If the value returned by 'askOracle' is ignored then 'askOracleWith' may help avoid ambiguous type messages.+-- Alternatively, use the result of 'addOracle', which is 'askOracle' restricted to the correct type.+--+-- As a more complex example, consider tracking Haskell package versions:+--+-- @+--newtype GhcPkgList = GhcPkgList () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+--newtype GhcPkgVersion = GhcPkgVersion String deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+--+--rules = do+-- getPkgList \<- 'addOracle' $ \\GhcPkgList{} -> do+-- Stdout out <- 'Development.Shake.cmd' \"ghc-pkg list --simple-output\"+-- return [(reverse b, reverse a) | x <- words out, let (a,_:b) = break (== \'-\') $ reverse x]+-- --+-- getPkgVersion \<- 'addOracle' $ \\(GhcPkgVersion pkg) -> do+-- pkgs <- getPkgList $ GhcPkgList ()+-- return $ lookup pkg pkgs+-- --+-- \"myrule\" %> \\_ -> do+-- getPkgVersion $ GhcPkgVersion \"shake\"+-- ... rule using the shake version ...+-- @+--+-- Using these definitions, any rule depending on the version of @shake@+-- should call @getPkgVersion $ GhcPkgVersion \"shake\"@ to rebuild when @shake@ is upgraded.+addOracle :: (+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue q, ShakeValue a+#else+ Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,+ Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a+#endif+ ) => (q -> Action a) -> Rules (q -> Action a)+addOracle act = do+ rule $ \(OracleQ q) -> Just $ fmap OracleA $ act q+ return askOracle+++-- | Get information previously added with 'addOracle'. The question/answer types must match those provided+-- to 'addOracle'.+askOracle :: (+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue q, ShakeValue a+#else+ Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,+ Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a+#endif+ ) => q -> Action a+askOracle question = do OracleA answer <- apply1 $ OracleQ question; return answer++-- | Get information previously added with 'addOracle'. The second argument is not used, but can+-- be useful to fix the answer type, avoiding ambiguous type error messages.+askOracleWith :: (+#if __GLASGOW_HASKELL__ >= 704+ ShakeValue q, ShakeValue a+#else+ Show q, Typeable q, Eq q, Hashable q, Binary q, NFData q,+ Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a+#endif+ ) => q -> a -> Action a+askOracleWith question _ = askOracle question
+ src/Development/Shake/Rules/OrderOnly.hs view
@@ -0,0 +1,56 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable #-}++module Development.Shake.Rules.OrderOnly(+ defaultRuleOrderOnly, orderOnly, orderOnlyBS+ ) where++import Development.Shake.Core+import General.String+import Development.Shake.ByteString+import Development.Shake.Classes+import Development.Shake.Rules.File+import qualified Data.ByteString.Char8 as BS+++newtype OrderOnlyQ = OrderOnlyQ BSU+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show OrderOnlyQ where show (OrderOnlyQ x) = unpackU x++newtype OrderOnlyA = OrderOnlyA ()+ deriving (Typeable,Eq,Hashable,Binary,NFData)++instance Show OrderOnlyA where show (OrderOnlyA ()) = "OrderOnly"+++instance Rule OrderOnlyQ OrderOnlyA where+ storedValue _ (OrderOnlyQ _) = return $ Just $ OrderOnlyA ()+++defaultRuleOrderOnly :: Rules ()+defaultRuleOrderOnly = rule $ \(OrderOnlyQ x) -> Just $ do+ needBS [unpackU_ x]+ return $ OrderOnlyA ()+++-- | Define order-only dependencies, these are dependencies that will always+-- be built before continuing, but which aren't dependencies of this action.+-- Mostly useful for defining generated dependencies you think might be real dependencies.+-- If they turn out to be real dependencies, you should add an explicit dependency afterwards.+--+-- @+-- \"source.o\" %> \\out -> do+-- 'orderOnly' [\"header.h\"]+-- () <- 'cmd' \"gcc -c source.c -o source.o -MMD -MF source.m\"+-- 'neededMakefileDependencies' \"source.m\"+-- @+--+-- If @header.h@ is included by @source.c@ then the call to 'needMakefileDependencies' will cause+-- it to be added as a real dependency. If it isn't, then the rule won't rebuild if it changes,+-- and you will have lost some opportunity for parallelism.+orderOnly :: [FilePath] -> Action ()+orderOnly xs = (apply $ map (OrderOnlyQ . packU_ . filepathNormalise . unpackU_ . packU) xs :: Action [OrderOnlyA]) >> return ()+++orderOnlyBS :: [BS.ByteString] -> Action ()+orderOnlyBS xs = (apply $ map (OrderOnlyQ . packU_ . filepathNormalise) xs :: Action [OrderOnlyA]) >> return ()
+ src/Development/Shake/Rules/Rerun.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}++module Development.Shake.Rules.Rerun(+ defaultRuleRerun, alwaysRerun+ ) where++import Development.Shake.Core+import Development.Shake.Classes+++newtype AlwaysRerunQ = AlwaysRerunQ ()+ deriving (Typeable,Eq,Hashable,Binary,NFData)+instance Show AlwaysRerunQ where show _ = "alwaysRerun"++newtype AlwaysRerunA = AlwaysRerunA ()+ deriving (Typeable,Hashable,Binary,NFData)+instance Show AlwaysRerunA where show _ = "<none>"+instance Eq AlwaysRerunA where a == b = False++instance Rule AlwaysRerunQ AlwaysRerunA where+ storedValue _ _ = return Nothing+++-- | Always rerun the associated action. Useful for defining rules that query+-- the environment. For example:+--+-- @+-- \"ghcVersion.txt\" 'Development.Shake.%>' \\out -> do+-- 'alwaysRerun'+-- 'Development.Shake.Stdout' stdout <- 'Development.Shake.cmd' \"ghc --numeric-version\"+-- 'Development.Shake.writeFileChanged' out stdout+-- @+alwaysRerun :: Action ()+alwaysRerun = do AlwaysRerunA _ <- apply1 $ AlwaysRerunQ (); return ()++defaultRuleRerun :: Rules ()+defaultRuleRerun = rule $ \AlwaysRerunQ{} -> Just $ return $ AlwaysRerunA()
+ src/Development/Shake/Shake.hs view
@@ -0,0 +1,29 @@++-- | The main entry point that calls all the default rules+module Development.Shake.Shake(shake) where++import Development.Shake.Types+import General.Timing+import Development.Shake.Core++import Development.Shake.Rules.Directory+import Development.Shake.Rules.File+import Development.Shake.Rules.OrderOnly+import Development.Shake.Rules.Rerun+++-- | Main entry point for running Shake build systems. For an example see the top of the module "Development.Shake".+-- Use 'ShakeOptions' to specify how the system runs, and 'Rules' to specify what to build. The function will throw+-- an exception if the build fails.+--+-- To use command line flags to modify 'ShakeOptions' see 'Development.Shake.shakeArgs'.+shake :: ShakeOptions -> Rules () -> IO ()+shake opts r = do+ addTiming "Function shake"+ run opts $ do+ r+ defaultRuleFile+ defaultRuleDirectory+ defaultRuleOrderOnly+ defaultRuleRerun+ return ()
+ src/Development/Shake/Special.hs view
@@ -0,0 +1,20 @@++-- | This module contains rule types that have special behaviour in some way.+-- Everything in this module is a hack.+module Development.Shake.Special(+ specialAlwaysRebuilds,+ specialIsFileKey+ ) where++import Development.Shake.Value+import Data.Typeable+++specialAlwaysRebuilds :: Value -> Bool+specialAlwaysRebuilds v = con `elem` ["AlwaysRerunA","OracleA"] || (con == "FileA" && show v == "File {mod=NEQ,size=NEQ,digest=NEQ}")+ where con = show $ fst $ splitTyConApp $ typeValue v+++specialIsFileKey :: TypeRep -> Bool+specialIsFileKey t = con == "FileQ"+ where con = show $ fst $ splitTyConApp t
+ src/Development/Shake/Storage.hs view
@@ -0,0 +1,245 @@+{-# LANGUAGE ScopedTypeVariables, PatternGuards, NamedFieldPuns, FlexibleInstances, MultiParamTypeClasses #-}+{-+This module stores the meta-data so its very important its always accurate+We can't rely on getting any exceptions or termination at the end, so we'd better write out a journal+We store a series of records, and if they contain twice as many records as needed, we compress+-}++module Development.Shake.Storage(+ withStorage+ ) where++import General.Binary+import Development.Shake.Types+import General.Timing++import Data.Tuple.Extra+import Control.Exception.Extra+import Control.Monad.Extra+import Control.Concurrent.Extra+import Data.Binary.Get+import Data.Binary.Put+import Data.Time+import Data.Char+import Development.Shake.Classes+import qualified Data.HashMap.Strict as Map+import Data.List+import Numeric+import System.Directory+import System.Exit+import System.FilePath+import System.IO++import qualified Data.ByteString.Lazy.Char8 as LBS+import qualified Data.ByteString.Lazy as LBS8+++type Map = Map.HashMap++-- Increment every time the on-disk format/semantics change,+-- @x@ is for the users version number+databaseVersion :: String -> String+-- THINGS I WANT TO DO ON THE NEXT CHANGE+-- * Change filepaths to store a 1 byte prefix saying 8bit ASCII or UTF8+-- * Duration and Time should be stored as number of 1/10000th seconds Int32+databaseVersion x = "SHAKE-DATABASE-10-" ++ s ++ "\r\n"+ where s = tail $ init $ show x -- call show, then take off the leading/trailing quotes+ -- ensures we do not get \r or \n in the user portion+++withStorage+ :: (Show w, Show k, Show v, Eq w, Eq k, Hashable k+ ,Binary w, BinaryWith w k, BinaryWith w v)+ => ShakeOptions -- ^ Storage options+ -> (String -> IO ()) -- ^ Logging function+ -> w -- ^ Witness+ -> (Map k v -> (k -> v -> IO ()) -> IO a) -- ^ Execute+ -> IO a+withStorage ShakeOptions{shakeVerbosity,shakeOutput,shakeVersion,shakeFlush,shakeFiles,shakeStorageLog} diagnostic witness act = do+ let dbfile = shakeFiles <.> "database"+ bupfile = shakeFiles <.> "bup"+ createDirectoryIfMissing True $ takeDirectory shakeFiles++ -- complete a partially failed compress+ b <- doesFileExist bupfile+ when b $ do+ unexpected "Backup file exists, restoring over the previous file\n"+ diagnostic $ "Backup file move to original"+ ignore $ removeFile dbfile+ renameFile bupfile dbfile++ addTiming "Database read"+ withBinaryFile dbfile ReadWriteMode $ \h -> do+ n <- hFileSize h+ diagnostic $ "Reading file of size " ++ show n+ src <- LBS.hGet h $ fromInteger n++ if not $ ver `LBS.isPrefixOf` src then do+ unless (LBS.null src) $ do+ let limit x = let (a,b) = splitAt 200 x in a ++ (if null b then "" else "...")+ let disp = map (\x -> if isPrint x && isAscii x then x else '?') . takeWhile (`notElem` "\r\n")+ outputErr $ unlines+ ["Error when reading Shake database - invalid version stamp detected:"+ ," File: " ++ dbfile+ ," Expected: " ++ disp (LBS.unpack ver)+ ," Found: " ++ disp (limit $ LBS.unpack src)+ ,"All rules will be rebuilt"]+ continue h Map.empty+ else+ -- make sure you are not handling exceptions from inside+ join $ handleJust (\e -> if asyncException e then Nothing else Just e) (\err -> do+ msg <- showException err+ outputErr $ unlines $+ ("Error when reading Shake database " ++ dbfile) :+ map (" "++) (lines msg) +++ ["All files will be rebuilt"]+ when shakeStorageLog $ do+ hSeek h AbsoluteSeek 0+ i <- hFileSize h+ bs <- LBS.hGet h $ fromInteger i+ let cor = shakeFiles <.> "corrupt"+ LBS.writeFile cor bs+ unexpected $ "Backup of corrupted file stored at " ++ cor ++ ", " ++ show i ++ " bytes\n"+ + -- exitFailure -- should never happen without external corruption+ -- add back to check during random testing+ return $ continue h Map.empty) $+ case readChunks $ LBS.drop (LBS.length ver) src of+ ([], slop) -> do+ when (LBS.length slop > 0) $ unexpected $ "Last " ++ show slop ++ " bytes do not form a whole record\n"+ diagnostic $ "Read 0 chunks, plus " ++ show slop ++ " slop"+ return $ continue h Map.empty+ (w:xs, slopRaw) -> do+ let slop = fromIntegral $ LBS.length slopRaw+ when (slop > 0) $ unexpected $ "Last " ++ show slop ++ " bytes do not form a whole record\n"+ diagnostic $ "Read " ++ show (length xs + 1) ++ " chunks, plus " ++ show slop ++ " slop"+ let ws = decode w+ f mp (k, v) = Map.insert k v mp+ ents = map (runGet $ getWith ws) xs+ mp = foldl' f Map.empty ents++ when (shakeVerbosity == Diagnostic) $ do+ let raw x = "[len " ++ show (LBS.length x) ++ "] " ++ concat+ [['0' | length c == 1] ++ c | x <- LBS8.unpack x, let c = showHex x ""]+ let pretty (Left x) = "FAILURE: " ++ show x+ pretty (Right x) = x+ diagnostic $ "Witnesses " ++ raw w+ forM_ (zip3 [1..] xs ents) $ \(i,x,ent) -> do+ x2 <- try_ $ evaluate $ let s = show ent in rnf s `seq` s+ diagnostic $ "Chunk " ++ show i ++ " " ++ raw x ++ " " ++ pretty x2+ diagnostic $ "Slop " ++ raw slopRaw++ diagnostic $ "Found " ++ show (Map.size mp) ++ " real entries"++ -- if mp is null, continue will reset it, so no need to clean up+ if Map.null mp || (ws == witness && Map.size mp * 2 > length xs - 2) then do+ -- make sure we reset to before the slop+ when (not (Map.null mp) && slop /= 0) $ do+ diagnostic $ "Dropping last " ++ show slop ++ " bytes of database (incomplete)"+ now <- hFileSize h+ hSetFileSize h $ now - slop+ hSeek h AbsoluteSeek $ now - slop+ hFlush h+ diagnostic $ "Drop complete"+ return $ continue h mp+ else do+ addTiming "Database compression"+ unexpected "Compressing database\n"+ diagnostic "Compressing database"+ hClose h -- two hClose are fine+ return $ do+ renameFile dbfile bupfile+ withBinaryFile dbfile ReadWriteMode $ \h -> do+ reset h mp+ removeFile bupfile+ diagnostic "Compression complete"+ continue h mp+ where+ unexpected x = when shakeStorageLog $ do+ t <- getCurrentTime+ appendFile (shakeFiles <.> "storage") $ "\n[" ++ show t ++ "]: " ++ x+ outputErr x = do+ when (shakeVerbosity >= Quiet) $ shakeOutput Quiet x+ unexpected x++ ver = LBS.pack $ databaseVersion shakeVersion++ writeChunk h s = do+ diagnostic $ "Writing chunk " ++ show (LBS.length s)+ LBS.hPut h $ toChunk s++ reset h mp = do+ diagnostic $ "Resetting database to " ++ show (Map.size mp) ++ " elements"+ hSetFileSize h 0+ hSeek h AbsoluteSeek 0+ LBS.hPut h ver+ writeChunk h $ encode witness+ mapM_ (writeChunk h . runPut . putWith witness) $ Map.toList mp+ hFlush h+ diagnostic "Flush"++ -- continuation (since if we do a compress, h changes)+ continue h mp = do+ when (Map.null mp) $+ reset h mp -- might as well, no data to lose, and need to ensure a good witness table+ -- also lets us recover in the case of corruption+ flushThread shakeFlush h $ \out -> do+ addTiming "With database"+ act mp $ \k v -> out $ toChunk $ runPut $ putWith witness (k, v)+++-- We avoid calling flush too often on SSD drives, as that can be slow+-- Make sure all exceptions happen on the caller, so we don't have to move exceptions back+-- Make sure we only write on one thread, otherwise async exceptions can cause partial writes+flushThread :: Maybe Double -> Handle -> ((LBS.ByteString -> IO ()) -> IO a) -> IO a+flushThread flush h act = do+ chan <- newChan -- operations to perform on the file+ kick <- newEmptyMVar -- kicked whenever something is written+ died <- newBarrier -- has the writing thread finished++ flusher <- case flush of+ Nothing -> return Nothing+ Just flush -> fmap Just $ forkIO $ forever $ do+ takeMVar kick+ threadDelay $ ceiling $ flush * 1000000+ tryTakeMVar kick+ writeChan chan $ hFlush h >> return True++ root <- myThreadId+ writer <- forkIO $ handle_ (\e -> signalBarrier died () >> throwTo root e) $+ -- only one thread ever writes, ensuring only the final write can be torn+ whileM $ join $ readChan chan++ (act $ \s -> do+ evaluate $ LBS.length s -- ensure exceptions occur on this thread+ writeChan chan $ LBS.hPut h s >> tryPutMVar kick () >> return True)+ `finally` do+ maybe (return ()) killThread flusher+ writeChan chan $ signalBarrier died () >> return False+ waitBarrier died+++-- Return the amount of junk at the end, along with all the chunk+readChunks :: LBS.ByteString -> ([LBS.ByteString], LBS.ByteString)+readChunks x+ | Just (n, x) <- grab 4 x+ , Just (y, x) <- grab (fromIntegral (decode n :: Word32)) x+ = first (y :) $ readChunks x+ | otherwise = ([], x)+ where+ grab i x | LBS.length a == i = Just (a, b)+ | otherwise = Nothing+ where (a,b) = LBS.splitAt i x+++toChunk :: LBS.ByteString -> LBS.ByteString+toChunk x = n `LBS.append` x+ where n = encode (fromIntegral $ LBS.length x :: Word32)+++-- | Is the exception asyncronous, not a "coding error" that should be ignored+asyncException :: SomeException -> Bool+asyncException e+ | Just (_ :: AsyncException) <- fromException e = True+ | Just (_ :: ExitCode) <- fromException e = True+ | otherwise = False
+ src/Development/Shake/Types.hs view
@@ -0,0 +1,223 @@+{-# LANGUAGE DeriveDataTypeable, PatternGuards #-}++-- | Types exposed to the user+module Development.Shake.Types(+ Progress(..), Verbosity(..), Assume(..), Lint(..), Change(..), EqualCost(..),+ ShakeOptions(..), shakeOptions+ ) where++import Data.Data+import Data.List+import Development.Shake.Progress+import qualified Data.ByteString.Char8 as BS+++-- | The current assumptions made by the build system, used by 'shakeAssume'. These options+-- allow the end user to specify that any rules run are either to be treated as clean, or as+-- dirty, regardless of what the build system thinks.+--+-- These assumptions only operate on files reached by the current 'Development.Shake.action' commands. Any+-- other files in the database are left unchanged.+data Assume+ = AssumeDirty+ -- ^ Assume that all rules reached are dirty and require rebuilding, equivalent to 'Development.Shake.Rule.storedValue' always+ -- returning 'Nothing'. Useful to undo the results of 'AssumeClean', for benchmarking rebuild speed and+ -- for rebuilding if untracked dependencies have changed. This assumption is safe, but may cause+ -- more rebuilding than necessary.+ | AssumeClean+ -- ^ /This assumption is unsafe, and may lead to incorrect build results in this run, and in future runs/.+ -- Assume and record that all rules reached are clean and do not require rebuilding, provided the rule+ -- has a 'Development.Shake.Rule.storedValue' and has been built before. Useful if you have modified a file in some+ -- inconsequential way, such as only the comments or whitespace, and wish to avoid a rebuild.+ | AssumeSkip+ -- ^ /This assumption is unsafe, and may lead to incorrect build results in this run/.+ -- Assume that all rules reached are clean in this run. Only useful for benchmarking, to remove any overhead+ -- from running 'Development.Shake.Rule.storedValue' operations.+ deriving (Eq,Ord,Show,Data,Typeable,Bounded,Enum)+++-- | Which lint checks to perform, used by 'shakeLint'.+data Lint+ = LintBasic+ -- ^ The most basic form of linting. Checks that the current directory does not change and that results do not change after they+ -- are first written. Any calls to 'needed' will assert that they do not cause a rule to be rebuilt.+ | LintTracker+ -- ^ Track which files are accessed by command line programs run by 'command' or 'cmd', using @tracker.exe@ as supplied+ -- with the Microsoft .NET 4.5 SDK (Windows only). Also performs all checks from 'LintBasic'. Note that some programs are not+ -- tracked properly, particularly cygwin programs (it seems).+ deriving (Eq,Ord,Show,Data,Typeable,Bounded,Enum)+++-- | How should you determine if a file has changed, used by 'shakeChange'. The most common values are+-- 'ChangeModtime' (very fast, @touch@ causes files to rebuild) and 'ChangeModtimeAndDigestInput'+-- (a bit slower, @touch@ does not cause input files to rebuild).+data Change+ = ChangeModtime+ -- ^ Compare equality of modification timestamps, a file has changed if its last modified time changes.+ -- A @touch@ will force a rebuild. This mode is fast and usually sufficiently accurate, so is the default.+ | ChangeDigest+ -- ^ Compare equality of file contents digests, a file has changed if its digest changes.+ -- A @touch@ will not force a rebuild. Use this mode if modification times on your file system are unreliable.+ | ChangeModtimeAndDigest+ -- ^ A file is rebuilt if both its modification time and digest have changed. For efficiency reasons, the modification+ -- time is checked first, and if that has changed, the digest is checked.+ | ChangeModtimeAndDigestInput+ -- ^ Use 'ChangeModtimeAndDigest' for input\/source files and 'ChangeModtime' for output files.+ | ChangeModtimeOrDigest+ -- ^ A file is rebuilt if either its modification time or its digest has changed. A @touch@ will force a rebuild,+ -- but even if a files modification time is reset afterwards, changes will also cause a rebuild.+ deriving (Eq,Ord,Show,Data,Typeable,Bounded,Enum)+++-- | Options to control the execution of Shake, usually specified by overriding fields in+-- 'shakeOptions':+--+-- @ 'shakeOptions'{'shakeThreads'=4, 'shakeReport'=[\"report.html\"]} @+--+-- The 'Data' instance for this type reports the 'shakeProgress' and 'shakeOutput' fields as having the abstract type 'Function',+-- because 'Data' cannot be defined for functions.+data ShakeOptions = ShakeOptions+ {shakeFiles :: FilePath+ -- ^ Defaults to @.shake@. The prefix of the filename used for storing Shake metadata files.+ -- All metadata files will be named @'shakeFiles'./extension/@, for some @/extension/@.+ -- If the 'shakeFiles' directory does not exist it will be created.+ ,shakeThreads :: Int+ -- ^ Defaults to @1@. Maximum number of rules to run in parallel, similar to @make --jobs=/N/@.+ -- For many build systems, a number equal to or slightly less than the number of physical processors+ -- works well.+ ,shakeVersion :: String+ -- ^ Defaults to @"1"@. The version number of your build rules.+ -- Change the version number to force a complete rebuild, such as when making+ -- significant changes to the rules that require a wipe. The version number should be+ -- set in the source code, and not passed on the command line.+ ,shakeVerbosity :: Verbosity+ -- ^ Defaults to 'Normal'. What level of messages should be printed out.+ ,shakeStaunch :: Bool+ -- ^ Defaults to 'False'. Operate in staunch mode, where building continues even after errors,+ -- similar to @make --keep-going@.+ ,shakeReport :: [FilePath]+ -- ^ Defaults to @[]@. Write a profiling report to a file, showing which rules rebuilt,+ -- why, and how much time they took. Useful for improving the speed of your build systems.+ -- If the file extension is @.json@ it will write JSON data; if @.js@ it will write Javascript;+ -- if @.trace@ it will write trace events (load into @about:\/\/tracing@ in Chrome);+ -- otherwise it will write HTML.+ ,shakeLint :: Maybe Lint+ -- ^ Defaults to 'Nothing'. Perform sanity checks during building, see 'Lint' for details.+ ,shakeFlush :: Maybe Double+ -- ^ Defaults to @'Just' 10@. How often to flush Shake metadata files in seconds, or 'Nothing' to never flush explicitly.+ -- It is possible that on abnormal termination (not Haskell exceptions) any rules that completed in the last+ -- 'shakeFlush' seconds will be lost.+ ,shakeAssume :: Maybe Assume+ -- ^ Defaults to 'Nothing'. Assume all build objects are clean/dirty, see 'Assume' for details.+ -- Can be used to implement @make --touch@.+ ,shakeAbbreviations :: [(String,String)]+ -- ^ Defaults to @[]@. A list of substrings that should be abbreviated in status messages, and their corresponding abbreviation.+ -- Commonly used to replace the long paths (e.g. @.make\/i586-linux-gcc\/output@) with an abbreviation (e.g. @$OUT@).+ ,shakeStorageLog :: Bool+ -- ^ Defaults to 'False'. Write a message to @'shakeFiles'.storage@ whenever a storage event happens which may impact+ -- on the current stored progress. Examples include database version number changes, database compaction or corrupt files.+ ,shakeLineBuffering :: Bool+ -- ^ Defaults to 'True'. Change 'stdout' and 'stderr' to line buffering while running Shake.+ ,shakeTimings :: Bool+ -- ^ Defaults to 'False'. Print timing information for each stage at the end.+ ,shakeRunCommands :: Bool+ -- ^ Default to 'True'. Should you run command line actions, set to 'False' to skip actions whose output streams and exit code+ -- are not used. Useful for profiling the non-command portion of the build system.+ ,shakeChange :: Change+ -- ^ Default to 'ChangeModtime'. How to check if a file has changed, see 'Change' for details.+ ,shakeCreationCheck :: Bool+ -- ^ Default to 'True'. After running a rule to create a file, is it an error if the file does not exist.+ -- Provided for compatibility with @make@ and @ninja@ (which have ugly file creation semantics).+ ,shakeLiveFiles :: [FilePath]+ -- ^ Default to '[]'. After the build system completes, write a list of all files which were /live/ in that run,+ -- i.e. those which Shake checked were valid or rebuilt. Produces best answers if nothing rebuilds.+ ,shakeProgress :: IO Progress -> IO ()+ -- ^ Defaults to no action. A function called when the build starts, allowing progress to be reported.+ -- The function is called on a separate thread, and that thread is killed when the build completes.+ -- For applications that want to display progress messages, 'progressSimple' is often sufficient, but more advanced+ -- users should look at the 'Progress' data type.+ ,shakeOutput :: Verbosity -> String -> IO ()+ -- ^ Defaults to writing using 'putStrLn'. A function called to output messages from Shake, along with the 'Verbosity' at+ -- which that message should be printed. This function will be called atomically from all other 'shakeOutput' functions.+ -- The 'Verbosity' will always be greater than or higher than 'shakeVerbosity'.+ }+ deriving Typeable++-- | The default set of 'ShakeOptions'.+shakeOptions :: ShakeOptions+shakeOptions = ShakeOptions+ ".shake" 1 "1" Normal False [] Nothing (Just 10) Nothing [] False True False+ True ChangeModtime True []+ (const $ return ())+ (const $ BS.putStrLn . BS.pack) -- try and output atomically using BS++fieldsShakeOptions =+ ["shakeFiles", "shakeThreads", "shakeVersion", "shakeVerbosity", "shakeStaunch", "shakeReport"+ ,"shakeLint", "shakeFlush", "shakeAssume", "shakeAbbreviations", "shakeStorageLog"+ ,"shakeLineBuffering", "shakeTimings", "shakeRunCommands", "shakeChange", "shakeCreationCheck"+ ,"shakeLiveFiles","shakeProgress", "shakeOutput"]+tyShakeOptions = mkDataType "Development.Shake.Types.ShakeOptions" [conShakeOptions]+conShakeOptions = mkConstr tyShakeOptions "ShakeOptions" fieldsShakeOptions Prefix+unhide x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 =+ ShakeOptions x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 (fromFunction x18) (fromFunction x19)++instance Data ShakeOptions where+ gfoldl k z (ShakeOptions x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19) =+ z unhide `k` x1 `k` x2 `k` x3 `k` x4 `k` x5 `k` x6 `k` x7 `k` x8 `k` x9 `k` x10 `k` x11 `k`+ x12 `k` x13 `k` x14 `k` x15 `k` x16 `k` x17 `k`+ Function x18 `k` Function x19+ gunfold k z c = k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ k $ z unhide+ toConstr ShakeOptions{} = conShakeOptions+ dataTypeOf _ = tyShakeOptions++instance Show ShakeOptions where+ show x = "ShakeOptions {" ++ intercalate ", " inner ++ "}"+ where+ inner = zipWith (\x y -> x ++ " = " ++ y) fieldsShakeOptions $ gmapQ f x++ f x | Just x <- cast x = show (x :: Int)+ | Just x <- cast x = show (x :: FilePath)+ | Just x <- cast x = show (x :: Verbosity)+ | Just x <- cast x = show (x :: Change)+ | Just x <- cast x = show (x :: Bool)+ | Just x <- cast x = show (x :: [FilePath])+ | Just x <- cast x = show (x :: Maybe Assume)+ | Just x <- cast x = show (x :: Maybe Lint)+ | Just x <- cast x = show (x :: Maybe Double)+ | Just x <- cast x = show (x :: [(String,String)])+ | Just x <- cast x = show (x :: Function (IO Progress -> IO ()))+ | Just x <- cast x = show (x :: Function (Verbosity -> String -> IO ()))+ | otherwise = error $ "Error while showing ShakeOptions, missing alternative for " ++ show (typeOf x)+++-- | Internal type, copied from Hide in Uniplate+newtype Function a = Function {fromFunction :: a}+ deriving Typeable++instance Show (Function a) where show _ = "<function>"++instance Typeable a => Data (Function a) where+ gfoldl k z x = z x+ gunfold k z c = error "Development.Shake.Types.ShakeProgress: gunfold not implemented - data type has no constructors"+ toConstr _ = error "Development.Shake.Types.ShakeProgress: toConstr not implemented - data type has no constructors"+ dataTypeOf _ = tyFunction++tyFunction = mkDataType "Development.Shake.Types.Function" []+++-- | The verbosity data type, used by 'shakeVerbosity'.+data Verbosity+ = Silent -- ^ Don't print any messages.+ | Quiet -- ^ Only print essential messages, typically errors.+ | Normal -- ^ Print errors and @# /command-name/ (for /file-name/)@ when running a 'Development.Shake.traced' command.+ | Loud -- ^ Print errors and full command lines when running a 'Development.Shake.command' or 'Development.Shake.cmd' command.+ | Chatty -- ^ Print errors, full command line and status messages when starting a rule.+ | Diagnostic -- ^ Print messages for virtually everything (mostly for debugging).+ deriving (Eq,Ord,Bounded,Enum,Show,Read,Typeable,Data)++-- | An equality check and a cost.+data EqualCost+ = EqualCheap -- ^ The equality check was cheap.+ | EqualExpensive -- ^ The equality check was expensive, as the results are not trivially equal.+ | NotEqual -- ^ The values are not equal.+ deriving (Eq,Ord,Bounded,Enum,Show,Read,Typeable,Data)
+ src/Development/Shake/Util.hs view
@@ -0,0 +1,60 @@++-- | A module for useful utility functions for Shake build systems.+module Development.Shake.Util(+ parseMakefile, needMakefileDependencies, neededMakefileDependencies,+ shakeArgsAccumulate+ ) where++import Development.Shake+import Development.Shake.Rules.File+import qualified Data.ByteString.Char8 as BS+import qualified Development.Shake.ByteString as BS+import Data.Tuple.Extra+import Data.List+import System.Console.GetOpt+++-- | Given the text of a Makefile, extract the list of targets and dependencies. Assumes a+-- small subset of Makefile syntax, mostly that generated by @gcc -MM@.+--+-- > parseMakefile "a: b c\nd : e" == [("a",["b","c"]),("d",["e"])]+parseMakefile :: String -> [(FilePath, [FilePath])]+parseMakefile = map (BS.unpack *** map BS.unpack) . BS.parseMakefile . BS.pack+++-- | Depend on the dependencies listed in a Makefile. Does not depend on the Makefile itself.+--+-- > needMakefileDependencies file = need . concatMap snd . parseMakefile =<< liftIO (readFile file)+needMakefileDependencies :: FilePath -> Action ()+needMakefileDependencies file = needBS . concatMap snd . BS.parseMakefile =<< liftIO (BS.readFile file)+++-- | Depend on the dependencies listed in a Makefile. Does not depend on the Makefile itself.+-- Use this function to indicate that you have /already/ used the files in question.+--+-- > neededMakefileDependencies file = needed . concatMap snd . parseMakefile =<< liftIO (readFile file)+neededMakefileDependencies :: FilePath -> Action ()+neededMakefileDependencies file = neededBS . concatMap snd . BS.parseMakefile =<< liftIO (BS.readFile file)+++-- | Like `shakeArgsWith`, but instead of accumulating a list of flags, apply functions to a default value.+-- Usually used to populate a record structure. As an example of a build system that can use either @gcc@ or @distcc@ for compiling:+--+-- @+--import System.Console.GetOpt+--+--data Flags = Flags {distCC :: Bool} deriving Eq+--flags = [Option \"\" [\"distcc\"] (NoArg $ Right $ \\x -> x{distCC=True}) \"Run distributed.\"]+--+--main = 'shakeArgsAccumulate' 'shakeOptions' flags (Flags False) $ \\flags targets -> return $ Just $ do+-- if null targets then 'want' [\"result.exe\"] else 'want' targets+-- let compiler = if distCC flags then \"distcc\" else \"gcc\"+-- \"*.o\" '%>' \\out -> do+-- 'need' ...+-- 'cmd' compiler ...+-- ...+-- @+--+-- Now you can pass @--distcc@ to use the @distcc@ compiler.+shakeArgsAccumulate :: ShakeOptions -> [OptDescr (Either String (a -> a))] -> a -> (a -> [String] -> IO (Maybe (Rules ()))) -> IO ()+shakeArgsAccumulate opts flags def f = shakeArgsWith opts flags $ \flags targets -> f (foldl' (flip ($)) def flags) targets
+ src/Development/Shake/Value.hs view
@@ -0,0 +1,138 @@+{-# LANGUAGE ExistentialQuantification, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}++{- |+This module implements the Key/Value types, to abstract over hetrogenous data types.+-}+module Development.Shake.Value(+ Value, newValue, fromValue, typeValue,+ Key, newKey, fromKey, typeKey,+ Witness, currentWitness, registerWitness+ ) where++import General.Binary+import Development.Shake.Classes+import Development.Shake.Errors+import Data.Typeable++import Data.Bits+import Data.Function+import Data.IORef+import Data.List+import Data.Maybe+import qualified Data.HashMap.Strict as Map+import qualified Data.ByteString.Char8 as BS+import System.IO.Unsafe+++-- We deliberately avoid Typeable instances on Key/Value to stop them accidentally+-- being used inside themselves+newtype Key = Key Value+ deriving (Eq,Hashable,NFData,BinaryWith Witness)++data Value = forall a . (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => Value a+++newKey :: (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => a -> Key+newKey = Key . newValue++newValue :: (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => a -> Value+newValue = Value++typeKey :: Key -> TypeRep+typeKey (Key v) = typeValue v++typeValue :: Value -> TypeRep+typeValue (Value x) = typeOf x++fromKey :: Typeable a => Key -> a+fromKey (Key v) = fromValue v++fromValue :: Typeable a => Value -> a+fromValue (Value x) = fromMaybe (err "fromValue, bad cast") $ cast x++instance Show Key where+ show (Key a) = show a++instance Show Value where+ show (Value a) = show a++instance NFData Value where+ rnf (Value a) = rnf a++instance Hashable Value where+ hashWithSalt salt (Value a) = hashWithSalt salt (typeOf a) `xor` hashWithSalt salt a++instance Eq Value where+ Value a == Value b = maybe False (a ==) $ cast b+ Value a /= Value b = maybe True (a /=) $ cast b+++---------------------------------------------------------------------+-- BINARY INSTANCES++{-# NOINLINE witness #-}+witness :: IORef (Map.HashMap TypeRep Value)+witness = unsafePerformIO $ newIORef Map.empty++registerWitness :: (Eq a, Show a, Typeable a, Hashable a, Binary a, NFData a) => a -> IO ()+registerWitness x = atomicModifyIORef witness $ \mp -> (Map.insert (typeOf x) (Value $ err msg `asTypeOf` x) mp, ())+ where msg = "registerWitness, type " ++ show (typeOf x)+++-- Produce a list in a predictable order from a Map TypeRep, which should be consistent regardless of the order+-- elements were added and stable between program executions.+-- Cannot rely on hash (not pure in hashable-1.2) or compare (not available before 7.2)+toStableList :: Map.HashMap TypeRep v -> [(TypeRep,v)]+toStableList = sortBy (compare `on` show . fst) . Map.toList+++data Witness = Witness+ {typeNames :: [String] -- the canonical data, the names of the types+ ,witnessIn :: Map.HashMap Word16 Value -- for reading in, the find the values (some may be missing)+ ,witnessOut :: Map.HashMap TypeRep Word16 -- for writing out, find the value+ } deriving Show++instance Eq Witness where+ -- Type names are produced by toStableList so should to remain consistent+ -- regardless of the order of registerWitness calls.+ a == b = typeNames a == typeNames b++currentWitness :: IO Witness+currentWitness = do+ ws <- readIORef witness+ let (ks,vs) = unzip $ toStableList ws+ return $ Witness (map show ks) (Map.fromList $ zip [0..] vs) (Map.fromList $ zip ks [0..])+++instance Binary Witness where+ put (Witness ts _ _) = put $ BS.unlines $ map BS.pack ts+ get = do+ ts <- fmap (map BS.unpack . BS.lines) get+ let ws = toStableList $ unsafePerformIO $ readIORefAfter ts witness+ let (is,ks,vs) = unzip3 [(i,k,v) | (i,t) <- zip [0..] ts, (k,v):_ <- [filter ((==) t . show . fst) ws]]+ return $ Witness ts (Map.fromList $ zip is vs) (Map.fromList $ zip ks is)+ where+ -- Read an IORef after examining a variable, used to avoid GHC over-optimisation+ {-# NOINLINE readIORefAfter #-}+ readIORefAfter :: a -> IORef b -> IO b+ readIORefAfter v ref = v `seq` readIORef ref+++instance BinaryWith Witness Value where+ putWith ws (Value x) = do+ let msg = "no witness for " ++ show (typeOf x)+ put $ fromMaybe (error msg) $ Map.lookup (typeOf x) (witnessOut ws)+ put x++ getWith ws = do+ h <- get+ case Map.lookup h $ witnessIn ws of+ Nothing | h >= 0 && h < genericLength (typeNames ws) -> error $+ "Failed to find a type " ++ (typeNames ws !! fromIntegral h) ++ " which is stored in the database.\n" +++ "The most likely cause is that your build tool has changed significantly."+ Nothing -> error $+ -- should not happen, unless proper data corruption+ "Corruption when reading Value, got type " ++ show h ++ ", but should be in range 0.." ++ show (length (typeNames ws) - 1)+ Just (Value t) -> do+ x <- get+ return $ Value $ x `asTypeOf` t
+ src/General/Bilist.hs view
@@ -0,0 +1,34 @@++module General.Bilist(+ Bilist, cons, snoc, uncons, toList, isEmpty+ ) where++import Prelude()+import General.Prelude+++data Bilist a = Bilist [a] [a]++toList :: Bilist a -> [a]+toList (Bilist as bs) = as ++ reverse bs++isEmpty :: Bilist a -> Bool+isEmpty (Bilist as bs) = null as && null bs++instance Eq a => Eq (Bilist a) where+ a == b = toList a == toList b++instance Monoid (Bilist a) where+ mempty = Bilist [] []+ mappend a b = Bilist (toList a ++ toList b) []++cons :: a -> Bilist a -> Bilist a+cons x (Bilist as bs) = Bilist (x:as) bs++snoc :: Bilist a -> a -> Bilist a+snoc (Bilist as bs) x = Bilist as (x:bs)++uncons :: Bilist a -> Maybe (a, Bilist a)+uncons (Bilist [] []) = Nothing+uncons (Bilist (a:as) bs) = Just (a, Bilist as bs)+uncons (Bilist [] bs) = uncons $ Bilist (reverse bs) []
+ src/General/Binary.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}++module General.Binary(+ BinaryWith(..), module Data.Binary,+ BinList(..), BinFloat(..)+ ) where++import Control.Applicative+import Control.Monad+import Data.Binary+import Data.List+import Foreign+import System.IO.Unsafe as U+++class BinaryWith ctx a where+ putWith :: ctx -> a -> Put+ getWith :: ctx -> Get a++instance (BinaryWith ctx a, BinaryWith ctx b) => BinaryWith ctx (a,b) where+ putWith ctx (a,b) = putWith ctx a >> putWith ctx b+ getWith ctx = liftA2 (,) (getWith ctx) (getWith ctx)++instance BinaryWith ctx a => BinaryWith ctx [a] where+ putWith ctx xs = put (length xs) >> mapM_ (putWith ctx) xs+ getWith ctx = do n <- get; replicateM n $ getWith ctx++instance BinaryWith ctx a => BinaryWith ctx (Maybe a) where+ putWith ctx Nothing = putWord8 0+ putWith ctx (Just x) = putWord8 1 >> putWith ctx x+ getWith ctx = do i <- getWord8; if i == 0 then return Nothing else fmap Just $ getWith ctx+++newtype BinList a = BinList {fromBinList :: [a]}++instance Show a => Show (BinList a) where show = show . fromBinList++instance Binary a => Binary (BinList a) where+ put (BinList xs) = case splitAt 254 xs of+ (a, []) -> putWord8 (genericLength xs) >> mapM_ put xs+ (a, b) -> putWord8 255 >> mapM_ put a >> put (BinList b)+ get = do+ x <- getWord8+ case x of+ 255 -> do xs <- replicateM 254 get; BinList ys <- get; return $ BinList $ xs ++ ys+ n -> fmap BinList $ replicateM (fromInteger $ toInteger n) get+++newtype BinFloat = BinFloat {fromBinFloat :: Float}++instance Show BinFloat where show = show . fromBinFloat++instance Binary BinFloat where+ put (BinFloat x) = put (convert x :: Word32)+ get = fmap (BinFloat . convert) (get :: Get Word32)+++-- Originally from data-binary-ieee754 package++convert :: (Storable a, Storable b) => a -> b+convert x = U.unsafePerformIO $ alloca $ \buf -> do+ poke (castPtr buf) x+ peek buf
+ src/General/Cleanup.hs view
@@ -0,0 +1,38 @@++-- | Code for ensuring cleanup actions are run.+module General.Cleanup(+ Cleanup, withCleanup, addCleanup+ ) where++import Control.Exception as E+import Control.Monad+import qualified Data.HashMap.Strict as Map+import Data.Function+import Data.IORef+import Data.List+++data S = S {unique :: !Int, items :: Map.HashMap Int (IO ())}++newtype Cleanup = Cleanup (IORef S)+++-- | Run with some cleanup scope. Regardless of exceptions/threads, all 'addCleanup' actions+-- will be run by the time it exits. The 'addCleanup' actions will be run in reverse order.+withCleanup :: (Cleanup -> IO a) -> IO a+withCleanup act = do+ ref <- newIORef $ S 0 Map.empty+ act (Cleanup ref) `finally` do+ items <- atomicModifyIORef ref $ \s -> (s{items=Map.empty}, items s)+ mapM_ snd $ sortBy (compare `on` negate . fst) $ Map.toList items+++-- | Add a cleanup action to a 'Cleanup' scope. If the return action is not run by the time+-- 'withCleanup' terminates then it will be run then. The argument 'Bool' is 'True' to say+-- run the action, 'False' to say ignore the action (and never run it).+addCleanup :: Cleanup -> IO () -> IO (Bool -> IO ())+addCleanup (Cleanup ref) act = atomicModifyIORef ref $ \s -> let i = unique s in+ (,) (S (unique s + 1) (Map.insert i act $ items s)) $ \b -> do+ join $ atomicModifyIORef ref $ \s -> case Map.lookup i $ items s of+ Nothing -> (s, return ())+ Just act -> (s{items = Map.delete i $ items s}, when b act)
+ src/General/Concurrent.hs view
@@ -0,0 +1,32 @@++module General.Concurrent(+ Fence, newFence, signalFence, waitFence, testFence,+ ) where++import Control.Applicative+import Control.Monad+import Data.IORef+++---------------------------------------------------------------------+-- FENCE++-- | Like a barrier, but based on callbacks+newtype Fence a = Fence (IORef (Either [a -> IO ()] a))+instance Show (Fence a) where show _ = "Fence"++newFence :: IO (Fence a)+newFence = Fence <$> newIORef (Left [])++signalFence :: Fence a -> a -> IO ()+signalFence (Fence ref) v = join $ atomicModifyIORef ref $ \x -> case x of+ Left queue -> (Right v, mapM_ ($ v) $ reverse queue)+ Right v -> error "Shake internal error, signalFence called twice on one Fence"++waitFence :: Fence a -> (a -> IO ()) -> IO ()+waitFence (Fence ref) call = join $ atomicModifyIORef ref $ \x -> case x of+ Left queue -> (Left (call:queue), return ())+ Right v -> (Right v, call v)++testFence :: Fence a -> IO (Maybe a)+testFence (Fence x) = either (const Nothing) Just <$> readIORef x
+ src/General/Extra.hs view
@@ -0,0 +1,75 @@+{-# LANGUAGE BangPatterns, CPP #-}++module General.Extra(+ getProcessorCount,+ randomElem,+ fastNub,+ showQuote+ ) where++import Control.Exception.Extra+import Data.Char+import Data.List+import qualified Data.HashSet as Set+import System.Environment.Extra+import System.IO.Unsafe+import System.Random+import Development.Shake.Classes+#if __GLASGOW_HASKELL__ >= 704+import Control.Concurrent+import Foreign.C.Types+#endif+++---------------------------------------------------------------------+-- Data.List++-- | Like 'nub', but the results may be in any order.+fastNub :: (Eq a, Hashable a) => [a] -> [a]+fastNub = f Set.empty+ where f seen [] = []+ f seen (x:xs) | x `Set.member` seen = f seen xs+ | otherwise = x : f (Set.insert x seen) xs+++showQuote :: String -> String+showQuote xs | any isSpace xs = "\"" ++ concatMap (\x -> if x == '\"' then "\"\"" else [x]) xs ++ "\""+ | otherwise = xs+++---------------------------------------------------------------------+-- System.Info++#if __GLASGOW_HASKELL__ >= 704+-- Use the underlying GHC function+foreign import ccall getNumberOfProcessors :: IO CInt+#endif+++{-# NOINLINE getProcessorCount #-}+getProcessorCount :: IO Int+-- unsafePefromIO so we cache the result and only compute it once+getProcessorCount = let res = unsafePerformIO act in return res+ where+ act =+#if __GLASGOW_HASKELL__ >= 704+ if rtsSupportsBoundThreads then+ fmap fromIntegral $ getNumberOfProcessors+ else+#endif+ handle_ (const $ return 1) $ do+ env <- lookupEnv "NUMBER_OF_PROCESSORS"+ case env of+ Just s | [(i,"")] <- reads s -> return i+ _ -> do+ src <- readFile "/proc/cpuinfo"+ return $ length [() | x <- lines src, "processor" `isPrefixOf` x]+++---------------------------------------------------------------------+-- System.Random++randomElem :: [a] -> IO a+randomElem xs = do+ i <- randomRIO (0, length xs - 1)+ return $ xs !! i
+ src/General/Intern.hs view
@@ -0,0 +1,48 @@+{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, MultiParamTypeClasses #-}++module General.Intern(+ Intern, Id,+ empty, insert, add, lookup, toList, fromList+ ) where++import General.Binary+import Development.Shake.Classes+import Prelude hiding (lookup)+import qualified Data.HashMap.Strict as Map+import Data.List(foldl')+++-- Invariant: The first field is the highest value in the Map+data Intern a = Intern {-# UNPACK #-} !Word32 !(Map.HashMap a Id)++newtype Id = Id Word32+ deriving (Eq,Hashable,Binary,Show,NFData)++instance BinaryWith w Id where+ putWith ctx = put+ getWith ctx = get+++empty :: Intern a+empty = Intern 0 Map.empty+++insert :: (Eq a, Hashable a) => a -> Id -> Intern a -> Intern a+insert k v@(Id i) (Intern n mp) = Intern (max n i) $ Map.insert k v mp+++add :: (Eq a, Hashable a) => a -> Intern a -> (Intern a, Id)+add k (Intern v mp) = (Intern v2 $ Map.insert k (Id v2) mp, Id v2)+ where v2 = v + 1+++lookup :: (Eq a, Hashable a) => a -> Intern a -> Maybe Id+lookup k (Intern n mp) = Map.lookup k mp+++toList :: Intern a -> [(a, Id)]+toList (Intern a b) = Map.toList b+++fromList :: (Eq a, Hashable a) => [(a, Id)] -> Intern a+fromList xs = Intern (foldl' max 0 [i | (_, Id i) <- xs]) (Map.fromList xs)
+ src/General/Prelude.hs view
@@ -0,0 +1,11 @@+{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- for GHC 7.9 compatibility++-- | Alternative Prelude which exports more things, so we can be+-- warning-compatible with GHC 7.10.+module General.Prelude(+ module Prelude,+ Monoid(..), Applicative(..)+ ) where++import Data.Monoid+import Control.Applicative
+ src/General/String.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++module General.String(+ BS, pack, unpack, pack_, unpack_,+ BSU, packU, unpackU, packU_, unpackU_, requireU+ ) where++import qualified Data.ByteString as BS (any)+import qualified Data.ByteString.Char8 as BS hiding (any)+import qualified Data.ByteString.UTF8 as UTF8+import Development.Shake.Classes+++---------------------------------------------------------------------+-- Data.ByteString+-- Mostly because ByteString does not have an NFData instance in older GHC++-- | ASCII ByteString+newtype BS = BS BS.ByteString+ deriving (Hashable, Binary, Eq)++instance Show BS where+ show (BS x) = show x++instance NFData BS where+ -- some versions of ByteString do not have NFData instances, but seq is equivalent+ -- for a strict bytestring. Therefore, we write our own instance.+ rnf (BS x) = x `seq` ()+++-- | UTF8 ByteString+newtype BSU = BSU BS.ByteString+ deriving (Hashable, Binary, Eq)++instance NFData BSU where+ rnf (BSU x) = x `seq` ()++++pack :: String -> BS+pack = pack_ . BS.pack++unpack :: BS -> String+unpack = BS.unpack . unpack_++pack_ :: BS.ByteString -> BS+pack_ = BS++unpack_ :: BS -> BS.ByteString+unpack_ (BS x) = x++packU :: String -> BSU+packU = packU_ . UTF8.fromString++unpackU :: BSU -> String+unpackU = UTF8.toString . unpackU_++unpackU_ :: BSU -> BS.ByteString+unpackU_ (BSU x) = x++packU_ :: BS.ByteString -> BSU+packU_ = BSU++requireU :: BSU -> Bool+requireU = BS.any (>= 0x80) . unpackU_
+ src/General/Template.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE ViewPatterns #-}++module General.Template(runTemplate) where++import System.FilePath.Posix+import Control.Monad+import Control.Monad.IO.Class+import Data.Char+import qualified Data.ByteString.Lazy.Char8 as LBS+import qualified Language.Javascript.Flot as Flot+import qualified Language.Javascript.JQuery as JQuery+++libraries =+ [("jquery.js", JQuery.file)+ ,("jquery.flot.js", Flot.file Flot.Flot)+ ,("jquery.flot.stack.js", Flot.file Flot.FlotStack)+ ]++-- | Template Engine. Perform the following replacements on a line basis:+--+-- * <script src="foo"></script> ==> <script>[[foo]]</script>+--+-- * <link href="foo" rel="stylesheet" type="text/css" /> ==> <style type="text/css">[[foo]]</style>+runTemplate :: MonadIO m => (FilePath -> m LBS.ByteString) -> LBS.ByteString -> m LBS.ByteString+runTemplate ask = liftM LBS.unlines . mapM f . LBS.lines+ where+ link = LBS.pack "<link href=\""+ script = LBS.pack "<script src=\""++ f x | Just file <- lbs_stripPrefix script y = do res <- grab file; return $ LBS.pack "<script>\n" `LBS.append` res `LBS.append` LBS.pack "\n</script>"+ | Just file <- lbs_stripPrefix link y = do res <- grab file; return $ LBS.pack "<style type=\"text/css\">\n" `LBS.append` res `LBS.append` LBS.pack "\n</style>"+ | otherwise = return x+ where+ y = LBS.dropWhile isSpace x+ grab = asker . takeWhile (/= '\"') . LBS.unpack++ asker o@(splitFileName -> ("lib/",x)) = case lookup x libraries of+ Just act -> liftIO $ LBS.readFile =<< act+ Nothing -> error $ "Template library, unknown library: " ++ o+ asker x = ask x+++lbs_stripPrefix :: LBS.ByteString -> LBS.ByteString -> Maybe LBS.ByteString+lbs_stripPrefix prefix text = if a == prefix then Just b else Nothing+ where (a,b) = LBS.splitAt (LBS.length prefix) text
+ src/General/Timing.hs view
@@ -0,0 +1,53 @@++module General.Timing(resetTimings, addTiming, printTimings) where++import Data.IORef+import Data.Time+import System.IO.Unsafe+import Numeric.Extra+import System.Time.Extra+++{-# NOINLINE timings #-}+timings :: IORef [(UTCTime, String)] -- number of times called, newest first+timings = unsafePerformIO $ newIORef []+++resetTimings :: IO ()+resetTimings = do+ now <- getCurrentTime+ writeIORef timings [(now, "Start")]+++-- | Print all withTiming information and clear the information.+printTimings :: IO ()+printTimings = do+ now <- getCurrentTime+ old <- atomicModifyIORef timings $ \ts -> ([(now, "Start")], ts)+ putStr $ unlines $ showTimings now $ reverse old+++addTiming :: String -> IO ()+addTiming msg = do+ now <- getCurrentTime+ atomicModifyIORef timings $ \ts -> ((now,msg):ts, ())+++showTimings :: UTCTime -> [(UTCTime, String)] -> [String]+showTimings _ [] = []+showTimings stop times = showGap $+ [(a ++ " ", showDP 3 b ++ "s " ++ showPerc b ++ " " ++ progress b) | (a,b) <- xs] +++ [("Total", showDP 3 sm ++ "s " ++ showPerc sm ++ " " ++ replicate 25 ' ')]+ where+ a // b = if b == 0 then 0 else a / b+ showPerc x = let s = show $ floor $ x * 100 // sm in replicate (3 - length s) ' ' ++ s ++ "%"+ progress x = let i = floor $ x * 25 // mx in replicate i '=' ++ replicate (25-i) ' '+ mx = maximum $ map snd xs+ sm = sum $ map snd xs+ xs = [ (name, stop `subtractTime` start)+ | ((start, name), stop) <- zip times $ map fst (drop 1 times) ++ [stop]]+++showGap :: [(String,String)] -> [String]+showGap xs = [a ++ replicate (n - length a - length b) ' ' ++ b | (a,b) <- xs]+ where n = maximum [length a + length b | (a,b) <- xs]
+ src/Paths.hs view
@@ -0,0 +1,22 @@+-- | Fake cabal module for local building++module Paths_shake where++import Data.Version+import System.IO.Unsafe+import System.Directory+import Control.Exception+++-- We want getDataFileName to be relative to the current directory even if+-- we issue a change directory command. Therefore, first call caches, future ones read.+curdir :: String+curdir = unsafePerformIO getCurrentDirectory++getDataFileName :: FilePath -> IO FilePath+getDataFileName x = do+ evaluate curdir+ return $ curdir ++ "/" ++ x++version :: Version+version = Version {versionBranch = [0,0], versionTags = []}
+ src/Run.hs view
@@ -0,0 +1,49 @@++module Run(main) where++import Development.Make.All+import Development.Ninja.All+import System.Environment+import Development.Shake+import Development.Shake.FilePath+import General.Timing+import Data.Maybe+import qualified System.Directory as IO+import System.Console.GetOpt+++main :: IO ()+main = do+ resetTimings+ args <- getArgs+ withArgs ("--no-time":args) $+ shakeArgsWith shakeOptions{shakeCreationCheck=False} flags $ \opts targets -> do+ let tool = listToMaybe [x | Tool x <- opts]+ makefile <- case reverse [x | UseMakefile x <- opts] of+ x:_ -> return x+ _ -> findMakefile+ if takeExtension makefile == ".ninja" then+ runNinja makefile targets tool+ else if isJust tool then+ error "--tool flag is not supported without a .ninja Makefile"+ else+ fmap Just $ runMakefile makefile targets+++data Flag = UseMakefile FilePath+ | Tool String++flags = [Option "f" ["file","makefile"] (ReqArg (Right . UseMakefile) "FILE") "Read FILE as a makefile."+ ,Option "t" ["tool"] (ReqArg (Right . Tool) "TOOL") "Ninja-compatible tools."+ ]+++findMakefile :: IO FilePath+findMakefile = do+ b <- IO.doesFileExist "makefile"+ if b then return "makefile" else do+ b <- IO.doesFileExist "Makefile"+ if b then return "Makefile" else do+ b <- IO.doesFileExist "build.ninja"+ if b then return "build.ninja" else+ error "Could not find `makefile', `Makefile' or `build.ninja'"
+ src/Test.hs view
@@ -0,0 +1,130 @@++module Test(main) where++import Control.Exception+import Control.Monad+import Data.Maybe+import System.Environment.Extra+import General.Timing+import Development.Shake.FileInfo+import General.String+import qualified Data.ByteString.Char8 as BS+import Test.Type(sleepFileTimeCalibrate)+import Control.Concurrent++import qualified Test.Assume as Assume+import qualified Test.Basic as Basic+import qualified Test.Benchmark as Benchmark+import qualified Test.C as C+import qualified Test.Cache as Cache+import qualified Test.Command as Command+import qualified Test.Config as Config+import qualified Test.Digest as Digest+import qualified Test.Directory as Directory+import qualified Test.Docs as Docs+import qualified Test.Errors as Errors+import qualified Test.Files as Files+import qualified Test.FilePath as FilePath+import qualified Test.FilePattern as FilePattern+import qualified Test.Journal as Journal+import qualified Test.Lint as Lint+import qualified Test.Live as Live+import qualified Test.Makefile as Makefile+import qualified Test.Manual as Manual+import qualified Test.Monad as Monad+import qualified Test.Ninja as Ninja+import qualified Test.Oracle as Oracle+import qualified Test.OrderOnly as OrderOnly+import qualified Test.Pool as Pool+import qualified Test.Progress as Progress+import qualified Test.Random as Random+import qualified Test.Resources as Resources+import qualified Test.Self as Self+import qualified Test.Tar as Tar+import qualified Test.Throttle as Throttle+import qualified Test.Unicode as Unicode+import qualified Test.Util as Util+import qualified Test.Verbosity as Verbosity++import qualified Run+++fakes = ["clean" * clean, "test" * test, "make" * makefile, "filetime" * filetime]+ where (*) = (,)++mains = ["tar" * Tar.main, "self" * Self.main, "c" * C.main+ ,"basic" * Basic.main, "cache" * Cache.main, "command" * Command.main+ ,"config" * Config.main, "digest" * Digest.main, "directory" * Directory.main+ ,"docs" * Docs.main, "errors" * Errors.main, "orderonly" * OrderOnly.main+ ,"filepath" * FilePath.main, "filepattern" * FilePattern.main, "files" * Files.main+ ,"journal" * Journal.main, "lint" * Lint.main, "live" * Live.main, "makefile" * Makefile.main, "manual" * Manual.main+ ,"monad" * Monad.main, "pool" * Pool.main, "random" * Random.main, "ninja" * Ninja.main+ ,"resources" * Resources.main, "assume" * Assume.main, "benchmark" * Benchmark.main+ ,"oracle" * Oracle.main, "progress" * Progress.main, "unicode" * Unicode.main, "util" * Util.main+ ,"throttle" * Throttle.main, "verbosity" * Verbosity.main]+ where (*) = (,)+++main :: IO ()+main = do+ resetTimings+ xs <- getArgs+ exePath <- getExecutablePath+ case flip lookup (fakes ++ mains) =<< listToMaybe xs of+ _ | null xs -> do+ putStrLn "******************************************************************"+ putStrLn "** Running shake test suite, run with '--help' to see arguments **"+ putStrLn "******************************************************************"+ withArgs ["test"] main+ withArgs ["random","test","3m"] main+ Nothing -> putStrLn $ unlines+ ["Welcome to the Shake demo"+ ,""+ ,unwords $ "Modes:" : map fst fakes+ ,unwords $ "Demos:" : map fst mains+ ,""+ ,"As an example, try:"+ ,""+ ,unwords [" ", exePath, "self", "--jobs=2", "--trace"]+ ,""+ ,"Which will build Shake, using Shake, on 2 threads."]+ Just main -> main =<< sleepFileTimeCalibrate+++makefile :: IO () -> IO ()+makefile _ = do+ args <- getArgs+ withArgs (drop 1 args) Run.main+++filetime :: IO () -> IO ()+filetime _ = do+ args <- getArgs+ addTiming "Reading files"+ files <- fmap concat $ forM (drop 1 args) $ \file ->+ fmap (BS.lines . BS.filter (/= '\r')) $ BS.readFile file+ let n = length files+ evaluate n+ addTiming "Modtime"+ let (a,bcd) = splitAt (n `div` 4) files+ let (b,cd) = splitAt (n `div` 4) bcd+ let (c,d) = splitAt (n `div` 4) cd+ vars <- forM [a,b,c,d] $ \xs -> do+ mvar <- newEmptyMVar+ forkIO $ do+ mapM_ (getFileInfo . packU_) xs+ putMVar mvar ()+ return $ takeMVar mvar+ sequence_ vars+ printTimings+++clean :: IO () -> IO ()+clean extra = sequence_ [withArgs [name,"clean"] $ main extra | (name,main) <- mains]+++test :: IO () -> IO ()+test yield = do+ args <- getArgs+ flip onException (putStrLn "TESTS FAILED") $+ sequence_ [withArgs (name:"test":drop 1 args) $ test yield | (name,test) <- mains, name /= "random"]
+ src/Test/Assume.hs view
@@ -0,0 +1,45 @@++module Test.Assume(main) where++import Development.Shake+import Test.Type+import Control.Monad+import Development.Shake.FilePath+++main = shaken test $ \args obj -> do+ want $ map obj args+ obj "*.out" %> \out -> do+ cs <- mapM (readFile' . obj . (:".src")) $ takeBaseName out+ writeFile' out $ concat cs+++test build obj = do+ let set file c = writeFile (obj $ file : ".src") [c]+ let ask file c = do src <- readFile (obj $ file ++ ".out"); src === c++ forM_ ['a'..'f'] $ \c -> set c c+ build ["--sleep","abc.out"]+ ask "abc" "abc"++ set 'b' 'd'+ build ["--sleep","abc.out"]+ ask "abc" "adc"+ set 'b' 'p'+ build ["--sleep","abc.out","--touch"]+ build ["abc.out"]+ ask "abc" "adc"+ set 'c' 'z'+ build ["--sleep","abc.out"]+ ask "abc" "apz"++ build ["bc.out","c.out"]+ ask "bc" "pz"+ set 'b' 'r'+ set 'c' 'n'+ build ["--sleep","abc.out","--touch"]+ ask "abc" "apz"+ build ["ab.out","--always-make"]+ ask "ab" "ar"+ build ["c.out"]+ ask "c" "z"
+ src/Test/Basic.hs view
@@ -0,0 +1,132 @@++module Test.Basic(main) where++import Development.Shake+import Test.Type+import System.Directory as IO+import Data.List+import Data.Maybe+import Control.Monad+import General.Extra+++main = shaken test $ \args obj -> do+ want $ map (\x -> fromMaybe (obj x) $ stripPrefix "!" x) args++ obj "AB.txt" %> \out -> do+ need [obj "A.txt", obj "B.txt"]+ text1 <- readFile' $ obj "A.txt"+ text2 <- readFile' $ obj "B.txt"+ writeFile' out $ text1 ++ text2++ obj "twice.txt" %> \out -> do+ let src = obj "once.txt"+ need [src, src]+ copyFile' src out++ obj "once.txt" %> \out -> do+ src <- readFile' $ obj "zero.txt"+ writeFile' out src++ phony "halfclean" $ do+ removeFilesAfter (obj "") ["//*e.txt"]++ phony "cleaner" $ do+ removeFilesAfter (obj "") ["//*"]++ phony (obj "configure") $ do+ liftIO $ appendFile (obj "configure") "1"++ phony "install" $ do+ need [obj "configure",obj "once.txt"]+ liftIO $ appendFile (obj "install") "1"++ phony "dummy" $ do+ liftIO $ appendFile (obj "dummy") "1"++ obj "dummer.txt" %> \out -> do+ need ["dummy","dummy"]+ need ["dummy"]+ liftIO $ appendFile out "1"++ r <- newResource ".log file" 1+ let trace x = withResource r 1 $ liftIO $ appendFile (obj ".log") x+ obj "*.par" %> \out -> do+ trace "["+ (if "unsafe" `isInfixOf` out then unsafeExtraThread else id) $ liftIO $ sleep 0.1+ trace "]"+ writeFile' out out++test build obj = do+ writeFile (obj "A.txt") "AAA"+ writeFile (obj "B.txt") "BBB"+ build ["AB.txt","--sleep"]+ assertContents (obj "AB.txt") "AAABBB"+ appendFile (obj "A.txt") "aaa"+ build ["AB.txt"]+ assertContents (obj "AB.txt") "AAAaaaBBB"++ writeFile (obj "zero.txt") "xxx"+ build ["twice.txt","--sleep"]+ assertContents (obj "twice.txt") "xxx"+ writeFile (obj "zero.txt") "yyy"+ build ["once.txt","--sleep"]+ assertContents (obj "twice.txt") "xxx"+ assertContents (obj "once.txt") "yyy"+ writeFile (obj "zero.txt") "zzz"+ build ["once.txt","twice.txt","--sleep"]+ assertContents (obj "twice.txt") "zzz"+ assertContents (obj "once.txt") "zzz"++ removeFile $ obj "twice.txt"+ build ["twice.txt"]+ assertContents (obj "twice.txt") "zzz"++ show shakeOptions === show shakeOptions++ build ["!halfclean"]+ b <- IO.doesDirectoryExist (obj "")+ assert b "Directory should exist, cleaner should not have removed it"++ build ["!cleaner"]+ sleep 1 -- sometimes takes a while for the file system to notice+ b <- IO.doesDirectoryExist (obj "")+ assert (not b) "Directory should not exist, cleaner should have removed it"++ IO.createDirectory $ obj ""+ writeFile (obj "zero.txt") ""+ build ["configure"]+ build ["!install"]+ build ["!install"]+ assertContents (obj "configure") "111"+ assertContents (obj "install") "11"++ writeFile (obj "dummy.txt") ""+ build ["!dummy"]+ assertContents (obj "dummy") "1"+ build ["!dummy"]+ assertContents (obj "dummy") "11"+ build ["!dummy","!dummy"]+ assertContents (obj "dummy") "111"++ writeFile (obj "dummer.txt") ""+ build ["dummer.txt"]+ assertContents (obj "dummer.txt") "1"+ build ["dummer.txt"]+ assertContents (obj "dummer.txt") "11"++ build ["1.par","2.par","-j1"]+ assertContents (obj ".log") "[][]"+ writeFile (obj ".log") ""+ build ["3.par","4.par","-j2"]+ assertContents (obj ".log") "[[]]"+ writeFile (obj ".log") ""+ i <- getProcessorCount+ putStrLn $ "getProcessorCount returned " ++ show i+ when (i > 1) $ do+ build ["5.par","6.par","-j0"]+ assertContents (obj ".log") "[[]]"++ writeFile (obj ".log") ""+ build ["unsafe1.par","unsafe2.par","-j2"]+ assertContents (obj ".log") "[[]]"
+ src/Test/Benchmark.hs view
@@ -0,0 +1,21 @@++module Test.Benchmark(main) where++import Development.Shake+import Test.Type+import Data.List+import Development.Shake.FilePath+++-- | Given a breadth and depth come up with a set of build files+main = shaken (\_ _ -> return ()) $ \args obj -> do+ let get ty = head $ [read $ drop (length ty + 1) a | a <- args, (ty ++ "=") `isPrefixOf` a] +++ error ("Could not find argument, expected " ++ ty ++ "=Number")+ depth = get "depth"+ breadth = get "breadth"++ want [obj $ "0." ++ show i | i <- [1..breadth]]+ obj "*" %> \out -> do+ let d = read $ takeBaseName out+ need [obj $ show (d + 1) ++ "." ++ show i | d < depth, i <- [1..breadth]]+ writeFile' out ""
+ src/Test/C.hs view
@@ -0,0 +1,28 @@++module Test.C(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type++main = shaken noTest $ \args obj -> do+ let src = "src/Test/C"+ want [obj "Main.exe"]++ obj "Main.exe" %> \out -> do+ cs <- getDirectoryFiles src ["*.c"]+ let os = map (obj . (<.> "o")) cs+ need os+ cmd "gcc -o" [out] os++ obj "*.c.o" %> \out -> do+ let c = src </> takeBaseName out+ need [c]+ headers <- cIncludes c+ need $ map ((</>) src . takeFileName) headers+ cmd "gcc -o" [out] "-c" [c]++cIncludes :: FilePath -> Action [FilePath]+cIncludes x = do+ Stdout stdout <- cmd "gcc" ["-MM",x]+ return $ drop 2 $ words stdout
+ src/Test/C/constants.c view
@@ -0,0 +1,7 @@++char msg[] = "Hello Shake Users!";++char* message()+{+ return msg;+}
+ src/Test/C/constants.h view
@@ -0,0 +1,1 @@+char* message();
+ src/Test/C/main.c view
@@ -0,0 +1,8 @@+#include <stdio.h>+#include "constants.h"++int main()+{+ printf("%s\n", message());+ return 0;+}
+ src/Test/Cache.hs view
@@ -0,0 +1,39 @@++module Test.Cache(main) where++import Development.Shake+import Development.Shake.FilePath+import Data.Char+import Test.Type+++main = shaken test $ \args obj -> do+ want $ map obj args+ vowels <- newCache $ \file -> do+ src <- readFile' file+ liftIO $ appendFile (obj "trace.txt") "1"+ return $ length $ filter isDigit src+ obj "*.out*" %> \x ->+ writeFile' x . show =<< vowels (dropExtension x <.> "txt")+++test build obj = do+ writeFile (obj "trace.txt") ""+ writeFile (obj "vowels.txt") "abc123a"+ build ["vowels.out1","vowels.out2","-j3","--sleep"]+ assertContents (obj "trace.txt") "1"+ assertContents (obj "vowels.out1") "3"+ assertContents (obj "vowels.out2") "3"++ build ["vowels.out2","-j3"]+ assertContents (obj "trace.txt") "1"+ assertContents (obj "vowels.out1") "3"++ writeFile (obj "vowels.txt") "12xyz34"+ build ["vowels.out2","-j3","--sleep"]+ assertContents (obj "trace.txt") "11"+ assertContents (obj "vowels.out2") "4"++ build ["vowels.out1","-j3","--sleep"]+ assertContents (obj "trace.txt") "111"+ assertContents (obj "vowels.out1") "4"
+ src/Test/Command.hs view
@@ -0,0 +1,79 @@++module Test.Command(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+++main = shaken test $ \args obj -> do+ want $ map obj args++ let a !> b = obj a %> \out -> do alwaysRerun; res <- b; writeFile' out res++ "ghc-version" !> do+ Stdout stdout <- cmd "ghc --version"+ return stdout++ "ghc-random" !> do+ (Stderr stderr, Exit _) <- cmd "ghc --random"+ return stderr++ "ghc-random2" !> do+ () <- cmd (EchoStderr False) (Cwd $ obj "") "ghc --random"+ return ""++ "triple" !> do+ (Exit exit, Stdout stdout, Stderr stderr) <- cmd "ghc --random"+ return $ show (exit, stdout, stderr) -- must force all three parts++ obj "pwd space.hs" %> \out -> writeFileLines out ["import System.Directory","main = putStrLn =<< getCurrentDirectory"]+ "pwd" !> do+ need [obj "pwd space.hs"]+ Stdout out <- cmd (Cwd $ obj "") "runhaskell" ["pwd space.hs"]+ return out++ "env" !> do+ (Exit _, Stdout out1) <- cmd (Env [("FOO","HELLO SHAKE")]) Shell "echo %FOO%"+ (Exit _, Stdout out2) <- liftIO $ cmd (Env [("FOO","HELLO SHAKE")]) Shell "echo $FOO"+ return $ unlines [out1, out2]++ obj "bin/myexe" <.> exe %> \out -> do+ liftIO $ writeFile (obj "myexe.hs") "main = return () :: IO ()"+ cmd "ghc --make" [obj "myexe.hs"] "-o" [out]++ "path_" !> do+ need [obj "bin/myexe" <.> exe]+ fmap fromStdout $ cmd "myexe"++ "path" !> do+ path <- addPath [obj "bin"] []+ () <- cmd $ obj "bin/myexe"+ () <- cmd $ obj "bin/myexe" <.> exe+ () <- cmd path Shell "myexe"+ () <- cmd path "myexe"+ return ""+++test build obj = do+ let crash args parts = assertException parts (build $ "--quiet" : args)++ build ["ghc-version"]+ assertContentsInfix (obj "ghc-version") "The Glorious Glasgow Haskell Compilation System"++ build ["ghc-random"]+ assertContentsInfix (obj "ghc-random") "unrecognised flag"+ assertContentsInfix (obj "ghc-random") "--random"++ crash ["ghc-random2"] [obj "","unrecognised flag","--random"]++ build ["pwd"]+ assertContentsInfix (obj "pwd") "command"++ build ["env","--no-lint"] -- since it blows away the $PATH, which is necessary for lint-tracker+ assertContentsInfix (obj "env") "HELLO SHAKE"++ build ["triple"]++ crash ["path_"] ["myexe"]+ build ["path"]
+ src/Test/Config.hs view
@@ -0,0 +1,61 @@++module Test.Config(main) where++import Development.Shake+import Development.Shake.FilePath+import Development.Shake.Config+import Test.Type+import Data.Char+import qualified Data.HashMap.Strict as Map+import Data.Maybe+import System.Directory+++main = shaken test $ \args obj -> do+ want $ map obj ["hsflags.var","cflags.var","none.var","keys"]+ usingConfigFile $ obj "config"+ obj "*.var" %> \out -> do+ cfg <- getConfig $ map toUpper $ takeBaseName out+ liftIO $ appendFile (out -<.> "times") "X"+ writeFile' out $ fromMaybe "" cfg+ obj "keys" %> \out -> do+ liftIO $ appendFile (obj "keys.times") "X"+ liftIO . writeFile out . unwords =<< getConfigKeys+++test build obj = do+ build ["clean"]+ createDirectoryIfMissing True $ obj ""+ writeFile (obj "config") $ unlines+ ["HEADERS_DIR = /path/to/dir"+ ,"CFLAGS = -O2 -I${HEADERS_DIR} -g"+ ,"HSFLAGS = -O2"]+ build []+ assertContents (obj "cflags.var") "-O2 -I/path/to/dir -g"+ assertContents (obj "hsflags.var") "-O2"+ assertContents (obj "none.var") ""+ assertContents (obj "keys") "CFLAGS HEADERS_DIR HSFLAGS"++ appendFile (obj "config") $ unlines+ ["CFLAGS = $CFLAGS -w"]+ build []+ assertContents (obj "cflags.var") "-O2 -I/path/to/dir -g -w"+ assertContents (obj "hsflags.var") "-O2"+ assertContents (obj "cflags.times") "XX"+ assertContents (obj "hsflags.times") "X"+ assertContents (obj "keys.times") "X"++ -- Test readConfigFileWithEnv+ writeFile (obj "config") $ unlines+ ["HEADERS_DIR = ${SOURCE_DIR}/path/to/dir"+ ,"CFLAGS = -O2 -I${HEADERS_DIR} -g"]+ vars <- readConfigFileWithEnv [("SOURCE_DIR", "/path/to/src")]+ (obj "config")+ assert (Map.lookup "HEADERS_DIR" vars == Just "/path/to/src/path/to/dir")+ $ "readConfigFileWithEnv:"+ ++ " Expected: " ++ show (Just "/path/to/src/path/to/dir")+ ++ " Got: " ++ show (Map.lookup "HEADERS_DIR" vars)+ assert (Map.lookup "CFLAGS" vars == Just "-O2 -I/path/to/src/path/to/dir -g")+ $ "readConfigFileWithEnv:"+ ++ " Expected: " ++ show (Just "-O2 -I/path/to/src/path/to/dir -g")+ ++ " Got: " ++ show (Map.lookup "CFLAGS" vars)
+ src/Test/Digest.hs view
@@ -0,0 +1,78 @@++module Test.Digest(main) where++import Control.Monad+import Development.Shake+import Test.Type+++main = shaken test $ \args obj -> do+ want [obj "Out.txt",obj "Out2.txt"]++ obj "Out.txt" %> \out -> do+ txt <- readFile' $ obj "In.txt"+ liftIO $ appendFile out txt++ [obj "Out1.txt",obj "Out2.txt"] &%> \[out1,out2] -> do+ txt <- readFile' $ obj "In.txt"+ liftIO $ appendFile out1 txt+ liftIO $ appendFile out2 txt+++test build obj = do+ let outs = take 1 $ map obj ["Out.txt","Out1.txt","Out2.txt"]+ let writeOut x = forM_ outs $ \out -> writeFile out x+ let writeIn x = writeFile (obj "In.txt") x+ let assertOut x = forM_ outs $ \out -> assertContents out x++ writeOut ""+ writeIn "X"+ build ["--sleep","--digest-and"]+ assertOut "X"++ -- should not involve a hash calculation (sadly no way to test that)+ build ["--sleep","--digest-and"]+ assertOut "X"++ writeIn "X"+ build ["--sleep","--digest-and"]+ assertOut "X"++ writeIn "X"+ build ["--sleep","--digest-or"]+ assertOut "XX"++ writeIn "X"+ build ["--sleep","--digest-and"]+ assertOut "XX"++ build ["--sleep","--digest-and"]+ writeOut "XX"+ build ["--sleep","--digest-and"]+ assertOut "XX"++ build ["--sleep","--digest-and"]+ writeOut "Y"+ build ["--sleep","--digest-and"]+ assertOut "YX"++ writeIn "X"+ build ["--sleep","--digest"]+ assertOut "YX"++ writeIn "Z"+ build ["--sleep","--digest-and-input"]+ assertOut "YXZ"++ build ["--sleep","--digest-and-input"]+ writeOut "YXZ"+ build ["--sleep","--digest-and-input"]+ assertOut "YXZZ"++ writeIn "Q"+ build ["--sleep","--digest-and-input"]+ assertOut "YXZZQ"++ writeIn "Q"+ build ["--sleep","--digest-and-input"]+ assertOut "YXZZQ"
+ src/Test/Directory.hs view
@@ -0,0 +1,110 @@++module Test.Directory(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+import Data.List+import Control.Monad+import System.Directory(getCurrentDirectory, setCurrentDirectory, createDirectory, createDirectoryIfMissing)+import qualified System.Directory as IO+++-- Use escape characters, _o=* _l=/ __=<space>+readEsc ('_':'o':xs) = '*' : readEsc xs+readEsc ('_':'l':xs) = '/' : readEsc xs+readEsc ('_':'_':xs) = ' ' : readEsc xs+readEsc (x:xs) = x : readEsc xs+readEsc [] = []++showEsc = concatMap f+ where f '*' = "_o"+ f '/' = "_l"+ f ' ' = "__"+ f x = [x]+++main = shaken test $ \args obj -> do+ want $ map obj args+ obj "*.contents" %> \out ->+ writeFileLines out =<< getDirectoryContents (obj $ readEsc $ dropExtension $ unobj out)+ obj "*.dirs" %> \out ->+ writeFileLines out =<< getDirectoryDirs (obj $ readEsc $ dropExtension $ unobj out)+ obj "*.files" %> \out -> do+ let pats = readEsc $ dropExtension $ unobj out+ let (x:xs) = ["" | " " `isPrefixOf` pats] ++ words pats+ writeFileLines out . map toStandard =<< getDirectoryFiles (obj x) xs++ obj "*.exist" %> \out -> do+ let xs = map obj $ words $ readEsc $ dropExtension $ unobj out+ fs <- mapM doesFileExist xs+ ds <- mapM doesDirectoryExist xs+ let bool x = if x then "1" else "0"+ writeFileLines out $ zipWith (\a b -> bool a ++ bool b) fs ds++ obj "dots" %> \out -> do+ cwd <- liftIO getCurrentDirectory+ liftIO $ setCurrentDirectory $ obj ""+ b1 <- liftM2 (==) (getDirectoryContents ".") (getDirectoryContents "")+ b2 <- liftM2 (==) (getDirectoryDirs ".") (getDirectoryDirs "")+ b3 <- liftM2 (==) (getDirectoryFiles "." ["*.txt"]) (getDirectoryFiles "" ["*.txt"])+ b4 <- liftM2 (==) (getDirectoryFiles "." ["C.txt/*.txt"]) (getDirectoryFiles "" ["C.txt/*.txt"])+ b5 <- liftM2 (==) (getDirectoryFiles "." ["//*.txt"]) (getDirectoryFiles "" ["//*.txt"])+ liftIO $ setCurrentDirectory cwd+ writeFileLines out $ map show [b1,b2,b3,b4,b5]++test build obj = do+ let demand x ys = let f = showEsc x in do build [f]; assertContents (obj f) $ unlines $ words ys+ build ["clean"]+ demand " *.txt.files" ""+ demand " //*.txt.files" ""+ demand ".dirs" ""+ demand "A.txt B.txt C.txt.exist" "00 00 00"++ writeFile (obj "A.txt") ""+ writeFile (obj "B.txt") ""+ createDirectory (obj "C.txt")+ writeFile (obj "C.txt/D.txt") ""+ writeFile (obj "C.txt/E.xtx") ""+ demand " *.txt.files" "A.txt B.txt"+ demand ".dirs" "C.txt"+ demand "A.txt B.txt C.txt.exist" "10 10 01"+ demand " //*.txt.files" "A.txt B.txt C.txt/D.txt"+ demand "C.txt *.txt.files" "D.txt"+ demand " *.txt //*.xtx.files" "A.txt B.txt C.txt/E.xtx"+ demand " C.txt/*.files" "C.txt/D.txt C.txt/E.xtx"++ build ["dots","--no-lint"]+ assertContents (obj "dots") $ unlines $ words "True True True True True"++ let removeTest pat del keep = do+ withTemporaryDirectory $ \dir -> do+ forM_ (del ++ keep) $ \s -> do+ createDirectoryIfMissing True $ dir </> takeDirectory s+ when (not $ hasTrailingPathSeparator s) $+ writeFile (dir </> s) ""+ removeFiles dir pat+ createDirectoryIfMissing True dir+ forM_ (map ((,) False) del ++ map ((,) True) keep) $ \(b,s) -> do+ b2 <- (if hasTrailingPathSeparator s then IO.doesDirectoryExist else IO.doesFileExist) $ dir </> s+ when (b /= b2) $ do+ let f b = if b then "present" else "missing"+ error $ "removeFiles mismatch: with pattern " ++ show pat ++ ", " ++ s +++ " should be " ++ f b ++ " but is " ++ f b2++ removeTest ["//bob"] ["test/bob","more/bob"] ["extra/obo"]+ removeTest ["bob"] ["bob/"] ["bar/"]+ removeTest ["*.hs"] ["test.hs"] ["extra/more.hs","new.txt"]+ removeTest ["baz"] ["baz"] ["foo","bar/bob"]+ removeTest ["baz"] ["baz/bob","baz/"] ["foo","bar/bob"]+ removeTest ["Foo//*"] ["Foo/bar","Foo/Quux/bar","Foo/Quux/"] []+ removeTest ["Foo//*"] ["Foo/"] ["bar"]+ removeTest ["baz"] [] ["test.hs","bar/","foo/"]+ removeTest ["bob//*"] [] ["test/bob/"]+ removeTest ["//bob"] ["test/bob/","test/"] []+ removeTest ["//*.txt"] ["more/","more/a.txt"] []+ removeTest ["//*.txt"] ["more/","more/a.txt/"] []+ removeTest ["//*.txt"] ["more/","more/a.txt/","more/b.txt"] []+ removeTest ["//*.txt"] [] ["more/"]+ removeTest ["a//b"] ["a/c/b"] []+ removeFiles "non-existing-directory" ["*"]
+ src/Test/Docs.hs view
@@ -0,0 +1,272 @@+{-# LANGUAGE PatternGuards #-}++module Test.Docs(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+import Control.Monad+import Data.Char+import Data.List+import Data.Maybe+import System.Directory+import System.Exit+++reps from to = map (\x -> if x == from then to else x)++main = shaken noTest $ \args obj -> do+ let index = "dist/doc/html/shake/index.html"+ want [obj "Success.txt"]++ want $ map (\x -> fromMaybe (obj x) $ stripPrefix "!" x) args++ let needSource = need =<< getDirectoryFiles "." ["src/Development/Shake.hs","src/Development/Shake//*.hs","src/Development/Ninja/*.hs","src/General//*.hs"]++ index %> \_ -> do+ needSource+ need ["shake.cabal"]+ trackAllow ["dist//*"]+ res <- liftIO $ findExecutable "cabal"+ if isJust res then cmd "cabal haddock" else do+ Exit exit <- cmd "runhaskell Setup.hs haddock"+ when (exit /= ExitSuccess) $ do+ () <- cmd "runhaskell Setup.hs configure"+ cmd "runhaskell Setup.hs haddock"++ obj "Paths_shake.hs" %> \out -> do+ copyFile' "src/Paths.hs" out++ obj "Part_*.hs" %> \out -> do+ need ["src/Test/Docs.hs"] -- so much of the generator is in this module+ let noR = filter (/= '\r')+ src <- if "_md" `isSuffixOf` takeBaseName out then+ fmap (findCodeMarkdown . lines . noR) $ readFile' $ "docs/" ++ drop 5 (reverse (drop 3 $ reverse $ takeBaseName out)) ++ ".md"+ else+ fmap (findCodeHaddock . noR) $ readFile' $ "dist/doc/html/shake/" ++ reps '_' '-' (drop 5 $ takeBaseName out) ++ ".html"+ let f i (Stmt x) | whitelist $ head x = []+ | otherwise = restmt i $ map undefDots $ trims x+ f i (Expr x) | takeWhile (not . isSpace) x `elem` types = ["type Expr_" ++ show i ++ " = " ++ x]+ | "import " `isPrefixOf` x = [x]+ | otherwise = ["expr_" ++ show i ++ " = (" ++ undefDots x2 ++ ")" | let x2 = trim $ dropComment x, not $ whitelist x2]+ code = concat $ zipWith f [1..] (nub src)+ (imports,rest) = partition ("import " `isPrefixOf`) code+ writeFileLines out $+ ["{-# LANGUAGE DeriveDataTypeable, ExtendedDefaultRules, GeneralizedNewtypeDeriving, NoMonomorphismRestriction #-}"+ ,"{-# OPTIONS_GHC -w #-}"+ ,"module " ++ takeBaseName out ++ "() where"+ ,"import Control.Concurrent"+ ,"import Control.Monad"+ ,"import Data.Char"+ ,"import Data.Data"+ ,"import Data.List"+ ,"import Data.Maybe"+ ,"import Data.Monoid"+ ,"import Development.Shake"+ ,"import Development.Shake.Classes"+ ,"import Development.Shake.Rule"+ ,"import Development.Shake.Util"+ ,"import Development.Shake.FilePath"+ ,"import System.Console.GetOpt"+ ,"import System.Exit"+ ,"import System.IO"] +++ ["import " ++ reps '_' '.' (drop 5 $ takeBaseName out) | not $ "_md.hs" `isSuffixOf` out] +++ imports +++ ["(==>) :: Bool -> Bool -> Bool"+ ,"(==>) = undefined"+ ,"(<==) = ()"+ ,"infix 1 ==>"+ ,"forAll f = f undefined"+ ,"remaining = 1.1"+ ,"done = 1.1"+ ,"time_elapsed = 1.1"+ ,"old = \"\""+ ,"new = \"\""+ ,"myfile = \"\""+ ,"inputs = [\"\"]"+ ,"files = [\"\"]"+ ,"input = \"\""+ ,"output = \"\""+ ,"opts = shakeOptions"+ ,"result = undefined :: IO (Maybe (Rules ()))"+ ,"launchMissiles = undefined :: Bool -> IO ()"+ ,"myVariable = ()"+ ,"instance Eq (OptDescr a)"+ ,"(foo,bar,baz) = undefined"+ ,"str1 = \"\""+ ,"str2 = \"\""+ ,"str = \"\""] +++ rest++ obj "Files.lst" %> \out -> do+ need ["src/Test/Docs.hs"] -- so much of the generator is in this module+ need [index,obj "Paths_shake.hs"]+ filesHs <- getDirectoryFiles "dist/doc/html/shake" ["Development-*.html"]+ filesMd <- getDirectoryFiles "docs" ["*.md"]+ writeFileChanged out $ unlines $+ ["Part_" ++ reps '-' '_' (takeBaseName x) | x <- filesHs, not $ "-Classes.html" `isSuffixOf` x] +++ ["Part_" ++ takeBaseName x ++ "_md" | x <- filesMd, takeBaseName x `notElem` ["Developing","Model"]]++ let needModules = do mods <- readFileLines $ obj "Files.lst"; need [obj m <.> "hs" | m <- mods]; return mods++ obj "Main.hs" %> \out -> do+ mods <- needModules+ writeFileLines out $ ["module Main(main) where"] ++ ["import " ++ m | m <- mods] ++ ["main = return ()"]++ obj "Success.txt" %> \out -> do+ needModules+ need [obj "Main.hs", obj "Paths_shake.hs"]+ needSource+ () <- cmd "runhaskell -ignore-package=hashmap " ["-i" ++ obj "","-isrc",obj "Main.hs"]+ writeFile' out ""+++data Code = Stmt [String] | Expr String deriving (Show,Eq)++findCodeHaddock :: String -> [Code]+findCodeHaddock x | Just x <- stripPrefix "<pre>" x = f (Stmt . shift . lines . strip) "</pre>" x+ | Just x <- stripPrefix "<code>" x = f (Expr . strip) "</code>" x+ where+ f ctor end x | Just x <- stripPrefix end x = ctor "" : findCodeHaddock x+ f ctor end (x:xs) = f (ctor . (x:)) end xs+findCodeHaddock (x:xs) = findCodeHaddock xs+findCodeHaddock [] = []++findCodeMarkdown :: [String] -> [Code]+findCodeMarkdown (x:xs) | indented x && not (blank x) =+ let (a,b) = span (\x -> indented x || blank x) (x:xs)+ in Stmt (map (drop 4) a) : findCodeMarkdown b+ where+ indented x = length (takeWhile isSpace x) >= 4+ blank x = all isSpace x+findCodeMarkdown (x:xs) = f x ++ findCodeMarkdown xs+ where+ f ('`':xs) = let (a,b) = break (== '`') xs in Expr a : f (drop 1 b)+ f (x:xs) = f xs+ f [] = []+findCodeMarkdown [] = []++trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace+trims = reverse . dropWhile (all isSpace) . reverse . dropWhile (all isSpace)++restmt i ("":xs) = restmt i xs+restmt i (x:xs) | " ?== " `isInfixOf` x || " == " `isInfixOf` x =+ zipWith (\j x -> "hack_" ++ show i ++ "_" ++ show j ++ " = " ++ x) [1..] (x:xs)+restmt i (x:xs) |+ not ("let" `isPrefixOf` x) && not ("[" `isPrefixOf` x) && (" = " `isInfixOf` x || " | " `isInfixOf` x) ||+ "import " `isPrefixOf` x || "infix" `isPrefixOf` x || "instance " `isPrefixOf` x = map f $ x:xs+ where f x = if takeWhile (not . isSpace) x `elem` dupes then "_" ++ show i ++ "_" ++ x else x+restmt i xs = ("stmt_" ++ show i ++ " = do") : map (" " ++) xs +++ [" undefined" | length xs == 1 && ("let" `isPrefixOf` (head xs) || "<-" `isInfixOf` (head xs))]+++shift :: [String] -> [String]+shift xs | all null xs = xs+ | all (\x -> null x || " " `isPrefixOf` x) xs = shift $ map (drop 1) xs+ | otherwise = xs+++dropComment ('-':'-':_) = []+dropComment xs = onTail dropComment xs+++undefDots o = f o+ where+ f ('.':'.':'.':xs) =+ (if any (`elem` words o) ["cmd","Development.Shake.cmd"] then "[\"\"]" else "undefined") +++ (if "..." `isSuffixOf` xs then "" else undefDots xs)+ f xs = onTail f xs++strip :: String -> String+strip x+ | Just x <- stripPrefix "<em>" x+ , (a,b) <- break (== '<') x+ , not $ ("</em>" `isPrefixOf` b) && a `elem` italics+ = error $ "Unexpected italics in code block: " ++ a ++ take 5 b ++ "..."+strip ('<':xs) = strip $ drop 1 $ dropWhile (/= '>') xs+strip ('&':xs)+ | Just xs <- stripPrefix "quot;" xs = '\"' : strip xs+ | Just xs <- stripPrefix "lt;" xs = '<' : strip xs+ | Just xs <- stripPrefix "gt;" xs = '>' : strip xs+ | Just xs <- stripPrefix "amp;" xs = '&' : strip xs+strip xs = onTail strip xs++onTail f (x:xs) = x : f xs+onTail f [] = []+++italics :: [String]+italics = words "extension command-name file-name"++whitelist :: String -> Bool+whitelist x | all (not . isSpace) x && takeExtension x `elem` words ".txt .hi .hs .o .exe .tar .cpp .cfg .dep .deps .h .c .html .zip" = True+whitelist x | elem x $ words $+ "newtype do MyFile.txt.digits excel a q m c x value key gcc cl os make contents tar ghc cabal clean _make distcc ghc " +++ ".. /./ /.. /../ ./ // \\ ../ //*.c //*.txt //* dir/*/* dir " +++ "ConstraintKinds GeneralizedNewtypeDeriving DeriveDataTypeable SetConsoleTitle " +++ "Data.List System.Directory Development.Shake.FilePath main.m run .rot13 " +++ "NoProgress Error src rot13 .js .json .trace about://tracing " +++ ".make/i586-linux-gcc/output _make/.database foo/.. file.src file.out build " +++ "/usr/special /usr/special/userbinary $CFLAGS %PATH% -O2 -j8 -j -j1 " +++ "-threaded -rtsopts -I0 Function extension $OUT $C_LINK_FLAGS $PATH xterm $TERM main opts result flagValues argValues " +++ "HEADERS_DIR /path/to/dir CFLAGS let -showincludes -MMD gcc.version linkFlags temp pwd touch code out err " +++ "_metadata/.database _shake _shake/build ./build.sh build.sh build.bat [out] manual " +++ "docs/manual _build _build/run ninja depfile build.ninja " +++ "Rule CmdResult ShakeValue Monoid Monad Eq Typeable Data " ++ -- work only with constraint kinds+ "@ndm_haskell "+ = True+whitelist x+ | "foo/" `isPrefixOf` x -- path examples+ = True+whitelist x = x `elem`+ ["[Foo.hi, Foo.o]"+ ,"shake-progress"+ ,"main -j6"+ ,"main clean"+ ,"1m25s (15%)"+ ,"3m12s (82%)"+ ,"getPkgVersion $ GhcPkgVersion \"shake\""+ ,"# command-name (for file-name)"+ ,"ghc --make MyBuildSystem -rtsopts -with-rtsopts=-I0"+ ,"-with-rtsopts"+ ,"-qg -qb"+ ,"gcc -MM"+ ,"# This is my Config file"+ ,"-g -I/path/to/dir -O2"+ ,"main _make/henry.txt"+ ,"<i>build rules</i>"+ ,"<i>actions</i>"+ ,"() <- cmd ..."+ ,"x <- inputs"+ ,"shakeFiles=\"_build/\""+ ,"#include \""+ ,"pattern %> actions = (pattern ?==) ?> actions" -- because it overlaps+ ,"buildDir = \"_build\""+ ,"-MMD -MF"+ ,"#!/bin/sh"+ ,"build _build/main.o"+ ,"build clean"+ ,"build -j8"+ ,"cabal update && cabal install shake"+ ,"shake-build-system"+ ,"runhaskell _build/run"+ ,"runhaskell _build/run clean"+ ,"gcc -c main.c -o main.o -MMD -MF main.m"+ ,"\"_build\" </> x -<.> \"o\""+ ,"cmd \"gcc -o\" [out] os"+ ,"rot13 file.txt -o file.rot13"+ ,"file.rot13"+ ,"out -<.> \"txt\""+ ,"[item1,item2,item2]"+ ,"runhaskell Build.hs"+ ,"cabal update"+ ,"cabal install shake"+ ,"shake -j4"+ ,"cmd \"gcc -o _make/run _build/main.o _build/constants.o\""+ ]++types = words $+ "MVar IO String FilePath Maybe [String] Char ExitCode Change " +++ "Action Resource Assume FilePattern Lint Verbosity Rules CmdOption Int Double"++dupes = words "main progressSimple rules"
+ src/Test/Errors.hs view
@@ -0,0 +1,144 @@++module Test.Errors(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+import Control.Monad+import Control.Concurrent+import Control.Exception.Extra hiding (assert)+import System.Directory as IO+import qualified System.IO.Extra as IO+++main = shaken test $ \args obj -> do+ want $ map obj args++ obj "norule" %> \_ ->+ need [obj "norule_isavailable"]++ obj "failcreate" %> \_ ->+ return ()++ [obj "failcreates", obj "failcreates2"] &%> \_ ->+ writeFile' (obj "failcreates") ""++ obj "recursive" %> \out ->+ need [out]++ obj "systemcmd" %> \_ ->+ cmd "random_missing_command"++ obj "stack1" %> \_ -> need [obj "stack2"]+ obj "stack2" %> \_ -> need [obj "stack3"]+ obj "stack3" %> \_ -> error "crash"++ obj "staunch1" %> \out -> do+ liftIO $ sleep 0.1+ writeFile' out "test"+ obj "staunch2" %> \_ -> error "crash"++ let catcher out op = obj out %> \out -> do+ writeFile' out "0"+ op $ do src <- IO.readFile' out; writeFile out $ show (read src + 1 :: Int)+ catcher "finally1" $ actionFinally $ fail "die"+ catcher "finally2" $ actionFinally $ return ()+ catcher "finally3" $ actionFinally $ liftIO $ sleep 10+ catcher "finally4" $ actionFinally $ need ["wait"]+ "wait" ~> do liftIO $ sleep 10+ catcher "exception1" $ actionOnException $ fail "die"+ catcher "exception2" $ actionOnException $ return ()++ res <- newResource "resource_name" 1+ obj "resource" %> \out -> do+ withResource res 1 $+ need ["resource-dep"]++ obj "overlap.txt" %> \out -> writeFile' out "overlap.txt"+ obj "overlap.t*" %> \out -> writeFile' out "overlap.t*"+ obj "overlap.*" %> \out -> writeFile' out "overlap.*"+ alternatives $ do+ obj "alternative.t*" %> \out -> writeFile' out "alternative.txt"+ obj "alternative.*" %> \out -> writeFile' out "alternative.*"++ obj "chain.2" %> \out -> do+ src <- readFile' $ obj "chain.1"+ if src == "err" then error "err_chain" else writeFileChanged out src+ obj "chain.3" %> \out -> copyFile' (obj "chain.2") out++ obj "tempfile" %> \out -> do+ file <- withTempFile $ \file -> do+ liftIO $ assertExists file+ return file+ liftIO $ assertMissing file+ withTempFile $ \file -> do+ liftIO $ assertExists file+ writeFile' out file+ fail "tempfile-died"++ obj "tempdir" %> \out -> do+ file <- withTempDir $ \dir -> do+ let file = dir </> "foo.txt"+ liftIO $ writeFile (dir </> "foo.txt") ""+ -- will throw if the directory does not exist+ writeFile' out ""+ return file+ liftIO $ assertMissing file+++test build obj = do+ let crash args parts = assertException parts (build $ "--quiet" : args)+ build ["clean"]+ build ["--sleep"]++ writeFile (obj "chain.1") "x"+ build ["chain.3","--sleep"]+ writeFile (obj "chain.1") "err"+ crash ["chain.3"] ["err_chain"]++ crash ["norule"] ["norule_isavailable"]+ crash ["failcreate"] ["failcreate"]+ crash ["failcreates"] ["failcreates"]+ crash ["recursive"] ["recursive"]+ crash ["systemcmd"] ["systemcmd","random_missing_command"]+ crash ["stack1"] ["stack1","stack2","stack3","crash"]++ b <- IO.doesFileExist $ obj "staunch1"+ when b $ removeFile $ obj "staunch1"+ crash ["staunch1","staunch2","-j2"] ["crash"]+ b <- IO.doesFileExist $ obj "staunch1"+ assert (not b) "File should not exist, should have crashed first"+ crash ["staunch1","staunch2","-j2","--keep-going","--silent"] ["crash"]+ b <- IO.doesFileExist $ obj "staunch1"+ assert b "File should exist, staunch should have let it be created"++ crash ["finally1"] ["die"]+ assertContents (obj "finally1") "1"+ build ["finally2"]+ assertContents (obj "finally2") "1"+ crash ["exception1"] ["die"]+ assertContents (obj "exception1") "1"+ build ["exception2"]+ assertContents (obj "exception2") "0"++ forM_ ["finally3","finally4"] $ \name -> do+ t <- forkIO $ ignore $ build [name,"--exception"]+ retry 10 $ sleep 0.1 >> assertContents (obj name) "0"+ throwTo t (IndexOutOfBounds "test")+ retry 10 $ sleep 0.1 >> assertContents (obj name) "1"++ crash ["resource"] ["cannot currently call apply","withResource","resource_name"]++ build ["overlap.foo"]+ assertContents (obj "overlap.foo") "overlap.*"+ build ["overlap.txt"]+ assertContents (obj "overlap.txt") "overlap.txt"+ crash ["overlap.txx"] ["key matches multiple rules","overlap.txx"]+ build ["alternative.foo","alternative.txt"]+ assertContents (obj "alternative.foo") "alternative.*"+ assertContents (obj "alternative.txt") "alternative.txt"++ crash ["tempfile"] ["tempfile-died"]+ src <- readFile $ obj "tempfile"+ assertMissing src+ build ["tempdir"]
+ src/Test/FilePath.hs view
@@ -0,0 +1,86 @@++module Test.FilePath(main) where++import Development.Shake.FilePath+import qualified System.FilePath as Native+import Test.Type+import Test.QuickCheck+import Control.Monad+import Data.List+import qualified Data.ByteString.Char8 as BS+import qualified Development.Shake.ByteString as BS+import System.Info.Extra+++main = shaken test $ \args obj -> return ()+++newtype File = File String deriving Show++instance Arbitrary File where+ arbitrary = fmap File $ listOf $ oneof $ map return "a /\\:."+ shrink (File x) = map File $ shrink x+++test build obj = do+ let a === b = a Test.Type.=== b -- duplicate definition in QuickCheck 2.7 and above++ let norm x =+ let s = toStandard $ normaliseEx x+ b = BS.unpack (BS.filepathNormalise $ BS.pack x)+ in if s == b then s else error $ show ("Normalise functions differ",x,s,b)+ -- basic examples+ norm "" === "."+ norm "." === "."+ norm "/" === "/"+ norm "./" === "./"+ norm "/." === "/."+ norm "/./" === "/"+ norm "a/." === "a"+ norm "./a" === "a"+ norm "./a/." === "a"+ norm "./a/./" === "a/"+ norm "a/.." === "."+ norm "a/./.." === "."+ norm "a/../" === "./"+ norm "/a/../" === "/"+ norm "/a/./../" === "/"+ norm "../a" === "../a"+ norm "/../a/" === "/../a/"++ -- more realistic examples+ norm "neil//./test/moo/../bar/bob/../foo" === "neil/test/bar/foo"+ norm "bar/foo" === "bar/foo"+ norm "bar/foo/" === "bar/foo/"+ norm "../../foo" === "../../foo"+ norm "foo/../..///" === "../"+ norm "foo/bar/../../neil" === "neil"+ norm "foo/../bar/../neil" === "neil"+ norm "/foo/bar" === "/foo/bar"+ norm "//./" === (if isWindows then "//" else "/")+ norm "//foo/./bar" === (if isWindows then "//foo/bar" else "/foo/bar")+ when isWindows $ norm "c:\\foo\\bar" === "c:/foo/bar"+ Success{} <- quickCheckWithResult stdArgs{maxSuccess=1000} $ \(File x) ->+ let y = norm x+ sep = Native.isPathSeparator+ noDrive = if isWindows then drop 1 else id+ ps = [length y >= 1+ ,null x || (sep (head x) == sep (head y) && sep (last x) == sep (last y))+ ,not $ "/./" `isInfixOf` y+ ,not isWindows || '\\' `notElem` y+ ,not $ "//" `isInfixOf` noDrive y+ ,".." `notElem` dropWhile (== "..") (dropWhile (\x -> all isPathSeparator x || isDrive x) $ splitDirectories y)+ ,norm y == y]+ in if and ps then True else error $ show (x, y, ps)++ dropDirectory1 "aaa/bbb" === "bbb"+ dropDirectory1 "aaa/" === ""+ dropDirectory1 "aaa" === ""+ dropDirectory1 "" === ""++ takeDirectory1 "aaa/bbb" === "aaa"+ takeDirectory1 "aaa/" === "aaa"+ takeDirectory1 "aaa" === "aaa"++ searchPathSeparator === Native.searchPathSeparator+ pathSeparators === Native.pathSeparators
+ src/Test/FilePattern.hs view
@@ -0,0 +1,65 @@++module Test.FilePattern(main) where++import Development.Shake.FilePattern+import Development.Shake.FilePath+import Data.Tuple.Extra+import System.Info.Extra+import Test.Type++main = shaken test $ \args obj -> return ()+++test build obj = do+ let f b pat file = assert (b == (pat ?== file)) $ show pat ++ " ?== " ++ show file ++ "\nEXPECTED: " ++ show b+ f True "//*.c" "foo/bar/baz.c"+ f isWindows "\\\\*.c" "foo/bar\\baz.c"+ f True "*.c" "baz.c"+ f True "//*.c" "baz.c"+ f True "test.c" "test.c"+ f False "*.c" "foor/bar.c"+ f False "*/*.c" "foo/bar/baz.c"+ f False "foo//bar" "foobar"+ f False "foo//bar" "foobar/bar"+ f False "foo//bar" "foo/foobar"+ f True "foo//bar" "foo/bar"++ assert (compatible []) "compatible"+ assert (compatible ["//*a.txt","foo//a*.txt"]) "compatible"+ assert (not $ compatible ["//*a.txt","foo//a*.*txt"]) "compatible"+ extract "//*a.txt" "foo/bar/testa.txt" === ["foo/bar/","test"]+ extract "//*a.txt" "testa.txt" === ["","test"]+ extract "//*a*.txt" "testada.txt" === ["","test","da"]+ substitute ["","test","da"] "//*a*.txt" === "testada.txt"+ substitute ["foo/bar/","test"] "//*a.txt" === "foo/bar/testa.txt"++ directories1 "*.xml" === ("",False)+ directories1 "//*.xml" === ("",True)+ directories1 "foo//*.xml" === ("foo",True)+ first toStandard (directories1 "foo/bar/*.xml") === ("foo/bar",False)+ directories1 "*/bar/*.xml" === ("",True)+ directories ["*.xml","//*.c"] === [("",True)]+ directories ["bar/*.xml","baz//*.c"] === [("bar",False),("baz",True)]+ directories ["bar/*.xml","baz//*.c"] === [("bar",False),("baz",True)]+++---------------------------------------------------------------------+-- LAZY SMALLCHECK PROPERTIES++{-+newtype Pattern = Pattern FilePattern deriving (Show,Eq)+newtype Path = Path FilePath deriving (Show,Eq)++-- Since / and * are the only "interesting" elements, just add ab to round out the set++instance Serial Pattern where+ series = cons Pattern >< f+ where f = cons [] \/ cons (:) >< const (drawnFrom "/*ab") >< f++instance Serial Path where+ series = cons Path >< f+ where f = cons [] \/ cons (:) >< const (drawnFrom "/ab") >< f++testSmallCheck = do+ smallCheck 10 $ \(Pattern p) (Path x) -> p ?== x ==> substitute (extract p x) p == x+-}
+ src/Test/Files.hs view
@@ -0,0 +1,39 @@++module Test.Files(main) where++import Development.Shake+import Test.Type+import Control.Monad+import Data.List+++main = shaken test $ \args obj -> do+ let fun = "@" `elem` args+ let rest = delete "@" args+ want $ map obj $ if null rest then ["even.txt","odd.txt"] else rest++ -- Since &?> and &%> are implemented separately we test everything in both modes+ let deps &?%> act | fun = (\x -> if x `elem` deps then Just deps else Nothing) &?> act+ | otherwise = deps &%> act++ map obj ["even.txt","odd.txt"] &?%> \[evens,odds] -> do+ src <- readFileLines $ obj "numbers.txt"+ let (es,os) = partition even $ map read src+ writeFileLines evens $ map show es+ writeFileLines odds $ map show os++ map obj ["dir1/out.txt","dir2/out.txt"] &?%> \[a,b] -> do+ writeFile' a "a"+ writeFile' b "b"+++test build obj = do+ forM_ [[],["@"]] $ \args -> do+ let nums = unlines . map show+ writeFile (obj "numbers.txt") $ nums [1,2,4,5,2,3,1]+ build ("--sleep":args)+ assertContents (obj "even.txt") $ nums [2,4,2]+ assertContents (obj "odd.txt" ) $ nums [1,5,3,1]+ build ["clean"]+ build ["--no-build","--report=-"]+ build ["dir1/out.txt"]
+ src/Test/Journal.hs view
@@ -0,0 +1,44 @@++module Test.Journal(main) where++import Control.Monad+import Data.IORef+import Development.Shake+import Development.Shake.FilePath+import Test.Type+import System.IO.Unsafe+++{-# NOINLINE rebuilt #-}+rebuilt :: IORef Int+rebuilt = unsafePerformIO $ newIORef 0+++main = shaken test $ \args obj -> do+ want $ map obj ["a.out","b.out","c.out"]+ obj "*.out" %> \out -> do+ liftIO $ atomicModifyIORef rebuilt $ \a -> (a+1,())+ copyFile' (out -<.> "in") out+++test build obj = do+ + let change x = writeFile (obj $ x <.> "in") x+ let count x = do+ before <- readIORef rebuilt+ build ["--sleep"]+ after <- readIORef rebuilt+ x === after - before++ change "a"+ change "b"+ change "c"+ count 3++ -- test that compressing the database doesn't corrupt anything+ replicateM_ 4 $ do+ change "a"+ count 1+ change "a"+ change "c"+ count 2
+ src/Test/Lint.hs view
@@ -0,0 +1,119 @@++module Test.Lint(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+import Control.Exception hiding (assert)+import System.Directory as IO+import Control.Monad+import Data.Maybe+++main = shaken test $ \args obj -> do+ want $ map obj args++ addOracle $ \() -> do+ liftIO $ createDirectoryIfMissing True $ obj "dir"+ liftIO $ setCurrentDirectory $ obj "dir"+ return ()++ obj "changedir" %> \out -> do+ () <- askOracle ()+ writeFile' out ""++ obj "pause.*" %> \out -> do+ liftIO $ sleep 0.1+ need [obj "cdir" <.> takeExtension out]+ writeFile' out ""++ obj "cdir.*" %> \out -> do+ pwd <- liftIO getCurrentDirectory+ let dir2 = obj $ "dir" ++ takeExtension out+ liftIO $ createDirectoryIfMissing True dir2+ liftIO $ setCurrentDirectory dir2+ liftIO $ sleep 0.2+ liftIO $ setCurrentDirectory pwd+ writeFile' out ""++ obj "createonce" %> \out -> do+ writeFile' out "X"++ obj "createtwice" %> \out -> do+ need [obj "createonce"]+ liftIO sleepFileTime+ writeFile' (obj "createonce") "Y"+ writeFile' out ""++ obj "listing" %> \out -> do+ writeFile' (out <.> "ls1") ""+ getDirectoryFiles (obj "") ["//*.ls*"]+ writeFile' (out <.> "ls2") ""+ writeFile' out ""++ obj "existance" %> \out -> do+ Development.Shake.doesFileExist $ obj "exists"+ writeFile' (obj "exists") ""+ writeFile' out ""++ obj "gen*" %> \out -> do+ writeFile' out out++ obj "needed1" %> \out -> do+ needed [obj "gen1"]+ writeFile' out ""++ obj "needed2" %> \out -> do+ orderOnly [obj "gen2"]+ needed [obj "gen2"]+ writeFile' out ""++ obj "tracker-write1" %> \out -> do+ () <- cmd "cmd /c" ["echo x > " ++ out <.> "txt"]+ need [out <.> "txt"]+ writeFile' out ""++ obj "tracker-write2" %> \out -> do+ () <- cmd "cmd /c" ["echo x > " ++ out <.> "txt"]+ writeFile' out ""++ obj "tracker-source2" %> \out -> copyFile' (obj "tracker-source1") out+ obj "tracker-read1" %> \out -> do+ () <- cmd "cmd /c" ["type " ++ toNative (obj "tracker-source1") ++ " > nul"]+ writeFile' out ""+ obj "tracker-read2" %> \out -> do+ () <- cmd "cmd /c" ["type " ++ toNative (obj "tracker-source1") ++ " > nul"]+ need [obj "tracker-source1"]+ writeFile' out ""+ obj "tracker-read3" %> \out -> do+ () <- cmd "cmd /c" ["type " ++ toNative (obj "tracker-source2") ++ " > nul"]+ need [obj "tracker-source2"]+ writeFile' out ""+++test build obj = do+ dir <- getCurrentDirectory+ let crash args parts = do+ assertException parts (build $ "--quiet" : args)+ `finally` setCurrentDirectory dir++ crash ["changedir"] ["current directory has changed"]+ build ["cdir.1","cdir.2","-j1"]+ build ["--clean","cdir.1","pause.2","-j1"]+ crash ["--clean","cdir.1","pause.2","-j2"] ["before building output/lint/","current directory has changed"]+ crash ["existance"] ["changed since being depended upon"]+ crash ["createtwice"] ["changed since being depended upon"]+ crash ["listing"] ["changed since being depended upon","output/lint"]+ crash ["--clean","listing","existance"] ["changed since being depended upon"]+ crash ["needed1"] ["'needed' file required rebuilding"]+ build ["needed2"]++ tracker <- findExecutable "tracker.exe"+ when (isJust tracker) $ do+ writeFile (obj "tracker-source1") ""+ writeFile (obj "tracker-source2") ""+ crash ["tracker-write1"] ["not have its creation tracked","lint/tracker-write1","lint/tracker-write1.txt"]+ build ["tracker-write2"]+ crash ["tracker-read1"] ["used but not depended upon","lint/tracker-source1"]+ build ["tracker-read2"]+ crash ["tracker-read3"] ["depended upon after being used","lint/tracker-source2"]
+ src/Test/Live.hs view
@@ -0,0 +1,28 @@++module Test.Live(main) where++import Development.Shake+import Test.Type+++main = shaken test $ \args obj -> do+ want $ map obj args++ obj "foo" %> \ out -> do+ need [obj "bar"]+ writeFile' out ""++ obj "bar" %> \out -> writeFile' out ""+ obj "baz" %> \out -> writeFile' out ""+++test build obj = do+ build ["clean"]+ build ["foo","baz","--live=" ++ obj "live.txt"]+ assertContentsUnordered (obj "live.txt") $ map obj $ words "foo bar baz"+ build ["foo","baz","--live=" ++ obj "live.txt"]+ assertContentsUnordered (obj "live.txt") $ map obj $ words "foo bar baz"+ build ["foo","--live=" ++ obj "live.txt"]+ assertContentsUnordered (obj "live.txt") $ map obj $ words "foo bar"+ build ["bar","--live=" ++ obj "live.txt"]+ assertContentsUnordered (obj "live.txt") $ map obj $ words "bar"
+ src/Test/MakeTutor/Makefile view
@@ -0,0 +1,17 @@+# From http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/, Makefile 4++CC=gcc+CFLAGS=-I.+DEPS = hellomake.h+OBJ = hellomake.o hellofunc.o ++hellomake$(EXE): $(OBJ)+ $(CC) -o $@ $^ $(CFLAGS)++%.o: %.c $(DEPS)+ $(CC) -c -o $@ $< $(CFLAGS)++.PHONY: clean+clean:+ rm hellomake$(EXE)+ rm *.o
+ src/Test/MakeTutor/hellofunc.c view
@@ -0,0 +1,9 @@+#include <stdio.h>+#include <hellomake.h>++void myPrintHelloMake(void) {++ printf("Hello makefiles!\n");++ return;+}
+ src/Test/MakeTutor/hellomake.c view
@@ -0,0 +1,8 @@+#include <hellomake.h>++int main() {+ // call a function in another file+ myPrintHelloMake();++ return(0);+}
+ src/Test/MakeTutor/hellomake.h view
@@ -0,0 +1,5 @@+/*+example include file+*/++void myPrintHelloMake(void);
+ src/Test/Makefile.hs view
@@ -0,0 +1,24 @@++module Test.Makefile(main) where++import Development.Shake(action, liftIO)+import qualified Run as Makefile+import System.Environment+import Test.Type+import Control.Monad+import Data.List+import Data.Maybe+++main = shaken test $ \args obj ->+ action $ liftIO $ do+ unless (["@@"] `isPrefixOf` args) $+ error "The 'makefile' example should only be used in test mode, to test using a makefile use the 'make' example."+ withArgs [fromMaybe x $ stripPrefix "@" x | x <- drop 1 args] Makefile.main+++test build obj = do+ copyDirectoryChanged "src/Test/MakeTutor" $ obj "MakeTutor"+ build ["@@","--directory=" ++ obj "MakeTutor","--no-report"]+ build ["@@","--directory=" ++ obj "MakeTutor","--no-report"]+ build ["@@","--directory=" ++ obj "MakeTutor","@clean","--no-report"]
+ src/Test/Manual.hs view
@@ -0,0 +1,24 @@++module Test.Manual(main) where++import Development.Shake hiding (copyFileChanged)+import Development.Shake.FilePath+import Test.Type+import System.Info.Extra+++main = shaken test $ \args obj ->+ action $ liftIO $ error "The 'manual' example should only be used in test mode"++test build obj = do+ copyDirectoryChanged "docs/manual" $ obj "manual"+ copyDirectoryChanged "src/Development" $ obj "manual/Development"+ copyDirectoryChanged "src/General" $ obj "manual/General"+ copyFileChanged "src/Paths.hs" $ obj "manual/Paths_shake.hs"+ let cmdline = if isWindows then "build.bat" else "/bin/sh build.sh"+ () <- cmd [Cwd $ obj "manual", Shell] cmdline "-j2"+ assertExists $ obj "manual/_build/run" <.> exe+ () <- cmd [Cwd $ obj "manual", Shell] cmdline+ () <- cmd [Cwd $ obj "manual", Shell] [cmdline,"clean"]+ assertMissing $ obj "manual/_build/run" <.> exe+ return ()
+ src/Test/Monad.hs view
@@ -0,0 +1,89 @@++module Test.Monad(main) where++import Test.Type+import Development.Shake.Monad++import Data.IORef+import Control.Concurrent+import Control.Exception hiding (assert)+import Control.Monad+import Control.Monad.IO.Class+++main = shaken test $ \args obj -> return ()+++run :: ro -> rw -> RAW ro rw a -> IO a+run ro rw m = do+ res <- newEmptyMVar+ runRAW ro rw m $ void . tryPutMVar res+ either throwIO return =<< readMVar res+++test build obj = do+ let conv x = either (Left . fromException) Right x :: Either (Maybe ArithException) Int+ let dump ro rw = do liftIO . (=== ro) =<< getRO; liftIO . (=== rw) =<< getRW++ -- test the basics plus exception handling+ run 1 "test" $ do+ dump 1 "test"+ putRW "more"+ dump 1 "more"+ res <- tryRAW $ withRO (+3) $ do+ dump 4 "more"+ withRW (++ "x") $ do+ dump 4 "morex"+ dump 4 "more"+ return 100+ liftIO $ conv res === Right 100+ dump 1 "more"+ putRW "new"+ dump 1 "new"+ res <- tryRAW $ withRO (+2) $ do+ dump 3 "new"+ withRW (++ "x") $ do+ dump 3 "newx"+ throwRAW Overflow+ error "Should not have reached here"+ return 9+ liftIO $ conv res === Left (Just Overflow)+ dump 1 "new"+ catchRAW (catchRAW (throwRAW Overflow) $ \_ -> modifyRW (++ "x")) $+ \_ -> modifyRW (++ "y")+ dump 1 "newx"+ catchRAW (catchRAW (throwRAW Overflow) $ \e -> modifyRW (++ "x") >> throwRAW e) $+ \_ -> modifyRW (++ "y")+ dump 1 "newxxy"++ -- test capture+ run 1 "test" $ do+ i <- captureRAW $ \k -> k $ Right 1+ liftIO $ i === 1+ i <- tryRAW $ captureRAW $ \k -> k $ Left $ toException Overflow+ liftIO $ conv i === Left (Just Overflow)+ captureRAW $ \k -> k $ Right ()+ i <- tryRAW $ throwRAW Underflow+ liftIO $ conv i === Left (Just Underflow)++ -- catch does not scope too far+ res <- try $ run 1 "test" $+ fmap (either show id) $ tryRAW $ captureRAW $ \k -> throwIO Overflow+ res === Left Overflow+ res <- try $ run 1 "test" $ do+ captureRAW $ \k -> throwIO Overflow+ return "x"+ res === Left Overflow++ -- catch works properly if continuation called multiple times+ ref <- newIORef []+ run 1 "test" $+ flip catchRAW (const $ liftIO $ modifyIORef ref ('x':)) $ do+ captureRAW $ \k -> do+ k $ Right ()+ k $ Right ()+ k $ Left $ toException Overflow+ k $ Right ()+ k $ Left $ toException Overflow+ flip catchRAW (const $ liftIO $ modifyIORef ref ('y':)) $ throwRAW $ toException Overflow+ (===) "xyxyy" =<< readIORef ref
+ src/Test/Ninja.hs view
@@ -0,0 +1,87 @@++module Test.Ninja(main) where++import Development.Shake+import Development.Shake.FilePath+import qualified Development.Shake.Config as Config+import System.Directory(copyFile)+import Control.Monad+import Test.Type+import qualified Data.HashMap.Strict as Map+import Data.List+import Data.Maybe+import System.IO.Extra+import qualified Run+import System.Environment+++main = shaken test $ \args obj -> do+ let args2 = ("-C" ++ obj "") : map tail (filter ("@" `isPrefixOf`) args)+ let real = "real" `elem` args+ action $+ if real then cmd "ninja" args2 else liftIO $ withArgs args2 Run.main+++test build obj = do+ -- when calling run anything with a leading @ gets given to Shake, anything without gets given to Ninja+ let run xs = build $ "--exception" : map (\x -> fromMaybe ('@':x) $ stripPrefix "@" x) (words xs)+ let runFail xs bad = assertException [bad] $ run $ xs ++ " --quiet"++ build ["clean"]+ run "-f../../src/Test/Ninja/test1.ninja"+ assertExists $ obj "out1.txt"++ run "-f../../src/Test/Ninja/test2.ninja"+ assertExists $ obj "out2.2"+ assertMissing $ obj "out2.1"+ build ["clean"]+ run "-f../../src/Test/Ninja/test2.ninja out2.1"+ assertExists $ obj "out2.1"+ assertMissing $ obj "out2.2"++ copyFile "src/Test/Ninja/test3-sub.ninja" $ obj "test3-sub.ninja"+ copyFile "src/Test/Ninja/test3-inc.ninja" $ obj "test3-inc.ninja"+ copyFile ("src/Test/Ninja/" ++ if null exe then "test3-unix.ninja" else "test3-win.ninja") $ obj "test3-platform.ninja"+ run "-f../../src/Test/Ninja/test3.ninja"+ assertNonSpace (obj "out3.1") "g4+b1+++i1"+ assertNonSpace (obj "out3.2") "g4++++i1"+ assertNonSpace (obj "out3.3") "g4++++i1"+ assertNonSpace (obj "out3.4") "g4+++s1+s2"++ run "-f../../src/Test/Ninja/test4.ninja out"+ assertExists $ obj "out.txt"+ assertExists $ obj "out2.txt"++ run "-f../../src/Test/Ninja/test5.ninja"+ assertExists $ obj "output file"++ writeFile (obj "nocreate.log") ""+ writeFile (obj "nocreate.in") ""+ run "-f../../src/Test/Ninja/nocreate.ninja"+ assertNonSpace (obj "nocreate.log") "x"+ run "-f../../src/Test/Ninja/nocreate.ninja"+ run "-f../../src/Test/Ninja/nocreate.ninja"+ assertNonSpace (obj "nocreate.log") "xxx"++ writeFile (obj "input") ""+ runFail "-f../../src/Test/Ninja/lint.ninja bad --lint" "'needed' file required rebuilding"+ run "-f../../src/Test/Ninja/lint.ninja good --lint"+ runFail "-f../../src/Test/Ninja/lint.ninja bad --lint" "not a pre-dependency"++ res <- fmap (drop 1 . lines . fst) $ captureOutput $ run "-f../../src/Test/Ninja/compdb.ninja -t compdb cxx @--no-report @--quiet"+ want <- fmap lines $ readFile "src/Test/Ninja/compdb.output"+ let eq a b | (a1,'*':a2) <- break (== '*') a = unless (a1 `isPrefixOf` b && a2 `isSuffixOf` b) $ a === b+ | otherwise = a === b+ length want === length res+ zipWithM_ eq want res++ -- Test initial variable bindings and variables in include/subninja statements+ let test6 = obj "test6"++ copyFile "src/Test/Ninja/test6-sub.ninja" $ test6 ++ "-sub.ninja"+ copyFile "src/Test/Ninja/test6-inc.ninja" $ test6 ++ "-inc.ninja"+ copyFile "src/Test/Ninja/test6.ninja" $ test6 ++ ".ninja"++ config <- Config.readConfigFileWithEnv [("v1", test6)] $ test6 ++ ".ninja"+ -- The file included by subninja should have a separate variable scope+ Map.lookup "v2" config === Just "g2"
+ src/Test/Ninja/compdb.ninja view
@@ -0,0 +1,45 @@+# Copied from the Ninja repo++ninja_required_version = 1.3++builddir = build+cxx = g+++ar = ar+cflags = -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti $+ -fno-exceptions -pipe -Wno-missing-field-initializers $+ -DNINJA_PYTHON="python.exe" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501+ldflags = -L$builddir -static++rule cxx+ command = $cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out+ description = CXX $out+ depfile = $out.d+ deps = gcc++rule ar+ command = cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out+ description = AR $out++rule link+ command = $cxx $ldflags -o $out $in $libs+ description = LINK $out++# the depfile parser and ninja lexers are generated using re2c.++# Core source files all build into ninja library.+build $builddir\build.o: cxx src\build.cc+build $builddir\build_log.o: cxx src\build_log.cc+build $builddir\clean.o: cxx src\clean.cc++rule doxygen+ command = doxygen $in+ description = DOXYGEN $in+doxygen_mainpage_generator = src\gen_doxygen_mainpage.sh+rule doxygen_mainpage+ command = $doxygen_mainpage_generator $in > $out+ description = DOXYGEN_MAINPAGE $out+build $builddir\doxygen_mainpage: doxygen_mainpage README COPYING | $+ $doxygen_mainpage_generator+build doxygen: doxygen doc\doxygen.config | $builddir\doxygen_mainpage++default ninja.exe
+ src/Test/Ninja/compdb.output view
@@ -0,0 +1,17 @@+[+ {+ "directory": "*",+ "command": "g++ -MMD -MT build\\build.o -MF build\\build.o.d -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti -fno-exceptions -pipe -Wno-missing-field-initializers -DNINJA_PYTHON=\"python.exe\" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501 -c src\\build.cc -o build\\build.o",+ "file": "src\\build.cc"+ },+ {+ "directory": "*",+ "command": "g++ -MMD -MT build\\build_log.o -MF build\\build_log.o.d -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti -fno-exceptions -pipe -Wno-missing-field-initializers -DNINJA_PYTHON=\"python.exe\" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501 -c src\\build_log.cc -o build\\build_log.o",+ "file": "src\\build_log.cc"+ },+ {+ "directory": "*",+ "command": "g++ -MMD -MT build\\clean.o -MF build\\clean.o.d -g -Wall -Wextra -Wno-deprecated -Wno-unused-parameter -fno-rtti -fno-exceptions -pipe -Wno-missing-field-initializers -DNINJA_PYTHON=\"python.exe\" -O2 -DNDEBUG -D_WIN32_WINNT=0x0501 -c src\\clean.cc -o build\\clean.o",+ "file": "src\\clean.cc"+ }+]
+ src/Test/Ninja/lint.ninja view
@@ -0,0 +1,13 @@++rule gen+ command = echo $out > $out++rule run+ command = (echo $out : $out.gen > $out.d) && (echo $out > $out)+ depfile = $out.d++build good: run || good.gen bad.gen+build good.gen: gen++build bad: run | input+build bad.gen: gen
+ src/Test/Ninja/nocreate.ninja view
@@ -0,0 +1,5 @@++rule gen+ command = echo x >> nocreate.log++build nocreate.out: gen nocreate.in
+ src/Test/Ninja/test1.ninja view
@@ -0,0 +1,5 @@++rule run+ command = touch $out++build out1.txt: run
+ src/Test/Ninja/test2.ninja view
@@ -0,0 +1,8 @@++rule run+ command = touch $out++build out2.1: run+build out2.2: run++default out2.2
+ src/Test/Ninja/test3-inc.ninja view
@@ -0,0 +1,3 @@+v5 = i1++build out3.3: dump
+ src/Test/Ninja/test3-sub.ninja view
@@ -0,0 +1,6 @@+v4 = s1+v5 = s1++build out3.4: dump++v5 = s2
+ src/Test/Ninja/test3-unix.ninja view
@@ -0,0 +1,3 @@++rule dump+ command = echo "$v1+$v2+$v3+$v4+$v5" > $out
+ src/Test/Ninja/test3-win.ninja view
@@ -0,0 +1,3 @@++rule dump+ command = cmd /c "echo $v1+$v2+$v3+$v4+$v5 > $out"
+ src/Test/Ninja/test3.ninja view
@@ -0,0 +1,21 @@+++v1 = g1+v5 = g1++include test3-platform.ninja++v1 = g2++build out3.1: dump+ v2 = b1++v1 = g3++subninja test3-sub.ninja++include test3-inc.ninja++build out3.2: dump++v1 = g4
+ src/Test/Ninja/test4.ninja view
@@ -0,0 +1,9 @@++rule run+ command = touch $out++build ./out.txt: run++build dir/../out2.txt: run++build out: phony ./out.txt out2.txt
+ src/Test/Ninja/test5.ninja view
@@ -0,0 +1,5 @@++rule run+ command = touch $out++build output$ file: run
+ src/Test/Ninja/test6-inc.ninja view
@@ -0,0 +1,1 @@+v2 = g2
+ src/Test/Ninja/test6-sub.ninja view
@@ -0,0 +1,1 @@+v2 = g3
+ src/Test/Ninja/test6.ninja view
@@ -0,0 +1,3 @@+v2 = g1+include ${v1}-inc.ninja+subninja ${v1}-sub.ninja
+ src/Test/Oracle.hs view
@@ -0,0 +1,76 @@+{-# LANGUAGE PatternGuards #-}++module Test.Oracle(main) where++import Development.Shake+import Test.Type+import Control.Monad+++main = shaken test $ \args obj -> do+ let f name lhs rhs = (,) name $+ (do addOracle $ \k -> let _ = k `asTypeOf` lhs in return rhs; return ()+ ,let o = obj name ++ ".txt" in do want [o]; o %> \_ -> do v <- askOracleWith lhs rhs; writeFile' o $ show v)+ let tbl = [f "str-bool" "" True+ ,f "str-int" "" (0::Int)+ ,f "bool-str" True ""+ ,f "int-str" (0::Int) ""]++ forM_ args $ \a -> case a of+ '+':x | Just (add,_) <- lookup x tbl -> add+ '*':x | Just (_,use) <- lookup x tbl -> use+ '@':key -> do addOracle $ \() -> return key; return ()+ '%':name -> let o = obj "unit.txt" in do want [o]; o %> \_ -> do {askOracleWith () ""; writeFile' o name}+ '!':name -> do want [obj "rerun"]; obj "rerun" %> \out -> do alwaysRerun; writeFile' out name++test build obj = do+ build ["clean"]++ -- check it rebuilds when it should+ build ["@key","%name"]+ assertContents (obj "unit.txt") "name"+ build ["@key","%test"]+ assertContents (obj "unit.txt") "name"+ build ["@foo","%test"]+ assertContents (obj "unit.txt") "test"++ -- check adding/removing redundant oracles does not trigger a rebuild+ build ["@foo","%newer","+str-bool"]+ assertContents (obj "unit.txt") "test"+ build ["@foo","%newer","+str-int"]+ assertContents (obj "unit.txt") "test"+ build ["@foo","%newer"]+ assertContents (obj "unit.txt") "test"++ -- check always run works+ build ["!foo"]+ assertContents (obj "rerun") "foo"+ build ["!bar"]+ assertContents (obj "rerun") "bar"++ -- check error messages are good+ let errors args err = assertException [err] $ build $ "--quiet" : args++ build ["+str-int","*str-int"]+ errors ["*str-int"] -- Building with an an Oracle that has been removed+ "missing a call to addOracle"++ errors ["*str-bool"] -- Building with an Oracle that I know nothing about+ "missing a call to addOracle"++ build ["+str-int","*str-int"]+ errors ["+str-bool","*str-int"] -- Building with an Oracle that has changed type+ "askOracle is used at the wrong type"++ errors ["+str-int","+str-bool"] -- Two Oracles with the same question type+ "Only one call to addOracle is allowed"++ errors ["+str-int","*str-bool"] -- Using an Oracle at the wrong answer type+ "askOracle is used at the wrong type"++ build ["+str-int","+str-int"] -- Two Oracles work if they aren't used+ errors ["+str-int","+str-int","*str-int"] -- Two Oracles fail if they are used+ "Only one call to addOracle is allowed"++ errors ["+str-int","+str-bool"] -- Two Oracles with the same answer type+ "Only one call to addOracle is allowed"
+ src/Test/OrderOnly.hs view
@@ -0,0 +1,41 @@++module Test.OrderOnly(main) where++import Development.Shake+import Test.Type+++main = shaken test $ \args obj -> do+ want $ map obj args++ obj "bar.txt" %> \out -> do+ alwaysRerun+ writeFile' out =<< liftIO (readFile $ obj "bar.in")++ obj "foo.txt" %> \out -> do+ let src = obj "bar.txt"+ orderOnly [src]+ writeFile' out =<< liftIO (readFile src)+ need [src]++ obj "baz.txt" %> \out -> do+ let src = obj "bar.txt"+ orderOnly [src]+ liftIO $ appendFile out "x"+++test build obj = do+ writeFile (obj "bar.in") "in"+ build ["foo.txt","--sleep"]+ assertContents (obj "foo.txt") "in"+ writeFile (obj "bar.in") "out"+ build ["foo.txt","--sleep"]+ assertContents (obj "foo.txt") "out"++ writeFile (obj "baz.txt") ""+ writeFile (obj "bar.in") "in"+ build ["baz.txt","--sleep"]+ assertContents (obj "baz.txt") "x"+ writeFile (obj "bar.in") "out"+ build ["baz.txt"]+ assertContents (obj "baz.txt") "x"
+ src/Test/Pool.hs view
@@ -0,0 +1,68 @@++module Test.Pool(main) where++import Test.Type+import Development.Shake.Pool++import Control.Concurrent+import Control.Exception hiding (assert)+import Control.Monad+++main = shaken test $ \args obj -> return ()+++test build obj = do+ let wait = sleep 0.01+ forM_ [False,True] $ \deterministic -> do++ -- check that it aims for exactly the limit+ forM_ [1..6] $ \n -> do+ var <- newMVar (0,0) -- (maximum, current)+ runPool deterministic n $ \pool ->+ forM_ [1..5] $ \i ->+ addPool pool $ do+ modifyMVar_ var $ \(mx,now) -> return (max (now+1) mx, now+1)+ wait+ modifyMVar_ var $ \(mx,now) -> return (mx,now-1)+ res <- takeMVar var+ res === (min n 5, 0)++ -- check that exceptions are immediate+ self <- myThreadId+ handle (\(ErrorCall msg) -> msg === "pass") $+ runPool deterministic 3 $ \pool -> do+ addPool pool $ do+ wait+ error "pass"+ addPool pool $ do+ wait >> wait+ throwTo self $ ErrorCall "fail" + wait >> wait -- give chance for a delayed exception++ -- check someone spawned when at zero todo still gets run+ done <- newMVar False+ runPool deterministic 1 $ \pool ->+ addPool pool $ do+ wait+ addPool pool $ do+ wait+ modifyMVar_ done $ const $ return True+ done <- readMVar done+ assert done "Waiting on someone"++ -- check that killing a thread pool stops the tasks, bug 545+ thread <- newEmptyMVar+ done <- newEmptyMVar+ res <- newMVar True+ t <- forkIO $ finally (putMVar done ()) $ runPool deterministic 1 $ \pool ->+ addPool pool $ do+ t <- takeMVar thread+ killThread t+ wait -- allow the thread to die first+ modifyMVar_ res (const $ return False)+ putMVar thread t+ takeMVar done+ wait >> wait >> wait -- allow the bad thread to continue+ res <- readMVar res+ assert res "Early termination"
+ src/Test/Progress.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE DeriveDataTypeable #-}++module Test.Progress(main) where++import Development.Shake.Progress+import Test.Type+import Data.Monoid+import System.Directory+import System.FilePath+++main = shaken test $ \args obj -> return ()+++-- | Given a list of todo times, get out a list of how long is predicted+prog = progEx 10000000000000000+++progEx :: Double -> [Double] -> IO [Double]+progEx mxDone todo = do+ let resolution = 10000 -- Use resolution to get extra detail on the numbers+ let done = scanl (+) 0 $ map (min mxDone . max 0) $ zipWith (-) todo (tail todo)+ let res = progressReplay $ zip (map (*resolution) [1..]) $ tail $ zipWith (\t d -> mempty{timeBuilt=d*resolution,timeTodo=(t*resolution,0)}) todo done+ return $ (0/0) : map ((/ resolution) . actualSecs) res+++test build obj = do+ -- perfect functions should match perfectly+ xs <- prog [10,9..1]+ drop 2 xs === [8,7..1]+ xs <- prog $ map (*5) [10,9..1]+ drop 2 xs === [8,7..1]+ xs <- prog $ map (*0.2) [10,9..1]+ let dp3 x = fromIntegral (round $ x * 1000 :: Int) / 1000+ map dp3 (drop 2 xs) === [8,7..1]++ -- The properties below this line could be weakened++ -- increasing functions can't match+ xs <- prog [5,6,7]+ last xs === 7++ -- the first value must be plausible, or missing+ xs <- prog [187]+ assert (isNaN $ head xs) "No first value"++ -- desirable properties, could be weakened+ xs <- progEx 2 $ 100:map (*2) [10,9..1]+ drop 5 xs === [6,5..1]+ xs <- progEx 1 $ [10,9,100,8,7,6,5,4,3,2,1]+ assert (all (<= 1.5) $ map abs $ zipWith (-) (drop 5 xs) [6,5..1]) "Close"++ -- if no progress is made, don't keep the time going up+ xs <- prog [10,9,8,7,7,7,7,7]+ drop 5 xs === [7,7,7]++ -- if the work rate changes, should somewhat reflect that+ xs <- prog [10,9,8,7,6.5,6,5.5,5]+ assert (last xs > 7.1) "Some discounting (factor=0 would give 7)"++ xs <- getDirectoryContents "src/Test/Progress"+ build $ ["--progress=replay=src/Test/Progress/" ++ x | x <- xs, takeExtension x == ".prog"] +++ ["--no-report","--report=-","--report=" ++ obj "progress.html"]
+ src/Test/Progress/self-clean-j2.prog view
@@ -0,0 +1,62 @@+(1.120224,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 254, countUnknown = 0, countTodo = 145, timeSkipped = 0.0, timeBuilt = 0.8861771221272647, timeUnknown = 0.0, timeTodo = (0.0,145)})+(2.4994998,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 258, countUnknown = 0, countTodo = 147, timeSkipped = 0.0, timeBuilt = 1.259251721901819, timeUnknown = 0.0, timeTodo = (0.0,147)})+(5.156031,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 259, countUnknown = 0, countTodo = 146, timeSkipped = 0.0, timeBuilt = 3.8557707152795047, timeUnknown = 0.0, timeTodo = (0.0,146)})+(6.4472423,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 261, countUnknown = 0, countTodo = 144, timeSkipped = 0.0, timeBuilt = 6.519303449196741, timeUnknown = 0.0, timeTodo = (0.0,144)})+(7.737371,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 262, countUnknown = 0, countTodo = 143, timeSkipped = 0.0, timeBuilt = 9.126777537865564, timeUnknown = 0.0, timeTodo = (0.0,143)})+(9.061503,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 267, countUnknown = 0, countTodo = 138, timeSkipped = 0.0, timeBuilt = 11.739121564431116, timeUnknown = 0.0, timeTodo = (0.0,138)})+(10.368634,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 268, countUnknown = 0, countTodo = 137, timeSkipped = 0.0, timeBuilt = 14.354383119149134, timeUnknown = 0.0, timeTodo = (0.0,137)})+(11.658763,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 272, countUnknown = 0, countTodo = 133, timeSkipped = 0.0, timeBuilt = 16.976646550698206, timeUnknown = 0.0, timeTodo = (0.0,133)})+(12.941892,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 274, countUnknown = 0, countTodo = 131, timeSkipped = 0.0, timeBuilt = 19.57990659098141, timeUnknown = 0.0, timeTodo = (0.0,131)})+(14.22602,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 279, countUnknown = 0, countTodo = 126, timeSkipped = 0.0, timeBuilt = 22.17116750101559, timeUnknown = 0.0, timeTodo = (0.0,126)})+(15.511148,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 282, countUnknown = 0, countTodo = 123, timeSkipped = 0.0, timeBuilt = 24.74242699961178, timeUnknown = 0.0, timeTodo = (0.0,123)})+(16.794277,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 283, countUnknown = 0, countTodo = 122, timeSkipped = 0.0, timeBuilt = 27.31368459085934, timeUnknown = 0.0, timeTodo = (0.0,122)})+(18.085405,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 288, countUnknown = 0, countTodo = 117, timeSkipped = 0.0, timeBuilt = 29.8999453864526, timeUnknown = 0.0, timeTodo = (0.0,117)})+(19.398537,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 294, countUnknown = 0, countTodo = 111, timeSkipped = 0.0, timeBuilt = 32.487208493752405, timeUnknown = 0.0, timeTodo = (0.0,111)})+(21.451742,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 295, countUnknown = 0, countTodo = 110, timeSkipped = 0.0, timeBuilt = 35.872547277016565, timeUnknown = 0.0, timeTodo = (0.0,110)})+(22.761873,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 297, countUnknown = 0, countTodo = 108, timeSkipped = 0.0, timeBuilt = 39.24288571695797, timeUnknown = 0.0, timeTodo = (0.0,108)})+(24.060003,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 298, countUnknown = 0, countTodo = 107, timeSkipped = 0.0, timeBuilt = 41.825143941445276, timeUnknown = 0.0, timeTodo = (0.0,107)})+(25.555153,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 304, countUnknown = 0, countTodo = 101, timeSkipped = 0.0, timeBuilt = 44.66642964701168, timeUnknown = 0.0, timeTodo = (0.0,101)})+(26.868284,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 305, countUnknown = 0, countTodo = 100, timeSkipped = 0.0, timeBuilt = 47.460708745522425, timeUnknown = 0.0, timeTodo = (0.0,100)})+(28.22642,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 306, countUnknown = 0, countTodo = 99, timeSkipped = 0.0, timeBuilt = 50.111974843544886, timeUnknown = 0.0, timeTodo = (0.0,99)})+(29.52355,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 308, countUnknown = 0, countTodo = 97, timeSkipped = 0.0, timeBuilt = 52.788244374794886, timeUnknown = 0.0, timeTodo = (0.0,97)})+(30.82868,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 309, countUnknown = 0, countTodo = 96, timeSkipped = 0.0, timeBuilt = 55.38850606302731, timeUnknown = 0.0, timeTodo = (0.0,96)})+(31.83378,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 309, countUnknown = 0, countTodo = 96, timeSkipped = 0.0, timeBuilt = 55.38850606302731, timeUnknown = 0.0, timeTodo = (0.0,96)})+(33.099907,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 311, countUnknown = 0, countTodo = 94, timeSkipped = 0.0, timeBuilt = 57.70873845438473, timeUnknown = 0.0, timeTodo = (0.0,94)})+(34.455044,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 312, countUnknown = 0, countTodo = 93, timeSkipped = 0.0, timeBuilt = 62.583227284951136, timeUnknown = 0.0, timeTodo = (0.0,93)})+(35.775173,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 323, countUnknown = 0, countTodo = 82, timeSkipped = 0.0, timeBuilt = 65.22149098734371, timeUnknown = 0.0, timeTodo = (0.0,82)})+(37.087307,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 324, countUnknown = 0, countTodo = 81, timeSkipped = 0.0, timeBuilt = 67.89576161722653, timeUnknown = 0.0, timeTodo = (0.0,81)})+(38.39644,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 332, countUnknown = 0, countTodo = 73, timeSkipped = 0.0, timeBuilt = 70.54603017191403, timeUnknown = 0.0, timeTodo = (0.0,73)})+(39.705566,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 336, countUnknown = 0, countTodo = 69, timeSkipped = 0.0, timeBuilt = 73.18129933695309, timeUnknown = 0.0, timeTodo = (0.0,69)})+(41.676765,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 339, countUnknown = 0, countTodo = 66, timeSkipped = 0.0, timeBuilt = 76.48663152079098, timeUnknown = 0.0, timeTodo = (0.0,66)})+(42.969894,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 342, countUnknown = 0, countTodo = 63, timeSkipped = 0.0, timeBuilt = 79.77195943216793, timeUnknown = 0.0, timeTodo = (0.0,63)})+(44.364033,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 345, countUnknown = 0, countTodo = 60, timeSkipped = 0.0, timeBuilt = 82.46222890238278, timeUnknown = 0.0, timeTodo = (0.0,60)})+(45.367134,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 348, countUnknown = 0, countTodo = 57, timeSkipped = 0.0, timeBuilt = 85.15849507669918, timeUnknown = 0.0, timeTodo = (0.0,57)})+(47.0483,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 351, countUnknown = 0, countTodo = 54, timeSkipped = 0.0, timeBuilt = 87.8587666831445, timeUnknown = 0.0, timeTodo = (0.0,54)})+(48.052402,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 351, countUnknown = 0, countTodo = 54, timeSkipped = 0.0, timeBuilt = 87.8587666831445, timeUnknown = 0.0, timeTodo = (0.0,54)})+(49.890587,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 0, countTodo = 51, timeSkipped = 0.0, timeBuilt = 90.69304478983395, timeUnknown = 0.0, timeTodo = (0.0,51)})+(50.894688,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 0, countTodo = 51, timeSkipped = 0.0, timeBuilt = 90.69304478983395, timeUnknown = 0.0, timeTodo = (0.0,51)})+(51.897785,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 0, countTodo = 51, timeSkipped = 0.0, timeBuilt = 90.69304478983395, timeUnknown = 0.0, timeTodo = (0.0,51)})+(54.92909,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 0, countTodo = 48, timeSkipped = 0.0, timeBuilt = 94.47342885355465, timeUnknown = 0.0, timeTodo = (0.0,48)})+(56.23222,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 358, countUnknown = 0, countTodo = 47, timeSkipped = 0.0, timeBuilt = 97.04368794779293, timeUnknown = 0.0, timeTodo = (0.0,47)})+(57.53035,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 360, countUnknown = 0, countTodo = 45, timeSkipped = 0.0, timeBuilt = 100.92107594828121, timeUnknown = 0.0, timeTodo = (0.0,45)})+(58.82748,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 361, countUnknown = 0, countTodo = 44, timeSkipped = 0.0, timeBuilt = 103.52433598856442, timeUnknown = 0.0, timeTodo = (0.0,44)})+(60.104607,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 368, countUnknown = 0, countTodo = 37, timeSkipped = 0.0, timeBuilt = 106.14560521463864, timeUnknown = 0.0, timeTodo = (0.0,37)})+(62.0268,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 369, countUnknown = 0, countTodo = 36, timeSkipped = 0.0, timeBuilt = 109.38093007425778, timeUnknown = 0.0, timeTodo = (0.0,36)})+(63.33293,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 372, countUnknown = 0, countTodo = 33, timeSkipped = 0.0, timeBuilt = 112.58624852518551, timeUnknown = 0.0, timeTodo = (0.0,33)})+(64.62606,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 374, countUnknown = 0, countTodo = 31, timeSkipped = 0.0, timeBuilt = 115.16150487284176, timeUnknown = 0.0, timeTodo = (0.0,31)})+(65.925186,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 379, countUnknown = 0, countTodo = 26, timeSkipped = 0.0, timeBuilt = 117.77476704935543, timeUnknown = 0.0, timeTodo = (0.0,26)})+(68.11641,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 0, countTodo = 18, timeSkipped = 0.0, timeBuilt = 122.62825597147457, timeUnknown = 0.0, timeTodo = (0.0,18)})+(69.121506,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 0, countTodo = 18, timeSkipped = 0.0, timeBuilt = 122.62825597147457, timeUnknown = 0.0, timeTodo = (0.0,18)})+(70.77867,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 390, countUnknown = 0, countTodo = 15, timeSkipped = 0.0, timeBuilt = 125.30251897196285, timeUnknown = 0.0, timeTodo = (0.0,15)})+(74.353035,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 393, countUnknown = 0, countTodo = 12, timeSkipped = 0.0, timeBuilt = 127.54874242166989, timeUnknown = 0.0, timeTodo = (0.0,12)})+(75.35613,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 396, countUnknown = 0, countTodo = 9, timeSkipped = 0.0, timeBuilt = 130.15401280741207, timeUnknown = 0.0, timeTodo = (0.0,9)})+(76.85028,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 399, countUnknown = 0, countTodo = 6, timeSkipped = 0.0, timeBuilt = 133.99539006571285, timeUnknown = 0.0, timeTodo = (0.0,6)})+(79.081505,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 402, countUnknown = 0, countTodo = 3, timeSkipped = 0.0, timeBuilt = 136.22862065653317, timeUnknown = 0.0, timeTodo = (0.0,3)})+(81.25272,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(82.260826,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(83.26492,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(84.27003,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(85.274124,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(86.28023,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(87.284325,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})+(88.28843,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 0, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.41584599833004, timeUnknown = 0.0, timeTodo = (0.0,1)})
+ src/Test/Progress/self-rebuild-j2.prog view
@@ -0,0 +1,56 @@+(3.6053605,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 258, countUnknown = 1, countTodo = 147, timeSkipped = 0.0, timeBuilt = 1.054105345858261, timeUnknown = 0.0, timeTodo = (135.01951599121094,0)})+(4.8964896,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 259, countUnknown = 1, countTodo = 146, timeSkipped = 0.0, timeBuilt = 3.6373634978663176, timeUnknown = 0.0, timeTodo = (132.3802523612976,0)})+(6.189619,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 260, countUnknown = 1, countTodo = 145, timeSkipped = 0.0, timeBuilt = 6.2686262771021575, timeUnknown = 0.0, timeTodo = (129.85099935531616,0)})+(7.4677467,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 262, countUnknown = 1, countTodo = 143, timeSkipped = 0.0, timeBuilt = 8.854884450091049, timeUnknown = 0.0, timeTodo = (127.25373983383179,0)})+(8.742874,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 268, countUnknown = 1, countTodo = 137, timeSkipped = 0.0, timeBuilt = 11.444143597735092, timeUnknown = 0.0, timeTodo = (124.70048475265503,0)})+(10.016002,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 271, countUnknown = 1, countTodo = 134, timeSkipped = 0.0, timeBuilt = 16.5466540500056, timeUnknown = 0.0, timeTodo = (119.64597797393799,0)})+(11.30813,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 271, countUnknown = 1, countTodo = 134, timeSkipped = 0.0, timeBuilt = 16.5466540500056, timeUnknown = 0.0, timeTodo = (119.64597797393799,0)})+(12.59526,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 276, countUnknown = 1, countTodo = 129, timeSkipped = 0.0, timeBuilt = 19.123910252703354, timeUnknown = 0.0, timeTodo = (117.0657205581665,0)})+(13.876388,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 278, countUnknown = 1, countTodo = 127, timeSkipped = 0.0, timeBuilt = 21.708168332232162, timeUnknown = 0.0, timeTodo = (114.43845868110657,0)})+(15.173517,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 280, countUnknown = 1, countTodo = 125, timeSkipped = 0.0, timeBuilt = 24.27642471040599, timeUnknown = 0.0, timeTodo = (111.89620327949524,0)})+(16.456646,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 282, countUnknown = 1, countTodo = 123, timeSkipped = 0.0, timeBuilt = 26.85868198121898, timeUnknown = 0.0, timeTodo = (109.3659496307373,0)})+(17.726772,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 284, countUnknown = 1, countTodo = 121, timeSkipped = 0.0, timeBuilt = 29.442940060747787, timeUnknown = 0.0, timeTodo = (106.83069705963135,0)})+(19.027903,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 288, countUnknown = 1, countTodo = 117, timeSkipped = 0.0, timeBuilt = 32.00519592012279, timeUnknown = 0.0, timeTodo = (104.28944301605225,0)})+(20.345034,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 292, countUnknown = 1, countTodo = 113, timeSkipped = 0.0, timeBuilt = 34.586452786577865, timeUnknown = 0.0, timeTodo = (101.74619007110596,0)})+(21.648165,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 300, countUnknown = 1, countTodo = 105, timeSkipped = 0.0, timeBuilt = 37.32872611726634, timeUnknown = 0.0, timeTodo = (99.18993377685547,0)})+(23.717371,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 301, countUnknown = 1, countTodo = 104, timeSkipped = 0.0, timeBuilt = 40.75507003511302, timeUnknown = 0.0, timeTodo = (96.41965675354004,0)})+(25.022503,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 303, countUnknown = 1, countTodo = 102, timeSkipped = 0.0, timeBuilt = 44.12840873445384, timeUnknown = 0.0, timeTodo = (93.89340400695801,0)})+(26.289629,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 304, countUnknown = 1, countTodo = 101, timeSkipped = 0.0, timeBuilt = 46.6976664706599, timeUnknown = 0.0, timeTodo = (91.36415100097656,0)})+(27.576757,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 305, countUnknown = 1, countTodo = 100, timeSkipped = 0.0, timeBuilt = 49.27292472566478, timeUnknown = 0.0, timeTodo = (88.50186347961426,0)})+(29.49495,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 308, countUnknown = 1, countTodo = 97, timeSkipped = 0.0, timeBuilt = 52.47924644197337, timeUnknown = 0.0, timeTodo = (84.93850708007813,0)})+(31.11511,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 311, countUnknown = 1, countTodo = 94, timeSkipped = 0.0, timeBuilt = 56.04560119356029, timeUnknown = 0.0, timeTodo = (81.36915397644043,0)})+(32.42124,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 313, countUnknown = 1, countTodo = 92, timeSkipped = 0.0, timeBuilt = 58.938888852251694, timeUnknown = 0.0, timeTodo = (78.84289932250977,0)})+(33.68837,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 315, countUnknown = 1, countTodo = 90, timeSkipped = 0.0, timeBuilt = 61.51514465059154, timeUnknown = 0.0, timeTodo = (75.96561431884766,0)})+(34.961494,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 322, countUnknown = 1, countTodo = 83, timeSkipped = 0.0, timeBuilt = 64.10740501130931, timeUnknown = 0.0, timeTodo = (73.41636085510254,0)})+(36.245625,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 330, countUnknown = 1, countTodo = 75, timeSkipped = 0.0, timeBuilt = 66.67165786470287, timeUnknown = 0.0, timeTodo = (70.8551082611084,0)})+(37.545753,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 331, countUnknown = 1, countTodo = 74, timeSkipped = 0.0, timeBuilt = 69.22791320527904, timeUnknown = 0.0, timeTodo = (68.3188533782959,0)})+(38.944893,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 336, countUnknown = 1, countTodo = 69, timeSkipped = 0.0, timeBuilt = 71.91318160737865, timeUnknown = 0.0, timeTodo = (65.60857582092285,0)})+(40.345036,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 337, countUnknown = 1, countTodo = 68, timeSkipped = 0.0, timeBuilt = 74.72146255220287, timeUnknown = 0.0, timeTodo = (62.849300384521484,0)})+(41.651165,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 340, countUnknown = 1, countTodo = 65, timeSkipped = 0.0, timeBuilt = 77.43573409761302, timeUnknown = 0.0, timeTodo = (60.147029876708984,0)})+(42.9913,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 345, countUnknown = 1, countTodo = 60, timeSkipped = 0.0, timeBuilt = 80.11199981416576, timeUnknown = 0.0, timeTodo = (57.615779876708984,0)})+(44.28843,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 347, countUnknown = 1, countTodo = 58, timeSkipped = 0.0, timeBuilt = 82.76326781953685, timeUnknown = 0.0, timeTodo = (55.096527099609375,0)})+(45.844585,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 350, countUnknown = 1, countTodo = 55, timeSkipped = 0.0, timeBuilt = 85.57555038179271, timeUnknown = 0.0, timeTodo = (53.285343170166016,0)})+(46.848686,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 88.44083816255443, timeUnknown = 0.0, timeTodo = (50.76008987426758,0)})+(47.852783,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 88.44083816255443, timeUnknown = 0.0, timeTodo = (50.76008987426758,0)})+(50.848083,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 1, countTodo = 48, timeSkipped = 0.0, timeBuilt = 92.16721374238841, timeUnknown = 0.0, timeTodo = (48.103824615478516,0)})+(52.852283,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 358, countUnknown = 1, countTodo = 47, timeSkipped = 0.0, timeBuilt = 95.5145495578181, timeUnknown = 0.0, timeTodo = (45.494564056396484,0)})+(54.130413,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 362, countUnknown = 1, countTodo = 43, timeSkipped = 0.0, timeBuilt = 100.13300735200755, timeUnknown = 0.0, timeTodo = (41.70818328857422,0)})+(55.41054,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 363, countUnknown = 1, countTodo = 42, timeSkipped = 0.0, timeBuilt = 102.67526275361888, timeUnknown = 0.0, timeTodo = (39.17192840576172,0)})+(56.414642,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 369, countUnknown = 1, countTodo = 36, timeSkipped = 0.0, timeBuilt = 105.25251800264232, timeUnknown = 0.0, timeTodo = (36.63368225097656,0)})+(59.073906,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 372, countUnknown = 1, countTodo = 33, timeSkipped = 0.0, timeBuilt = 107.67676574434154, timeUnknown = 0.0, timeTodo = (34.10843276977539,0)})+(60.356033,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 374, countUnknown = 1, countTodo = 31, timeSkipped = 0.0, timeBuilt = 110.21202117647044, timeUnknown = 0.0, timeTodo = (31.546173095703125,0)})+(61.641163,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 375, countUnknown = 1, countTodo = 30, timeSkipped = 0.0, timeBuilt = 114.02240401948802, timeUnknown = 0.0, timeTodo = (28.913909912109375,0)})+(62.92029,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 381, countUnknown = 1, countTodo = 24, timeSkipped = 0.0, timeBuilt = 116.60766250337474, timeUnknown = 0.0, timeTodo = (26.366653442382813,0)})+(65.09751,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 121.40914184297435, timeUnknown = 0.0, timeTodo = (22.06322479248047,0)})+(66.10161,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 121.40914184297435, timeUnknown = 0.0, timeTodo = (22.06322479248047,0)})+(67.678764,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 390, countUnknown = 1, countTodo = 15, timeSkipped = 0.0, timeBuilt = 123.98239928926341, timeUnknown = 0.0, timeTodo = (19.453964233398438,0)})+(71.20812,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 393, countUnknown = 1, countTodo = 12, timeSkipped = 0.0, timeBuilt = 126.19761687959544, timeUnknown = 0.0, timeTodo = (17.226730346679688,0)})+(72.21122,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 396, countUnknown = 1, countTodo = 9, timeSkipped = 0.0, timeBuilt = 128.785888974322, timeUnknown = 0.0, timeTodo = (14.163421630859375,0)})+(73.53935,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 399, countUnknown = 1, countTodo = 6, timeSkipped = 0.0, timeBuilt = 133.6913836642634, timeUnknown = 0.0, timeTodo = (11.642166137695313,0)})+(75.757576,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 402, countUnknown = 1, countTodo = 3, timeSkipped = 0.0, timeBuilt = 135.9266131564509, timeUnknown = 0.0, timeTodo = (8.530860900878906,0)})+(77.91779,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})+(78.92289,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})+(79.925995,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})+(80.93109,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})+(81.93419,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})+(82.93929,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 138.08883697236888, timeUnknown = 0.0, timeTodo = (6.776679992675781,0)})
+ src/Test/Progress/self-zero-j2.prog view
@@ -0,0 +1,57 @@+(1.020102,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 254, countUnknown = 4, countTodo = 148, timeSkipped = 0.0, timeBuilt = 0.7620761110447347, timeUnknown = 2.0004000980407e-3, timeTodo = (146.13152742385864,0)})+(3.7443745,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 258, countUnknown = 1, countTodo = 147, timeSkipped = 0.0, timeBuilt = 1.0521051175892353, timeUnknown = 0.0, timeTodo = (145.76045322418213,0)})+(5.032503,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 260, countUnknown = 1, countTodo = 145, timeSkipped = 0.0, timeBuilt = 3.678367782384157, timeUnknown = 0.0, timeTodo = (143.16193342208862,0)})+(6.339634,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 261, countUnknown = 1, countTodo = 144, timeSkipped = 0.0, timeBuilt = 6.317631412297487, timeUnknown = 0.0, timeTodo = (140.56067323684692,0)})+(7.6067605,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 262, countUnknown = 1, countTodo = 143, timeSkipped = 0.0, timeBuilt = 8.911890674382448, timeUnknown = 0.0, timeTodo = (137.99141645431519,0)})+(8.867887,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 265, countUnknown = 1, countTodo = 140, timeSkipped = 0.0, timeBuilt = 11.489148784428835, timeUnknown = 0.0, timeTodo = (135.31988191604614,0)})+(10.124012,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 266, countUnknown = 1, countTodo = 139, timeSkipped = 0.0, timeBuilt = 14.01840179041028, timeUnknown = 0.0, timeTodo = (132.74862432479858,0)})+(11.394139,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 270, countUnknown = 1, countTodo = 135, timeSkipped = 0.0, timeBuilt = 16.545654464513063, timeUnknown = 0.0, timeTodo = (130.13927960395813,0)})+(12.661266,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 278, countUnknown = 1, countTodo = 127, timeSkipped = 0.0, timeBuilt = 19.09290998056531, timeUnknown = 0.0, timeTodo = (127.51380348205566,0)})+(13.928392,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 280, countUnknown = 1, countTodo = 125, timeSkipped = 0.0, timeBuilt = 21.638164687901735, timeUnknown = 0.0, timeTodo = (124.94054412841797,0)})+(15.19352,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 283, countUnknown = 1, countTodo = 122, timeSkipped = 0.0, timeBuilt = 24.176418472081423, timeUnknown = 0.0, timeTodo = (122.32628202438354,0)})+(16.462646,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 284, countUnknown = 1, countTodo = 121, timeSkipped = 0.0, timeBuilt = 26.708671737462282, timeUnknown = 0.0, timeTodo = (119.71102046966553,0)})+(17.723772,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 286, countUnknown = 1, countTodo = 119, timeSkipped = 0.0, timeBuilt = 29.24492471292615, timeUnknown = 0.0, timeTodo = (117.13076210021973,0)})+(18.9989,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 290, countUnknown = 1, countTodo = 115, timeSkipped = 0.0, timeBuilt = 31.782178092747927, timeUnknown = 0.0, timeTodo = (114.32748413085938,0)})+(20.265026,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 294, countUnknown = 1, countTodo = 111, timeSkipped = 0.0, timeBuilt = 34.328432250767946, timeUnknown = 0.0, timeTodo = (110.95114421844482,0)})+(21.525152,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 296, countUnknown = 1, countTodo = 109, timeSkipped = 0.0, timeBuilt = 36.87168710306287, timeUnknown = 0.0, timeTodo = (108.3658857345581,0)})+(22.792278,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 297, countUnknown = 1, countTodo = 108, timeSkipped = 0.0, timeBuilt = 39.39593904092908, timeUnknown = 0.0, timeTodo = (105.79362773895264,0)})+(24.09941,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 301, countUnknown = 1, countTodo = 104, timeSkipped = 0.0, timeBuilt = 41.934190917760134, timeUnknown = 0.0, timeTodo = (103.46539211273193,0)})+(25.552555,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 307, countUnknown = 1, countTodo = 98, timeSkipped = 0.0, timeBuilt = 44.71846978738904, timeUnknown = 0.0, timeTodo = (100.06105041503906,0)})+(27.156715,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 310, countUnknown = 1, countTodo = 95, timeSkipped = 0.0, timeBuilt = 47.48474519327283, timeUnknown = 0.0, timeTodo = (97.22976875305176,0)})+(28.427843,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 311, countUnknown = 1, countTodo = 94, timeSkipped = 0.0, timeBuilt = 50.347032714635134, timeUnknown = 0.0, timeTodo = (94.5565013885498,0)})+(29.692968,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 312, countUnknown = 1, countTodo = 93, timeSkipped = 0.0, timeBuilt = 53.222318816930056, timeUnknown = 0.0, timeTodo = (91.93223762512207,0)})+(30.960096,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 314, countUnknown = 1, countTodo = 91, timeSkipped = 0.0, timeBuilt = 55.76357476785779, timeUnknown = 0.0, timeTodo = (89.2559642791748,0)})+(32.22322,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 317, countUnknown = 1, countTodo = 88, timeSkipped = 0.0, timeBuilt = 58.305828262120485, timeUnknown = 0.0, timeTodo = (86.59769439697266,0)})+(33.50235,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 321, countUnknown = 1, countTodo = 84, timeSkipped = 0.0, timeBuilt = 60.847080398350954, timeUnknown = 0.0, timeTodo = (83.98942756652832,0)})+(34.50545,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 321, countUnknown = 1, countTodo = 84, timeSkipped = 0.0, timeBuilt = 60.847080398350954, timeUnknown = 0.0, timeTodo = (83.98942756652832,0)})+(35.778576,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 327, countUnknown = 1, countTodo = 78, timeSkipped = 0.0, timeBuilt = 64.42744653299451, timeUnknown = 0.0, timeTodo = (79.1019344329834,0)})+(37.039703,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 331, countUnknown = 1, countTodo = 74, timeSkipped = 0.0, timeBuilt = 67.99280183389783, timeUnknown = 0.0, timeTodo = (75.79260063171387,0)})+(38.30183,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 332, countUnknown = 1, countTodo = 73, timeSkipped = 0.0, timeBuilt = 70.5080529935658, timeUnknown = 0.0, timeTodo = (73.16133689880371,0)})+(39.60196,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 337, countUnknown = 1, countTodo = 68, timeSkipped = 0.0, timeBuilt = 73.04030625894666, timeUnknown = 0.0, timeTodo = (70.54007148742676,0)})+(40.9971,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 341, countUnknown = 1, countTodo = 64, timeSkipped = 0.0, timeBuilt = 75.7465783841908, timeUnknown = 0.0, timeTodo = (67.84580421447754,0)})+(42.251225,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 343, countUnknown = 1, countTodo = 62, timeSkipped = 0.0, timeBuilt = 78.44684617593884, timeUnknown = 0.0, timeTodo = (64.56347465515137,0)})+(43.51035,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 348, countUnknown = 1, countTodo = 57, timeSkipped = 0.0, timeBuilt = 80.97609345987439, timeUnknown = 0.0, timeTodo = (61.85720443725586,0)})+(45.31053,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 85.3115312345326, timeUnknown = 0.0, timeTodo = (56.32666015625,0)})+(46.31663,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 354, countUnknown = 1, countTodo = 51, timeSkipped = 0.0, timeBuilt = 85.3115312345326, timeUnknown = 0.0, timeTodo = (56.32666015625,0)})+(47.953796,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 1, countTodo = 48, timeSkipped = 0.0, timeBuilt = 87.96779649332166, timeUnknown = 0.0, timeTodo = (52.5462760925293,0)})+(49.22192,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 357, countUnknown = 1, countTodo = 48, timeSkipped = 0.0, timeBuilt = 87.96779649332166, timeUnknown = 0.0, timeTodo = (52.5462760925293,0)})+(50.483047,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 358, countUnknown = 1, countTodo = 47, timeSkipped = 0.0, timeBuilt = 90.48504655435681, timeUnknown = 0.0, timeTodo = (49.943016052246094,0)})+(51.742172,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 362, countUnknown = 1, countTodo = 43, timeSkipped = 0.0, timeBuilt = 94.27242677286267, timeUnknown = 0.0, timeTodo = (46.054622650146484,0)})+(53.0143,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 364, countUnknown = 1, countTodo = 41, timeSkipped = 0.0, timeBuilt = 96.79567353799939, timeUnknown = 0.0, timeTodo = (43.455360412597656,0)})+(54.279427,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 365, countUnknown = 1, countTodo = 40, timeSkipped = 0.0, timeBuilt = 99.32792680338025, timeUnknown = 0.0, timeTodo = (40.88410568237305,0)})+(55.549553,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 368, countUnknown = 1, countTodo = 37, timeSkipped = 0.0, timeBuilt = 101.87118165567517, timeUnknown = 0.0, timeTodo = (38.3088493347168,0)})+(56.90669,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 371, countUnknown = 1, countTodo = 34, timeSkipped = 0.0, timeBuilt = 104.48744599893689, timeUnknown = 0.0, timeTodo = (35.06652069091797,0)})+(58.179817,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 372, countUnknown = 1, countTodo = 33, timeSkipped = 0.0, timeBuilt = 107.11970918253064, timeUnknown = 0.0, timeTodo = (32.46625900268555,0)})+(59.453945,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 380, countUnknown = 1, countTodo = 25, timeSkipped = 0.0, timeBuilt = 109.69997041299939, timeUnknown = 0.0, timeTodo = (29.24193572998047,0)})+(61.17312,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 114.0083963163197, timeUnknown = 0.0, timeTodo = (24.391448974609375,0)})+(62.17922,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 387, countUnknown = 1, countTodo = 18, timeSkipped = 0.0, timeBuilt = 114.0083963163197, timeUnknown = 0.0, timeTodo = (24.391448974609375,0)})+(63.787376,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 390, countUnknown = 1, countTodo = 15, timeSkipped = 0.0, timeBuilt = 116.61765687540174, timeUnknown = 0.0, timeTodo = (21.717185974121094,0)})+(67.25372,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 393, countUnknown = 1, countTodo = 12, timeSkipped = 0.0, timeBuilt = 118.84489076212049, timeUnknown = 0.0, timeTodo = (19.470962524414063,0)})+(69.114914,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 399, countUnknown = 1, countTodo = 6, timeSkipped = 0.0, timeBuilt = 124.42945497110486, timeUnknown = 0.0, timeTodo = (13.024314880371094,0)})+(70.91309,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 402, countUnknown = 1, countTodo = 3, timeSkipped = 0.0, timeBuilt = 127.54076020792127, timeUnknown = 0.0, timeTodo = (10.791084289550781,0)})+(72.67527,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})+(73.68037,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})+(74.683464,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})+(75.68657,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})+(76.68967,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})+(77.69477,Progress {isFailure = Nothing, countSkipped = 0, countBuilt = 404, countUnknown = 1, countTodo = 1, timeSkipped = 0.0, timeBuilt = 129.2949411161244, timeUnknown = 0.0, timeTodo = (8.603858947753906,0)})
+ src/Test/Random.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE PatternGuards #-}++module Test.Random(main) where++import Development.Shake+import Numeric.Extra+import Test.Type+import Control.Exception.Extra+import Control.Monad+import Data.List+import Data.Maybe+import System.Environment+import System.Exit+import System.Random+import General.Extra+import qualified System.IO.Extra as IO+import System.Time.Extra+++inputRange = [1..10]++data Value = Single Int | Multiple [[Value]]+ deriving (Read,Show,Eq)++data Source = Input Int | Output Int | Bang+ deriving (Read,Show)++data Logic = Logic Int [[Source]]+ | Want [Int]+ deriving (Read,Show)+++main = shaken test $ \args obj -> do+ let toFile (Input i) = obj $ "input-" ++ show i ++ ".txt"+ toFile (Output i) = obj $ "output-" ++ show i ++ ".txt"+ toFile Bang = error "BANG"++ let randomSleep = liftIO $ do+ i <- randomRIO (0, 25)+ sleep $ intToDouble i / 100++ forM_ (map read $ filter (isNothing . asDuration) args) $ \x -> case x of+ Want xs -> want $ map (toFile . Output) xs+ Logic out srcs -> toFile (Output out) %> \out -> do+ res <- fmap (show . Multiple) $ forM srcs $ \src -> do+ randomSleep+ need $ map toFile src+ mapM (liftIO . fmap read . IO.readFile' . toFile) src+ randomSleep+ writeFileChanged out res+++asDuration :: String -> Maybe Double+asDuration x+ | "s" `isSuffixOf` x, [(i,"")] <- reads $ init x = Just i+ | "m" `isSuffixOf` x, [(i,"")] <- reads $ init x = Just $ i * 60+ | otherwise = Nothing+++test build obj = do+ limit <- do+ args <- getArgs+ let bound = listToMaybe $ reverse $ mapMaybe asDuration args+ time <- offsetTime+ return $ when (isJust bound) $ do+ now <- time+ when (now > fromJust bound) exitSuccess++ forM_ [1..] $ \count -> do+ limit+ putStrLn $ "* PERFORMING RANDOM TEST " ++ show count+ build ["clean"]+ build [] -- to create the directory+ forM_ inputRange $ \i ->+ writeFile (obj $ "input-" ++ show i ++ ".txt") $ show $ Single i+ logic <- randomLogic+ runLogic [] logic+ chng <- filterM (const randomIO) inputRange + forM_ chng $ \i ->+ writeFile (obj $ "input-" ++ show i ++ ".txt") $ show $ Single $ negate i+ runLogic chng logic+ forM_ inputRange $ \i ->+ writeFile (obj $ "input-" ++ show i ++ ".txt") $ show $ Single i+ logicBang <- addBang =<< addBang logic+ j <- randomRIO (1::Int,8)+ res <- try_ $ build $ "--exception" : ("-j" ++ show j) : map show (logicBang ++ [Want [i | Logic i _ <- logicBang]])+ case res of+ Left err+ | "BANG" `isInfixOf` show err -> return () -- error I expected+ | otherwise -> error $ "UNEXPECTED ERROR: " ++ show err+ _ -> return () -- occasionally we only put BANG in places with no dependenies that don't get rebuilt+ runLogic [] $ logic ++ [Want [i | Logic i _ <- logic]]+ where+ runLogic :: [Int] -> [Logic] -> IO ()+ runLogic negated xs = do+ let poss = [i | Logic i _ <- xs]+ i <- randomRIO (0, 7)+ wants <- replicateM i $ do+ i <- randomRIO (0, 5)+ replicateM i $ randomElem poss+ sleepFileTime+ j <- randomRIO (1::Int,8)+ build $ ("-j" ++ show j) : map show (xs ++ map Want wants)++ let value i = case [ys | Logic j ys <- xs, j == i] of+ [ys] -> Multiple $ flip map ys $ map $ \i -> case i of+ Input i -> Single $ if i `elem` negated then negate i else i+ Output i -> value i+ forM_ (concat wants) $ \i -> do+ let wanted = value i+ got <- fmap read $ IO.readFile' $ obj $ "output-" ++ show i ++ ".txt"+ when (wanted /= got) $+ error $ "INCORRECT VALUE for " ++ show i+++addBang :: [Logic] -> IO [Logic]+addBang xs = do+ i <- randomRIO (0, length xs - 1)+ let (before,now:after) = splitAt i xs+ now <- f now+ return $ before ++ now : after+ where+ f (Logic log xs) = do+ i <- randomRIO (0, length xs)+ let (before,after) = splitAt i xs+ return $ Logic log $ before ++ [Bang] : after+++randomLogic :: IO [Logic] -- only Logic constructors+randomLogic = do+ rules <- randomRIO (1,100)+ f rules $ map Input inputRange+ where+ f 0 avail = return []+ f i avail = do+ needs <- randomRIO (0,3)+ xs <- replicateM needs $ do+ ns <- randomRIO (0,3)+ replicateM ns $ randomElem avail+ let r = Logic i xs+ fmap (r:) $ f (i-1) (Output i:avail)
+ src/Test/Resources.hs view
@@ -0,0 +1,33 @@++module Test.Resources(main) where++import Development.Shake+import Test.Type+import Control.Monad+import Data.IORef+++main extra = do+ let cap = 2++ ref <- newIORef 0+ flip (shaken test) extra $ \args obj -> do+ want $ map obj ["file1.txt","file2.txt","file3.txt","file4.txt"]+ res <- newResource "test" cap+ res2 <- newResource "test" cap+ unless (res < res2 || res2 < res) $ error "Resources should have a good ordering"+ obj "*.txt" %> \out ->+ withResource res 1 $ do+ old <- liftIO $ atomicModifyIORef ref $ \i -> (i+1,i)+ when (old >= cap) $ error "Too many resources in use at one time"+ liftIO $ sleep 0.1+ liftIO $ atomicModifyIORef ref $ \i -> (i-1,i)+ writeFile' out ""++test build obj = do+ build ["clean"]+ build ["-j2"]+ build ["clean"]+ build ["-j4"]+ build ["clean"]+ build ["-j10"]
+ src/Test/Self.hs view
@@ -0,0 +1,87 @@+{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-}++module Test.Self(main) where++import Development.Shake+import Development.Shake.Classes+import Development.Shake.FilePath+import Test.Type++import Control.Monad+import Data.Char+import Data.List.Extra+import System.Info+++newtype GhcPkg = GhcPkg () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+newtype GhcFlags = GhcFlags () deriving (Show,Typeable,Eq,Hashable,Binary,NFData)+++main = shaken noTest $ \args obj -> do+ let moduleToFile ext xs = map (\x -> if x == '.' then '/' else x) xs <.> ext+ want $ if null args then [obj "Main" <.> exe] else args++ -- fixup to cope with Cabal's generated files+ let fixPaths x = if x == "Paths_shake.hs" then "Paths.hs" else x++ ghcPkg <- addOracle $ \GhcPkg{} -> do+ Stdout out <- quietly $ cmd "ghc-pkg list --simple-output"+ return $ words out++ ghcFlags <- addOracle $ \GhcFlags{} -> do+ pkgs <- readFileLines $ obj ".pkgs"+ return $ map ("-package=" ++) pkgs++ let ghc args = do+ -- since ghc-pkg includes the ghc package, it changes if the version does+ ghcPkg $ GhcPkg ()+ flags <- ghcFlags $ GhcFlags ()+ cmd "ghc" flags args++ obj "Main" <.> exe %> \out -> do+ src <- readFileLines $ obj "Run.deps"+ let os = map (obj . moduleToFile "o") $ "Run" : src+ need os+ ghc $ ["-o",out] ++ os++ obj "/*.deps" %> \out -> do+ dep <- readFileLines $ out -<.> "dep"+ let xs = map (obj . moduleToFile "deps") dep+ need xs+ ds <- fmap (nub . sort . (++) dep . concat) $ mapM readFileLines xs+ writeFileLines out ds++ obj "/*.dep" %> \out -> do+ src <- readFile' $ "src" </> fixPaths (unobj $ out -<.> "hs")+ let xs = hsImports src+ xs <- filterM (doesFileExist . ("src" </>) . fixPaths . moduleToFile "hs") xs+ writeFileLines out xs++ [obj "/*.o",obj "/*.hi"] &%> \[out,_] -> do+ deps <- readFileLines $ out -<.> "deps"+ let hs = "src" </> fixPaths (unobj $ out -<.> "hs")+ need $ hs : map (obj . moduleToFile "hi") deps+ ghc $ ["-c",hs,"-isrc","-main-is","Run.main"+ ,"-hide-all-packages","-odir=output/self","-hidir=output/self","-i=output/self"] +++ ["-DPORTABLE","-fwarn-unused-imports","-Werror"] -- to test one CPP branch++ obj ".pkgs" %> \out -> do+ src <- readFile' "shake.cabal"+ writeFileLines out $ sort $ cabalBuildDepends src+++---------------------------------------------------------------------+-- GRAB INFORMATION FROM FILES++hsImports :: String -> [String]+hsImports xs = [ takeWhile (\x -> isAlphaNum x || x `elem` "._") $ dropWhile (not . isUpper) x+ | x <- concatMap (wordsBy (== ';')) $ lines xs, "import " `isPrefixOf` trim x]+++-- FIXME: Should actually parse the list from the contents of the .cabal file+cabalBuildDepends :: String -> [String]+cabalBuildDepends _ = packages ++ ["unix" | os /= "mingw32"]++packages = words $+ "base transformers binary unordered-containers hashable time old-time bytestring " +++ "filepath directory process deepseq random utf8-string extra js-jquery js-flot"
+ src/Test/Tar.hs view
@@ -0,0 +1,13 @@++module Test.Tar(main) where++import Development.Shake+import Test.Type+++main = shaken noTest $ \args obj -> do+ want [obj "result.tar"]+ obj "result.tar" %> \out -> do+ contents <- readFileLines "src/Test/Tar/list.txt"+ need contents+ cmd "tar -cf" [out] contents
+ src/Test/Tar/list.txt view
@@ -0,0 +1,3 @@+src/Test/Tar.hs+src/Run.hs+src/Test/Tar/list.txt
+ src/Test/Throttle.hs view
@@ -0,0 +1,30 @@++module Test.Throttle(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+import Control.Exception.Extra hiding (assert)+import Control.Monad.Extra+import System.Time.Extra+++main = shaken test $ \args obj -> do+ res <- newThrottle "test" 2 0.4+ want $ map obj ["file1.1","file2.1","file3.2","file4.1","file5.2"]+ obj "*.*" %> \out -> do+ withResource res (read $ drop 1 $ takeExtension out) $+ when (takeBaseName out == "file3") $ liftIO $ sleep 0.2+ writeFile' out ""++test build obj = do+ forM_ [[],["-j8"]] $ \flags -> do+ -- we are sometimes over the window if the machine is "a bit loaded" at some particular time+ -- therefore we rerun the test three times, and only fail if it fails on all of them+ retry 3 $ do+ build ["clean"]+ (s, _) <- duration $ build []+ -- the 0.1s cap is a guess at an upper bound for how long everything else should take+ -- and should be raised on slower machines+ assert (s >= 1.4 && s < 1.6) $+ "Bad throttling, expected to take 0.7s + computation time (cap of 0.1s), took " ++ show s ++ "s"
+ src/Test/Type.hs view
@@ -0,0 +1,211 @@++module Test.Type(sleep, module Test.Type) where++import Development.Shake hiding (copyFileChanged)+import Development.Shake.Rule() -- ensure the module gets imported, and thus tested+import General.String+import Development.Shake.FileInfo+import Development.Shake.FilePath++import Control.Exception.Extra hiding (assert)+import Control.Monad.Extra+import Data.Char+import Data.List+import Data.Maybe+import qualified Data.ByteString as BS+import System.Directory as IO+import System.Environment+import System.Random+import System.Console.GetOpt+import System.IO+import System.Time.Extra+++shaken+ :: (([String] -> IO ()) -> (String -> String) -> IO ())+ -> ([String] -> (String -> String) -> Rules ())+ -> IO ()+ -> IO ()+shaken test rules sleeper = do+ name:args <- getArgs+ when ("--sleep" `elem` args) sleeper+ putStrLn $ "## BUILD " ++ unwords (name:args)+ args <- return $ delete "--sleep" args+ let out = "output/" ++ name ++ "/"+ createDirectoryIfMissing True out+ case args of+ "test":extra -> do+ putStrLn $ "## TESTING " ++ name+ -- if the extra arguments are not --quiet/--loud it's probably going to go wrong+ let obj x = if "/" `isPrefixOf` x then init out ++ x else out ++ x+ test (\args -> withArgs (name:args ++ extra) $ shaken test rules sleeper) obj+ putStrLn $ "## FINISHED TESTING " ++ name+ "clean":_ -> removeDirectoryRecursive out+{-+ "lint":args -> do+ let dbfile = out ++ ".database"+ tempfile = "output/" ++ name ++ ".database"+ b <- IO.doesFileExist dbfile+ when b $ renameFile dbfile tempfile+ removeDirectoryRecursive out+ createDirectoryIfMissing True out+ when b $ renameFile tempfile dbfile+ shake shakeOptions{shakeFiles=out, shakeLint=True} $ rules args (out++)+-}++ "perturb":args -> forever $ do+ del <- removeFilesRandom out+ threads <- randomRIO (1,4)+ putStrLn $ "## TESTING PERTURBATION (" ++ show del ++ " files, " ++ show threads ++ " threads)"+ shake shakeOptions{shakeFiles=out, shakeThreads=threads, shakeVerbosity=Quiet} $ rules args (out++)++ args -> do+ let (_,files,_) = getOpt Permute [] args+ tracker <- findExecutable "tracker.exe"+ withArgs (args \\ files) $+ shakeWithClean+ (removeDirectoryRecursive out) + (shakeOptions{shakeFiles=out, shakeReport=["output/" ++ name ++ "/report.html"], shakeLint=Just $ if isJust tracker then LintTracker else LintBasic})+ (rules files (out++))+++shakeWithClean :: IO () -> ShakeOptions -> Rules () -> IO ()+shakeWithClean clean opts rules = shakeArgsWith opts [cleanOpt] f+ where+ cleanOpt = Option "c" ["clean"] (NoArg $ Right ()) "Clean before building."++ f extra files = do+ when (extra /= []) clean+ if "clean" `elem` files then+ clean >> return Nothing+ else+ return $ Just $ if null files then rules else want files >> withoutActions rules+++unobj :: FilePath -> FilePath+unobj = dropDirectory1 . dropDirectory1++assert :: Bool -> String -> IO ()+assert b msg = unless b $ error $ "ASSERTION FAILED: " ++ msg++infix 4 ===++(===) :: (Show a, Eq a) => a -> a -> IO ()+a === b = assert (a == b) $ "failed in ===\nLHS: " ++ show a ++ "\nRHS: " ++ show b+++assertExists :: FilePath -> IO ()+assertExists file = do+ b <- IO.doesFileExist file+ assert b $ "File was expected to exist, but is missing: " ++ file++assertMissing :: FilePath -> IO ()+assertMissing file = do+ b <- IO.doesFileExist file+ assert (not b) $ "File was expected to be missing, but exists: " ++ file++assertContents :: FilePath -> String -> IO ()+assertContents file want = do+ got <- readFile file+ assert (want == got) $ "File contents are wrong: " ++ file ++ "\nWANT: " ++ want ++ "\nGOT: " ++ got++assertContentsOn :: (String -> String) -> FilePath -> String -> IO ()+assertContentsOn f file want = do+ got <- readFile file+ assert (f want == f got) $ "File contents are wrong: " ++ file ++ "\nWANT: " ++ want ++ "\nGOT: " ++ got +++ "\nWANT (transformed): " ++ f want ++ "\nGOT (transformed): " ++ f got++assertNonSpace :: FilePath -> String -> IO ()+assertNonSpace = assertContentsOn $ filter (not . isSpace)++assertContentsInfix :: FilePath -> String -> IO ()+assertContentsInfix file want = do+ got <- readFile file+ assert (want `isInfixOf` got) $ "File contents are wrong: " ++ file ++ "\nWANT (anywhere): " ++ want ++ "\nGOT: " ++ got++assertContentsUnordered :: FilePath -> [String] -> IO ()+assertContentsUnordered file xs = assertContentsOn (unlines . sort . lines) file (unlines xs)++assertException :: [String] -> IO () -> IO ()+assertException parts act = do+ res <- try_ act+ case res of+ Left err -> let s = show err in forM_ parts $ \p ->+ assert (p `isInfixOf` s) $ "Incorrect exception, missing part:\nGOT: " ++ s ++ "\nWANTED: " ++ p+ Right _ -> error "Expected an exception but succeeded"+++noTest :: ([String] -> IO ()) -> (String -> String) -> IO ()+noTest build obj = do+ build ["--abbrev=output=$OUT","-j3"]+ build ["--no-build","--report=-"]+ build []+++-- | Sleep long enough for the modification time resolution to catch up+sleepFileTime :: IO ()+sleepFileTime = sleep 1+++sleepFileTimeCalibrate :: IO (IO ())+sleepFileTimeCalibrate = do+ let file = "output/calibrate"+ createDirectoryIfMissing True $ takeDirectory file+ mtimes <- forM [1..10] $ \i -> fmap fst $ duration $ do+ writeFile file $ show i+ let time = fmap (fst . fromMaybe (error "File missing during sleepFileTimeCalibrate")) $ getFileInfo $ packU file+ t1 <- time+ flip loopM 0 $ \j -> do+ writeFile file $ show (i,j)+ t2 <- time+ return $ if t1 == t2 then Left $ j+1 else Right ()+ putStrLn $ "Longest file modification time lag was " ++ show (ceiling (maximum mtimes * 1000)) ++ "ms"+ return $ sleep $ min 1 $ maximum mtimes * 2+++removeFilesRandom :: FilePath -> IO Int+removeFilesRandom x = do+ files <- getDirectoryContentsRecursive x+ n <- randomRIO (0,length files)+ rs <- replicateM (length files) (randomIO :: IO Double)+ mapM_ (removeFile . snd) $ sort $ zip rs files+ return n+++getDirectoryContentsRecursive :: FilePath -> IO [FilePath]+getDirectoryContentsRecursive dir = do+ xs <- IO.getDirectoryContents dir+ (dirs,files) <- partitionM IO.doesDirectoryExist [dir </> x | x <- xs, not $ "." `isPrefixOf` x]+ rest <- concatMapM getDirectoryContentsRecursive dirs+ return $ files++rest+++copyDirectoryChanged :: FilePath -> FilePath -> IO ()+copyDirectoryChanged old new = do+ xs <- getDirectoryContentsRecursive old+ forM_ xs $ \from -> do+ let to = new </> drop (length $ addTrailingPathSeparator old) from+ createDirectoryIfMissing True $ takeDirectory to+ copyFileChanged from to+++copyFileChanged :: FilePath -> FilePath -> IO ()+copyFileChanged old new = do+ good <- IO.doesFileExist new+ good <- if not good then return False else liftM2 (==) (BS.readFile old) (BS.readFile new)+ when (not good) $ copyFile old new+++withTemporaryDirectory :: (FilePath -> IO ()) -> IO ()+withTemporaryDirectory act = do+ tdir <- getTemporaryDirectory+ bracket+ (openTempFile tdir "shake.hs")+ (removeFile . fst)+ $ \(file,h) -> do+ hClose h+ let dir = file ++ "_"+ bracket_ (createDirectory dir) (removeDirectoryRecursive dir) (act dir)++skip :: Monad m => a -> m ()+skip x = return ()
+ src/Test/Unicode.hs view
@@ -0,0 +1,60 @@++module Test.Unicode(main) where++import Development.Shake+import Development.Shake.FilePath+import Test.Type+import Control.Exception.Extra+import Control.Monad+import System.Directory(createDirectoryIfMissing)+++-- | Decode a dull ASCII string to certain unicode points, necessary because+-- withArgs (even the UTF8 version) throws an encoding error on the > 256 code points+decode :: String -> String+decode ('e':'^':xs) = '\xEA' : decode xs -- Latin Small Letter E With Circumflex+decode (':':')':xs) = '\x263A' : decode xs -- White Smiling Face+decode (x:xs) = x : decode xs+decode [] = []+++main = shaken test $ \xs obj -> do+ let pre:args = map decode xs+ want $ map obj args++ obj (pre ++ "dir/*") %> \out -> do+ let src = takeDirectory (takeDirectory out) </> takeFileName out+ copyFile' src out++ obj (pre ++ ".out") %> \out -> do+ a <- readFile' $ obj $ pre ++ "dir" </> pre <.> "source"+ b <- readFile' $ obj pre <.> "multi1"+ writeFile' out $ a ++ b++ map obj ["*.multi1","*.multi2"] &%> \[m1,m2] -> do+ b <- doesFileExist $ m1 -<.> "exist"+ writeFile' m1 $ show b+ writeFile' m2 $ show b+++test build obj = do+ build ["clean"]+ -- Useful, if the error message starts crashing...+ -- IO.hSetEncoding IO.stdout IO.char8+ -- IO.hSetEncoding IO.stderr IO.char8+ forM_ ["normal","e^",":)","e^-:)"] $ \pre -> do+ createDirectoryIfMissing True $ obj ""+ let ext x = obj $ decode pre <.> x+ res <- try_ $ writeFile (ext "source") "x"+ case res of+ Left err ->+ putStrLn $ "WARNING: Failed to write file " ++ pre ++ ", skipping unicode test (LANG=C ?)"+ Right _ -> do+ build [pre,pre <.> "out","--sleep"]+ assertContents (ext "out") $ "x" ++ "False"+ writeFile (ext "source") "y"+ build [pre,pre <.> "out","--sleep"]+ assertContents (ext "out") $ "y" ++ "False"+ writeFile (ext "exist") ""+ build [pre,pre <.> "out"]+ assertContents (ext "out") $ "y" ++ "True"
+ src/Test/Util.hs view
@@ -0,0 +1,20 @@++module Test.Util(main) where++import Development.Shake.Util+import Test.Type+++main = shaken test $ \args obj -> return ()+++test build obj = do+ parseMakefile "" === []+ parseMakefile "a:b c\ndef : ee" === [("a",["b","c"]),("def",["ee"])]+ parseMakefile "a: #comment\n#comment : b\nc : d" === [("a",[]),("c",["d"])]+ parseMakefile "a \\\n\t:b" === [("a",["b"])]+ parseMakefile "#comment\\ a : b" === []+ parseMakefile "a: b c \\\n d e\n\nf:g" === [("a",["b","c","d","e"]),("f",["g"])]+ parseMakefile "foo/bar: \\\r\n c:/a1 \\\r\n x\r\n" === [("foo/bar",["c:/a1","x"])]+ parseMakefile "output.o: src/file/with\\ space.cpp" === [("output.o",["src/file/with space.cpp"])]+ parseMakefile "a: b\\ c" === [("a",["b ","c"])]
+ src/Test/Verbosity.hs view
@@ -0,0 +1,39 @@++module Test.Verbosity(main) where++import Development.Shake+import Test.Type+++main = shaken test $ \args obj -> do+ want $ map obj args++ obj "in.txt" %> \out -> do+ a <- getVerbosity+ b <- withVerbosity Normal $ getVerbosity+ writeFile' out $ unwords $ map show [a,b]++ obj "out.txt" %> \out -> do+ x <- getVerbosity+ ys <- withVerbosity Loud $ do+ a <- getVerbosity+ need [obj "in.txt"] -- make sure the inherited verbosity does not get passed along+ b <- getVerbosity+ c <- quietly getVerbosity+ d <- fmap shakeVerbosity getShakeOptions+ return [a,b,c,d]+ z <- getVerbosity+ writeFile' out $ unwords $ map show $ [x] ++ ys ++ [z]++test build obj = do+ build ["out.txt","--clean"]+ assertContents (obj "in.txt") "Normal Normal"+ assertContents (obj "out.txt") "Normal Loud Loud Quiet Normal Normal"++ build ["out.txt","--clean","--verbose"]+ assertContents (obj "in.txt") "Loud Normal"+ assertContents (obj "out.txt") "Loud Loud Loud Quiet Loud Loud"++ build ["out.txt","--clean","--quiet"]+ assertContents (obj "in.txt") "Quiet Normal"+ assertContents (obj "out.txt") "Quiet Loud Loud Quiet Quiet Quiet"