Skip to content

Commit

Permalink
hlint refactor: various suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
flandweber committed May 21, 2024
1 parent b2bc747 commit 0800ebb
Show file tree
Hide file tree
Showing 10 changed files with 29 additions and 27 deletions.
8 changes: 3 additions & 5 deletions src/Niv/Cli.hs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ li = liftIO
cli :: IO ()
cli = do
((fsj, colors), nio) <-
execParserPure' Opts.defaultPrefs opts <$> getArgs
>>= Opts.handleParseResult
getArgs >>= Opts.handleParseResult . execParserPure' Opts.defaultPrefs opts
setColors colors
runReaderT (runNIO nio) fsj
where
Expand Down Expand Up @@ -471,8 +470,7 @@ cmdUpdate = \case
Just "git" -> gitCmd
Just "local" -> localCmd
_ -> githubCmd
finalSpec <- fmap attrsToSpec <$> li (doUpdate initialSpec cmd)
pure finalSpec
fmap attrsToSpec <$> li (doUpdate initialSpec cmd)
let (failed, sources') = partitionEithersHMS esources'
unless (HMS.null failed) $
li $
Expand Down Expand Up @@ -578,7 +576,7 @@ cmdDrop packageName = \case
tsay $ "Dropping package: " <> unPackageName packageName
fsj <- getFindSourcesJson
sources <- unSources <$> li (getSources fsj)
when (not $ HMS.member packageName sources) $
unless (HMS.member packageName sources) $
li $
abortCannotDropNoSuchPackage packageName
li $
Expand Down
7 changes: 4 additions & 3 deletions src/Niv/Git/Cmd.hs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import qualified Data.ByteString.Char8 as B8
import qualified Data.HashMap.Strict as HMS
import Data.Maybe
import qualified Data.Text as T
import Data.Char (isDigit)
import Data.Text.Extended as T
import Niv.Cmd
import Niv.Logger
Expand Down Expand Up @@ -52,7 +53,7 @@ gitExtraLogs attrs = noteRef <> warnRefBranch <> warnRefTag
mkWarn
"Your source contains both a `ref` and a `tag`. The `ref` will be used by Nix to fetch the repo."
member x = HMS.member x attrs
textIf cond txt = if cond then [txt] else []
textIf cond txt = [txt | cond]

parseGitShortcut :: T.Text -> Maybe (PackageName, Aeson.Object)
parseGitShortcut txt'@(T.dropWhileEnd (== '/') -> txt) =
Expand Down Expand Up @@ -179,7 +180,7 @@ latestRev repo branch = do
sout <- runGit gitArgs
case sout of
ls@(_ : _ : _) -> abortTooMuchOutput gitArgs ls
(l1 : []) -> parseRev gitArgs l1
[l1] -> parseRev gitArgs l1
[] -> abortNoOutput gitArgs
where
parseRev args l = maybe (abortNoRev args l) pure $ do
Expand Down Expand Up @@ -241,7 +242,7 @@ runGit args = do
isRev :: T.Text -> Bool
isRev t =
-- commit hashes are comprised of abcdef0123456789
T.all (\c -> (c >= 'a' && c <= 'f') || (c >= '0' && c <= '9')) t
T.all (\c -> (c >= 'a' && c <= 'f') || isDigit c) t
&&
-- commit _should_ be 40 chars long, but to be sure we pick 7
T.length t >= 7
Expand Down
4 changes: 2 additions & 2 deletions src/Niv/Git/Test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ test_gitUpdateRev :: IO ()
test_gitUpdateRev = do
interState <- evalUpdate initialState $ proc () ->
gitUpdate (error "should be def") defaultBranchAndHEAD' -< ()
let interState' = HMS.map (first (\_ -> Free)) interState
let interState' = HMS.map (first (const Free)) interState
actualState <- evalUpdate interState' $ proc () ->
gitUpdate latestRev' (error "should update") -< ()
unless ((snd <$> actualState) == expectedState) $
Expand Down Expand Up @@ -109,7 +109,7 @@ test_gitCalledOnce = do
latestRev'' <- once2 latestRev'
interState <- evalUpdate initialState $ proc () ->
gitUpdate (error "should be def") defaultBranchAndHEAD'' -< ()
let interState' = HMS.map (first (\_ -> Free)) interState
let interState' = HMS.map (first (const Free)) interState
actualState <- evalUpdate interState' $ proc () ->
gitUpdate latestRev'' (error "should update") -< ()
unless ((snd <$> actualState) == expectedState) $
Expand Down
4 changes: 2 additions & 2 deletions src/Niv/GitHub.hs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ githubUpdate prefetch latestRev ghRepo = proc () -> do
let isTarGuess = (\u -> "tar.gz" `T.isSuffixOf` u || ".tgz" `T.isSuffixOf` u) <$> url
type' <- useOrSet "type" -< bool "file" "tarball" <$> isTarGuess :: Box T.Text
let doUnpack = (== "tarball") <$> type'
_sha256 <- update "sha256" <<< run (\(up, u) -> prefetch up u) -< (,) <$> doUnpack <*> url
_sha256 <- update "sha256" <<< run (uncurry prefetch) -< (,) <$> doUnpack <*> url
returnA -< ()
where
completeSpec :: Update () (Box T.Text)
completeSpec = proc () -> do
owner <- load "owner" -< ()
repo <- load "repo" -< ()
repoInfo <- run (\(a, b) -> ghRepo a b) -< (,) <$> owner <*> repo
repoInfo <- run (uncurry ghRepo) -< (,) <$> owner <*> repo
branch <-
useOrSet "branch" <<< arr (fmap $ fromMaybe "master")
-<
Expand Down
10 changes: 7 additions & 3 deletions src/Niv/GitHub/API.hs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,8 @@ defaultRequest (map T.encodeUtf8 -> parts) = do
let path = T.encodeUtf8 githubPath <> BS8.intercalate "/" parts
mtoken <- lookupEnv' "GITHUB_TOKEN"
pure
$ ( flip (maybe id) mtoken $ \token ->
HTTP.addRequestHeader "authorization" ("token " <> BS8.pack token)
)
$ maybe id (\token ->
HTTP.addRequestHeader "authorization" ("token " <> BS8.pack token)) mtoken
$ HTTP.setRequestPath path
$ HTTP.addRequestHeader "user-agent" "niv"
$ HTTP.addRequestHeader "accept" "application/vnd.github.v3+json"
Expand Down Expand Up @@ -140,18 +139,21 @@ lookupEnv' vn =
Nothing -> lookupEnv ("NIV_" <> vn)

githubHost :: T.Text
{-# NOINLINE githubHost #-}
githubHost = unsafePerformIO $ do
lookupEnv' "GITHUB_HOST" >>= \case
Just (T.pack -> x) -> pure x
Nothing -> pure "github.com"

githubApiPort :: Int
{-# NOINLINE githubApiPort #-}
githubApiPort = unsafePerformIO $ do
lookupEnv' "GITHUB_API_PORT" >>= \case
Just (readMaybe -> Just x) -> pure x
_ -> pure $ if githubSecure then 443 else 80

githubApiHost :: T.Text
{-# NOINLINE githubApiHost #-}
githubApiHost = unsafePerformIO $ do
lookupEnv' "GITHUB_API_HOST" >>= \case
Just (T.pack -> x) -> pure x
Expand All @@ -162,13 +164,15 @@ githubApiHost = unsafePerformIO $ do
-- https://github.com/nmattia/niv/issues/280

githubSecure :: Bool
{-# NOINLINE githubSecure #-}
githubSecure = unsafePerformIO $ do
lookupEnv "NIV_GITHUB_INSECURE" >>= \case
Just "" -> pure True
Just _ -> pure False
Nothing -> pure True

githubPath :: T.Text
{-# NOINLINE githubPath #-}
githubPath = unsafePerformIO $ do
lookupEnv "NIV_GITHUB_PATH" >>= \case
Just (T.pack -> x) -> pure $ fromMaybe x (T.stripSuffix "/" x) <> "/"
Expand Down
8 changes: 3 additions & 5 deletions src/Niv/GitHub/Cmd.hs
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@ parseGitHubPackageSpec =
-- Shortcuts for common attributes
shortcutAttributes :: Opts.Parser (K.Key, Aeson.Value)
shortcutAttributes =
foldr (<|>) empty $
mkShortcutAttribute
<$> ["branch", "owner", "rev", "version"]
foldr ((<|>) . mkShortcutAttribute) empty ["branch", "owner", "rev", "version"]
-- TODO: infer those shortcuts from 'Update' keys
mkShortcutAttribute :: T.Text -> Opts.Parser (K.Key, Aeson.Value)
mkShortcutAttribute = \case
Expand Down Expand Up @@ -165,15 +163,15 @@ nixPrefetchURL unpack turl@(T.unpack -> url) = do
(ExitSuccess, l : _) -> pure $ T.pack l
_ -> abortNixPrefetchExpectedOutput (T.pack <$> args) (T.pack sout) (T.pack serr)
where
args = (if unpack then ["--unpack"] else []) <> [url, "--name", sanitizeName basename]
args = (["--unpack" | unpack]) <> [url, "--name", sanitizeName basename]
runNixPrefetch = readProcessWithExitCode "nix-prefetch-url" args ""
sanitizeName = T.unpack . T.filter isOk
basename = last $ T.splitOn "/" turl
-- From the nix-prefetch-url documentation:
-- Path names are alphanumeric and can include the symbols +-._?= and must
-- not begin with a period.
-- (note: we assume they don't begin with a period)
isOk = \c -> isAlphaNum c || T.any (c ==) "+-._?="
isOk c = isAlphaNum c || T.any (c ==) "+-._?="

abortNixPrefetchExpectedOutput :: [T.Text] -> T.Text -> T.Text -> IO a
abortNixPrefetchExpectedOutput args sout serr =
Expand Down
2 changes: 1 addition & 1 deletion src/Niv/GitHub/Test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ test_githubUpdatesOnce = do
error $
"State mismatch: " <> show tmpState
-- Set everything free
let tmpState' = HMS.map (first (\_ -> Free)) tmpState
let tmpState' = HMS.map (first (const Free)) tmpState
actualState <- evalUpdate tmpState' $ proc () ->
githubUpdate (prefetch ioref) latestRev ghRepo -< ()
unless ((snd <$> actualState) == expectedState) $
Expand Down
4 changes: 3 additions & 1 deletion src/Niv/Logger.hs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ setColors :: Colors -> IO ()
setColors = writeIORef colors

useColors :: Bool
useColors = unsafePerformIO $ (\c -> c == Always) <$> readIORef colors
{-# NOINLINE useColors #-}
useColors = unsafePerformIO $ (== Always) <$> readIORef colors

type S = String -> String

Expand Down Expand Up @@ -83,6 +84,7 @@ jobStackSize :: (MonadIO io) => io Int
jobStackSize = readIORef jobStack

jobStack :: IORef Int
{-# NOINLINE jobStack #-}
jobStack = unsafePerformIO $ newIORef 0

{-# NOINLINE jobStackSize #-}
Expand Down
7 changes: 3 additions & 4 deletions src/Niv/Sources.hs
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,12 @@ getSourcesEither fsj = do
valueToSources :: Aeson.Value -> Maybe Sources
valueToSources = \case
Aeson.Object obj ->
fmap (Sources . mapKeys PackageName . KM.toHashMapText) $
traverse
(Sources . mapKeys PackageName . KM.toHashMapText <$> traverse
( \case
Aeson.Object obj' -> Just (PackageSpec obj')
_ -> Nothing
)
obj
obj)
_ -> Nothing
mapKeys :: (Eq k2, Hashable k2) => (k1 -> k2) -> HMS.HashMap k1 v -> HMS.HashMap k2 v
mapKeys f = HMS.fromList . map (first f) . HMS.toList
Expand All @@ -86,7 +85,7 @@ getSources fsj = do
pure

setSources :: FindSourcesJson -> Sources -> IO ()
setSources fsj sources = Aeson.encodeFilePretty (pathNixSourcesJson fsj) sources
setSources fsj = Aeson.encodeFilePretty (pathNixSourcesJson fsj)

newtype PackageName = PackageName {unPackageName :: T.Text}
deriving newtype (Eq, Hashable, FromJSONKey, ToJSONKey, Show)
Expand Down
2 changes: 1 addition & 1 deletion src/Niv/Update.hs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ runUpdate' attrs = \case
v' <- runBox v
case renderTemplate
( \k ->
(decodeBox $ "When rendering template " <> v') . snd
decodeBox ("When rendering template " <> v') . snd
<$> HMS.lookup k attrs
)
v' of
Expand Down

0 comments on commit 0800ebb

Please sign in to comment.