@@ -5,43 +5,17 @@
5{-# LANGUAGE MultiWayIf #-}
5{-# LANGUAGE MultiWayIf #-}
6{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
7{-# LANGUAGE PatternGuards #-}
7{-# LANGUAGE PatternGuards #-}
8+{-# LANGUAGE QuasiQuotes #-}
8{-# LANGUAGE ScopedTypeVariables #-}
9{-# LANGUAGE ScopedTypeVariables #-}
9{-# LANGUAGE TypeApplications #-}
10{-# LANGUAGE TypeApplications #-}
10−module Obelisk.Command.Thunk
11+module Obelisk.Command.Thunk where
13− , ReadThunkError (..)
16− , ThunkPackConfig (..)
20− , ThunkUpdateConfig (..)
23− , createThunkWithLatest
28− , nixBuildAttrWithCache
29− , nixBuildThunkAttrWithCache
35− , updateThunkToLatest
39import Control.Applicative
13import Control.Applicative
40import Control.Exception (displayException, try)
14import Control.Exception (displayException, try)
41−import qualified Control.Lens as Lens
15+import Control.Lens (ifor, ifor_, (.~))
42−import Control.Lens.Indexed hiding ((<.>))
43import Control.Monad
16import Control.Monad
44−import Control.Monad.Catch (handle)
17+import Control.Monad.Extra (findM, unlessM, whenM)
18+import Control.Monad.Catch (MonadCatch, handle)
45import Control.Monad.Except
19import Control.Monad.Except
46import Data.Aeson ((.=))
20import Data.Aeson ((.=))
47import qualified Data.Aeson as Aeson
21import qualified Data.Aeson as Aeson
@@ -51,21 +25,27 @@ import qualified Data.ByteString.Lazy as LBS
51import Data.Containers.ListUtils (nubOrd)
25import Data.Containers.ListUtils (nubOrd)
52import Data.Default
26import Data.Default
53import Data.Either.Combinators (fromRight', rightToMaybe)
27import Data.Either.Combinators (fromRight', rightToMaybe)
28+import Data.Foldable (toList)
29+import Data.Function ((&))
30+import Data.Functor ((<&>))
54import Data.Git.Ref (Ref)
31import Data.Git.Ref (Ref)
55import qualified Data.Git.Ref as Ref
32import qualified Data.Git.Ref as Ref
56import qualified Data.List as L
33import qualified Data.List as L
57−import Data.List.NonEmpty (NonEmpty (..))
34+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
58import qualified Data.List.NonEmpty as NonEmpty
35import qualified Data.List.NonEmpty as NonEmpty
59import Data.Map (Map)
36import Data.Map (Map)
60import qualified Data.Map as Map
37import qualified Data.Map as Map
61import Data.Maybe
38import Data.Maybe
62import Data.Set (Set)
39import Data.Set (Set)
63import qualified Data.Set as Set
40import qualified Data.Set as Set
41+import Data.String.Here.Interpolated (i)
42+import Data.String.Here.Uninterpolated (here)
64import Data.Text (Text)
43import Data.Text (Text)
65import qualified Data.Text as T
44import qualified Data.Text as T
66import Data.Text.Encoding
45import Data.Text.Encoding
67import qualified Data.Text.IO as T
46import qualified Data.Text.IO as T
68import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
47import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
48+import Data.Traversable (for)
69import Data.Yaml (parseMaybe)
49import Data.Yaml (parseMaybe)
70import GitHub
50import GitHub
71import GitHub.Data.Name
51import GitHub.Data.Name
@@ -84,11 +64,10 @@ import Obelisk.Command.Utils
85--TODO: Support symlinked thunk data
65--TODO: Support symlinked thunk data
86data ThunkData
66data ThunkData
87− = ThunkData_Packed ThunkPtr
67+ = ThunkData_Packed ThunkSpec ThunkPtr
88 -- ^ Packed thunk
68 -- ^ Packed thunk
89− | ThunkData_Checkout (Maybe ThunkPtr)
69+ | ThunkData_Checkout
90 -- ^ Checked out thunk that was unpacked from this pointer
70 -- ^ Checked out thunk that was unpacked from this pointer
91− deriving (Show, Eq, Ord)
93-- | A reference to the exact data that a thunk should translate into
72-- | A reference to the exact data that a thunk should translate into
94data ThunkPtr = ThunkPtr
73data ThunkPtr = ThunkPtr
@@ -213,96 +192,117 @@ nixPrefetchGit uri rev fetchSubmodules =
214--TODO: Pretty print these
193--TODO: Pretty print these
215data ReadThunkError
194data ReadThunkError
216− = ReadThunkError_UnrecognizedFiles
195+ = ReadThunkError_UnrecognizedThunk
217− | ReadThunkError_AmbiguousFiles
196+ | ReadThunkError_UnrecognizedPaths (NonEmpty FilePath)
218− | ReadThunkError_UnrecognizedLoader Text
197+ | ReadThunkError_MissingPaths (NonEmpty FilePath)
219− | ReadThunkError_UnparseablePtr LBS.ByteString
198+ | ReadThunkError_UnparseablePtr FilePath String
199+ | ReadThunkError_FileError IOError
200+ | ReadThunkError_FileDoesNotMatch FilePath Text
201+ | ReadThunkError_UnrecognizedState String
202+ | ReadThunkError_AmbiguousPackedState ThunkPtr ThunkPtr
220− deriving (Show)
203+ deriving (Show)
222−-- | Read a thunk and validate that it is only a thunk, either packed or unpacked.
205+unpackedDirName :: FilePath
223−-- If the thunk is packed and additional data is present, fail.
206+unpackedDirName = "local"
224−readThunk :: MonadObelisk m => FilePath -> m (Either ReadThunkError ThunkData)
225−readThunk thunkDir = do
226− files <- liftIO $ listDirectory thunkDir
227− case ".git" `elem` files of
228− True -> fmap ThunkData_Checkout <$> do
229− let origThunkPath = thunkDir </> ".git" </> "obelisk" </> "orig-thunk"
230− liftIO $ doesDirectoryExist origThunkPath >>= \case
231− True -> fmap Just <$> readPackedThunk origThunkPath
232− False -> return $ return Nothing
233− False -> liftIO $ fmap ThunkData_Packed <$> readPackedThunk thunkDir
235attrCacheFileName :: FilePath
208attrCacheFileName :: FilePath
236attrCacheFileName = ".attr-cache"
209attrCacheFileName = ".attr-cache"
238−data ThunkType = ThunkType
211+-- | Specification for how a file in a thunk version works.
239− { _thunkType_loader :: FilePath
212+data ThunkFileSpec
240− , _thunkType_json :: FilePath
213+ = ThunkFileSpec_Ptr (LBS.ByteString -> Either String ThunkPtr) -- ^ This file specifies 'ThunkPtr' data
241− , _thunkType_optional :: Set FilePath
214+ | ThunkFileSpec_FileMatches Text -- ^ This file must match the given content exactly
242− , _thunkType_loaderVersions :: NonEmpty Text
215+ | ThunkFileSpec_CheckoutIndicator -- ^ Existence of this directory indicates that the thunk is unpacked
243− , _thunkType_parser :: Aeson.Object -> Aeson.Parser ThunkPtr
216+ | ThunkFileSpec_AttrCache -- ^ This directory is an attribute cache
245−
218+-- | Specification for how a set of files in a thunk version work.
246−gitHubThunkType :: ThunkType
219+data ThunkSpec = ThunkSpec
247−gitHubThunkType = ThunkType
220+ { _thunkSpec_name :: !Text
248− { _thunkType_loader = "default.nix"
221+ , _thunkSpec_files :: !(Map FilePath ThunkFileSpec)
249− , _thunkType_json = "github.json"
250− , _thunkType_optional = Set.fromList [attrCacheFileName]
251− , _thunkType_loaderVersions = gitHubStandaloneLoaders
252− , _thunkType_parser = parseThunkPtr $ \v ->
253− ThunkSource_GitHub <$> parseGitHubSource v <|> ThunkSource_Git <$> parseGitSource v
256−gitThunkType :: ThunkType
257−gitThunkType = ThunkType
258− { _thunkType_loader = "default.nix"
259− , _thunkType_json = "git.json"
260− , _thunkType_optional = Set.fromList [attrCacheFileName]
261− , _thunkType_loaderVersions = plainGitStandaloneLoaders
262− , _thunkType_parser = parseThunkPtr $ fmap ThunkSource_Git . parseGitSource
265−thunkTypes :: [ThunkType]
224+thunkSpecTypes :: NonEmpty (NonEmpty ThunkSpec)
266−thunkTypes = [gitThunkType, gitHubThunkType]
225+thunkSpecTypes = gitThunkSpecs :| [gitHubThunkSpecs]
268−findThunkType :: [ThunkType] -> FilePath -> IO (Either ReadThunkError ThunkType)
227+-- | Attempts to match a 'ThunkSpec' to a given directory.
269−findThunkType types thunkDir = do
228+matchThunkSpecToDir
270− matches <- fmap catMaybes $ forM types $ \thunkType -> do
229+ :: (MonadError ReadThunkError m, MonadIO m, MonadCatch m)
271− let
230+ => ThunkSpec -- ^ 'ThunkSpec' to match against the given files/directory
272− expectedContents = Set.fromList $ (thunkDir </>) <$>
231+ -> FilePath -- ^ Path to directory
273− [ _thunkType_loader thunkType
232+ -> Set FilePath -- ^ Set of file paths relative to the given directory
274− , _thunkType_json thunkType
233+ -> m ThunkData
275− ]
234+matchThunkSpecToDir thunkSpec dir dirFiles = do
276− optionalContents = Set.map (thunkDir </>) (_thunkType_optional thunkType)
235+ case nonEmpty (toList $ dirFiles `Set.difference` expectedPaths) of
277−
236+ Just fs -> throwError $ ReadThunkError_UnrecognizedPaths $ (dir </>) <$> fs
278− -- Ensure that there aren't any other files in the thunk
237+ Nothing -> pure ()
279− -- NB: System.Directory.listDirectory returns the contents without the directory path
238+ case nonEmpty (toList $ requiredPaths `Set.difference` dirFiles) of
280− files <- liftIO $ Set.fromList . fmap (thunkDir </>) <$> listDirectory thunkDir
239+ Just fs -> throwError $ ReadThunkError_MissingPaths $ (dir </>) <$> fs
281− let unexpectedContents = files `Set.difference` (expectedContents `Set.union` optionalContents)
240+ Nothing -> pure ()
282− missingContents = expectedContents `Set.difference` files
241+ datas <- fmap toList $ flip Map.traverseMaybeWithKey (_thunkSpec_files thunkSpec) $ \expectedPath -> \case
283− pure $ if Set.null unexpectedContents && Set.null missingContents
242+ ThunkFileSpec_AttrCache -> Nothing <$ dirMayExist expectedPath
284− then Just thunkType
243+ ThunkFileSpec_CheckoutIndicator -> liftIO (doesDirectoryExist (dir </> expectedPath)) <&> \case
285− else Nothing
244+ False -> Nothing
286−
245+ True -> Just ThunkData_Checkout
287− pure $ case matches of
246+ ThunkFileSpec_FileMatches expectedContents -> handle (\(e :: IOError) -> throwError $ ReadThunkError_FileError e) $ do
288− [singleMatch] -> Right singleMatch
247+ actualContents <- liftIO (T.readFile $ dir </> expectedPath)
289− [] -> Left ReadThunkError_UnrecognizedFiles
248+ case T.strip expectedContents == T.strip actualContents of
290− _ -> Left ReadThunkError_AmbiguousFiles
249+ True -> pure Nothing
250+ False -> throwError $ ReadThunkError_FileDoesNotMatch (dir </> expectedPath) expectedContents
251+ ThunkFileSpec_Ptr parser -> handle (\(e :: IOError) -> throwError $ ReadThunkError_FileError e) $ do
252+ let path = dir </> expectedPath
253+ liftIO (doesFileExist path) >>= \case
254+ False -> pure Nothing
256+ actualContents <- liftIO $ LBS.readFile path
257+ case parser actualContents of
258+ Right v -> pure $ Just (ThunkData_Packed thunkSpec v)
259+ Left e -> throwError $ ReadThunkError_UnparseablePtr (dir </> expectedPath) e
261+ case nonEmpty datas of
262+ Nothing -> throwError ReadThunkError_UnrecognizedThunk
263+ Just xs -> fold1WithM xs $ \a b -> either throwError pure (mergeThunkData a b)
265+ rootPathsOnly = Set.fromList . mapMaybe takeRootDir . Map.keys
266+ takeRootDir = fmap NonEmpty.head . nonEmpty . splitPath
268+ expectedPaths = rootPathsOnly $ _thunkSpec_files thunkSpec
270+ requiredPaths = rootPathsOnly $ Map.filter isRequiredFileSpec $ _thunkSpec_files thunkSpec
271+ isRequiredFileSpec = \case
272+ ThunkFileSpec_FileMatches _ -> True
275+ dirMayExist expectedPath = liftIO (doesFileExist (dir </> expectedPath)) >>= \case
276+ True -> throwError $ ReadThunkError_UnrecognizedPaths $ expectedPath :| []
279+ -- Combine 'ThunkData' from different files, preferring "Checkout" over "Packed"
280+ mergeThunkData ThunkData_Checkout ThunkData_Checkout = Right ThunkData_Checkout
281+ mergeThunkData ThunkData_Checkout ThunkData_Packed{} = Left bothPackedAndUnpacked
282+ mergeThunkData ThunkData_Packed{} ThunkData_Checkout = Left bothPackedAndUnpacked
283+ mergeThunkData a@(ThunkData_Packed _ ptrA) (ThunkData_Packed _ ptrB) =
284+ if ptrA == ptrB then Right a else Left $ ReadThunkError_AmbiguousPackedState ptrA ptrB
286+ bothPackedAndUnpacked = ReadThunkError_UnrecognizedState "Both packed data and checkout present"
288+ fold1WithM (x :| xs) f = foldM f x xs
292+ => NonEmpty (NonEmpty ThunkSpec) -> FilePath -> m (Either ReadThunkError ThunkData)
293+readThunkWith specTypes dir = do
294+ dirFiles <- Set.fromList <$> liftIO (listDirectory dir)
295+ let specs = concatMap toList $ toList $ NonEmpty.transpose specTypes -- Interleave spec types so we try each one in a "fair" ordering
296+ flip fix specs $ \loop -> \case
297+ [] -> pure $ Left ReadThunkError_UnrecognizedThunk
298+ spec:rest -> runExceptT (matchThunkSpecToDir spec dir dirFiles) >>= \case
299+ Left e -> putLog Debug [i|Thunk specification ${_thunkSpec_name spec} did not match ${dir}: ${e}|] *> loop rest
300+ x@(Right _) -> x <$ putLog Debug [i|Thunk specification ${_thunkSpec_name spec} matched ${dir}|]
292-- | Read a thunk and validate that it is exactly a packed thunk.
302-- | Read a thunk and validate that it is exactly a packed thunk.
293-- If additional data is present, fail.
303-- If additional data is present, fail.
294−readPackedThunk :: FilePath -> IO (Either ReadThunkError ThunkPtr)
304+readThunk :: (MonadObelisk m) => FilePath -> m (Either ReadThunkError ThunkData)
295−readPackedThunk thunkDir = runExceptT $ do
305+readThunk = readThunkWith thunkSpecTypes
296− thunkType <- ExceptT $ findThunkType thunkTypes thunkDir
297− -- Ensure that we recognize the thunk loader
298− loader <- liftIO $ T.readFile $ thunkDir </> _thunkType_loader thunkType
299− unless (loader `elem` _thunkType_loaderVersions thunkType) $ do
300− throwError $ ReadThunkError_UnrecognizedLoader loader
302− txt <- liftIO $ LBS.readFile $ thunkDir </> _thunkType_json thunkType
303− case parseMaybe (_thunkType_parser thunkType) =<< Aeson.decode txt of
304− Nothing -> throwError $ ReadThunkError_UnparseablePtr txt
305− Just ptr -> return ptr
307parseThunkPtr :: (Aeson.Object -> Aeson.Parser ThunkSource) -> Aeson.Object -> Aeson.Parser ThunkPtr
307parseThunkPtr :: (Aeson.Object -> Aeson.Parser ThunkSource) -> Aeson.Object -> Aeson.Parser ThunkPtr
308parseThunkPtr parseSrc v = do
308parseThunkPtr parseSrc v = do
@@ -346,16 +346,18 @@ parseGitSource v = do
346overwriteThunk :: MonadObelisk m => FilePath -> ThunkPtr -> m ()
346overwriteThunk :: MonadObelisk m => FilePath -> ThunkPtr -> m ()
347overwriteThunk target thunk = do
347overwriteThunk target thunk = do
348 -- Ensure that this directory is a valid thunk (i.e. so we aren't losing any data)
348 -- Ensure that this directory is a valid thunk (i.e. so we aren't losing any data)
349− Right _ <- readThunk target
349+ readThunk target >>= \case
350+ Left e -> failWith [i|Invalid thunk at ${target}: ${e}|]
351 --TODO: Is there a safer way to do this overwriting?
353 --TODO: Is there a safer way to do this overwriting?
352− liftIO $ removeDirectoryRecursive target
354+ callProcessAndLogOutput (Debug, Error) $ proc rmPath ["-r", target] -- target may be a symlink
353− liftIO $ createThunk target thunk
355+ createThunk target $ Right thunk
355−thunkPtrLoader :: ThunkPtr -> Text
357+thunkPtrToSpec :: ThunkPtr -> ThunkSpec
356−thunkPtrLoader thunk = case _thunkPtr_source thunk of
358+thunkPtrToSpec thunk = case _thunkPtr_source thunk of
357− ThunkSource_GitHub _ -> NonEmpty.head gitHubStandaloneLoaders
359+ ThunkSource_GitHub _ -> NonEmpty.head gitHubThunkSpecs
358− ThunkSource_Git _ -> NonEmpty.head plainGitStandaloneLoaders
360+ ThunkSource_Git _ -> NonEmpty.head gitThunkSpecs
360-- It's important that formatting be very consistent here, because
362-- It's important that formatting be very consistent here, because
361-- otherwise when people update thunks, their patches will be messy
363-- otherwise when people update thunks, their patches will be messy
@@ -402,35 +404,56 @@ encodeThunkPtrData (ThunkPtr rev src) = case src of
402 , confTrailingNewline = True
404 , confTrailingNewline = True
405−createThunk :: MonadIO m => FilePath -> ThunkPtr -> m ()
407+-- | Initialize a git repository to an unpacked thunk.
408+initThunk :: MonadObelisk m => FilePath -> m ()
409+initThunk target = withSpinner [i|Initializing thunk at ${target}|] $ do
410+ checkThunkDirectory target
411+ unlessM (liftIO $ doesDirectoryExist $ target </> ".git") $ failWith [i|${target} is not a git checkout.|]
412+ ptr <- getThunkPtr False target Nothing
413+ let tempThunkDir = target <.> "thunk-init"
414+ whenM (liftIO $ doesPathExist tempThunkDir) $
415+ failWith [i|A previous 'thunk init' left unfinished state at ${tempThunkDir}. You will need to rename or remove that path before trying again.|]
416+ createThunk tempThunkDir $ Left (thunkPtrToSpec ptr) -- Only write the skeleton, but skip the ptr itself since it's unpacked
418+ renameDirectory target (tempThunkDir </> unpackedDirName)
419+ removePathForcibly target
420+ renameDirectory tempThunkDir target
422+createThunk :: MonadObelisk m => FilePath -> Either ThunkSpec ThunkPtr -> m ()
406−createThunk target thunk = liftIO $ do
423+createThunk target ptrInfo =
407− createDirectoryIfMissing True (target </> attrCacheFileName)
424+ ifor_ (_thunkSpec_files spec) $ \path -> \case
408− T.writeFile (target </> "default.nix") (thunkPtrLoader thunk)
425+ ThunkFileSpec_FileMatches content -> withReadyPath path $ \p -> liftIO $ T.writeFile p content
409− let
426+ ThunkFileSpec_Ptr _ -> case ptrInfo of
410− jsonFileName = case _thunkPtr_source thunk of
427+ Left _ -> pure () -- We can't write the ptr without it
411− ThunkSource_GitHub _ -> "github"
412− ThunkSource_Git _ -> "git"
413− LBS.writeFile (target </> jsonFileName <.> "json") (encodeThunkPtrData thunk)
428+ Right ptr -> withReadyPath path $ \p -> liftIO $ LBS.writeFile p (encodeThunkPtrData ptr)
431+ spec = either id thunkPtrToSpec ptrInfo
432+ withReadyPath path f = do
433+ let fullPath = target </> path
434+ putLog Debug $ "Writing thunk file " <> T.pack fullPath
435+ liftIO $ createDirectoryIfMissing True $ takeDirectory fullPath
415createThunkWithLatest :: MonadObelisk m => FilePath -> ThunkSource -> m ()
438createThunkWithLatest :: MonadObelisk m => FilePath -> ThunkSource -> m ()
416createThunkWithLatest target s = do
439createThunkWithLatest target s = do
417 rev <- getLatestRev s
440 rev <- getLatestRev s
418− createThunk target $ ThunkPtr
441+ createThunk target $ Right $ ThunkPtr
419 { _thunkPtr_source = s
442 { _thunkPtr_source = s
420 , _thunkPtr_rev = rev
443 , _thunkPtr_rev = rev
423updateThunkToLatest :: MonadObelisk m => ThunkUpdateConfig -> FilePath -> m ()
446updateThunkToLatest :: MonadObelisk m => ThunkUpdateConfig -> FilePath -> m ()
424−updateThunkToLatest (ThunkUpdateConfig mBranch thunkConfig) target = withSpinner' ("Updating thunk " <> T.pack target <> " to latest") (pure $ const $ "Thunk " <> T.pack target <> " updated to latest") $ do
447+updateThunkToLatest (ThunkUpdateConfig mBranch thunkConfig) target = spinner $ do
425− checkThunkDirectory "ob thunk update directory cannot be '.'" target
448+ checkThunkDirectory target
426 -- check to see if thunk should be updated to a specific branch or just update it's current branch
449 -- check to see if thunk should be updated to a specific branch or just update it's current branch
427 case mBranch of
450 case mBranch of
428 Nothing -> do
451 Nothing -> do
429 (overwrite, ptr) <- readThunk target >>= \case
452 (overwrite, ptr) <- readThunk target >>= \case
430− Left err -> failWith $ T.pack $ "thunk update: " <> show err
453+ Left err -> failWith [i|Thunk update: ${err}|]
431 Right c -> case c of
454 Right c -> case c of
432− ThunkData_Packed t -> return (target, t)
455+ ThunkData_Packed _ t -> return (target, t)
433− ThunkData_Checkout _ -> failWith "cannot update an unpacked thunk"
456+ ThunkData_Checkout -> failWith "cannot update an unpacked thunk"
434 let src = _thunkPtr_source ptr
457 let src = _thunkPtr_source ptr
435 rev <- getLatestRev src
458 rev <- getLatestRev src
436 overwriteThunk overwrite $ modifyThunkPtrByConfig thunkConfig $ ThunkPtr
459 overwriteThunk overwrite $ modifyThunkPtrByConfig thunkConfig $ ThunkPtr
@@ -438,14 +461,16 @@ updateThunkToLatest (ThunkUpdateConfig mBranch thunkConfig) target = withSpinner
438 , _thunkPtr_rev = rev
461 , _thunkPtr_rev = rev
440 Just branch -> readThunk target >>= \case
463 Just branch -> readThunk target >>= \case
441− Left err -> failWith $ T.pack $ "thunk update: " <> show err
464+ Left err -> failWith [i|Thunk update: ${err}|]
442 Right c -> case c of
465 Right c -> case c of
443− ThunkData_Packed t -> case _thunkPtr_source t of
466+ ThunkData_Packed _ t -> case _thunkPtr_source t of
444 ThunkSource_Git tsg -> setThunk thunkConfig target tsg branch
467 ThunkSource_Git tsg -> setThunk thunkConfig target tsg branch
445 ThunkSource_GitHub tsgh -> do
468 ThunkSource_GitHub tsgh -> do
446 let tsg = forgetGithub False tsgh
469 let tsg = forgetGithub False tsgh
447 setThunk thunkConfig target tsg branch
470 setThunk thunkConfig target tsg branch
448− ThunkData_Checkout _ -> failWith $ T.pack $ "thunk located at " <> show target <> " is unpacked. Use ob thunk pack on the desired directory and then try ob thunk update again."
471+ ThunkData_Checkout -> failWith [i|Thunk located at ${target} is unpacked. Use 'ob thunk pack' on the desired directory and then try 'ob thunk update' again.|]
473+ spinner = withSpinner' ("Updating thunk " <> T.pack target <> " to latest") (pure $ const $ "Thunk " <> T.pack target <> " updated to latest")
450setThunk :: MonadObelisk m => ThunkConfig -> FilePath -> GitSource -> String -> m ()
475setThunk :: MonadObelisk m => ThunkConfig -> FilePath -> GitSource -> String -> m ()
451setThunk thunkConfig target gs branch = do
476setThunk thunkConfig target gs branch = do
@@ -455,21 +480,21 @@ setThunk thunkConfig target gs branch = do
456-- | All recognized github standalone loaders, ordered from newest to oldest.
481-- | All recognized github standalone loaders, ordered from newest to oldest.
457-- This tool will only ever produce the newest one when it writes a thunk.
482-- This tool will only ever produce the newest one when it writes a thunk.
458−gitHubStandaloneLoaders :: NonEmpty Text
483+gitHubThunkSpecs :: NonEmpty ThunkSpec
459−gitHubStandaloneLoaders =
484+gitHubThunkSpecs =
460− gitHubStandaloneLoaderV4 :|
485+ gitHubThunkSpecV5 :|
461− [ gitHubStandaloneLoaderV3
486+ [ gitHubThunkSpecV4
462− , gitHubStandaloneLoaderV2
487+ , gitHubThunkSpecV3
463− , gitHubStandaloneLoaderV1
488+ , gitHubThunkSpecV2
466−gitHubStandaloneLoaderV1 :: Text
492+gitHubThunkSpecV1 :: ThunkSpec
467−gitHubStandaloneLoaderV1 = T.unlines
493+gitHubThunkSpecV1 = legacyGitHubThunkSpec "github-v1"
468− [ "import ((import <nixpkgs> {}).fetchFromGitHub (builtins.fromJSON (builtins.readFile ./github.json)))"
494+ "import ((import <nixpkgs> {}).fetchFromGitHub (builtins.fromJSON (builtins.readFile ./github.json)))"
471−gitHubStandaloneLoaderV2 :: Text
496+gitHubThunkSpecV2 :: ThunkSpec
472−gitHubStandaloneLoaderV2 = T.unlines
497+gitHubThunkSpecV2 = legacyGitHubThunkSpec "github-v2" $ T.unlines
473 [ "# DO NOT HAND-EDIT THIS FILE" --TODO: Add something about how to get more info on Obelisk, etc.
498 [ "# DO NOT HAND-EDIT THIS FILE" --TODO: Add something about how to get more info on Obelisk, etc.
474 , "import ((import <nixpkgs> {}).fetchFromGitHub ("
499 , "import ((import <nixpkgs> {}).fetchFromGitHub ("
475 , " let json = builtins.fromJSON (builtins.readFile ./github.json);"
500 , " let json = builtins.fromJSON (builtins.readFile ./github.json);"
@@ -479,8 +504,8 @@ gitHubStandaloneLoaderV2 = T.unlines
482−gitHubStandaloneLoaderV3 :: Text
507+gitHubThunkSpecV3 :: ThunkSpec
483−gitHubStandaloneLoaderV3 = T.unlines
508+gitHubThunkSpecV3 = legacyGitHubThunkSpec "github-v3" $ T.unlines
484 [ "# DO NOT HAND-EDIT THIS FILE"
509 [ "# DO NOT HAND-EDIT THIS FILE"
486 , " fetch = { private ? false, ... }@args: if private && builtins.hasAttr \"fetchGit\" builtins"
511 , " fetch = { private ? false, ... }@args: if private && builtins.hasAttr \"fetchGit\" builtins"
@@ -499,8 +524,8 @@ gitHubStandaloneLoaderV3 = T.unlines
499 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
524 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
502−gitHubStandaloneLoaderV4 :: Text
527+gitHubThunkSpecV4 :: ThunkSpec
503−gitHubStandaloneLoaderV4 = T.unlines
528+gitHubThunkSpecV4 = legacyGitHubThunkSpec "github-v4" $ T.unlines
504 [ "# DO NOT HAND-EDIT THIS FILE"
529 [ "# DO NOT HAND-EDIT THIS FILE"
505 , "let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:"
530 , "let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:"
506 , " if !fetchSubmodules && !private then builtins.fetchTarball {"
531 , " if !fetchSubmodules && !private then builtins.fetchTarball {"
@@ -511,24 +536,50 @@ gitHubStandaloneLoaderV4 = T.unlines
511 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
536 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
514−plainGitStandaloneLoaders :: NonEmpty Text
539+legacyGitHubThunkSpec :: Text -> Text -> ThunkSpec
515−plainGitStandaloneLoaders =
540+legacyGitHubThunkSpec name loader = ThunkSpec name $ Map.fromList
516− plainGitStandaloneLoaderV4 :|
541+ [ ("default.nix", ThunkFileSpec_FileMatches $ T.strip loader)
517− [ plainGitStandaloneLoaderV1
542+ , ("github.json" , ThunkFileSpec_Ptr parseGitHubJsonBytes)
518− , plainGitStandaloneLoaderV2
543+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
519− , plainGitStandaloneLoaderV3
544+ , (".git", ThunkFileSpec_CheckoutIndicator)
522−plainGitStandaloneLoaderV1 :: Text
547+gitHubThunkSpecV5 :: ThunkSpec
523−plainGitStandaloneLoaderV1 = T.unlines
548+gitHubThunkSpecV5 = mkThunkSpec "github-v5" "github.json" parseGitHubJsonBytes [here|
549+# DO NOT HAND-EDIT THIS FILE
550+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
551+ if !fetchSubmodules && !private then builtins.fetchTarball {
552+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
553+ } else (import <nixpkgs> {}).fetchFromGitHub {
554+ inherit owner repo rev sha256 fetchSubmodules private;
556+ json = builtins.fromJSON (builtins.readFile ./github.json);
557+in if builtins.pathExists ./local then ./local else fetch json
560+parseGitHubJsonBytes :: LBS.ByteString -> Either String ThunkPtr
561+parseGitHubJsonBytes = parseJsonObject $ parseThunkPtr $ \v ->
562+ ThunkSource_GitHub <$> parseGitHubSource v <|> ThunkSource_Git <$> parseGitSource v
564+gitThunkSpecs :: NonEmpty ThunkSpec
573+gitThunkSpecV1 :: ThunkSpec
574+gitThunkSpecV1 = legacyGitThunkSpec "git-v1" $ T.unlines
524 [ "# DO NOT HAND-EDIT THIS FILE"
575 [ "# DO NOT HAND-EDIT THIS FILE"
525 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
576 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
526 , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
577 , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
527 , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
578 , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
530−plainGitStandaloneLoaderV2 :: Text
581+gitThunkSpecV2 :: ThunkSpec
531−plainGitStandaloneLoaderV2 = T.unlines
582+gitThunkSpecV2 = legacyGitThunkSpec "git-v2" $ T.unlines
532 [ "# DO NOT HAND-EDIT THIS FILE"
583 [ "# DO NOT HAND-EDIT THIS FILE"
533 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
584 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
534 , " if builtins.hasAttr \"fetchGit\" builtins"
585 , " if builtins.hasAttr \"fetchGit\" builtins"
@@ -539,8 +590,8 @@ plainGitStandaloneLoaderV2 = T.unlines
540-- This loader has a bug because @builtins.fetchGit@ is not given a @ref@
591-- This loader has a bug because @builtins.fetchGit@ is not given a @ref@
541-- and will fail to find commits without this because it does shallow clones.
592-- and will fail to find commits without this because it does shallow clones.
542−plainGitStandaloneLoaderV3 :: Text
593+gitThunkSpecV3 :: ThunkSpec
543−plainGitStandaloneLoaderV3 = T.unlines
594+gitThunkSpecV3 = legacyGitThunkSpec "git-v3" $ T.unlines
544 [ "# DO NOT HAND-EDIT THIS FILE"
595 [ "# DO NOT HAND-EDIT THIS FILE"
545 , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
596 , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
546 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
597 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
@@ -555,8 +606,8 @@ plainGitStandaloneLoaderV3 = T.unlines
555 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
606 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
558−plainGitStandaloneLoaderV4 :: Text
609+gitThunkSpecV4 :: ThunkSpec
559−plainGitStandaloneLoaderV4 = T.unlines
610+gitThunkSpecV4 = legacyGitThunkSpec "git-v4" $ T.unlines
560 [ "# DO NOT HAND-EDIT THIS FILE"
611 [ "# DO NOT HAND-EDIT THIS FILE"
561 , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
612 , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
562 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
613 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
@@ -572,10 +623,52 @@ plainGitStandaloneLoaderV4 = T.unlines
572 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
623 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
575−thunkFileNames :: [FilePath]
626+legacyGitThunkSpec :: Text -> Text -> ThunkSpec
576−thunkFileNames = ["default.nix", "github.json", "git.json"]
627+legacyGitThunkSpec name loader = ThunkSpec name $ Map.fromList
628+ [ ("default.nix", ThunkFileSpec_FileMatches $ T.strip loader)
629+ , ("git.json" , ThunkFileSpec_Ptr parseGitJsonBytes)
630+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
631+ , (".git", ThunkFileSpec_CheckoutIndicator)
578−--TODO: when checking something out, make a shallow clone
634+gitThunkSpecV5 :: ThunkSpec
635+gitThunkSpecV5 = mkThunkSpec "git-v5" "git.json" parseGitJsonBytes [here|
636+# DO NOT HAND-EDIT THIS FILE
637+let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:
638+ let realUrl = let firstChar = builtins.substring 0 1 url; in
639+ if firstChar == "/" then /. + url
640+ else if firstChar == "." then ./. + url
642+ in if !fetchSubmodules && private then builtins.fetchGit {
643+ url = realUrl; inherit rev;
644+ ${if branch == null then null else "ref"} = branch;
645+ } else (import <nixpkgs> {}).fetchgit {
646+ url = realUrl; inherit rev sha256;
648+ json = builtins.fromJSON (builtins.readFile ./git.json);
649+in if builtins.pathExists ./local then ./local else fetch json
652+parseGitJsonBytes :: LBS.ByteString -> Either String ThunkPtr
653+parseGitJsonBytes = parseJsonObject $ parseThunkPtr $ fmap ThunkSource_Git . parseGitSource
655+mkThunkSpec :: Text -> FilePath -> (LBS.ByteString -> Either String ThunkPtr) -> Text -> ThunkSpec
656+mkThunkSpec name jsonFileName parser srcNix = ThunkSpec name $ Map.fromList
657+ [ ("default.nix", ThunkFileSpec_FileMatches defaultNixViaSrc)
658+ , ("thunk.nix", ThunkFileSpec_FileMatches srcNix)
659+ , (jsonFileName, ThunkFileSpec_Ptr parser)
660+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
661+ , (unpackedDirName, ThunkFileSpec_CheckoutIndicator)
664+ defaultNixViaSrc = [here|
665+# DO NOT HAND-EDIT THIS FILE
666+import (import ./thunk.nix)
670+parseJsonObject :: (Aeson.Object -> Aeson.Parser a) -> LBS.ByteString -> Either String a
671+parseJsonObject p bytes = Aeson.parseEither p =<< Aeson.eitherDecode bytes
580-- | Checks a cache directory to see if there is a fresh symlink
673-- | Checks a cache directory to see if there is a fresh symlink
581-- to the result of building an attribute of a thunk.
674-- to the result of building an attribute of a thunk.
@@ -583,44 +676,49 @@ thunkFileNames = ["default.nix", "github.json", "git.json"]
583-- and the result is symlinked into the cache.
676-- and the result is symlinked into the cache.
584nixBuildThunkAttrWithCache
677nixBuildThunkAttrWithCache
585 :: MonadObelisk m
678 :: MonadObelisk m
586− => FilePath
680+ -> FilePath
587 -- ^ Path to directory containing Thunk
681 -- ^ Path to directory containing Thunk
588 -> String
682 -> String
589 -- ^ Attribute to build
683 -- ^ Attribute to build
590− -> m FilePath
684+ -> m (Maybe FilePath)
591 -- ^ Symlink to cached or built nix output
685 -- ^ Symlink to cached or built nix output
592-- WARNING: If the thunk uses an impure reference such as '<nixpkgs>'
686-- WARNING: If the thunk uses an impure reference such as '<nixpkgs>'
593-- the caching mechanism will fail as it merely measures the modification
687-- the caching mechanism will fail as it merely measures the modification
594-- time of the cache link and the expression to build.
688-- time of the cache link and the expression to build.
595−nixBuildThunkAttrWithCache thunkDir attr = do
689+nixBuildThunkAttrWithCache thunkSpec thunkDir attr = do
596− --NB: Expects thunkDir to be normalised with no trailing path separator.
597− --This should be guaranteed by the command argument parser.
598− let cacheErrHandler e
599− | isDoesNotExistError e = return Nothing -- expected from a cache miss
600− | otherwise = putLog Error (T.pack $ displayException e) >> return Nothing
601− cacheDir = thunkDir </> attrCacheFileName
602− cachePath = cacheDir </> attr <.> "out"
603 latestChange <- liftIO $ do
690 latestChange <- liftIO $ do
604− createDirectoryIfMissing False cacheDir
691+ let
605− let getModificationTimeMaybe = fmap rightToMaybe . try @IOError . getModificationTime
692+ getModificationTimeMaybe = fmap rightToMaybe . try @IOError . getModificationTime
693+ thunkFileNames = Map.keys $ _thunkSpec_files thunkSpec
606− maximum . catMaybes <$> mapM (getModificationTimeMaybe . (thunkDir </>)) thunkFileNames
694+ maximum . catMaybes <$> traverse (getModificationTimeMaybe . (thunkDir </>)) thunkFileNames
696+ let cachePaths' = nonEmpty $ Map.keys $ Map.filter (\case ThunkFileSpec_AttrCache -> True; _ -> False) $
697+ _thunkSpec_files thunkSpec
698+ for cachePaths' $ \cachePaths ->
699+ fmap NonEmpty.head $ for cachePaths $ \cacheDir -> do
701+ cachePath = cacheDir </> attr <.> "out"
703+ | isDoesNotExistError e = pure Nothing -- expected from a cache miss
704+ | otherwise = Nothing <$ putLog Error (T.pack $ displayException e)
607− cacheHit <- handle cacheErrHandler $ do
705+ cacheHit <- handle cacheErrHandler $ do
608− cacheTime <- liftIO $ posixSecondsToUTCTime . realToFrac . modificationTime <$> getSymbolicLinkStatus cachePath
706+ cacheTime <- liftIO $ posixSecondsToUTCTime . realToFrac . modificationTime <$> getSymbolicLinkStatus cachePath
609− return $ if latestChange <= cacheTime
707+ pure $ if latestChange <= cacheTime
610− then Just cachePath
708+ then Just cachePath
611− else Nothing
709+ else Nothing
612− case cacheHit of
710+ case cacheHit of
613− Just c -> return c
711+ Just c -> pure c
614− Nothing -> do
712+ Nothing -> do
615− putLog Warning $ T.pack $ mconcat [thunkDir, ": ", attr, " not cached, building ..."]
713+ putLog Warning $ T.pack $ mconcat [thunkDir, ": ", attr, " not cached, building ..."]
714+ liftIO $ createDirectoryIfMissing True (takeDirectory cachePath)
616− _ <- nixCmd $ NixCmd_Build $ def
715+ (cachePath <$) $ nixCmd $ NixCmd_Build $ def
617− Lens.& nixBuildConfig_outLink Lens..~ OutLink_IndirectRoot cachePath
716+ & nixBuildConfig_outLink .~ OutLink_IndirectRoot cachePath
618− Lens.& nixCmdConfig_target Lens..~ Target
717+ & nixCmdConfig_target .~ Target
619− { _target_path = Just thunkDir
718+ { _target_path = Just thunkDir
620− , _target_attr = Just attr
719+ , _target_attr = Just attr
621− , _target_expr = Nothing
720+ , _target_expr = Nothing
625-- | Build a nix attribute, and cache the result if possible
723-- | Build a nix attribute, and cache the result if possible
626nixBuildAttrWithCache
724nixBuildAttrWithCache
@@ -631,13 +729,15 @@ nixBuildAttrWithCache
631 -- ^ Attribute to build
729 -- ^ Attribute to build
632 -> m FilePath
730 -> m FilePath
633 -- ^ Symlink to cached or built nix output
731 -- ^ Symlink to cached or built nix output
634−nixBuildAttrWithCache exprPath attr = do
732+nixBuildAttrWithCache exprPath attr = readThunk exprPath >>= \case
635− readThunk exprPath >>= \case
636− -- Only packed thunks are cached. in particular, checkouts are not
733+ -- Only packed thunks are cached. In particular, checkouts are not.
734+ Right (ThunkData_Packed spec _) ->
637− Right (ThunkData_Packed _) -> nixBuildThunkAttrWithCache exprPath attr
735+ maybe build pure =<< nixBuildThunkAttrWithCache spec exprPath attr
638− _ -> nixCmd $ NixCmd_Build $ def
738+ build = nixCmd $ NixCmd_Build $ def
639− Lens.& nixBuildConfig_outLink Lens..~ OutLink_None
739+ & nixBuildConfig_outLink .~ OutLink_None
640− Lens.& nixCmdConfig_target Lens..~ Target
740+ & nixCmdConfig_target .~ Target
641 { _target_path = Just exprPath
741 { _target_path = Just exprPath
642 , _target_attr = Just attr
742 , _target_attr = Just attr
643 , _target_expr = Nothing
743 , _target_expr = Nothing
@@ -658,7 +758,7 @@ updateThunk p f = withSystemTempDirectory "obelisk-thunkptr-" $ \tmpDir -> do
659 copyThunkToTmp tmpDir thunkDir = readThunk thunkDir >>= \case
759 copyThunkToTmp tmpDir thunkDir = readThunk thunkDir >>= \case
660 Left err -> failWith $ "withThunkUnpacked: " <> T.pack (show err)
760 Left err -> failWith $ "withThunkUnpacked: " <> T.pack (show err)
661− Right (ThunkData_Packed _) -> do
761+ Right ThunkData_Packed{} -> do
662 let tmpThunk = tmpDir </> "thunk"
762 let tmpThunk = tmpDir </> "thunk"
663 callProcessAndLogOutput (Notice, Error) $
763 callProcessAndLogOutput (Notice, Error) $
664 proc cp ["-r", "-T", thunkDir, tmpThunk]
764 proc cp ["-r", "-T", thunkDir, tmpThunk]
@@ -676,58 +776,64 @@ unpackThunk :: MonadObelisk m => FilePath -> m ()
676unpackThunk = unpackThunk' False
776unpackThunk = unpackThunk' False
678-- | Check that we are not somewhere inside the thunk directory
778-- | Check that we are not somewhere inside the thunk directory
679−checkThunkDirectory :: MonadObelisk m => Text -> FilePath -> m ()
779+checkThunkDirectory :: MonadObelisk m => FilePath -> m ()
680−checkThunkDirectory msg thunkDir = do
780+checkThunkDirectory thunkDir = do
681 currentDir <- liftIO getCurrentDirectory
781 currentDir <- liftIO getCurrentDirectory
682 thunkDir' <- liftIO $ canonicalizePath thunkDir
782 thunkDir' <- liftIO $ canonicalizePath thunkDir
683− when (thunkDir' `L.isInfixOf` currentDir) $ failWith msg
783+ when (thunkDir' `L.isInfixOf` currentDir) $
784+ failWith [i|Can't perform thunk operations from within the thunk directory: ${thunkDir}|]
786+ -- Don't let thunk commands work when directly given an unpacked repo
787+ when (takeFileName thunkDir == unpackedDirName) $
788+ readThunk (takeDirectory thunkDir) >>= \case
789+ Right _ -> failWith [i|Refusing to perform thunk operation on ${thunkDir} because it is a thunk's unpacked source|]
685unpackThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
792unpackThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
686−unpackThunk' noTrail thunkDir = checkThunkDirectory "Can't pack/unpack from within the thunk directory" thunkDir >> readThunk thunkDir >>= \case
793+unpackThunk' noTrail thunkDir = checkThunkDirectory thunkDir *> readThunk thunkDir >>= \case
687− Left err -> failWith $ "thunk unpack: " <> T.pack (show err)
794+ Left err -> failWith [i|Invalid thunk at ${thunkDir}: ${err}|]
688 --TODO: Overwrite option that rechecks out thunk; force option to do so even if working directory is dirty
795 --TODO: Overwrite option that rechecks out thunk; force option to do so even if working directory is dirty
689− Right (ThunkData_Checkout _) -> failWith "thunk unpack: thunk is already unpacked"
796+ Right ThunkData_Checkout -> failWith [i|Thunk at ${thunkDir} is already unpacked|]
690− Right (ThunkData_Packed tptr) -> do
797+ Right (ThunkData_Packed _ tptr) -> do
691 let (thunkParent, thunkName) = splitFileName thunkDir
798 let (thunkParent, thunkName) = splitFileName thunkDir
692− withTempDirectory thunkParent thunkName $ \tmpRepo -> do
799+ withTempDirectory thunkParent thunkName $ \tmpThunk -> do
693− let obGitDir = tmpRepo </> ".git" </> "obelisk"
800+ let
694− s = case _thunkPtr_source tptr of
801+ (gitSrc, newSpec) = case _thunkPtr_source tptr of
695− ThunkSource_GitHub s' -> forgetGithub False s'
802+ ThunkSource_GitHub s' -> (forgetGithub False s', NonEmpty.head gitHubThunkSpecs)
696− ThunkSource_Git s' -> s'
803+ ThunkSource_Git s' -> (s', NonEmpty.head gitThunkSpecs)
697 withSpinner' ("Fetching thunk " <> T.pack thunkName)
804 withSpinner' ("Fetching thunk " <> T.pack thunkName)
698 (finalMsg noTrail $ const $ "Fetched thunk " <> T.pack thunkName) $ do
805 (finalMsg noTrail $ const $ "Fetched thunk " <> T.pack thunkName) $ do
699− let git = callProcessAndLogOutput (Notice, Notice) . gitProc tmpRepo
806+ let git = callProcessAndLogOutput (Notice, Notice) . gitProc (tmpThunk </> unpackedDirName)
700 git $ [ "clone" ]
807 git $ [ "clone" ]
701− ++ ("--recursive" <$ guard (_gitSource_fetchSubmodules s))
808+ ++ ["--recursive" | _gitSource_fetchSubmodules gitSrc]
702− ++ [ T.unpack $ gitUriToText $ _gitSource_url s ]
809+ ++ [ T.unpack $ gitUriToText $ _gitSource_url gitSrc ]
703− ++ do branch <- maybeToList $ _gitSource_branch s
810+ ++ do branch <- maybeToList $ _gitSource_branch gitSrc
704 [ "--branch", T.unpack $ untagName branch ]
811 [ "--branch", T.unpack $ untagName branch ]
705 git ["reset", "--hard", Ref.toHexString $ _thunkRev_commit $ _thunkPtr_rev tptr]
812 git ["reset", "--hard", Ref.toHexString $ _thunkRev_commit $ _thunkPtr_rev tptr]
706− when (_gitSource_fetchSubmodules s) $
813+ when (_gitSource_fetchSubmodules gitSrc) $
707 git ["submodule", "update", "--recursive", "--init"]
814 git ["submodule", "update", "--recursive", "--init"]
709− liftIO $ createDirectory obGitDir
816+ createThunk tmpThunk $ Left newSpec
710− callProcessAndLogOutput (Notice, Error) $
817+
711− proc cp ["-r", "-T", thunkDir </> ".", obGitDir </> "orig-thunk"]
818+ liftIO $ do
712− callProcessAndLogOutput (Notice, Error) $
819+ removePathForcibly thunkDir
713− proc "rm" ["-r", thunkDir]
820+ renameDirectory tmpThunk thunkDir
714− callProcessAndLogOutput (Notice, Error) $
821+
715− proc "mv" ["-T", tmpRepo, thunkDir]
717--TODO: add a rollback mode to pack to the original thunk
823--TODO: add a rollback mode to pack to the original thunk
718packThunk :: MonadObelisk m => ThunkPackConfig -> FilePath -> m ThunkPtr
824packThunk :: MonadObelisk m => ThunkPackConfig -> FilePath -> m ThunkPtr
719packThunk = packThunk' False
825packThunk = packThunk' False
721packThunk' :: MonadObelisk m => Bool -> ThunkPackConfig -> FilePath -> m ThunkPtr
827packThunk' :: MonadObelisk m => Bool -> ThunkPackConfig -> FilePath -> m ThunkPtr
722−packThunk' noTrail (ThunkPackConfig force thunkConfig) thunkDir = checkThunkDirectory "Can't pack/unpack from within the thunk directory" thunkDir >> readThunk thunkDir >>= \case
828+packThunk' noTrail (ThunkPackConfig force thunkConfig) thunkDir = checkThunkDirectory thunkDir *> readThunk thunkDir >>= \case
723− Left err -> failWith $ T.pack $ "thunk pack: " <> show err
724− Right (ThunkData_Packed _) -> failWith "pack: thunk is already packed"
829+ Right ThunkData_Packed{} -> failWith [i|Thunk at ${thunkDir} is is already packed|]
725− Right (ThunkData_Checkout _) -> do
830+ _ -> withSpinner'
726− withSpinner' ("Packing thunk " <> T.pack thunkDir)
831+ ("Packing thunk " <> T.pack thunkDir)
727− (finalMsg noTrail $ const $ "Packed thunk " <> T.pack thunkDir) $ do
832+ (finalMsg noTrail $ const $ "Packed thunk " <> T.pack thunkDir) $
728 thunkPtr <- modifyThunkPtrByConfig thunkConfig <$> getThunkPtr (not force) thunkDir (_thunkConfig_private thunkConfig)
834 thunkPtr <- modifyThunkPtrByConfig thunkConfig <$> getThunkPtr (not force) thunkDir (_thunkConfig_private thunkConfig)
729− callProcessAndLogOutput (Debug, Error) $ proc "rm" ["-rf", thunkDir]
835+ callProcessAndLogOutput (Debug, Error) $ proc rmPath ["-rf", thunkDir] -- thunkDir may be a symlink
730− liftIO $ createThunk thunkDir thunkPtr
836+ createThunk thunkDir $ Right thunkPtr
731 pure thunkPtr
837 pure thunkPtr
733modifyThunkPtrByConfig :: ThunkConfig -> ThunkPtr -> ThunkPtr
839modifyThunkPtrByConfig :: ThunkConfig -> ThunkPtr -> ThunkPtr
@@ -739,28 +845,29 @@ modifyThunkPtrByConfig (ThunkConfig markPrivate') ptr = case markPrivate' of
741getThunkPtr :: forall m. MonadObelisk m => Bool -> FilePath -> Maybe Bool -> m ThunkPtr
847getThunkPtr :: forall m. MonadObelisk m => Bool -> FilePath -> Maybe Bool -> m ThunkPtr
742−getThunkPtr checkClean thunkDir mPrivate = do
848+getThunkPtr checkClean dir mPrivate = do
849+ let repoLocations = [(".git", "."), (unpackedDirName, unpackedDirName)]
850+ repoLocation' <- liftIO $ flip findM repoLocations $ doesDirectoryExist . (dir </>) . fst
851+ thunkDir <- case repoLocation' of
852+ Nothing -> failWith [i|Can't find an unpacked thunk in ${dir}|]
853+ Just (_, path) -> pure $ normalise $ dir </> path
743 when checkClean $ ensureCleanGitRepo thunkDir True
855 when checkClean $ ensureCleanGitRepo thunkDir True
744 "thunk pack: thunk checkout contains unsaved modifications"
856 "thunk pack: thunk checkout contains unsaved modifications"
746 -- Check whether there are any stashes
858 -- Check whether there are any stashes
859+ when checkClean $ do
747− stashOutput <- readGitProcess thunkDir ["stash", "list"]
860+ stashOutput <- readGitProcess thunkDir ["stash", "list"]
748− when checkClean $ case T.null stashOutput of
861+ unless (T.null stashOutput) $
750 failWith $ T.unlines $
862 failWith $ T.unlines $
751 [ "thunk pack: thunk checkout has stashes"
863 [ "thunk pack: thunk checkout has stashes"
752 , "git stash list:"
864 , "git stash list:"
753 ] ++ T.lines stashOutput
865 ] ++ T.lines stashOutput
756 -- Get current branch
867 -- Get current branch
757 (mCurrentBranch, mCurrentCommit) <- do
868 (mCurrentBranch, mCurrentCommit) <- do
760− <$> readGitProcess thunkDir ["rev-parse", "--abbrev-ref", "HEAD"]
869+ b <- listToMaybe . T.lines <$> readGitProcess thunkDir ["rev-parse", "--abbrev-ref", "HEAD"]
763− <$> readGitProcess thunkDir ["rev-parse", "HEAD"]
870+ c <- listToMaybe . T.lines <$> readGitProcess thunkDir ["rev-parse", "HEAD"]
764 case b of
871 case b of
765 (Just "HEAD") -> failWith $ T.unlines
872 (Just "HEAD") -> failWith $ T.unlines
766 [ "thunk pack: You are in 'detached HEAD' state."
873 [ "thunk pack: You are in 'detached HEAD' state."
@@ -771,7 +878,7 @@ getThunkPtr checkClean thunkDir mPrivate = do
772 -- Get information on all branches and their (optional) designated upstream
879 -- Get information on all branches and their (optional) designated upstream
773 -- correspondents
880 -- correspondents
774− (headDump :: [Text]) <- T.lines <$> readGitProcess thunkDir
881+ headDump :: [Text] <- T.lines <$> readGitProcess thunkDir
775 [ "for-each-ref"
882 [ "for-each-ref"
776 , "--format=%(refname:short) %(upstream:short) %(upstream:remotename)"
883 , "--format=%(refname:short) %(upstream:short) %(upstream:remotename)"
777 , "refs/heads/"
884 , "refs/heads/"
@@ -817,7 +924,7 @@ getThunkPtr checkClean thunkDir mPrivate = do
819 -- loosely by https://stackoverflow.com/questions/7773939/show-git-ahead-and-behind-info-for-all-branches-including-remotes
926 -- loosely by https://stackoverflow.com/questions/7773939/show-git-ahead-and-behind-info-for-all-branches-including-remotes
820− stats <- iforM headUpstream $ \branch (upstream, _remote) -> do
927+ stats <- ifor headUpstream $ \branch (upstream, _remote) -> do
821 (stat :: [Text]) <- T.lines <$> readGitProcess thunkDir
928 (stat :: [Text]) <- T.lines <$> readGitProcess thunkDir
822 [ "rev-list", "--left-right"
929 [ "rev-list", "--left-right"
823 , T.unpack branch <> "..." <> T.unpack upstream
930 , T.unpack branch <> "..." <> T.unpack upstream
@@ -841,8 +948,9 @@ getThunkPtr checkClean thunkDir mPrivate = do
841 \pushed but this repo's remote tracking branches don't know it.)"
948 \pushed but this repo's remote tracking branches don't know it.)"
951+ when checkClean $ do
844− -- We assume it's safe to pack the thunk at this point
952+ -- We assume it's safe to pack the thunk at this point
845− putLog Informational "All changes safe in git remotes. OK to pack thunk."
953+ putLog Informational "All changes safe in git remotes. OK to pack thunk."
847 let remote = maybe "origin" snd $ flip Map.lookup headUpstream =<< mCurrentBranch
955 let remote = maybe "origin" snd $ flip Map.lookup headUpstream =<< mCurrentBranch