shellify (empty) → 0.10.0
raw patch · 19 files changed
+898/−0 lines, 19 filesdep +HStringTemplatedep +basedep +containers
Dependencies added: HStringTemplate, base, containers, data-default-class, directory, extra, hspec, hspec-core, mtl, raw-strings-qq, shake, shellify, text, unordered-containers
Files
- CHANGELOG.md +8/−0
- LICENSE +201/−0
- app/Main.hs +13/−0
- shellify.cabal +72/−0
- src/Constants.hs +33/−0
- src/FlakeTemplate.hs +27/−0
- src/Options.hs +105/−0
- src/Shellify.hs +71/−0
- src/ShellifyTemplate.hs +20/−0
- src/TemplateGeneration.hs +112/−0
- test/Spec.hs +118/−0
- test/outputs/inputs-from-different-registries-flake.nix +22/−0
- test/outputs/inputs-from-different-registries-shell.nix +10/−0
- test/outputs/inputs-from-know-and-unknown-sources-flake.nix +22/−0
- test/outputs/inputs-from-know-and-unknown-sources-shell.nix +10/−0
- test/outputs/multiple-repository-sources-shell.nix +10/−0
- test/outputs/two-build-inputs-and-command-shell.nix +14/−0
- test/outputs/two-nixpkgs-inputs-flake.nix +20/−0
- test/outputs/two-nixpkgs-inputs-shell.nix +10/−0
+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Changelog for Shellify++## 0.10.0+- Add dependency bounds++## 0.9.0+- Completed usable with good test coverage. I'll await some feedback before declaring a v1.0.0 release.+
+ LICENSE view
@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.
+ app/Main.hs view
@@ -0,0 +1,13 @@+module Main where++import Data.Text (pack)+import Shellify (runShellify)+import System.Environment (getArgs, getProgName)++main :: IO ()+main = do+ progName <- pack <$> getProgName+ getTextArgs+ >>= runShellify . (<>) [progName]++getTextArgs = fmap pack <$> getArgs
+ shellify.cabal view
@@ -0,0 +1,72 @@+cabal-version: 3.0+name: shellify+version: 0.10.0++author: Daniel Rolls+maintainer: daniel.rolls.27@googlemail.com+license: Apache-2.0+license-files: LICENSE+copyright: (c) 2023 Daniel Rolls+synopsis: A tool for generating shell.nix files+description:+ Please see the README on GitHub at <https://github.com/danielrolls/shellify>+category: Packaging+extra-source-files:+ CHANGELOG.md+ test/outputs/*.nix++common deps+ default-language: GHC2021+ build-depends:+ base >=4.16.4.0 && <4.17,+ raw-strings-qq >=1.1 && <1.2,+ text >=1.2.5.0 && <1.3++ default-extensions:+ LambdaCase+ OverloadedStrings+ QuasiQuotes+ +library+ import: deps+ exposed-modules:+ Constants+ FlakeTemplate+ Options+ Shellify+ ShellifyTemplate+ TemplateGeneration+ Paths_shellify+ autogen-modules:+ Paths_shellify+ hs-source-dirs: src+ build-depends:+ containers >=0.6.5.1 && <0.7,+ data-default-class >=0.1.2.0 && <0.2,+ directory >=1.3.6.2 && <1.4,+ extra >=1.7.13 && <1.8,+ HStringTemplate >=0.8.8 && <0.9,+ mtl >=2.2.2 && <2.3,+ shake >=0.19.7 && <0.20,+ unordered-containers >=0.2.19.1 && <0.3++executable shellify+ import: deps+ main-is: Main.hs+ build-depends: + shellify >=0+ hs-source-dirs: app++test-suite haskelltest-test+ import: deps+ type: exitcode-stdio-1.0+ main-is: Spec.hs+ hs-source-dirs: test+ other-modules:+ Paths_shellify+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ build-depends:+ hspec >=2.9.7 && <2.10,+ hspec-core >=2.9.7 && <2.10,+ shellify >=0+
+ src/Constants.hs view
@@ -0,0 +1,33 @@+module Constants where++import Data.Text (Text())+import Text.RawString.QQ (r)++helpText :: Text -> Text+helpText progName = "USAGE: " <> progName <> [r| -p [PACKAGES] + |] <> progName <> [r| [--with-flakes] [PACKAGES]++Pass nix-shell arguments to nix-shellify to have it generate a shell.nix in+the current directory. You can then just run nix shell or nix-shell in that+directory to have those packages in your environment. To run nix commands+you must first install Nix.++Options++ -p / --packages+ Specify packages for nix-shell compatability++ --command / --run+ Command to run after creating the shell++ --with-flake+ When using the command in a flake-like style use this switch to have a+ flake.nix created in addition to a shell.nix. Highly recommended to ensure+ the versions of dependencies are kept for reproducibility and so that+ shells are cached to load faster.+|]++noPackagesError = [r|I can't write out a shell file without any packages specified.+Try 'nix-shellify --help' for more information.|] :: Text++pkgsDecl var repo = var <> [r| = if builtins.hasAttr "packages" |] <> repo <> [r| then |] <> repo <> [r|.packages.${system} else ( if builtins.hasAttr "legacyPackages" |] <> repo <> [r| then |] <> repo <> [r|.legacyPackages.${system} else |] <> repo <> [r|);|]
+ src/FlakeTemplate.hs view
@@ -0,0 +1,27 @@+module FlakeTemplate where++import Text.RawString.QQ (r)+++flakeTemplate = [r|{+ description = "my project description";++ inputs = {++ flake-utils.url = "github:numtide/flake-utils";+ $repo_inputs;separator='+ '$++ };++ outputs = { self, $repos;separator=', '$, flake-utils }:+ flake-utils.lib.eachDefaultSystem+ (system:+ let $pkgs_decls;separator='+ '$+ in+ {+ devShells.default = import ./shell.nix { $shell_args;separator=' '$ };+ }+ );+}|]
+ src/Options.hs view
@@ -0,0 +1,105 @@+module Options (Package(..), Options(..), def, Packages, options) where+import Prelude hiding (takeWhile, writeFile)++import Constants+import FlakeTemplate+import ShellifyTemplate++import Control.Applicative ((<|>))+import Control.Arrow ((+++))+import Control.Monad (when)+import Data.Bool (bool)+import Data.Default.Class (Default(def))+import Data.List (find, sort)+import Data.Maybe (fromMaybe)+import Data.Text (isInfixOf, isPrefixOf, pack, replace, splitOn, stripPrefix, takeWhile, Text(), unpack)+import Data.Text.IO (hPutStrLn, writeFile)+import qualified Data.Text.IO as Text+import GHC.IO.Exception (ExitCode(ExitSuccess, ExitFailure))+import System.Directory (doesPathExist)+import System.Exit (exitWith)+import System.IO (stderr)+import Text.StringTemplate (newSTMP, render, setAttribute, StringTemplate)++type Package = Text+type Packages = [ Package ]+data Options = Options {+ packages :: Packages+ , command :: Maybe Text+ , generateFlake :: Bool+}++data OptionsParser = OptionsParser [Text] -- remainingOptions+ (Either Text (Options -> Options)) -- result++options :: Text -> [Text] -> Either Text Options+options progName args =+ let optionsHandler | hasShellArg args = newStyleOption+ | otherwise = oldStyleOption+ shellArgFilter | hasShellArg args = filter (/= "shell")+ | otherwise = id+ optionsCaller f = worker + where worker (OptionsParser [] t) = t+ worker (OptionsParser (hd:tl) res) =+ let (OptionsParser newRemaining newRes) = f hd tl+ in worker $ OptionsParser newRemaining ((.) <$> newRes <*> res)++ screenForNoPackages (Right opts) | null (packages opts) = Left noPackagesError+ screenForNoPackages anyThingElse = anyThingElse+ initialArgumentsToParse = shellArgFilter args+ initialModifier = Right $ if hasShellArg args then setFlakeGeneration else id+ initialOptionParser = OptionsParser initialArgumentsToParse initialModifier+ in screenForNoPackages $ ($ def) <$> optionsCaller optionsHandler initialOptionParser++ where oldStyleOption :: Text -> [Text] -> OptionsParser+ oldStyleOption "-p" = handlePackageSwitch+ oldStyleOption "--packages" = handlePackageSwitch+ oldStyleOption opt = baseOption opt+ newStyleOption "-p" = returnError "-p not supported with new style commands"+ newStyleOption "--packages" = returnError "--packages not supported with new style commands"+ newStyleOption arg | isSwitch arg = baseOption arg+ | otherwise = transformOptionsWith $ appendPackages [arg]+ baseOption :: Text -> [Text] -> OptionsParser+ baseOption "-h" = returnError $ helpText progName+ baseOption "--help" = returnError $ helpText progName+ baseOption "--command" = handleCommandSwitch+ baseOption "--run" = handleCommandSwitch+ baseOption "--with-flake" = transformOptionsWith setFlakeGeneration+ baseOption _ = transformOptionsWith id+ --doNothing = transformOptionsWith id+ transformOptionsWith fun wds = OptionsParser wds (Right fun)+ handlePackageSwitch wds = let (pkgs, remainingOptions) = consumePackageArgs wds+ in transformOptionsWith (appendPackages pkgs) remainingOptions+ handleCommandSwitch (hd:tl) | isSwitch hd+ = returnError "Argument missing to switch" tl+ | otherwise+ = transformOptionsWith (setCommand hd) tl+ handleCommandSwitch [] = returnError "Argument missing to switch" []++ appendPackages ps opts = opts{packages=ps ++ packages opts}+ setCommand cmd opts = opts{command=Just cmd}+ setFlakeGeneration opts = opts{generateFlake=True}+ returnError errorText remaining = OptionsParser remaining $ Left errorText++consumePackageArgs :: [Text] -> (Packages, [Text])+consumePackageArgs = worker []+ where worker pkgs [] = (pkgs, [])+ worker pkgs options@(hd:_) | isSwitch hd+ = (pkgs, options)+ worker pkgs (hd:tl) = worker (hd:pkgs) tl++hasShellArg [] = False+hasShellArg ("shell":_) = True+hasShellArg (hd:tl) | isSwitch hd = hasShellArg tl+ | otherwise = False++isSwitch = isPrefixOf "-"++instance Default Options where+ def = Options [] Nothing False++instance Eq Options where+ a == b = isEqual command+ && isEqual (sort . packages)+ && isEqual generateFlake+ where isEqual f = f a == f b
+ src/Shellify.hs view
@@ -0,0 +1,71 @@+module Shellify (parseOptionsAndCalculateExpectedFiles, runShellify) where++import Prelude hiding (writeFile)+import Constants+import FlakeTemplate+import Options+import ShellifyTemplate+import TemplateGeneration++import Control.Monad (when, (>=>))+import Data.Bool (bool)+import Data.Text (pack, Text(), unpack)+import Data.Text.IO (hPutStrLn, writeFile)+import qualified Data.Text.IO as Text+import GHC.IO.Exception (ExitCode(ExitSuccess, ExitFailure))+import System.Directory (doesPathExist)+import System.Exit (exitWith)+import System.IO (stderr)++createAFile (name, content) = do extCde <- createFile (unpack name) content+ when (extCde /= ExitSuccess)+ $ exitWith extCde+++runShellify :: [Text] -> IO ()+runShellify(pName:args) = getRegistryDB+ >>= either+ ((printErrorAndReturnFailure . ("Error calling nix registry: " <>) ) >=> exitWith)+ (\registryDB -> either printError+ (mapM_ createAFile)+ $ parseOptionsAndCalculateExpectedFiles registryDB pName args)+++parseOptionsAndCalculateExpectedFiles :: Text -> Text -> [Text] -> Either Text [(Text,Text)]+parseOptionsAndCalculateExpectedFiles registry programName =+ fmap+ (\opts ->+ ("shell.nix", generateShellDotNixText opts)+ : maybe+ []+ (pure . ("flake.nix",))+ (generateFlakeText registry opts))+ . options programName++createFile :: FilePath -> Text -> IO ExitCode+createFile fileName expectedContents = do+ fileContents <- doesPathExist fileName+ >>= bool+ (return Nothing)+ (Just <$> Text.readFile fileName)+ printError $ actionDescription (pack fileName) expectedContents fileContents+ when (shouldGenerateNewFile fileContents)+ $ writeFile fileName expectedContents+ return $ returnCode expectedContents fileContents++actionDescription :: Text -> Text -> Maybe Text -> Text+actionDescription fName _ Nothing = fName <> " does not exist. Creating one"+actionDescription fName a (Just b) | a == b = "The existing " <> fName <> " is good already"+actionDescription fName _ _ = "A " <> fName <> " exists already. Delete it or move it and try again"++returnCode :: Text -> Maybe Text -> ExitCode+returnCode _ Nothing = ExitSuccess+returnCode a (Just b) | a == b = ExitSuccess+returnCode _ _ = ExitFailure 1++shouldGenerateNewFile :: Maybe Text -> Bool+shouldGenerateNewFile = (== Nothing)++printErrorAndReturnFailure err = printError err >> return (ExitFailure 1)+printError = hPutStrLn stderr+
+ src/ShellifyTemplate.hs view
@@ -0,0 +1,20 @@+module ShellifyTemplate where++import Text.RawString.QQ (r)++shellifyTemplate = [r|{ $parameters;separator=', '$ }:++pkgs.mkShell {++ buildInputs = [+ $build_inputs;separator='+ '$+ ];+$if(shell_hook)$++ shellHook = ''+ $shell_hook$+ '';+$endif$+}+|]
+ src/TemplateGeneration.hs view
@@ -0,0 +1,112 @@+module TemplateGeneration (generateShellDotNixText, generateFlakeText, getRegistryDB) where++import Prelude hiding (lines)++import Constants+import FlakeTemplate+import Options+import ShellifyTemplate++import Data.Bool (bool)+import Data.List (find, sort)+import Data.List.Extra ((!?))+import Data.Maybe (catMaybes, fromMaybe)+import Data.Set (fromList, toList)+import Data.Text (isInfixOf, isPrefixOf, lines, pack, splitOn, Text())+import Development.Shake.Command (cmd, Exit(Exit), Stderr(Stderr), Stdout(Stdout))+import System.Exit (ExitCode (ExitSuccess))+import Text.StringTemplate (newSTMP, render, setAttribute)++generateFlakeText :: Text -> Options -> Maybe Text+generateFlakeText db Options{packages=packages, generateFlake=shouldGenerateFlake} =+ bool+ Nothing+ (Just $ render+ $ setAttribute "repo_inputs" repoInputs+ $ setAttribute "repos" repos+ $ setAttribute "pkgs_decls" pkgsDecls+ $ setAttribute "shell_args" shellArgs+ $ newSTMP flakeTemplate)+ shouldGenerateFlake+ where repos = uniq $ getPackageRepo <$> sort packages+ repoVars = getPackageRepoVarName <$> repos+ repoInputs = repoInput <$> repos+ repoInputLine repoName url = repoName <> ".url = \"" <> url <> "\";"+ repoInput repoName = repoInputLine repoName .+ either+ (error "Unexpected output from nix registry call: " <>)+ (fromMaybe "PLEASE ENTER input here")+ . findFlakeRepoUrl db $ repoName+ pkgsVar = (<> "Pkgs")+ pkgsVars = pkgsVar <$> repos+ pkgsDecls = (\repo -> pkgsDecl (pkgsVar repo) repo) <$> repos+ shellArgs = (\(a,b) -> a <> "=" <> b <> ";") <$> zip repoVars pkgsVars ++generateShellDotNixText :: Options -> Text+generateShellDotNixText Options{packages=packages, command=command} =+ render+ $ setAttribute "build_inputs" pkgs+ $ setAttribute "parameters" parameters+ $ maybe id+ (setAttribute "shell_hook")+ command+ $ newSTMP shellifyTemplate+ where pkgs = generateBuildInput <$> sort packages+ parameters = uniq $ generateParameters <$> sort packages+ generateBuildInput input = (toImportVar . getPackageRepo) input <> "." <> getPackageName input++getPackageRepo input | "#" `isInfixOf` input+ = head $ splitOn "#" input+ | otherwise+ = "nixpkgs"++getPackageName input | "#" `isInfixOf` input+ = head $ tail $ splitOn "#" input+ | otherwise+ = input++toImportVar var | var == "nixpkgs"+ = "pkgs"+ | otherwise+ = var++getPackageRepoVarName "nixpkgs" = "pkgs"+getPackageRepoVarName a = a++generateParameters :: Package -> Text+generateParameters package | "#" `isInfixOf` package+ && not ("nixpkgs#" `isPrefixOf` package)+ = getPackageRepo package+generateParameters _ = "pkgs ? import <nixpkgs> {}"++uniq :: Ord a => [a] -> [a]+uniq = toList . fromList++getRegistryDB :: IO (Either Text Text)+getRegistryDB =+ do (Stdout out, Stderr err, Exit ex) <- cmd+ ("nix --extra-experimental-features nix-command --extra-experimental-features flakes registry list" :: String)+ return $ bool (Left $ pack err)+ (Right $ pack out)+ (ex == ExitSuccess)++findFlakeRepoUrl :: Text -> Text -> Either Text (Maybe Text)+findFlakeRepoUrl haystack needle =+ fmap repoUrl . find ((needle ==) . repoName) . catMaybes <$> mapM getFlakeRepo (lines haystack)++data FlakeRepo = FlakeRepo {+ repoName :: Text+ , repoUrl :: Text+}++getFlakeRepo :: Text -> Either Text (Maybe FlakeRepo)+getFlakeRepo line = let expectedField = maybe (Left "unexepected nix registry command format")+ Right+ . (!?) (splitOn " " line)+ urlField = expectedField 2+ splitRepoField = splitOn ":" <$> expectedField 1+ potentialFlakeName ["flake", b] = Just b+ potentialFlakeName _ = Nothing+ f x y = (`FlakeRepo` y) <$> potentialFlakeName x+ in f <$> splitRepoField <*> urlField+
+ test/Spec.hs view
@@ -0,0 +1,118 @@+import Test.Hspec (describe, hspec, it, shouldBe)++import Options+import TestHelpers+++main = hspec $ do++ describe "When passing option combinations" $ do+ it "should print a message saying no package is specified when no argument is supplied" $+ shellifyWithArgs ""+ `shouldReturnSubstring`+ "without any packages specified"++ it "should complain if no package is specified" $+ shellifyWithArgs "nipkgs#cowsay"+ `shouldReturnSubstring`+ "without any packages specified"++ it "should show help text when requested" $ do+ shellifyWithArgs "-h"+ `shouldReturnSubstring` "USAGE:"+ shellifyWithArgs "--help"+ `shouldReturnSubstring` "USAGE:"++ it "should not support -p with shell" $ do+ shellifyWithArgs "shell -p cowsay"+ `shouldBe`+ Left "-p not supported with new style commands"+ shellifyWithArgs "shell nixpkgs#python --packages foo nixpkgs#cowsay"+ `shouldBe`+ Left "--packages not supported with new style commands"++ it "should allow a simple command to be specified with a package" $+ theOptions "-p python --command cowsay"+ `shouldBe`+ Right def{packages=["python"], command=Just "cowsay"}++ it "should allow a simple command to be specified before a package" $+ theOptions "--run cowsay -p python"+ `shouldBe`+ Right def{packages=["python"], command=Just "cowsay"}++ it "should allow a simple command to be specified before and after a package" $+ theOptions "-p cowsay --command cowsay -p python"+ `shouldBe`+ Right def{packages=[ "cowsay", "python" ], command=Just "cowsay"}++ it "Should fail if command has no argument" $ do+ shellifyWithArgs "--command -p python"+ `shouldReturnSubstring` "Argument missing to switch"+ shellifyWithArgs "--command"+ `shouldReturnSubstring` "Argument missing to switch"++ it "should be able to specify one program to install after other arguments" $+ "foo -p python"+ `shouldResultInPackages`+ [ "python" ]++ it "should support multiple packages passed to -p" $+ "-p python cowsay"+ `shouldResultInPackages`+ [ "cowsay", "python" ]++ it "should only accept packages up to the next switch" $+ "-p python --arg x 2"+ `shouldResultInPackages`+ [ "python" ]++ it "should support multiple adjacent -p switches" $+ "-p python -p cowsay"+ `shouldResultInPackages`+ [ "python", "cowsay" ]++ it "should support separated -p switches" $+ "-p cowsay --foo -p python"+ `shouldResultInPackages`+ [ "cowsay", "python" ]++ it "should support long switches" $+ "--packages cowsay"+ `shouldResultInPackages`+ [ "cowsay" ]++ it "should support new shell commands" $+ theOptions "shell nixpkgs#python nixpkgs#cowsay"+ `shouldBe`+ Right def{packages=[ "nixpkgs#python", "nixpkgs#cowsay" ], generateFlake=True}++ describe "when two buildInputs are required from two sources" $+ shellifyWithArgs "--with-flake shell foo#cowsay nixpkgs#python"+ `shouldReturnShellAndFlakeTextDefinedBy`+ "inputs-from-know-and-unknown-sources"++ describe "when using 2 simple buildInputs from one source" $+ shellifyWithArgs "shell --with-flake python cowsay"+ `shouldReturnShellAndFlakeTextDefinedBy`+ "two-nixpkgs-inputs"++ describe "when pulling from 2 different known sources" $+ shellifyWithArgs "shell nixpkgs#python blender-bin#blender_3_5"+ `shouldReturnShellAndFlakeTextDefinedBy`+ "inputs-from-different-registries"++ describe "when working with 2 nixkgs buildInputs" $+ shellifyWithArgs "shell nixpkgs#python nixpkgs#cowsay"+ `shouldReturnShellTextDefinedBy`+ "two-nixpkgs-inputs"++ describe "when working with multiple repos for known and unknown sources" $+ shellifyWithArgs "shell nixpkgs#python foo#cowsay"+ `shouldReturnShellTextDefinedBy`+ "multiple-repository-sources"++ describe "when a command is specified" $+ shellifyWithArgs "-p python -p cowsay --command cowsay"+ `shouldReturnShellTextDefinedBy`+ "two-build-inputs-and-command"
+ test/outputs/inputs-from-different-registries-flake.nix view
@@ -0,0 +1,22 @@+{+ description = "my project description";++ inputs = {++ flake-utils.url = "github:numtide/flake-utils";+ blender-bin.url = "github:edolstra/nix-warez?dir=blender";+ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";++ };++ outputs = { self, blender-bin, nixpkgs, flake-utils }:+ flake-utils.lib.eachDefaultSystem+ (system:+ let blender-binPkgs = if builtins.hasAttr "packages" blender-bin then blender-bin.packages.${system} else ( if builtins.hasAttr "legacyPackages" blender-bin then blender-bin.legacyPackages.${system} else blender-bin);+ nixpkgsPkgs = if builtins.hasAttr "packages" nixpkgs then nixpkgs.packages.${system} else ( if builtins.hasAttr "legacyPackages" nixpkgs then nixpkgs.legacyPackages.${system} else nixpkgs);+ in+ {+ devShells.default = import ./shell.nix { blender-bin=blender-binPkgs; pkgs=nixpkgsPkgs; };+ }+ );+}
+ test/outputs/inputs-from-different-registries-shell.nix view
@@ -0,0 +1,10 @@+{ blender-bin, pkgs ? import <nixpkgs> {} }:++pkgs.mkShell {++ buildInputs = [+ blender-bin.blender_3_5+ pkgs.python+ ];++}
+ test/outputs/inputs-from-know-and-unknown-sources-flake.nix view
@@ -0,0 +1,22 @@+{+ description = "my project description";++ inputs = {++ flake-utils.url = "github:numtide/flake-utils";+ foo.url = "PLEASE ENTER input here";+ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";++ };++ outputs = { self, foo, nixpkgs, flake-utils }:+ flake-utils.lib.eachDefaultSystem+ (system:+ let fooPkgs = if builtins.hasAttr "packages" foo then foo.packages.${system} else ( if builtins.hasAttr "legacyPackages" foo then foo.legacyPackages.${system} else foo);+ nixpkgsPkgs = if builtins.hasAttr "packages" nixpkgs then nixpkgs.packages.${system} else ( if builtins.hasAttr "legacyPackages" nixpkgs then nixpkgs.legacyPackages.${system} else nixpkgs);+ in+ {+ devShells.default = import ./shell.nix { foo=fooPkgs; pkgs=nixpkgsPkgs; };+ }+ );+}
+ test/outputs/inputs-from-know-and-unknown-sources-shell.nix view
@@ -0,0 +1,10 @@+{ foo, pkgs ? import <nixpkgs> {} }:++pkgs.mkShell {++ buildInputs = [+ foo.cowsay+ pkgs.python+ ];++}
+ test/outputs/multiple-repository-sources-shell.nix view
@@ -0,0 +1,10 @@+{ foo, pkgs ? import <nixpkgs> {} }:++pkgs.mkShell {++ buildInputs = [+ foo.cowsay+ pkgs.python+ ];++}
+ test/outputs/two-build-inputs-and-command-shell.nix view
@@ -0,0 +1,14 @@+{ pkgs ? import <nixpkgs> {} }:++pkgs.mkShell {++ buildInputs = [+ pkgs.cowsay+ pkgs.python+ ];++ shellHook = ''+ cowsay+ '';++}
+ test/outputs/two-nixpkgs-inputs-flake.nix view
@@ -0,0 +1,20 @@+{+ description = "my project description";++ inputs = {++ flake-utils.url = "github:numtide/flake-utils";+ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";++ };++ outputs = { self, nixpkgs, flake-utils }:+ flake-utils.lib.eachDefaultSystem+ (system:+ let nixpkgsPkgs = if builtins.hasAttr "packages" nixpkgs then nixpkgs.packages.${system} else ( if builtins.hasAttr "legacyPackages" nixpkgs then nixpkgs.legacyPackages.${system} else nixpkgs);+ in+ {+ devShells.default = import ./shell.nix { pkgs=nixpkgsPkgs; };+ }+ );+}
+ test/outputs/two-nixpkgs-inputs-shell.nix view
@@ -0,0 +1,10 @@+{ pkgs ? import <nixpkgs> {} }:++pkgs.mkShell {++ buildInputs = [+ pkgs.cowsay+ pkgs.python+ ];++}