on master help sign in
Merge branch 'develop' into depend-on-reflex-dom-core
d8612b1Elliot Cameron
ChangeLog.md+28−3
@@ -1,16 +1,41 @@
1# Revision history for obelisk
1# Revision history for obelisk
2
2
3−This project's release branch is `master`. This log is written from the perspective of the release branch: when changes hit `master`, they are considered released, and the date should reflect that release.
3+This project's release branch is `master`. This log is written from the perspective of the release branch: when changes hit `master`, they are considered released.
4
4
5## Unreleased
5## Unreleased
6
6
7+* ([#715](https://github.com/obsidiansystems/obelisk/pull/715)) In `Obelisk.Route` deprecate `isoEncoder` and `prismEncoder` in favor of more precisely named `viewEncoder` and `reviewEncoder` (respectively) and improve documentation regarding contravariance of `reviewEncoder`.
8+* ([#606](https://github.com/obsidiansystems/obelisk/pull/606)) Obelisk now depends directly on `reflex-dom-core` instead of `reflex-dom`. This avoids requiring a `jsaddle-webkit2gtk` dependency in apps that are only using `jsaddle-warp`.
9+
10+## v0.8.0.0
11+
12+* ([#674](https://github.com/obsidiansystems/obelisk/pull/674), [#711](https://github.com/obsidiansystems/obelisk/pull/711)) Introduce a new thunk format to support accessing the thunk's source directly when packed. When packed, thunks have an additional file called `thunk.nix` and `default.nix` is now a think wrapper around that.
13+* ([#665](https://github.com/obsidiansystems/obelisk/pull/665)) Add `--interpret` and `--no-interpret` options to `ob run`/`ob watch`/`ob repl`/`ob shell`. These options allow you to pick which paths will be pre-compiled by `nix` when entering the shell/session and which won't. For example `ob run --no-interpret dep` will ensure that any dependencies found in `./dep` will be built by `nix` before loading the rest of the project into the `ghci` session. The same configuration for `ob shell` will ensure that those packages are built and available in the `ghc` package database inside the shell.
14+
15+ **NOTE:** `ob shell`'s default behavior is now different. By default it now behaves like `ob run`/`ob watch`/`ob repl` in that it does *not* pre-build any packages whose `.cabal` or `package.yaml` files are found in the project. To regain the previous behavior, use `ob shell --no-interpret . --interpret backend --interpret common --interpret frontend` from the project root.
16+* ([#695](https://github.com/obsidiansystems/obelisk/pull/695)) `ob deploy init` now requires that your obelisk project be a clean `git` checkout with pushed changes. It has always required that your obelisk project be a `git` repository, but it did not require that your local changes be committed and pushed. This new requirement is added to ensure users don't accidentally create a deployment pointing to an old version of the project.
17+* ([#705](https://github.com/obsidiansystems/obelisk/pull/705)) Add `Obelisk.Route.packTextEncoder` and generalize `Obelisk.Route.unpackTextEncoder` over any `Data.Text.Lens.IsText`.
18+* ([#712](https://github.com/obsidiansystems/obelisk/pull/712)) Update [`reflex-platform`](https://github.com/reflex-frp/reflex-platform) to version 0.5.3.0.
19+* ([#700](https://github.com/obsidiansystems/obelisk/pull/700)) Ensure `ob init` uses the thunk format of the target obelisk rather than the one currently running the init command. If a user had installed a version of obelisk with a new thunk format, a newly initialized skeleton of an older version would not be able to unpack it's own `.obelisk/impl`.
20+* ([#693](https://github.com/obsidiansystems/obelisk/pull/693)) Fix a bug where some packages in `.attr-cache` directories would be incorrectly picked up and used instead of the correct ones when using `ob run`/`ob watch`/`ob repl`.
21+* ([#709](https://github.com/obsidiansystems/obelisk/pull/709)) Fix a bug in obelisk's preprocessor causing it to incorrectly skip files in some circumstances.
22+* ([#663](https://github.com/obsidiansystems/obelisk/pull/663)) Add **experimental** support for [`ghcide`](https://github.com/digital-asset/ghcide). See the README for more information.
23+* ([#714](https://github.com/obsidiansystems/obelisk/pull/714)) Miscellaneous improvements to CLI help and logging.
24+
25+## v0.7.0.1
26+
27+* Fix the version number for `ob` the command-line tool. ([#679](https://github.com/obsidiansystems/obelisk/pull/679))
28+
29+## v0.7.0.0
30+
7* Fully support HTTP [Range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range) requests on static assets to support Safari. ([#664](https://github.com/obsidiansystems/obelisk/pull/664))
31* Fully support HTTP [Range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range) requests on static assets to support Safari. ([#664](https://github.com/obsidiansystems/obelisk/pull/664))
8* Support non-EC2 deployments. ([#658](https://github.com/obsidiansystems/obelisk/pull/658))
32* Support non-EC2 deployments. ([#658](https://github.com/obsidiansystems/obelisk/pull/658))
9* Fix `ob deploy test android` to work. ([#645](https://github.com/obsidiansystems/obelisk/pull/645))
33* Fix `ob deploy test android` to work. ([#645](https://github.com/obsidiansystems/obelisk/pull/645))
10* Fix vulnerability where Android deployments would leave signing keys in the nix store which is world readable. ([#645](https://github.com/obsidiansystems/obelisk/pull/645)) (Thanks to [kmicklas](https://github.com/kmicklas) for the report.)
34* Fix vulnerability where Android deployments would leave signing keys in the nix store which is world readable. ([#645](https://github.com/obsidiansystems/obelisk/pull/645)) (Thanks to [kmicklas](https://github.com/kmicklas) for the report.)
11−* Add `Obelisk.Backend.runBackendWith` to allow customization of how GHCJS resources are loaded in the page. ([#668](https://github.com/obsidiansystems/obelisk/pull/668))
35+* Add `Obelisk.Backend.runBackendWith` to allow several customizations. ([#668](https://github.com/obsidiansystems/obelisk/pull/668), [#644](https://github.com/obsidiansystems/obelisk/pull/644))
12* Add `ob profile` command to run Obelisk projects with profiling. `ob profile` works like `ob run`, but instead of using `ghci`, it builds an executable that is built with profiling enabled. ([#654](https://github.com/obsidiansystems/obelisk/pull/654))
36* Add `ob profile` command to run Obelisk projects with profiling. `ob profile` works like `ob run`, but instead of using `ghci`, it builds an executable that is built with profiling enabled. ([#654](https://github.com/obsidiansystems/obelisk/pull/654))
13−* Obelisk now depends directly on `reflex-dom-core` instead of `reflex-dom`. This avoids requiring a `jsaddle-webkit2gtk` dependency in apps that are only using `jsaddle-warp`. ([#606](https://github.com/obsidiansystems/obelisk/pull/606))
37+* Obelisk's `default.nix` now exposes `mkAssets` function which is used to construct the assets served by an Obelisk application. ([#651](https://github.com/obsidiansystems/obelisk/pull/651))
38+* Bump reflex-platform to v0.5.2.0. ([#671](https://github.com/obsidiansystems/obelisk/pull/671))
14
39
15## v0.6.0.0 - 2020-02-21
40## v0.6.0.0 - 2020-02-21
16
41
README.md+45−4
@@ -10,7 +10,10 @@ Obelisk provides an easy way to develop and deploy your [Reflex](https://github.
10- [Developing an Obelisk project](#developing-an-obelisk-project)
10- [Developing an Obelisk project](#developing-an-obelisk-project)
11 - [Adding Packages](#adding-packages)
11 - [Adding Packages](#adding-packages)
12 - [Adding Package Overrides](#adding-package-overrides)
12 - [Adding Package Overrides](#adding-package-overrides)
13− - [Running over https](#running-over-https)
13+ - [Running over HTTPS](#running-over-https)
14+ - [IDE Support](#ide-support)
15+ - [Terminal-based feedback](#terminal-based-feedback)
16+ - [Experimental `ghcide` support](#experimental-ghcide-support)
14- [Deploying](#deploying)
17- [Deploying](#deploying)
15 - [Locally](#locally)
18 - [Locally](#locally)
16 - [Default EC2 Deployment](#default-ec2-deployment)
19 - [Default EC2 Deployment](#default-ec2-deployment)
@@ -169,9 +172,47 @@ project ./. ({ pkgs, ... }: {
169
172
170### Running over HTTPS
173### Running over HTTPS
171
174
172−To run your app locally over https, update the protocol in `config/common/route` to `https`, and then use `ob run` as normal.
175+To run your app locally over HTTPS, update the protocol in `config/common/route` to `https`, and then use `ob run` as normal.
173−
176+
174−Since Obelisk generates a self-signed certificate for running https, the browser will issue a warning about using an invalid certificate. On Chrome, you can go to `chrome://flags/#allow-insecure-localhost` to enable invalid certificates for localhost.
177+Since Obelisk generates a self-signed certificate for running HTTPS, the browser will issue a warning about using an invalid certificate. On Chrome, you can go to `chrome://flags/#allow-insecure-localhost` to enable invalid certificates for localhost.
178+
179+### IDE Support
180+
181+#### Terminal-based feedback
182+
183+Obelisk officially supports terminal-based feedback (akin to [`ghcid`](https://github.com/ndmitchell/ghcid)) in `ob run` and `ob watch`.
184+
185+#### **Experimental** `ghcide` support
186+
187+> **NOTE:** `ghcide` support is strictly **experimental** and **not officially supported**. There is no guarantee that it will work for you or that this support will be maintained over time.
188+
189+To try out the **experimental** [`ghcide`](https://github.com/digital-asset/ghcide) support:
190+
191+ * Install a `ghcide` plugin for your editor.
192+ * Add `__withGhcide = true;` to your Obelisk project's `default.nix` (inside the call to `project`). With this setting, `ob shell` will provide `ghcide` as well.
193+ * Add `hie-bios.sh` to the root of your project:
194+ ```shell
195+ cat > hie-bios.sh <<'EOF'
196+ #!/usr/bin/env bash
197+ source "$HOME/.bash_profile"; # NOTE: Some editors need help finding 'ob' and this assumes that `ob` is made available on your `$PATH` in `.bash_profile`
198+ ob internal export-ghci-configuration > "$HIE_BIOS_OUTPUT"
199+ EOF
200+ chmod +x hie-bios.sh
201+ ```
202+ * **Note:** In some projects you need to use `ob internal export-ghci-configuration --use-relative-paths` in this script instead. This is known to happen when your project contains symlinks to other packages.
203+ * Add `hie.yaml` to the root of your project:
204+ ```shell
205+ echo 'cradle: { bios: { program: hie-bios.sh } }' > hie.yaml
206+ ```
207+ * Test the configuration with `ob shell ghcide`. Assuming your project compiles and works with `ghcide` otherwise, this should succeed.
208+ * Start your editor in a way that it can access the appropriate `ghcide`:
209+ * This can sometimes be achieved with `ob shell 'start my editor'`.
210+ * If you can't easily start your editor in a way that it inherits your shell, you may need to customize how your `ghcide` plugin finds `ghcide` or create a custom `ghcide` replacement script that you install globally. For example, for Visual Studio Code on macOS adding a script called `ghcide` to your `PATH` like the one below will cause `ghcide` from each project's `ob shell` to be used:
211+ ```shell
212+ #!/usr/bin/env bash
213+ source "$HOME/.bash_profile" # NOTE: This assumes that `ob` is made available on your `$PATH` in `.bash_profile`
214+ ob shell "ghcide $@"
215+ ```
175
216
176## Deploying
217## Deploying
177
218
all-builds.nix+15−9
@@ -3,10 +3,7 @@
3 iosSdkVersion = "10.2";
3 iosSdkVersion = "10.2";
4 }
4 }
5, local-self ? import ./. self-args
5, local-self ? import ./. self-args
6−, supportedSystems ? [
6+, supportedSystems ? [ builtins.currentSystem ]
7− "x86_64-linux"
8− "x86_64-darwin"
9− ]
10}:
7}:
11
8
12let
9let
@@ -56,19 +53,28 @@ let
56 obelisk.haskellPackageSets.ghcjs
53 obelisk.haskellPackageSets.ghcjs
57 obeliskPackagesCommon;
54 obeliskPackagesCommon;
58 command = obelisk.command;
55 command = obelisk.command;
56+
57+ withSkeletonOptions = skel: options: (skel.passthru.__unstable__.self.extend (self: super: {
58+ userSettings = super.userSettings // options;
59+ })).project;
59− skeleton = import ./skeleton { inherit obelisk; };
60+ rawSkeleton = import ./skeleton { inherit obelisk; };
61+ skeleton = withSkeletonOptions rawSkeleton {
62+ withHoogle = true; # cache the Hoogle database for the skeleton
63+ __withGhcide = true; # cache the ghcide build for the skeleton
64+ };
65+
60− serverSkeletonExe = skeleton.exe;
66+ serverSkeletonExe = rawSkeleton.exe;
61 # TODO fix nixpkgs so it doesn't try to run the result of haskell shells as setup hooks.
67 # TODO fix nixpkgs so it doesn't try to run the result of haskell shells as setup hooks.
62 serverSkeletonShell = local-self.nixpkgs.runCommand "shell-safe-for-dep" {} ''
68 serverSkeletonShell = local-self.nixpkgs.runCommand "shell-safe-for-dep" {} ''
63 touch "$out"
69 touch "$out"
64 echo "return" >> "$out"
70 echo "return" >> "$out"
65 cat "${skeleton.shells.ghc}" >> "$out"
71 cat "${skeleton.shells.ghc}" >> "$out"
66 '';
72 '';
67− androidSkeleton = (import ./skeleton { inherit obelisk; }).android.frontend;
73+ androidSkeleton = skeleton.android.frontend;
68− iosSkeleton = (import ./skeleton { inherit obelisk; }).ios.frontend;
74+ iosSkeleton = skeleton.ios.frontend;
69 nameSuffix = if profiling then "profiled" else "unprofiled";
75 nameSuffix = if profiling then "profiled" else "unprofiled";
70 packages = {
76 packages = {
71− skeletonProfiledObRun = skeleton.__unstable__.profiledObRun;
77+ skeletonProfiledObRun = rawSkeleton.__unstable__.profiledObRun;
72 inherit
78 inherit
73 command
79 command
74 serverSkeletonShell
80 serverSkeletonShell
all-tests.nix+17−17
@@ -63,15 +63,18 @@ in
63 '';
63 '';
64 in ''
64 in ''
65 start_all()
65 start_all()
66− githost.wait_for_open_port("22")
67
66
68− with subtest("test obelisk is installed"):
67+ with subtest("obelisk is installed and git is configured"):
69 client.succeed("ob --help")
68 client.succeed("ob --help")
69+ client.succeed('git config --global user.email "you@example.com"')
70+ client.succeed('git config --global user.name "Your Name"')
71+
72+ githost.wait_for_open_port("22")
70
73
71− with subtest("test the client can access the server via ssh"):
74+ with subtest("the client can access the server via ssh"):
72 client.succeed("mkdir -p ~/.ssh/")
75 client.succeed("mkdir -p ~/.ssh/")
73 client.succeed(
76 client.succeed(
74− "cp ${privateKeyFile} ~/.ssh/id_rsa"
77+ "cp ${privateKeyFile} ~/.ssh/id_rsa"
75 )
78 )
76 client.succeed("chmod 600 ~/.ssh/id_rsa")
79 client.succeed("chmod 600 ~/.ssh/id_rsa")
77 client.wait_until_succeeds(
80 client.wait_until_succeeds(
@@ -82,36 +85,35 @@ in
82 )
85 )
83 client.wait_until_succeeds("ssh githost true")
86 client.wait_until_succeeds("ssh githost true")
84
87
85− with subtest("test a remote bare repo can be started"):
88+ with subtest("a remote bare repo can be started"):
86 githost.succeed("mkdir -p ~/myorg/myapp.git")
89 githost.succeed("mkdir -p ~/myorg/myapp.git")
87 githost.succeed("cd ~/myorg/myapp.git && git init --bare")
90 githost.succeed("cd ~/myorg/myapp.git && git init --bare")
88
91
89− with subtest("test a git project can be configured with a remote using ssh"):
92+ with subtest("a git project can be configured with a remote using ssh"):
90 client.succeed("mkdir -p ~/code/myapp")
93 client.succeed("mkdir -p ~/code/myapp")
91 client.succeed("cd ~/code/myapp && git init")
94 client.succeed("cd ~/code/myapp && git init")
92 client.succeed(
95 client.succeed(
93 "cp ${thunkableSample} ~/code/myapp/default.nix"
96 "cp ${thunkableSample} ~/code/myapp/default.nix"
94 )
97 )
95 client.succeed("cd ~/code/myapp && git add .")
98 client.succeed("cd ~/code/myapp && git add .")
96− client.succeed('git config --global user.email "you@example.com"')
99+
97− client.succeed('git config --global user.name "Your Name"')
98 client.succeed('cd ~/code/myapp && git commit -m "Initial"')
100 client.succeed('cd ~/code/myapp && git commit -m "Initial"')
99 client.succeed(
101 client.succeed(
100 "cd ~/code/myapp && git remote add origin root@githost:/root/myorg/myapp.git"
102 "cd ~/code/myapp && git remote add origin root@githost:/root/myorg/myapp.git"
101 )
103 )
102
104
103
105
104− with subtest("test pushing code to the remote"):
106+ with subtest("pushing code to the remote"):
105 client.succeed("cd ~/code/myapp && git push -u origin master")
107 client.succeed("cd ~/code/myapp && git push -u origin master")
106 client.succeed("cd ~/code/myapp && git status")
108 client.succeed("cd ~/code/myapp && git status")
107
109
108− with subtest("test obelisk can pack"):
110+ with subtest("obelisk can pack"):
109 client.succeed("ob -v thunk pack ~/code/myapp")
111 client.succeed("ob -v thunk pack ~/code/myapp")
110− client.succeed("grep -qF 'git' ~/code/myapp/default.nix")
112+ client.succeed("grep -qF 'git.json' ~/code/myapp/thunk.nix")
111 client.succeed("grep -qF 'myorg' ~/code/myapp/git.json")
113 client.succeed("grep -qF 'myorg' ~/code/myapp/git.json")
112 client.succeed("ob -v thunk unpack ~/code/myapp")
114 client.succeed("ob -v thunk unpack ~/code/myapp")
113
115
114− with subtest("test obelisk can set the public / private flag"):
116+ with subtest("obelisk can set the public / private flag"):
115 client.succeed("ob -v thunk pack ~/code/myapp --private")
117 client.succeed("ob -v thunk pack ~/code/myapp --private")
116 client.fail("""grep -qF '"private": practice' ~/code/myapp/git.json""")
118 client.fail("""grep -qF '"private": practice' ~/code/myapp/git.json""")
117 client.succeed("""grep -qF '"private": true' ~/code/myapp/git.json""")
119 client.succeed("""grep -qF '"private": true' ~/code/myapp/git.json""")
@@ -122,22 +124,20 @@ in
122 client.succeed("nix-build ~/code/myapp")
124 client.succeed("nix-build ~/code/myapp")
123 client.succeed("ob -v thunk unpack ~/code/myapp")
125 client.succeed("ob -v thunk unpack ~/code/myapp")
124
126
125− with subtest("test building an invalid thunk fails"):
127+ with subtest("building an invalid thunk fails"):
126 client.succeed("cd ~/code/myapp && git checkout -b bad")
128 client.succeed("cd ~/code/myapp && git checkout -b bad")
127 client.succeed(
129 client.succeed(
128 "cp ${invalidThunkableSample} ~/code/myapp/default.nix"
130 "cp ${invalidThunkableSample} ~/code/myapp/default.nix"
129 )
131 )
130 client.succeed("cd ~/code/myapp && git add .")
132 client.succeed("cd ~/code/myapp && git add .")
131− client.succeed('git config --global user.email "you@example.com"')
132− client.succeed('git config --global user.name "Your Name"')
133 client.succeed('cd ~/code/myapp && git commit -m "Bad commit"')
133 client.succeed('cd ~/code/myapp && git commit -m "Bad commit"')
134 client.succeed("cd ~/code/myapp && git push -u origin bad")
134 client.succeed("cd ~/code/myapp && git push -u origin bad")
135 client.succeed("ob -v thunk pack ~/code/myapp --public")
135 client.succeed("ob -v thunk pack ~/code/myapp --public")
136− client.fail("nix-build ~/code/myapp")
136+ client.fail("nix-build ~/code/myapp")
137 client.succeed("ob -v thunk unpack ~/code/myapp")
137 client.succeed("ob -v thunk unpack ~/code/myapp")
138 client.succeed("cd ~/code/myapp && git checkout master")
138 client.succeed("cd ~/code/myapp && git checkout master")
139
139
140− with subtest("test obelisk can detect private repos"):
140+ with subtest("obelisk can detect private repos"):
141 client.succeed("ob -v thunk pack ~/code/myapp")
141 client.succeed("ob -v thunk pack ~/code/myapp")
142 client.succeed("""grep -qF '"private": true' ~/code/myapp/git.json""")
142 client.succeed("""grep -qF '"private": true' ~/code/myapp/git.json""")
143 client.succeed("ob -v thunk unpack ~/code/myapp")
143 client.succeed("ob -v thunk unpack ~/code/myapp")
default.nix+20−93
@@ -11,103 +11,18 @@ let
11
11
12 inherit (import dep/gitignore.nix { inherit (nixpkgs) lib; }) gitignoreSource;
12 inherit (import dep/gitignore.nix { inherit (nixpkgs) lib; }) gitignoreSource;
13
13
14− cleanSource = src:
15− # WARNING: The order of application here seems to matter a great deal to
16− # how quickly `ghcid` is able to reload changes. As a rule of thumb,
17− # always apply `gitignoreSource` first.
18− # See https://github.com/obsidiansystems/obelisk/pull/666 and related.
19− pkgs.lib.cleanSource (gitignoreSource src);
20−
21− commandRuntimeDeps = pkgs: with pkgs; [
22− coreutils
23− git
24− nix-prefetch-git
25− openssh
26− ];
27−
28 getReflexPlatform = { system, enableLibraryProfiling ? profiling }: reflex-platform-func {
14 getReflexPlatform = { system, enableLibraryProfiling ? profiling }: reflex-platform-func {
29 inherit iosSdkVersion config system enableLibraryProfiling;
15 inherit iosSdkVersion config system enableLibraryProfiling;
30
16
31 nixpkgsOverlays = [
17 nixpkgsOverlays = [
32− (self: super: {
18+ (import ./nixpkgs-overlays)
33− obeliskExecutableConfig = import ./lib/executable-config { nixpkgs = pkgs; filterGitSource = cleanSource; };
34− })
35 ];
19 ];
36
20
37 haskellOverlays = [
21 haskellOverlays = [
38−
22+ (import ./haskell-overlays/misc-deps.nix { inherit hackGet; })
39− # Fix misc upstream packages
40− (self: super: let
41− pkgs = self.callPackage ({ pkgs }: pkgs) {};
42− haskellLib = pkgs.haskell.lib;
43− in {
44− hnix = haskellLib.dontCheck (haskellLib.doJailbreak (self.callCabal2nix "hnix" (hackGet dep/hnix) {}));
45− hnix-store-core = self.callHackage "hnix-store-core" "0.1.0.0" {};
46−
47− ghcid = self.callCabal2nix "ghcid" (hackGet ./dep/ghcid) {};
48− # Exports more internals
49− snap-core = haskellLib.dontCheck (self.callCabal2nix "snap-core" (hackGet ./dep/snap-core) {});
50− })
51−
52 pkgs.obeliskExecutableConfig.haskellOverlay
23 pkgs.obeliskExecutableConfig.haskellOverlay
53−
24+ (import ./haskell-overlays/obelisk.nix)
54− # Add obelisk packages
25+ (import ./haskell-overlays/tighten-ob-exes.nix)
55− (self: super: let
56− pkgs = self.callPackage ({ pkgs }: pkgs) {};
57− onLinux = pkg: f: if pkgs.stdenv.isLinux then f pkg else pkg;
58− in {
59− shelly = self.callHackage "shelly" "1.9.0" {};
60−
61− obelisk-executable-config-inject = pkgs.obeliskExecutableConfig.platforms.web.inject self;
62−
63− obelisk-asset-manifest = self.callCabal2nix "obelisk-asset-manifest" (cleanSource ./lib/asset/manifest) {};
64− obelisk-asset-serve-snap = self.callCabal2nix "obelisk-asset-serve-snap" (cleanSource ./lib/asset/serve-snap) {};
65− obelisk-backend = self.callCabal2nix "obelisk-backend" (cleanSource ./lib/backend) {};
66− obelisk-cliapp = self.callCabal2nix "obelisk-cliapp" (cleanSource ./lib/cliapp) {};
67− obelisk-command = haskellLib.overrideCabal (self.callCabal2nix "obelisk-command" (cleanSource ./lib/command) {}) {
68− librarySystemDepends = [
69− pkgs.jre
70− pkgs.nix
71− (haskellLib.justStaticExecutables self.ghcid)
72− ];
73− };
74− obelisk-frontend = self.callCabal2nix "obelisk-frontend" (cleanSource ./lib/frontend) {};
75− obelisk-run = onLinux (self.callCabal2nix "obelisk-run" (cleanSource ./lib/run) {}) (pkg:
76− haskellLib.overrideCabal pkg (drv: { librarySystemDepends = [ pkgs.iproute ]; })
77− );
78− obelisk-route = self.callCabal2nix "obelisk-route" (cleanSource ./lib/route) {};
79− obelisk-selftest = haskellLib.overrideCabal (self.callCabal2nix "obelisk-selftest" (cleanSource ./lib/selftest) {}) {
80− librarySystemDepends = [
81− pkgs.cabal-install
82− pkgs.coreutils
83− pkgs.git
84− pkgs.nix
85− ];
86− };
87− obelisk-snap-extras = self.callCabal2nix "obelisk-snap-extras" (cleanSource ./lib/snap-extras) {};
88− tabulation = self.callCabal2nix "tabulation" (cleanSource ./lib/tabulation) {};
89− })
90−
91− (self: super: let
92− pkgs = self.callPackage ({ pkgs }: pkgs) {};
93− haskellLib = pkgs.haskell.lib;
94− in {
95− # Dynamic linking with split objects dramatically increases startup time (about
96− # 0.5 seconds on a decent machine with SSD), so we do `justStaticExecutables`.
97− obelisk-command = haskellLib.overrideCabal
98− (haskellLib.generateOptparseApplicativeCompletion "ob"
99− (haskellLib.justStaticExecutables super.obelisk-command))
100− (drv: {
101− buildTools = (drv.buildTools or []) ++ [ pkgs.buildPackages.makeWrapper ];
102− postFixup = ''
103− ${drv.postFixup or ""}
104− # Make `ob` reference its runtime dependencies.
105− wrapProgram "$out"/bin/ob --prefix PATH : ${pkgs.lib.makeBinPath (commandRuntimeDeps pkgs)}
106− '';
107− });
108− obelisk-selftest = haskellLib.justStaticExecutables super.obelisk-selftest;
109− })
110−
111 ];
26 ];
112 };
27 };
113
28
@@ -130,7 +45,7 @@ in rec {
130 obelisk = ghcObelisk;
45 obelisk = ghcObelisk;
131 obeliskEnvs = pkgs.lib.filterAttrs (k: _: pkgs.lib.strings.hasPrefix "obelisk-" k) ghcObeliskEnvs;
46 obeliskEnvs = pkgs.lib.filterAttrs (k: _: pkgs.lib.strings.hasPrefix "obelisk-" k) ghcObeliskEnvs;
132 command = ghcObelisk.obelisk-command;
47 command = ghcObelisk.obelisk-command;
133− shell = pinBuildInputs "obelisk-shell" ([command] ++ commandRuntimeDeps pkgs);
48+ shell = pinBuildInputs "obelisk-shell" ([command] ++ command.commandRuntimeDeps);
134
49
135 selftest = pkgs.writeScript "selftest" ''
50 selftest = pkgs.writeScript "selftest" ''
136 #!${pkgs.runtimeShell}
51 #!${pkgs.runtimeShell}
@@ -250,6 +165,8 @@ in rec {
250 };
165 };
251 };
166 };
252
167
168+ inherit mkAssets;
169+
253 serverExe = backend: frontend: assets: optimizationLevel: version:
170 serverExe = backend: frontend: assets: optimizationLevel: version:
254 pkgs.runCommand "serverExe" {} ''
171 pkgs.runCommand "serverExe" {} ''
255 mkdir $out
172 mkdir $out
@@ -290,13 +207,14 @@ in rec {
290 , shellToolOverrides ? _: _: {}
207 , shellToolOverrides ? _: _: {}
291 , withHoogle ? false # Setting this to `true` makes shell reloading far slower
208 , withHoogle ? false # Setting this to `true` makes shell reloading far slower
292 , __closureCompilerOptimizationLevel ? "ADVANCED" # Set this to `null` to skip the closure-compiler step
209 , __closureCompilerOptimizationLevel ? "ADVANCED" # Set this to `null` to skip the closure-compiler step
210+ , __withGhcide ? false
293 }:
211 }:
294 let
212 let
295 allConfig = nixpkgs.lib.makeExtensible (self: {
213 allConfig = nixpkgs.lib.makeExtensible (self: {
296 base = base';
214 base = base';
297 inherit args;
215 inherit args;
298 userSettings = {
216 userSettings = {
299− inherit android ios packages overrides tools shellToolOverrides withHoogle __closureCompilerOptimizationLevel;
217+ inherit android ios packages overrides tools shellToolOverrides withHoogle __closureCompilerOptimizationLevel __withGhcide;
300 staticFiles = if staticFiles == null then self.base + /static else staticFiles;
218 staticFiles = if staticFiles == null then self.base + /static else staticFiles;
301 };
219 };
302 frontendName = "frontend";
220 frontendName = "frontend";
@@ -353,9 +271,17 @@ in rec {
353 self.frontendName
271 self.frontendName
354 ];
272 ];
355
273
274+ shellToolOverrides = lib.composeExtensions
275+ self.userSettings.shellToolOverrides
276+ (if self.userSettings.__withGhcide
277+ then (import ./haskell-overlays/ghcide.nix)
278+ else (_: _: {})
279+ );
280+
356 project = reflexPlatformProject ({...}: self.projectConfig);
281 project = reflexPlatformProject ({...}: self.projectConfig);
357 projectConfig = {
282 projectConfig = {
283+ inherit (self) shellToolOverrides;
358− inherit (self.userSettings) shellToolOverrides tools withHoogle;
284+ inherit (self.userSettings) tools withHoogle;
359 overrides = self.totalOverrides;
285 overrides = self.totalOverrides;
360 packages = self.combinedPackages;
286 packages = self.combinedPackages;
361 shells = {
287 shells = {
@@ -416,8 +342,9 @@ in rec {
416 in nixpkgs.runCommand "ob-run" {
342 in nixpkgs.runCommand "ob-run" {
417 buildInputs = [ (profiled.ghc.ghcWithPackages (p: [ p.backend p.frontend])) ];
343 buildInputs = [ (profiled.ghc.ghcWithPackages (p: [ p.backend p.frontend])) ];
418 } ''
344 } ''
345+ cp ${exeSource} $PWD/ob-run.hs
419 mkdir -p $out/bin/
346 mkdir -p $out/bin/
420− ghc -x hs -prof -fno-prof-auto -threaded ${exeSource} -o $out/bin/ob-run
347+ ghc -x hs -prof -fno-prof-auto -threaded ob-run.hs -o $out/bin/ob-run
421 '';
348 '';
422
349
423 linuxExeConfigurable = linuxExe;
350 linuxExeConfigurable = linuxExe;
dep/.gitignoredeleted−5
@@ -1,5 +0,0 @@
1−*
2−!*/
3−!.gitignore
4−!*/*.json
5−!*/default.nix
dep/reflex-platform/github.json+3−3
@@ -1,8 +1,8 @@
1{
1{
2 "owner": "reflex-frp",
2 "owner": "reflex-frp",
3 "repo": "reflex-platform",
3 "repo": "reflex-platform",
4− "branch": "develop",
4+ "branch": "release/0.5.3.0",
5 "private": false,
5 "private": false,
6− "rev": "156ebb7c391ec909d19e794e591f107462862543",
6+ "rev": "9779ea3b4c87fdc971057c561262696d5e9b1847",
7− "sha256": "0rvbaimcvcica80538i6vxckv8si1gbd1ynvgxv7zr5jd1gk6vi5"
7+ "sha256": "0v87ilal9355xwz8y9m0zh14pm9c0f7pqch0854kkj92ybc5l62q"
8}
8}
guides/app-deploy/README.mdnew file+318
@@ -0,0 +1,318 @@
1+# Obelisk Application Deployment Guide
2+This document serves two purposes, the first one is to guide new users that want to deploy Obelisk/Reflex apps and the second one to provide a walk-through for test driving Obelisk releases.
3+
4+> **Note:** To complete this *entire* guide you need access to a macOS machine running the latest OSX release, a Linux machine (can be a VM on that mac) with Nix installed, an iPhone or iPad, and a recent Android device. It also assumes that you have Nix correctly set up and that your system is set up to fetch from binary caches instead of building everything on your machine. If you notice any of the commands below takes more than 5 minutes, then caches are not likely enabled.
5+>
6+> Refer to the [Obelisk Installation Documentation](https://github.com/obsidiansystems/obelisk#installing-obelisk) for instructions on configuring the binary caches for any Nix-compatible setup.
7+
8+## a) Get Obelisk
9+
10+There are several ways to install Obelisk, but the one we are going to use here allows us to test a single version of Obelisk in different ways. The approach is to clone Obelisk from it's GitHub repository and start a project that uses that local check out.
11+
12+Open a terminal and run the following:
13+
14+```bash
15+export WORKDIR=~/obelisk-guide
16+mkdir -p "$WORKDIR"
17+```
18+
19+Then let's get Obelisk from GitHub using a specific branch:
20+
21+```bash
22+export OBELISK_BRANCH=develop
23+git clone https://github.com/obsidiansystems/obelisk.git -b "$OBELISK_BRANCH" "$WORKDIR/obelisk"
24+```
25+
26+Once you have an Obelisk check out, you can build it using Nix and make a shortcut (alias) for the rest of the terminal session. With this you will be able to type `ob` anywhere as long as you do not close the terminal.
27+
28+```bash
29+alias ob=$(nix-build "$WORKDIR/obelisk" -A command --no-out-link)/bin/ob
30+```
31+
32+In order to start an Obelisk project, we need initialize it in a new directory. Let's call it `myapp`:
33+
34+```bash
35+mkdir -p "$WORKDIR/myapp"
36+cd "$WORKDIR/myapp"
37+ob init --branch "$OBELISK_BRANCH"
38+```
39+
40+> **Note:** If the `--branch` parameter is not used, then Obelisk sets your project up to look at the `master` branch from GitHub. This is quite handy for real life projects but distracting for our test drive since we want to make sure any changes we do to the Obelisk codebase (like testing a pull request) are immediately picked up.
41+
42+## b) Run the Obelisk app on localhost
43+
44+Let's test that we can run a server on localhost. This is quite easy:
45+
46+```bash
47+cd "$WORKDIR/myapp"
48+ob run
49+```
50+
51+Now open a browser and point it to http://localhost:8000 (or just click on this link). You should see the following:
52+
53+![](assets/app-deploy.png)
54+
55+## c) Deploy the web app on a remote machine
56+
57+### Import the NixOS VirtualBox appliance
58+Install [VirtualBox](https://www.virtualbox.org/) on your machine.
59+
60+On NixOS, do this by adding the following line to your `/etc/nixos/configuration.nix` before the last line containing `}`:
61+
62+```nix
63+ virtualisation.virtualbox.host.enable = true;
64+```
65+
66+then `sudo nixos-rebuild switch`.
67+
68+The NixOS [download page](https://nixos.org/nixos/download.html) has a section called "VirtualBox appliances". Download that as the target system. The author used the 19.09 `.ova` file.
69+
70+With the downloaded file, open VirtualBox and import the `.ova` file:
71+
72+![](assets/virtualbox-appliance-import.png)
73+
74+Leave the default settings and finish the import. That will take a few minutes:
75+
76+![](assets/virtualbox-appliance-import-loading.png)
77+
78+You should now see a NixOS machine in the dashboard:
79+
80+![](assets/virtualbox-dashboard-nixos.png)
81+
82+If you are on a network with DHCP on your wireless or network card then select right-click on the "NixOS" image and click "Settings". Go to the "Network" section and make "Attached to:" set to "Bridged Adapter".
83+
84+![](assets/virtualbox-image-settings-network.png)
85+
86+Finally, double-click on the "NixOS" machine and wait for it boot up. If it asks for a password, use `demo`.
87+
88+![](assets/virtualbox-nioxs-after-boot.png)
89+
90+### Configure the virtual machine for SSH
91+
92+Inside the virtual machine open up "Konsole" by clicking on the start menu in the bottom left corner and typing in "Konsole" until you see it as an option in the menu. Then click on it to open it.
93+
94+Change the system configuration using `sudo` to enable SSH access:
95+
96+```bash
97+sudo nano /etc/nixos/configuration.nix
98+```
99+
100+This will ask you to enter your password. Enter `demo`.
101+
102+![](assets/nano-edit-nixos-configuration.png)
103+
104+You need to add the following snippet right before the final line containing `}`.
105+
106+```nix
107+ services.openssh.enable = true;
108+ services.openssh.permitRootLogin = "yes";
109+```
110+
111+Save and close the editor by typing <kbd>Ctrl</kbd>+<kbd>O</kbd>, <kbd>Enter</kbd>, and then <kbd>Ctrl</kbd>+<kbd>X</kbd>.
112+
113+Now run `sudo nixos-rebuild switch` (if it asks for a password, again use `demo`) and then set the root password using `sudo passwd root`. Pick a simple password like `root`. You'll need to use it again.
114+
115+To get the virtual machine's IP address go back to the terminal on your *host* machine (not the virtual machine) and run:
116+
117+```bash
118+export VM_ID=$(VBoxManage list runningvms | grep "NixOS" | awk -F'[{}]' '{print $2}')
119+echo "$VM_ID"
120+```
121+
122+You should see a single identifier that looks like `388bbbe5-e0a2-4b20-9c76-bbaa5746682e`. If you see anything else then you likely you have multiple NixOS machines running. Stop any other machines and run this command again. (Of course, if you're a power user, just change the `grep` to pick out right VM.)
123+
124+Now get the IP address for that machine:
125+
126+```bash
127+export VM_IP=$(VBoxManage guestproperty enumerate "$VM_ID" | grep /V4/IP | awk '{print $4}' | sed 's/,//')
128+echo "$VM_IP"
129+```
130+
131+You should see an IP like `192.168.7.86`.
132+
133+With that you will be able to SSH into that machine from a terminal, using the username `root`.
134+
135+```bash
136+ssh root@$VM_IP echo "Access granted"
137+```
138+
139+This may ask if you want to trust the fingerprint for this server. Answer `yes`. It will ask you for a password. Enter the one you specified above. You should see `Access granted` printed after you type your password and hit <kbd>Enter</kbd>.
140+
141+> **Note:** If instead you see an error like this
142+>
143+> ```
144+> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
145+> @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
146+> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
147+> IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
148+> Someone could be eavesdropping on you right now (man-in-the-middle attack)!
149+> It is also possible that a host key has just been changed.
150+> ```
151+>
152+> you need to remove the old fingerprint for this IP. Run the following:
153+>
154+> ```bash
155+> sed -i "/^$VM_IP /d" ~/.ssh/known_hosts
156+> ```
157+>
158+> and then try the previous `ssh` command again.
159+
160+Now we'll allow access with an SSH key instead of a password. Create a new SSH key with `ssh-keygen`:
161+
162+```bash
163+ssh-keygen -t ed25519 -f "$WORKDIR/obkey" -P ""
164+```
165+
166+Now copy your local SSH key to the server:
167+
168+```bash
169+ssh-copy-id -i "$WORKDIR/obkey.pub" root@$VM_IP
170+```
171+
172+This will ask you for your password again.
173+
174+Now test login with your key instead:
175+
176+```bash
177+ssh -i "$WORKDIR/obkey" root@$VM_IP echo "Access granted"
178+```
179+
180+This should print `Access granted` *without* asking for a password.
181+
182+### Configure the git remote
183+
184+Before the project can be deployed, it needs to be a valid `git` repository.
185+
186+> **Note:** You need `git` installed and configured. You can do that with:
187+>
188+> ```bash
189+> nix-env -i git
190+> git config --global user.name "John Doe"
191+> git config --global user.email johndoe@example.com
192+> ```
193+
194+```bash
195+git init --bare "$WORKDIR/myapp-git-remote"
196+cd "$WORKDIR/myapp"
197+git init
198+git add --all
199+git commit -m "initial commit"
200+git remote add origin "$WORKDIR/myapp-git-remote"
201+git push -u origin master
202+```
203+
204+### Deploy
205+
206+With that, we can come back to the Obelisk app and initialize the deployment:
207+
208+```bash
209+cd "$WORKDIR/myapp"
210+ob deploy init --ssh-key "$WORKDIR/obkey" --admin-email a@a.a --hostname $VM_IP --route https://$VM_IP "$WORKDIR/myappdeploy" --disable-https
211+```
212+
213+Then configure the deployment for VirtualBox:
214+
215+```bash
216+echo '{nixosPkgs, ...}: {...}: { imports = [ (nixosPkgs.path + /nixos/modules/virtualisation/virtualbox-image.nix) ]; }' > "$WORKDIR/myappdeploy/module.nix"
217+```
218+
219+And deploy:
220+
221+```bash
222+cd "$WORKDIR/myappdeploy"
223+ob deploy push -v
224+```
225+
226+Once that is complete, open the webpage with
227+
228+```bash
229+xdg-open http://$VM_IP
230+```
231+
232+If that fails, just get the URL by running
233+
234+```bash
235+echo http://$VM_IP
236+```
237+
238+and copy/paste that URL into your browser navigation input.
239+
240+It should look like this:
241+
242+![](assets/app-deploy-2.png)
243+
244+Congratulations! You have deployed an Obelisk application to a remote server via SSH.
245+
246+## d) Deploy an Android app (Linux host only)
247+
248+> **Note:** This section requires that you be running a Linux *host*.
249+
250+Modify `$WORKDIR/myapp/default.nix` to set `config.android_sdk.accept_license = true;` and then update your app.
251+
252+```bash
253+cd "$WORKDIR/myapp"
254+sed -i 's/# config.android_sdk.accept_license = false;/config.android_sdk.accept_license = true;/g' default.nix
255+git add default.nix
256+git commit -m"Accept license"
257+git push
258+```
259+
260+Make sure *USB debugging* is enabled in your Android device ([instructions here](https://developer.android.com/studio/debug/dev-options)) and connect the device using USB. Be sure to confirm any security prompts on the device.
261+
262+Now update your deployment and deploy to Android:
263+
264+```bash
265+cd "$WORKDIR/myappdeploy"
266+ob deploy update
267+ob deploy test android -v
268+```
269+
270+This deployment will ask you to create a password (at least 6 characters long) and then ask you a series of questions. You can pick arbitrary answers. When you are presented with prompt like:
271+
272+```
273+Is CN=a, OU=b, O=c, L=d, ST=e, C=f correct?
274+ [no]:
275+```
276+
277+You can enter `yes` to continue. If the deployment fails, try using different USB ports on your computer and running `ob deploy test android -v` again. The USB cable you use can also make a difference.
278+
279+When connecting your Android device you may be asked to "Allow USB debugging". You need to allow it.
280+![](assets/android-confirm-usb-debugging.jpg)
281+
282+
283+When the deployment is complete opening the app should look something like
284+
285+![](assets/android-app.jpg)
286+
287+Congratulations! You have deployed an Obelisk Android app via USB.
288+
289+## e) Deploy an iOS app (macOS host only)
290+
291+> **Note:** This section requires that you be running a macOS *host*.
292+
293+Verify that you can see the device from XCode and you have installed a Provisioning profile that links your Apple Developer Id and the Device identifier. The workflow depends on whether or not you are an independent developer or part of an organization and is out of scope for this manual.
294+
295+![](assets/xcode-devices.png)
296+
297+Find your `Team ID` at the following URL (Apple Developer Membership details): https://developer.apple.com/account/#/membership/
298+
299+It will be something like `5B445B3WY1`. With that, you can start the deployment workflow after plugging in an iPhone or iPad via USB and setting it to trust the computer:
300+
301+```bash
302+cd "$WORKDIR/myappdeploy"
303+ob deploy test ios <TEAM-ID> # Use your Team ID here
304+```
305+
306+![](assets/ios-deploy-keychain.png)
307+
308+![](assets/ios-deploy-example.png)
309+
310+If there are no errors and the last line says `100% Installed Package` you can open the device and look for the Obelisk app:
311+
312+![](assets/ios-obelisk-app-icon.jpg)
313+
314+![](assets/ios-obelisk-app-open.jpg)
315+
316+Congratulations, you have deployed an Obelisk app on an iOS device.
317+
318+You are now ready to create your own multi-platform application using Obelisk!
guides/app-deploy/assets/android-app.jpgnew file

Binary file not shown.

guides/app-deploy/assets/android-confirm-usb-debugging.jpgnew file

Binary file not shown.

guides/app-deploy/assets/app-deploy-2.pngnew file

Binary file not shown.

guides/app-deploy/assets/app-deploy.pngnew file

Binary file not shown.

guides/app-deploy/assets/ios-deploy-example.pngnew file

Binary file not shown.

guides/app-deploy/assets/ios-deploy-keychain.pngnew file

Binary file not shown.

guides/app-deploy/assets/ios-obelisk-app-icon.jpgnew file

Binary file not shown.

guides/app-deploy/assets/ios-obelisk-app-open.jpgnew file

Binary file not shown.

guides/app-deploy/assets/nano-edit-nixos-configuration.pngnew file

Binary file not shown.

guides/app-deploy/assets/virtualbox-appliance-import-loading.pngnew file

Binary file not shown.

guides/app-deploy/assets/virtualbox-appliance-import.pngnew file

Binary file not shown.

guides/app-deploy/assets/virtualbox-dashboard-nixos.pngnew file

Binary file not shown.

guides/app-deploy/assets/virtualbox-image-settings-network.pngnew file

Binary file not shown.

guides/app-deploy/assets/virtualbox-nioxs-after-boot.pngnew file

Binary file not shown.

guides/app-deploy/assets/xcode-devices.pngnew file

Binary file not shown.

haskell-overlays/ghcide.nixnew file+34
@@ -0,0 +1,34 @@
1+self: super:
2+ let
3+ pkgs = self.callPackage ({ pkgs }: pkgs) {};
4+ inherit (pkgs.haskell.lib) dontCheck;
5+ in {
6+ ghcide = pkgs.haskell.lib.justStaticExecutables (dontCheck ((self.override {
7+ overrides = self: super: {
8+ ghc-check = self.callHackageDirect {
9+ pkg = "ghc-check";
10+ ver = "0.1.0.3";
11+ sha256 = "038llbvryk5y27jbdpbshp0zw5lw1j6m7qk7vx1n96ykqdzkh649";
12+ } {};
13+ lsp-test = dontCheck (self.callHackage "lsp-test" "0.6.1.0" {});
14+ haddock-library = dontCheck (self.callHackage "haddock-library" "1.8.0" {});
15+ haskell-lsp = dontCheck (self.callHackage "haskell-lsp" "0.19.0.0" {});
16+ haskell-lsp-types = dontCheck (self.callHackage "haskell-lsp-types" "0.19.0.0" {});
17+ regex-posix = dontCheck (self.callHackage "regex-posix" "0.96.0.0" {});
18+ test-framework = dontCheck (self.callHackage "test-framework" "0.8.2.0" {});
19+ regex-base = dontCheck (self.callHackage "regex-base" "0.94.0.0" {});
20+ regex-tdfa = dontCheck (self.callHackage "regex-tdfa" "1.3.1.0" {});
21+ shake = dontCheck (self.callHackage "shake" "0.18.4" {});
22+ hie-bios = dontCheck (self.callHackageDirect {
23+ pkg = "hie-bios";
24+ ver = "0.4.0";
25+ sha256 = "19lpg9ymd9656cy17vna8wr1hvzfal94gpm2d3xpnw1d5qr37z7x";
26+ } {});
27+ };
28+ }).callCabal2nix "ghcide" (pkgs.fetchFromGitHub {
29+ owner = "digital-asset";
30+ repo = "ghcide";
31+ rev = "v0.1.0";
32+ sha256 = "1kf71iix46hvyxviimrcv7kvsj67hcnnqlpdsmazmlmybf7wbqbb";
33+ }) {}));
34+}
haskell-overlays/misc-deps.nixnew file+20
@@ -0,0 +1,20 @@
1+{ hackGet }:
2+
3+# Fix misc upstream packages
4+self: super:
5+
6+let
7+ pkgs = self.callPackage ({ pkgs }: pkgs) {};
8+ haskellLib = pkgs.haskell.lib;
9+in
10+
11+{
12+ hnix = haskellLib.dontCheck (haskellLib.doJailbreak (self.callCabal2nix "hnix" (hackGet ../dep/hnix) {}));
13+ hnix-store-core = self.callHackage "hnix-store-core" "0.1.0.0" {};
14+
15+ ghcid = self.callCabal2nix "ghcid" (hackGet ../dep/ghcid) {};
16+ # Exports more internals
17+ snap-core = haskellLib.dontCheck (self.callCabal2nix "snap-core" (hackGet ../dep/snap-core) {});
18+
19+ shelly = self.callHackage "shelly" "1.9.0" {};
20+}
haskell-overlays/obelisk.nixnew file+43
@@ -0,0 +1,43 @@
1+# Add obelisk packages
2+
3+self: super:
4+
5+let
6+ pkgs = self.callPackage ({ pkgs }: pkgs) {};
7+ inherit (pkgs) obeliskCleanSource;
8+ haskellLib = pkgs.haskell.lib;
9+ onLinux = pkg: f: if pkgs.stdenv.isLinux then f pkg else pkg;
10+in
11+
12+{
13+ obelisk-executable-config-inject = pkgs.obeliskExecutableConfig.platforms.web.inject self;
14+
15+ obelisk-asset-manifest = self.callCabal2nix "obelisk-asset-manifest" (obeliskCleanSource ../lib/asset/manifest) {};
16+ obelisk-asset-serve-snap = self.callCabal2nix "obelisk-asset-serve-snap" (obeliskCleanSource ../lib/asset/serve-snap) {};
17+ obelisk-backend = self.callCabal2nix "obelisk-backend" (obeliskCleanSource ../lib/backend) {};
18+ obelisk-cliapp = self.callCabal2nix "obelisk-cliapp" (obeliskCleanSource ../lib/cliapp) {};
19+ obelisk-command = haskellLib.overrideCabal (self.callCabal2nix "obelisk-command" (obeliskCleanSource ../lib/command) {}) {
20+ librarySystemDepends = [
21+ pkgs.jre
22+ pkgs.nix
23+ (haskellLib.justStaticExecutables self.ghcid)
24+ ];
25+ };
26+ obelisk-frontend = self.callCabal2nix "obelisk-frontend" (obeliskCleanSource ../lib/frontend) {};
27+ obelisk-run = onLinux (self.callCabal2nix "obelisk-run" (obeliskCleanSource ../lib/run) {}) (pkg:
28+ haskellLib.overrideCabal pkg (drv: { librarySystemDepends = [ pkgs.iproute ]; })
29+ );
30+ obelisk-route = self.callCabal2nix "obelisk-route" (obeliskCleanSource ../lib/route) {};
31+ obelisk-selftest = haskellLib.overrideCabal (self.callCabal2nix "obelisk-selftest" (obeliskCleanSource ../lib/selftest) {}) {
32+ librarySystemDepends = [
33+ pkgs.cabal-install
34+ pkgs.coreutils
35+ pkgs.git
36+ pkgs.nix
37+ pkgs.nix-prefetch-git
38+ pkgs.rsync
39+ ];
40+ };
41+ obelisk-snap-extras = self.callCabal2nix "obelisk-snap-extras" (obeliskCleanSource ../lib/snap-extras) {};
42+ tabulation = self.callCabal2nix "tabulation" (obeliskCleanSource ../lib/tabulation) {};
43+}
haskell-overlays/tighten-ob-exes.nixnew file+32
@@ -0,0 +1,32 @@
1+self: super:
2+
3+let
4+ pkgs = self.callPackage ({ pkgs }: pkgs) {};
5+ haskellLib = pkgs.haskell.lib;
6+
7+ commandRuntimeDeps = with pkgs; [
8+ coreutils
9+ git
10+ nix-prefetch-git
11+ openssh
12+ ];
13+in
14+
15+{
16+ # Dynamic linking with split objects dramatically increases startup time (about
17+ # 0.5 seconds on a decent machine with SSD), so we do `justStaticExecutables`.
18+ obelisk-command = haskellLib.overrideCabal
19+ (haskellLib.generateOptparseApplicativeCompletion "ob"
20+ (haskellLib.justStaticExecutables super.obelisk-command))
21+ (drv: {
22+ buildTools = (drv.buildTools or []) ++ [ pkgs.buildPackages.makeWrapper ];
23+ postFixup = ''
24+ ${drv.postFixup or ""}
25+ # Make `ob` reference its runtime dependencies.
26+ wrapProgram "$out"/bin/ob --prefix PATH : ${pkgs.lib.makeBinPath commandRuntimeDeps}
27+ '';
28+ passthru = { inherit commandRuntimeDeps; };
29+ });
30+
31+ obelisk-selftest = haskellLib.justStaticExecutables super.obelisk-selftest;
32+}
lib/backend/src/Obelisk/Backend.hs+39−16
@@ -1,4 +1,5 @@
1{-# LANGUAGE DeriveFunctor #-}
1{-# LANGUAGE DeriveFunctor #-}
2+{-# LANGUAGE DeriveGeneric #-}
2{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE GADTs #-}
5{-# LANGUAGE GADTs #-}
@@ -10,6 +11,10 @@
10{-# OPTIONS_GHC -fno-warn-orphans #-}
11{-# OPTIONS_GHC -fno-warn-orphans #-}
11module Obelisk.Backend
12module Obelisk.Backend
12 ( Backend (..)
13 ( Backend (..)
14+ , BackendConfig (..)
15+ , defaultBackendConfig
16+ , StaticAssets (..)
17+ , defaultStaticAssets
13 -- * Running a backend
18 -- * Running a backend
14 , runBackend
19 , runBackend
15 , runBackendWith
20 , runBackendWith
@@ -21,14 +26,15 @@ module Obelisk.Backend
21 , delayedGhcjsScript
26 , delayedGhcjsScript
22 -- * all.js preload functions
27 -- * all.js preload functions
23 , preloadGhcjs
28 , preloadGhcjs
29+ , renderAllJsPath
24 -- * Re-exports
30 -- * Re-exports
25 , Default (def)
31 , Default (def)
26 , getPageName
32 , getPageName
27 , getRouteWith
33 , getRouteWith
28 , runSnapWithCommandLineArgs
34 , runSnapWithCommandLineArgs
35+ , runSnapWithConfig
29 , serveDefaultObeliskApp
36 , serveDefaultObeliskApp
30 , prettifyOutput
37 , prettifyOutput
31− , renderAllJsPath
32 , staticRenderContentType
38 , staticRenderContentType
33 , getPublicConfigs
39 , getPublicConfigs
34 ) where
40 ) where
@@ -46,6 +52,7 @@ import qualified Data.Map as Map
46import Data.Monoid ((<>))
52import Data.Monoid ((<>))
47import Data.Text (Text)
53import Data.Text (Text)
48import qualified Data.Text as T
54import qualified Data.Text as T
55+import GHC.Generics (Generic)
49import Obelisk.Asset.Serve.Snap (serveAsset)
56import Obelisk.Asset.Serve.Snap (serveAsset)
50import qualified Obelisk.ExecutableConfig.Lookup as Lookup
57import qualified Obelisk.ExecutableConfig.Lookup as Lookup
51import Obelisk.Frontend
58import Obelisk.Frontend
@@ -61,13 +68,21 @@ import System.IO (BufferMode (..), hSetBuffering, stderr, stdout)
61data Backend backendRoute frontendRoute = Backend
68data Backend backendRoute frontendRoute = Backend
62 { _backend_routeEncoder :: Encoder (Either Text) Identity (R (FullRoute backendRoute frontendRoute)) PageName
69 { _backend_routeEncoder :: Encoder (Either Text) Identity (R (FullRoute backendRoute frontendRoute)) PageName
63 , _backend_run :: ((R backendRoute -> Snap ()) -> IO ()) -> IO ()
70 , _backend_run :: ((R backendRoute -> Snap ()) -> IO ()) -> IO ()
64− }
71+ } deriving (Generic)
72+
73+data BackendConfig frontendRoute = BackendConfig
74+ { _backendConfig_runSnap :: !(Snap () -> IO ()) -- ^ Function to run the snap server
75+ , _backendConfig_staticAssets :: !StaticAssets -- ^ Static assets
76+ , _backendConfig_ghcjsWidgets :: !(GhcjsWidgets (Text -> FrontendWidgetT (R frontendRoute) ()))
77+ -- ^ Given the URL of all.js, return the widgets which are responsible for
78+ -- loading the script.
79+ } deriving (Generic)
65
80
66-- | The static assets provided must contain a compiled GHCJS app that corresponds exactly to the Frontend provided
81-- | The static assets provided must contain a compiled GHCJS app that corresponds exactly to the Frontend provided
67data GhcjsApp route = GhcjsApp
82data GhcjsApp route = GhcjsApp
68 { _ghcjsApp_compiled :: !StaticAssets
83 { _ghcjsApp_compiled :: !StaticAssets
69 , _ghcjsApp_value :: !(Frontend route)
84 , _ghcjsApp_value :: !(Frontend route)
70− }
85+ } deriving (Generic)
71
86
72-- | Widgets used to load all.js on the frontend
87-- | Widgets used to load all.js on the frontend
73data GhcjsWidgets a = GhcjsWidgets
88data GhcjsWidgets a = GhcjsWidgets
@@ -75,7 +90,8 @@ data GhcjsWidgets a = GhcjsWidgets
75 -- ^ A preload widget, placed in the document head
90 -- ^ A preload widget, placed in the document head
76 , _ghcjsWidgets_script :: a
91 , _ghcjsWidgets_script :: a
77 -- ^ A script widget, placed in the document body
92 -- ^ A script widget, placed in the document body
78− } deriving Functor
93+ } deriving (Functor, Generic)
94+
79
95
80-- | Given the URL of all.js, return the widgets which are responsible for
96-- | Given the URL of all.js, return the widgets which are responsible for
81-- loading the script. Defaults to 'preloadGhcjs' and 'deferredGhcjsScript'.
97-- loading the script. Defaults to 'preloadGhcjs' and 'deferredGhcjsScript'.
@@ -122,17 +138,20 @@ defaultFrontendGhcjsAssets = StaticAssets
122 , _staticAssets_unprocessed = "frontend.jsexe"
138 , _staticAssets_unprocessed = "frontend.jsexe"
123 }
139 }
124
140
125−runSnapWithCommandLineArgs :: MonadIO m => Snap () -> m ()
141+runSnapWithConfig :: MonadIO m => Config Snap a -> Snap () -> m ()
126−runSnapWithCommandLineArgs a = do
142+runSnapWithConfig conf a = do
127− -- Get the web server configuration from the command line
128− cmdLineConf <- liftIO $ commandLineConfig defaultConfig
129− let httpConf = cmdLineConf
143+ let httpConf = conf
130 { accessLog = Just $ ConfigIoLog BSC8.putStrLn
144 { accessLog = Just $ ConfigIoLog BSC8.putStrLn
131 , errorLog = Just $ ConfigIoLog BSC8.putStrLn
145 , errorLog = Just $ ConfigIoLog BSC8.putStrLn
132 }
146 }
133 -- Start the web server
147 -- Start the web server
134 liftIO $ httpServe httpConf a
148 liftIO $ httpServe httpConf a
135
149
150+-- Get the web server configuration from the command line
151+runSnapWithCommandLineArgs :: MonadIO m => Snap () -> m ()
152+runSnapWithCommandLineArgs s = liftIO (commandLineConfig defaultConfig) >>= \c ->
153+ runSnapWithConfig c s
154+
136getPageName :: (MonadSnap m) => m PageName
155getPageName :: (MonadSnap m) => m PageName
137getPageName = do
156getPageName = do
138 p <- getsRequest rqPathInfo
157 p <- getsRequest rqPathInfo
@@ -200,27 +219,31 @@ serveGhcjsApp urlEnc ghcjsWidgets app config = \case
200 writeBS <=< renderGhcjsFrontend urlEnc ghcjsWidgets (appRouteComponent :/ appRouteRest) config $ _ghcjsApp_value app
219 writeBS <=< renderGhcjsFrontend urlEnc ghcjsWidgets (appRouteComponent :/ appRouteRest) config $ _ghcjsApp_value app
201 GhcjsAppRoute_Resource :=> Identity pathSegments -> serveStaticAssets (_ghcjsApp_compiled app) pathSegments
220 GhcjsAppRoute_Resource :=> Identity pathSegments -> serveStaticAssets (_ghcjsApp_compiled app) pathSegments
202
221
222+-- | Default obelisk backend configuration.
223+defaultBackendConfig :: BackendConfig frontendRoute
224+defaultBackendConfig = BackendConfig runSnapWithCommandLineArgs defaultStaticAssets defaultGhcjsWidgets
225+
226+-- | Run an obelisk backend with the default configuration.
203runBackend :: Backend backendRoute frontendRoute -> Frontend (R frontendRoute) -> IO ()
227runBackend :: Backend backendRoute frontendRoute -> Frontend (R frontendRoute) -> IO ()
204−runBackend = runBackendWith defaultGhcjsWidgets
228+runBackend = runBackendWith defaultBackendConfig
205
229
230+-- | Run an obelisk backend with the given configuration.
206runBackendWith
231runBackendWith
207− :: GhcjsWidgets (Text -> FrontendWidgetT (R frontendRoute) ())
232+ :: BackendConfig frontendRoute
208− -- ^ Given the URL of all.js, return the widgets which are responsible for
209− -- loading the script.
210 -> Backend backendRoute frontendRoute
233 -> Backend backendRoute frontendRoute
211 -> Frontend (R frontendRoute)
234 -> Frontend (R frontendRoute)
212 -> IO ()
235 -> IO ()
213−runBackendWith ghcjsWidgets backend frontend = case checkEncoder $ _backend_routeEncoder backend of
236+runBackendWith (BackendConfig runSnap staticAssets ghcjsWidgets) backend frontend = case checkEncoder $ _backend_routeEncoder backend of
214 Left e -> fail $ "backend error:\n" <> T.unpack e
237 Left e -> fail $ "backend error:\n" <> T.unpack e
215 Right validFullEncoder -> do
238 Right validFullEncoder -> do
216 publicConfigs <- getPublicConfigs
239 publicConfigs <- getPublicConfigs
217 _backend_run backend $ \serveRoute ->
240 _backend_run backend $ \serveRoute ->
218− runSnapWithCommandLineArgs $
241+ runSnap $
219 getRouteWith validFullEncoder >>= \case
242 getRouteWith validFullEncoder >>= \case
220 Identity r -> case r of
243 Identity r -> case r of
221 FullRoute_Backend backendRoute :/ a -> serveRoute $ backendRoute :/ a
244 FullRoute_Backend backendRoute :/ a -> serveRoute $ backendRoute :/ a
222 FullRoute_Frontend obeliskRoute :/ a ->
245 FullRoute_Frontend obeliskRoute :/ a ->
223− serveDefaultObeliskApp routeToUrl (($ allJsUrl) <$> ghcjsWidgets) (serveStaticAssets defaultStaticAssets) frontend publicConfigs $
246+ serveDefaultObeliskApp routeToUrl (($ allJsUrl) <$> ghcjsWidgets) (serveStaticAssets staticAssets) frontend publicConfigs $
224 obeliskRoute :/ a
247 obeliskRoute :/ a
225 where
248 where
226 routeToUrl (k :/ v) = renderObeliskRoute validFullEncoder $ FullRoute_Frontend (ObeliskRoute_App k) :/ v
249 routeToUrl (k :/ v) = renderObeliskRoute validFullEncoder $ FullRoute_Frontend (ObeliskRoute_App k) :/ v
lib/cliapp/src/Obelisk/CliApp.hs+1
@@ -39,6 +39,7 @@ module Obelisk.CliApp
39 , callCommand
39 , callCommand
40 , callProcess
40 , callProcess
41 , callProcessAndLogOutput
41 , callProcessAndLogOutput
42+ , createProcess
42 , createProcess_
43 , createProcess_
43 , overCreateProcess
44 , overCreateProcess
44 , proc
45 , proc
lib/cliapp/src/Obelisk/CliApp/Spinner.hs−1
@@ -3,7 +3,6 @@
3{-# LANGUAGE MultiParamTypeClasses #-}
3{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE TupleSections #-}
7-- | Provides a simple CLI spinner that interoperates cleanly with the rest of the logging output.
6-- | Provides a simple CLI spinner that interoperates cleanly with the rest of the logging output.
8module Obelisk.CliApp.Spinner
7module Obelisk.CliApp.Spinner
9 ( withSpinner
8 ( withSpinner
lib/command/obelisk-command.cabal+3−3
@@ -1,5 +1,5 @@
1name: obelisk-command
1name: obelisk-command
2−version: 0.6
2+version: 0.8.0.0
3cabal-version: >= 1.8
3cabal-version: >= 1.8
4build-type: Simple
4build-type: Simple
5
5
@@ -10,8 +10,6 @@ library
10 , aeson-pretty
10 , aeson-pretty
11 , ansi-terminal
11 , ansi-terminal
12 , base
12 , base
13− , base16-bytestring
14− , binary
15 , bytestring
13 , bytestring
16 , Cabal
14 , Cabal
17 , containers
15 , containers
@@ -20,6 +18,7 @@ library
20 , either
18 , either
21 , errors
19 , errors
22 , exceptions
20 , exceptions
21+ , extra
23 , filepath
22 , filepath
24 , git
23 , git
25 , github
24 , github
@@ -32,6 +31,7 @@ library
32 , megaparsec
31 , megaparsec
33 , modern-uri
32 , modern-uri
34 , monad-loops
33 , monad-loops
34+ , monoidal-containers
35 , mtl
35 , mtl
36 , network
36 , network
37 , network-uri
37 , network-uri
lib/command/src/Obelisk/Command.hs+115−94
@@ -3,20 +3,18 @@
3{-# LANGUAGE MultiParamTypeClasses #-}
3{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE ScopedTypeVariables #-}
6+{-# LANGUAGE TupleSections #-}
6module Obelisk.Command where
7module Obelisk.Command where
7
8
8−import Control.Monad
9+import Control.Monad.IO.Class (MonadIO, liftIO)
9−import Control.Monad.IO.Class (liftIO)
10−import qualified Data.Binary as Binary
11import Data.Bool (bool)
10import Data.Bool (bool)
12−import qualified Data.ByteString.Base16 as Base16
13−import qualified Data.ByteString.Lazy as LBS
14import Data.Foldable (for_)
11import Data.Foldable (for_)
15−import Data.List
12+import Data.List (isInfixOf, isPrefixOf)
13+import Data.List.NonEmpty (NonEmpty, nonEmpty)
14+import qualified Data.List.NonEmpty as NonEmpty
15+import qualified Data.Map as Map
16import qualified Data.Text as T
16import qualified Data.Text as T
17−import Data.Text.Encoding
17+import Data.Traversable (for)
18−import Data.Text.Encoding.Error (lenientDecode)
19−import GHC.StaticPtr
20import Options.Applicative
18import Options.Applicative
21import Options.Applicative.Help.Pretty (text, (<$$>))
19import Options.Applicative.Help.Pretty (text, (<$$>))
22import System.Directory
20import System.Directory
@@ -76,8 +74,8 @@ argsInfo cfg = info (args cfg <**> helper) $ mconcat
76initSource :: Parser InitSource
74initSource :: Parser InitSource
77initSource = foldl1 (<|>)
75initSource = foldl1 (<|>)
78 [ pure InitSource_Default
76 [ pure InitSource_Default
79− , InitSource_Branch <$> strOption (long "branch" <> metavar "BRANCH")
77+ , InitSource_Branch <$> strOption (long "branch" <> metavar "BRANCH" <> help "Initialize the project using the given BRANCH of Obelisk's official repository")
80− , InitSource_Symlink <$> strOption (long "symlink" <> action "directory" <> metavar "PATH")
78+ , InitSource_Symlink <$> strOption (long "symlink" <> action "directory" <> metavar "PATH" <> help "(Use with caution) Initialize the project using the copy of Obelisk found at the given PATH")
81 ]
79 ]
82
80
83initForce :: Parser Bool
81initForce :: Parser Bool
@@ -86,11 +84,11 @@ initForce = switch (long "force" <> help "Allow ob init to overwrite files")
86data ObCommand
84data ObCommand
87 = ObCommand_Init InitSource Bool
85 = ObCommand_Init InitSource Bool
88 | ObCommand_Deploy DeployCommand
86 | ObCommand_Deploy DeployCommand
89− | ObCommand_Run
87+ | ObCommand_Run [(FilePath, Interpret)]
90 | ObCommand_Profile String [String]
88 | ObCommand_Profile String [String]
91− | ObCommand_Thunk ThunkCommand
89+ | ObCommand_Thunk ThunkOption
92− | ObCommand_Repl
90+ | ObCommand_Repl [(FilePath, Interpret)]
93− | ObCommand_Watch
91+ | ObCommand_Watch [(FilePath, Interpret)]
94 | ObCommand_Shell ShellOpts
92 | ObCommand_Shell ShellOpts
95 | ObCommand_Doc String [String] -- shell and list of packages
93 | ObCommand_Doc String [String] -- shell and list of packages
96 | ObCommand_Hoogle String Int -- shell and port
94 | ObCommand_Hoogle String Int -- shell and port
@@ -101,6 +99,9 @@ data ObInternal
101 -- the preprocessor argument syntax is also handled outside
99 -- the preprocessor argument syntax is also handled outside
102 -- optparse-applicative, but it shouldn't ever conflict with another syntax
100 -- optparse-applicative, but it shouldn't ever conflict with another syntax
103 = ObInternal_ApplyPackages String String String [String]
101 = ObInternal_ApplyPackages String String String [String]
102+ | ObInternal_ExportGhciConfig
103+ [(FilePath, Interpret)]
104+ Bool -- ^ Use relative paths
104 deriving Show
105 deriving Show
105
106
106obCommand :: ArgsConfig -> Parser ObCommand
107obCommand :: ArgsConfig -> Parser ObCommand
@@ -108,11 +109,11 @@ obCommand cfg = hsubparser
108 (mconcat
109 (mconcat
109 [ command "init" $ info (ObCommand_Init <$> initSource <*> initForce) $ progDesc "Initialize an Obelisk project"
110 [ command "init" $ info (ObCommand_Init <$> initSource <*> initForce) $ progDesc "Initialize an Obelisk project"
110 , command "deploy" $ info (ObCommand_Deploy <$> deployCommand cfg) $ progDesc "Prepare a deployment for an Obelisk project"
111 , command "deploy" $ info (ObCommand_Deploy <$> deployCommand cfg) $ progDesc "Prepare a deployment for an Obelisk project"
111− , command "run" $ info (pure ObCommand_Run) $ progDesc "Run current project in development mode"
112+ , command "run" $ info (ObCommand_Run <$> interpretOpts) $ progDesc "Run current project in development mode"
112 , command "profile" $ info (uncurry ObCommand_Profile <$> profileCommand) $ progDesc "Run current project with profiling enabled"
113 , command "profile" $ info (uncurry ObCommand_Profile <$> profileCommand) $ progDesc "Run current project with profiling enabled"
113− , command "thunk" $ info (ObCommand_Thunk <$> thunkCommand) $ progDesc "Manipulate thunk directories"
114+ , command "thunk" $ info (ObCommand_Thunk <$> thunkOption) $ progDesc "Manipulate thunk directories"
114− , command "repl" $ info (pure ObCommand_Repl) $ progDesc "Open an interactive interpreter"
115+ , command "repl" $ info (ObCommand_Repl <$> interpretOpts) $ progDesc "Open an interactive interpreter"
115− , command "watch" $ info (pure ObCommand_Watch) $ progDesc "Watch current project for errors and warnings"
116+ , command "watch" $ info (ObCommand_Watch <$> interpretOpts) $ progDesc "Watch current project for errors and warnings"
116 , command "shell" $ info (ObCommand_Shell <$> shellOpts) $ progDesc "Enter a shell with project dependencies"
117 , command "shell" $ info (ObCommand_Shell <$> shellOpts) $ progDesc "Enter a shell with project dependencies"
117 , command "doc" $ info (ObCommand_Doc <$> shellFlags <*> packageNames) $
118 , command "doc" $ info (ObCommand_Doc <$> shellFlags <*> packageNames) $
118 progDesc "List paths to haddock documentation for specified packages"
119 progDesc "List paths to haddock documentation for specified packages"
@@ -120,8 +121,17 @@ obCommand cfg = hsubparser
120 text "Hint: To open the documentation you can pipe the output of this command like"
121 text "Hint: To open the documentation you can pipe the output of this command like"
121 <$$> text "ob doc reflex reflex-dom-core | xargs -n1 xdg-open")
122 <$$> text "ob doc reflex reflex-dom-core | xargs -n1 xdg-open")
122 , command "hoogle" $ info (ObCommand_Hoogle <$> shellFlags <*> portOpt 8080) $ progDesc "Run a hoogle server locally for your project's dependency tree"
123 , command "hoogle" $ info (ObCommand_Hoogle <$> shellFlags <*> portOpt 8080) $ progDesc "Run a hoogle server locally for your project's dependency tree"
124+ , command "internal" $ info (ObCommand_Internal <$> internalCommand) $ progDesc "Internal Obelisk commands with unstable APIs"
123 ])
125 ])
124
126
127+internalCommand :: Parser ObInternal
128+internalCommand = hsubparser $ mconcat
129+ [ command "export-ghci-configuration" $ info (ObInternal_ExportGhciConfig <$> interpretOpts <*> useRelativePathsFlag)
130+ $ progDesc "Export the GHCi configuration used by ob run, etc.; useful for IDE integration"
131+ ]
132+ where
133+ useRelativePathsFlag = switch (long "use-relative-paths" <> help "Use relative paths")
134+
125packageNames :: Parser [String]
135packageNames :: Parser [String]
126packageNames = some (strArgument (metavar "PACKAGE-NAME..."))
136packageNames = some (strArgument (metavar "PACKAGE-NAME..."))
127
137
@@ -175,16 +185,6 @@ data DeployCommand
175 | DeployCommand_Update
185 | DeployCommand_Update
176 deriving Show
186 deriving Show
177
187
178−data DeployInitOpts = DeployInitOpts
179− { _deployInitOpts_outputDir :: FilePath
180− , _deployInitOpts_sshKey :: FilePath
181− , _deployInitOpts_hostname :: [String]
182− , _deployInitOpts_route :: String
183− , _deployInitOpts_adminEmail :: String
184− , _deployInitOpts_enableHttps :: Bool
185− }
186− deriving Show
187−
188profileCommand :: Parser (String, [String])
188profileCommand :: Parser (String, [String])
189profileCommand = (,)
189profileCommand = (,)
190 <$> strOption
190 <$> strOption
@@ -203,15 +203,6 @@ profileCommand = (,)
203 <> showDefault
203 <> showDefault
204 ))
204 ))
205
205
206−
207−--TODO: Result should provide normalised path and also original user input for error reporting.
208−thunkDirectoryParser :: Parser FilePath
209−thunkDirectoryParser = fmap (dropTrailingPathSeparator . normalise) . strArgument $ mconcat
210− [ action "directory"
211− , metavar "THUNKDIR"
212− , help "Path to directory containing thunk data"
213− ]
214−
215thunkConfig :: Parser ThunkConfig
206thunkConfig :: Parser ThunkConfig
216thunkConfig = ThunkConfig
207thunkConfig = ThunkConfig
217 <$>
208 <$>
@@ -230,22 +221,36 @@ thunkPackConfig = ThunkPackConfig
230 <$> switch (long "force" <> short 'f' <> help "Force packing thunks even if there are branches not pushed upstream, uncommitted changes, stashes. This will cause changes that have not been pushed upstream to be lost; use with care.")
221 <$> switch (long "force" <> short 'f' <> help "Force packing thunks even if there are branches not pushed upstream, uncommitted changes, stashes. This will cause changes that have not been pushed upstream to be lost; use with care.")
231 <*> thunkConfig
222 <*> thunkConfig
232
223
224+data ThunkOption = ThunkOption
225+ { _thunkOption_thunks :: NonEmpty FilePath
226+ , _thunkOption_command :: ThunkCommand
227+ } deriving Show
228+
233data ThunkCommand
229data ThunkCommand
234− = ThunkCommand_Update [FilePath] ThunkUpdateConfig
230+ = ThunkCommand_Update ThunkUpdateConfig
235− | ThunkCommand_Unpack [FilePath]
231+ | ThunkCommand_Unpack
236− | ThunkCommand_Pack [FilePath] ThunkPackConfig
232+ | ThunkCommand_Pack ThunkPackConfig
237 deriving Show
233 deriving Show
238
234
239−thunkCommand :: Parser ThunkCommand
235+thunkOption :: Parser ThunkOption
240−thunkCommand = hsubparser $ mconcat
236+thunkOption = hsubparser $ mconcat
241− [ command "update" $ info (ThunkCommand_Update <$> some thunkDirectoryParser <*> thunkUpdateConfig) $ progDesc "Update thunk to latest revision available"
237+ [ command "update" $ info (thunkOptionWith $ ThunkCommand_Update <$> thunkUpdateConfig) $ progDesc "Update packed thunk to latest revision available on the tracked branch"
242− , command "unpack" $ info (ThunkCommand_Unpack <$> some thunkDirectoryParser) $ progDesc "Unpack thunk into git checkout of revision it points to"
238+ , command "unpack" $ info (thunkOptionWith $ pure ThunkCommand_Unpack) $ progDesc "Unpack thunk into git checkout of revision it points to"
243− , command "pack" $ info (ThunkCommand_Pack <$> some thunkDirectoryParser <*> thunkPackConfig) $ progDesc "Pack git checkout into thunk that points at the current branch's upstream"
239+ , command "pack" $ info (thunkOptionWith $ ThunkCommand_Pack <$> thunkPackConfig) $ progDesc "Pack git checkout or unpacked thunk into thunk that points at the current branch's upstream"
244 ]
240 ]
241+ where
242+ thunkOptionWith f = ThunkOption
243+ <$> ((NonEmpty.:|)
244+ <$> thunkDirArg (metavar "THUNKDIRS..." <> help "Paths to directories containing thunk data")
245+ <*> many (thunkDirArg mempty)
246+ )
247+ <*> f
248+ thunkDirArg opts = fmap (dropTrailingPathSeparator . normalise) $ strArgument $ action "directory" <> opts
245
249
246data ShellOpts
250data ShellOpts
247 = ShellOpts
251 = ShellOpts
248 { _shellOpts_shell :: String
252 { _shellOpts_shell :: String
253+ , _shellOpts_interpretPaths :: [(FilePath, Interpret)]
249 , _shellOpts_command :: Maybe String
254 , _shellOpts_command :: Maybe String
250 }
255 }
251 deriving Show
256 deriving Show
@@ -256,9 +261,30 @@ shellFlags =
256 <|> flag "ghc" "ghcjs" (long "ghcjs" <> help "Enter a shell having ghcjs rather than ghc")
261 <|> flag "ghc" "ghcjs" (long "ghcjs" <> help "Enter a shell having ghcjs rather than ghc")
257 <|> strOption (short 'A' <> long "argument" <> metavar "NIXARG" <> help "Use the environment specified by the given nix argument of `shells'")
262 <|> strOption (short 'A' <> long "argument" <> metavar "NIXARG" <> help "Use the environment specified by the given nix argument of `shells'")
258
263
264+interpretOpts :: Parser [(FilePath, Interpret)]
265+interpretOpts = many
266+ ( (, Interpret_Interpret) <$>
267+ strOption (common <> long "interpret" <> help
268+ "Don't pre-build packages found in DIR when constructing the package database. The default behavior is \
269+ \'--interpret <project-root>', which will load everything which is unpacked into GHCi. \
270+ \ Use --interpret and --no-interpret multiple times to add or remove multiple trees \
271+ \ from the environment. Settings for right-most directories will \
272+ \ override settings for any identical directories given earlier."
273+ )
274+ <|> (, Interpret_NoInterpret) <$>
275+ strOption (common <> long "no-interpret" <> help
276+ "Make packages found in DIR available in the package database (but only when they are used dependencies). \
277+ \ This will build the packages in DIR before loading GHCi. \
278+ \See help for --interpret for how the two options are related."
279+ )
280+ )
281+ where
282+ common = action "directory" <> metavar "DIR"
283+
259shellOpts :: Parser ShellOpts
284shellOpts :: Parser ShellOpts
260shellOpts = ShellOpts
285shellOpts = ShellOpts
261 <$> shellFlags
286 <$> shellFlags
287+ <*> interpretOpts
262 <*> optional (strArgument (metavar "COMMAND"))
288 <*> optional (strArgument (metavar "COMMAND"))
263
289
264portOpt :: Int -> Parser Int
290portOpt :: Int -> Parser Int
@@ -269,9 +295,6 @@ parserPrefs = defaultPrefs
269 { prefShowHelpOnEmpty = True
295 { prefShowHelpOnEmpty = True
270 }
296 }
271
297
272−parseCLIArgs :: ArgsConfig -> [String] -> IO Args
273−parseCLIArgs cfg = handleParseResult . execParserPure parserPrefs (argsInfo cfg)
274−
275-- | Create an Obelisk config for the current process.
298-- | Create an Obelisk config for the current process.
276mkObeliskConfig :: IO Obelisk
299mkObeliskConfig :: IO Obelisk
277mkObeliskConfig = do
300mkObeliskConfig = do
@@ -356,29 +379,7 @@ ob :: MonadObelisk m => ObCommand -> m ()
356ob = \case
379ob = \case
357 ObCommand_Init source force -> initProject source force
380 ObCommand_Init source force -> initProject source force
358 ObCommand_Deploy dc -> case dc of
381 ObCommand_Deploy dc -> case dc of
359− DeployCommand_Init deployOpts -> withProjectRoot "." $ \root -> do
382+ DeployCommand_Init deployOpts -> withProjectRoot "." $ \root -> deployInit deployOpts root
360− let deployDir = _deployInitOpts_outputDir deployOpts
361− r <- liftIO $ canonicalizePath root
362− rootEqualsTarget <- liftIO $ equalFilePath r <$> canonicalizePath deployDir
363− when rootEqualsTarget $
364− failWith $ "Deploy directory " <> T.pack deployDir <> " should not be the same as project root."
365− thunkPtr <- readThunk root >>= \case
366− Left err -> failWith $ case err of
367− ReadThunkError_AmbiguousFiles ->
368− "Project root " <> T.pack r <> " is not a git repository or valid thunk"
369− ReadThunkError_UnrecognizedFiles ->
370− "Project root " <> T.pack r <> " is not a git repository or valid thunk"
371− _ -> "thunk read: " <> T.pack (show err)
372− Right (ThunkData_Packed ptr) -> return ptr
373− Right (ThunkData_Checkout (Just ptr)) -> return ptr
374− Right (ThunkData_Checkout Nothing) ->
375− getThunkPtr False root Nothing
376− let sshKeyPath = _deployInitOpts_sshKey deployOpts
377− hostname = _deployInitOpts_hostname deployOpts
378− route = _deployInitOpts_route deployOpts
379− adminEmail = _deployInitOpts_adminEmail deployOpts
380− enableHttps = _deployInitOpts_enableHttps deployOpts
381− deployInit thunkPtr deployDir sshKeyPath hostname route adminEmail enableHttps
382 DeployCommand_Push remoteBuilder -> do
383 DeployCommand_Push remoteBuilder -> do
383 deployPath <- liftIO $ canonicalizePath "."
384 deployPath <- liftIO $ canonicalizePath "."
384 deployPush deployPath $ case remoteBuilder of
385 deployPush deployPath $ case remoteBuilder of
@@ -386,23 +387,36 @@ ob = \case
386 Just RemoteBuilder_ObeliskVM -> (:[]) <$> VmBuilder.getNixBuildersArg
387 Just RemoteBuilder_ObeliskVM -> (:[]) <$> VmBuilder.getNixBuildersArg
387 DeployCommand_Update -> deployUpdate "."
388 DeployCommand_Update -> deployUpdate "."
388 DeployCommand_Test (platform, extraArgs) -> deployMobile platform extraArgs
389 DeployCommand_Test (platform, extraArgs) -> deployMobile platform extraArgs
389− ObCommand_Run -> run
390+ ObCommand_Run interpretPathsList -> withInterpretPaths interpretPathsList run
390 ObCommand_Profile basePath rtsFlags -> profile basePath rtsFlags
391 ObCommand_Profile basePath rtsFlags -> profile basePath rtsFlags
391− ObCommand_Thunk tc -> case tc of
392+ ObCommand_Thunk to -> case _thunkOption_command to of
392− ThunkCommand_Update thunks config -> for_ thunks (updateThunkToLatest config)
393+ ThunkCommand_Update config -> for_ thunks (updateThunkToLatest config)
393− ThunkCommand_Unpack thunks -> for_ thunks unpackThunk
394+ ThunkCommand_Unpack -> for_ thunks unpackThunk
394− ThunkCommand_Pack thunks config -> for_ thunks (packThunk config)
395+ ThunkCommand_Pack config -> for_ thunks (packThunk config)
396+ where
397+ thunks = _thunkOption_thunks to
395− ObCommand_Repl -> runRepl
398+ ObCommand_Repl interpretPathsList -> withInterpretPaths interpretPathsList runRepl
396− ObCommand_Watch -> runWatch
399+ ObCommand_Watch interpretPathsList -> withInterpretPaths interpretPathsList runWatch
397− ObCommand_Shell so -> withProjectRoot "." $ \root ->
400+ ObCommand_Shell (ShellOpts shellAttr interpretPathsList cmd) -> withInterpretPaths interpretPathsList $ \root interpretPaths ->
398− projectShell root False (_shellOpts_shell so) (_shellOpts_command so)
401+ nixShellForInterpretPaths False shellAttr root interpretPaths cmd
399− ObCommand_Doc shell' pkgs -> withProjectRoot "." $ \root ->
402+ ObCommand_Doc shellAttr pkgs -> withInterpretPaths [] $ \root interpretPaths ->
400− projectShell root False shell' (Just $ haddockCommand pkgs)
403+ nixShellForInterpretPaths True shellAttr root interpretPaths $ Just $ haddockCommand pkgs
401 ObCommand_Hoogle shell' port -> withProjectRoot "." $ \root -> do
404 ObCommand_Hoogle shell' port -> withProjectRoot "." $ \root -> do
402 nixShellWithHoogle root True shell' $ Just $ "hoogle server -p " <> show port <> " --local"
405 nixShellWithHoogle root True shell' $ Just $ "hoogle server -p " <> show port <> " --local"
403 ObCommand_Internal icmd -> case icmd of
406 ObCommand_Internal icmd -> case icmd of
404 ObInternal_ApplyPackages origPath inPath outPath packagePaths -> do
407 ObInternal_ApplyPackages origPath inPath outPath packagePaths -> do
405 liftIO $ Preprocessor.applyPackages origPath inPath outPath packagePaths
408 liftIO $ Preprocessor.applyPackages origPath inPath outPath packagePaths
409+ ObInternal_ExportGhciConfig interpretPathsList useRelativePaths ->
410+ liftIO . putStrLn . unlines =<< withInterpretPaths interpretPathsList (exportGhciConfig useRelativePaths)
411+
412+-- | A helper for the common case that the command you want to run needs the project root and a resolved
413+-- set of interpret paths.
414+withInterpretPaths :: MonadObelisk m => [(FilePath, Interpret)] -> (FilePath -> PathTree Interpret -> m a) -> m a
415+withInterpretPaths interpretPathsList f = withProjectRoot "." $ \root -> do
416+ interpretPaths' <- resolveInterpretPaths $ (root, Interpret_Interpret) : interpretPathsList
417+ case interpretPaths' of
418+ Nothing -> failWith "No paths provided for finding packages"
419+ Just interpretPaths -> f root interpretPaths
406
420
407haddockCommand :: [String] -> String
421haddockCommand :: [String] -> String
408haddockCommand pkgs = unwords
422haddockCommand pkgs = unwords
@@ -417,14 +431,21 @@ haddockCommand pkgs = unwords
417getArgsConfig :: IO ArgsConfig
431getArgsConfig :: IO ArgsConfig
418getArgsConfig = pure $ ArgsConfig { _argsConfig_enableVmBuilderByDefault = System.Info.os == "darwin" }
432getArgsConfig = pure $ ArgsConfig { _argsConfig_enableVmBuilderByDefault = System.Info.os == "darwin" }
419
433
420−encodeStaticKey :: StaticKey -> String
434+-- | Resolves an ordered list of paths for use with @--interpret@/@--no-interpret@ by coalescing
421−encodeStaticKey = T.unpack . decodeUtf8With lenientDecode . Base16.encode . LBS.toStrict . Binary.encode
435+-- paths into a non-ambiguous set of paths. Ambiguity is resolved by choosing right-most paths
422−
436+-- over any preceeding identical paths.
423−-- TODO: Use failWith in place of fail to be consistent.
437+--
424−decodeStaticKey :: String -> Either String StaticKey
438+-- For example: @a/b=ON a/b/c=OFF@ and @a/b/c=OFF a/b=ON@ are the same.
425−decodeStaticKey s = case Base16.decode $ encodeUtf8 $ T.pack s of
439+-- @a/b=ON a/b=OFF@ is reduced to @a/b=OFF@. We prefer right-biased choice to increase
426− (b, "") -> case Binary.decodeOrFail $ LBS.fromStrict b of
440+-- scriptability.
427− Right ("", _, a) -> pure a
441+--
428− Right _ -> fail "decodeStaticKey: Binary.decodeOrFail didn't consume all input"
442+-- N.B. All the paths in the result will be canonicalized. It's impossible to determine path
429− Left (_, _, e) -> fail $ "decodeStaticKey: Binary.decodeOrFail failed: " <> show e
443+-- overlap otherwise.
430− _ -> fail $ "decodeStaticKey: could not decode hex string: " <> show s
444+resolveInterpretPaths :: MonadIO m => [(FilePath, a)] -> m (Maybe (PathTree a))
445+resolveInterpretPaths ps = do
446+ trees <- liftIO $ for ps $ \(p, a) -> pathToTree a <$> canonicalizePath p
447+ pure $ foldr1 mergeTrees <$> nonEmpty trees
448+ where
449+ -- | Merge two 'PathTree's preferring leaves on the right in as much as they overlap with paths on the left.
450+ mergeTrees :: PathTree a -> PathTree a -> PathTree a
451+ mergeTrees (PathTree_Node ax x) (PathTree_Node ay y) = PathTree_Node (ay <|> ax) $ Map.unionWith mergeTrees x y
lib/command/src/Obelisk/Command/Deploy.hs+33−16
@@ -1,21 +1,24 @@
1+{-# LANGUAGE DeriveGeneric #-}
1{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE LambdaCase #-}
3{-# LANGUAGE LambdaCase #-}
3{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE OverloadedStrings #-}
5+{-# LANGUAGE QuasiQuotes #-}
4{-# LANGUAGE ScopedTypeVariables #-}
6{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE ViewPatterns #-}
7{-# LANGUAGE ViewPatterns #-}
6−{-# LANGUAGE DeriveGeneric #-}
7module Obelisk.Command.Deploy where
8module Obelisk.Command.Deploy where
8
9
10+import Control.Applicative (liftA2)
9import Control.Lens
11import Control.Lens
10import Control.Monad
12import Control.Monad
11import Control.Monad.Catch (Exception (displayException), MonadThrow, bracket, throwM, try)
13import Control.Monad.Catch (Exception (displayException), MonadThrow, bracket, throwM, try)
12−import Control.Monad.IO.Class (liftIO)
14+import Control.Monad.IO.Class (MonadIO, liftIO)
13import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
15import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
14import Data.Bits
16import Data.Bits
15import qualified Data.ByteString.Lazy as BSL
17import qualified Data.ByteString.Lazy as BSL
16import Data.Default
18import Data.Default
17import qualified Data.Map as Map
19import qualified Data.Map as Map
18import qualified Data.Set as Set
20import qualified Data.Set as Set
21+import Data.String.Here.Interpolated (i)
19import qualified Data.Text as T
22import qualified Data.Text as T
20import qualified Data.Text.IO as T
23import qualified Data.Text.IO as T
21import GHC.Generics
24import GHC.Generics
@@ -36,18 +39,32 @@ import Obelisk.Command.Project
36import Obelisk.Command.Thunk
39import Obelisk.Command.Thunk
37import Obelisk.Command.Utils
40import Obelisk.Command.Utils
38
41
42+data DeployInitOpts = DeployInitOpts
43+ { _deployInitOpts_outputDir :: FilePath
44+ , _deployInitOpts_sshKey :: FilePath
45+ , _deployInitOpts_hostname :: [String]
46+ , _deployInitOpts_route :: String
47+ , _deployInitOpts_adminEmail :: String
48+ , _deployInitOpts_enableHttps :: Bool
49+ } deriving Show
50+
51+deployInit :: MonadObelisk m => DeployInitOpts -> FilePath -> m ()
52+deployInit deployOpts root = do
53+ let deployDir = _deployInitOpts_outputDir deployOpts
54+ rootEqualsTarget <- liftIO $ liftA2 equalFilePath (canonicalizePath root) (canonicalizePath deployDir)
55+ when rootEqualsTarget $
56+ failWith [i|Deploy directory ${deployDir} should not be the same as project root.|]
57+ thunkPtr <- readThunk root >>= \case
58+ Right (ThunkData_Packed _ ptr) -> return ptr
59+ _ -> getThunkPtr CheckClean_NotIgnored root Nothing
60+ deployInit' thunkPtr deployOpts
39
61
40−deployInit
62+deployInit'
41 :: MonadObelisk m
63 :: MonadObelisk m
42 => ThunkPtr
64 => ThunkPtr
43− -> FilePath
65+ -> DeployInitOpts
44− -> FilePath
45− -> [String] -- ^ hostnames
46− -> String -- ^ route
47− -> String -- ^ admin email
48− -> Bool -- ^ enable https
49 -> m ()
66 -> m ()
50−deployInit thunkPtr deployDir sshKeyPath hostnames route adminEmail enableHttps = do
67+deployInit' thunkPtr (DeployInitOpts deployDir sshKeyPath hostnames route adminEmail enableHttps) = do
51 liftIO $ createDirectoryIfMissing True deployDir
68 liftIO $ createDirectoryIfMissing True deployDir
52 localKey <- withSpinner ("Preparing " <> T.pack deployDir) $ do
69 localKey <- withSpinner ("Preparing " <> T.pack deployDir) $ do
53 localKey <- liftIO (doesFileExist sshKeyPath) >>= \case
70 localKey <- liftIO (doesFileExist sshKeyPath) >>= \case
@@ -77,8 +94,8 @@ deployInit thunkPtr deployDir sshKeyPath hostnames route adminEmail enableHttps
77 ]
94 ]
78
95
79 let srcDir = deployDir </> "src"
96 let srcDir = deployDir </> "src"
80− withSpinner ("Creating source thunk (" <> T.pack (makeRelative deployDir srcDir) <> ")") $ liftIO $ do
97+ withSpinner ("Creating source thunk (" <> T.pack (makeRelative deployDir srcDir) <> ")") $ do
81− createThunk srcDir thunkPtr
98+ createThunk srcDir $ Right thunkPtr
82 setupObeliskImpl deployDir
99 setupObeliskImpl deployDir
83
100
84 withSpinner "Writing deployment configuration" $ do
101 withSpinner "Writing deployment configuration" $ do
@@ -92,8 +109,8 @@ deployInit thunkPtr deployDir sshKeyPath hostnames route adminEmail enableHttps
92 withSpinner ("Initializing git repository (" <> T.pack deployDir <> ")") $
109 withSpinner ("Initializing git repository (" <> T.pack deployDir <> ")") $
93 initGit deployDir
110 initGit deployDir
94
111
95−setupObeliskImpl :: FilePath -> IO ()
112+setupObeliskImpl :: MonadIO m => FilePath -> m ()
96−setupObeliskImpl deployDir = do
113+setupObeliskImpl deployDir = liftIO $ do
97 let
114 let
98 implDir = toImplDir deployDir
115 implDir = toImplDir deployDir
99 goBackUp = foldr (</>) "" $ (".." <$) $ splitPath $ makeRelative deployDir implDir
116 goBackUp = foldr (</>) "" $ (".." <$) $ splitPath $ makeRelative deployDir implDir
@@ -109,8 +126,8 @@ deployPush deployPath getNixBuilders = do
109 routeHost <- getHostFromRoute enableHttps route
126 routeHost <- getHostFromRoute enableHttps route
110 let srcPath = deployPath </> "src"
127 let srcPath = deployPath </> "src"
111 thunkPtr <- readThunk srcPath >>= \case
128 thunkPtr <- readThunk srcPath >>= \case
112− Right (ThunkData_Packed ptr) -> return ptr
129+ Right (ThunkData_Packed _ ptr) -> return ptr
113− Right (ThunkData_Checkout _) -> do
130+ Right ThunkData_Checkout -> do
114 checkGitCleanStatus srcPath True >>= \case
131 checkGitCleanStatus srcPath True >>= \case
115 True -> packThunk (ThunkPackConfig False (ThunkConfig Nothing)) srcPath
132 True -> packThunk (ThunkPackConfig False (ThunkConfig Nothing)) srcPath
116 False -> failWith $ T.pack $ "ob deploy push: ensure " <> srcPath <> " has no pending changes and latest is pushed upstream."
133 False -> failWith $ T.pack $ "ob deploy push: ensure " <> srcPath <> " has no pending changes and latest is pushed upstream."
lib/command/src/Obelisk/Command/Nix.hs+4−4
@@ -207,7 +207,7 @@ nixCmdProc' cmdCfg = (proc (T.unpack cmd) options, cmd)
207 )
207 )
208
208
209nixCmd :: MonadObelisk m => NixCmd -> m FilePath
209nixCmd :: MonadObelisk m => NixCmd -> m FilePath
210−nixCmd cmdCfg = withSpinner' ("Running " <> cmd <> desc) (Just $ const $ "Built " <> desc) $ do
210+nixCmd cmdCfg = withSpinner' (T.unwords $ "Running" : cmd : desc) (Just $ const $ T.unwords $ "Built" : desc) $ do
211 output <- readProcessAndLogStderr Debug cmdProc
211 output <- readProcessAndLogStderr Debug cmdProc
212 -- Remove final newline that Nix appends
212 -- Remove final newline that Nix appends
213 Just (outPath, '\n') <- pure $ T.unsnoc output
213 Just (outPath, '\n') <- pure $ T.unsnoc output
@@ -218,7 +218,7 @@ nixCmd cmdCfg = withSpinner' ("Running " <> cmd <> desc) (Just $ const $ "Built
218 NixCmd_Build cfg' -> cfg' ^. nixCommonConfig
218 NixCmd_Build cfg' -> cfg' ^. nixCommonConfig
219 NixCmd_Instantiate cfg' -> cfg' ^. nixCommonConfig
219 NixCmd_Instantiate cfg' -> cfg' ^. nixCommonConfig
220 path = commonCfg ^. nixCmdConfig_target . target_path
220 path = commonCfg ^. nixCmdConfig_target . target_path
221− desc = T.pack $ mconcat $ catMaybes
221+ desc = concat $ catMaybes
222− [ ("on " <>) <$> path
222+ [ (\x -> ["on", T.pack x]) <$> path
223− , (\a -> " [" <> a <> "]") <$> (commonCfg ^. nixCmdConfig_target . target_attr)
223+ , (\a -> ["[" <> T.pack a <> "]"]) <$> (commonCfg ^. nixCmdConfig_target . target_attr)
224 ]
224 ]
lib/command/src/Obelisk/Command/Preprocessor.hs+18−19
@@ -11,49 +11,48 @@ import qualified Data.Text.Lazy.Builder as TL
11import qualified Data.Text.Lazy.Encoding as TL
11import qualified Data.Text.Lazy.Encoding as TL
12import Distribution.Compiler (CompilerFlavor (..))
12import Distribution.Compiler (CompilerFlavor (..))
13import Language.Haskell.Extension (Extension (..), Language(..))
13import Language.Haskell.Extension (Extension (..), Language(..))
14+import System.Directory (canonicalizePath)
14−import System.IO (IOMode (..), hClose, hPutStrLn, openFile, stderr)
15+import System.IO (IOMode (..), hPutStrLn, stderr, withFile)
15−import System.FilePath (hasTrailingPathSeparator, joinPath, normalise, splitPath)
16+import System.FilePath (hasTrailingPathSeparator, joinPath, splitPath)
16
17
17import Obelisk.Command.Run (CabalPackageInfo (..), parseCabalPackage')
18import Obelisk.Command.Run (CabalPackageInfo (..), parseCabalPackage')
18
19
19applyPackages :: FilePath -> FilePath -> FilePath -> [FilePath] -> IO ()
20applyPackages :: FilePath -> FilePath -> FilePath -> [FilePath] -> IO ()
20−applyPackages origPath inPath outPath packagePaths = do
21+applyPackages origPath inPath outPath packagePaths' = withFile outPath WriteMode $ \outFile -> do
21 -- This code is intended to be executed via ghci's -pgmF preprocessor option
22 -- This code is intended to be executed via ghci's -pgmF preprocessor option
22 -- The command line arguments are passed in via ghc, which dictates the first three options and meanings
23 -- The command line arguments are passed in via ghc, which dictates the first three options and meanings
23− -- In order for this code to execute, origPath must contain either a '.' character or a '/' character.
24+ -- In order for this code to execute, origPath must contain either a '.' character or a '/' character.
24 -- (This is to avoid the possibility of the command line syntax conflicting with another ob command)
25 -- (This is to avoid the possibility of the command line syntax conflicting with another ob command)
25 -- We do have control over the remaining arguments, but they must be the same for all files.
26 -- We do have control over the remaining arguments, but they must be the same for all files.
26 -- Thus, the fourth command line argument must be "apply-packages", which has already been handled.
27 -- Thus, the fourth command line argument must be "apply-packages", which has already been handled.
27 -- We assume all the remaining arguments passed in are paths to cabal or hpack package specifications.
28 -- We assume all the remaining arguments passed in are paths to cabal or hpack package specifications.
28−
29− outFile <- openFile outPath WriteMode
30− let hPutTextBuilder h = BU.hPutBuilder h . TL.encodeUtf8Builder . TL.toLazyText
31−
32− -- putStr "--------------------------------------------------------------------------------\n"
33− -- print args
34− -- putStr "--------------------------------------------------------------------------------\n"
35−
36 -- Thus we must select among the packagePaths for the file we are going to parse.
29 -- Thus we must select among the packagePaths for the file we are going to parse.
37
30
31+ origPathCanonical <- canonicalizePath origPath
32+ packagePaths <- traverse canonicalizePath packagePaths'
33+
38 let takeDirs = takeWhile hasTrailingPathSeparator
34 let takeDirs = takeWhile hasTrailingPathSeparator
39− packageDirs = sortOn (negate . length . takeDirs) $ map (splitPath . normalise) packagePaths
35+ packageDirs = sortOn (negate . length . takeDirs) $ map splitPath packagePaths
40− origDir = splitPath $ normalise origPath
36+ origDir = splitPath origPathCanonical
41 matches = [ joinPath d | d <- packageDirs, takeDirs d `isPrefixOf` origDir ]
37 matches = [ joinPath d | d <- packageDirs, takeDirs d `isPrefixOf` origDir ]
42
38
43 -- So the first element of matches is going to be the deepest path to a package spec that contains
39 -- So the first element of matches is going to be the deepest path to a package spec that contains
44 -- our file as a subdirectory.
40 -- our file as a subdirectory.
45
41
46 case matches of
42 case matches of
47− [] -> hPutTextBuilder outFile (lineNumberPragma origPath) -- TODO: probably should produce a warning
43+ [] ->
44+ hPutStrLn stderr $ "Error: Unable to find cabal information for " <> origPath <> "; Skipping preprocessor."
48− (packagePath:_) -> do
45+ packagePath:_ -> do
49 parseCabalPackage' packagePath >>= \case
46 parseCabalPackage' packagePath >>= \case
50 Left err ->
47 Left err ->
51− hPutStrLn stderr $ "Error: Unable to parse cabal package " <> packagePath <> "; Skipping preprocessor on " <> origPath <> ". Error was " <> show err
48+ hPutStrLn stderr $ "Error: Unable to parse cabal package " <> packagePath <> "; Skipping preprocessor on " <> origPath <> ". Error: " <> show err
52 Right (_warnings, packageInfo) ->
49 Right (_warnings, packageInfo) ->
53 hPutTextBuilder outFile (generateHeader origPath packageInfo)
50 hPutTextBuilder outFile (generateHeader origPath packageInfo)
54
51
55 BL.readFile inPath >>= BL.hPut outFile
52 BL.readFile inPath >>= BL.hPut outFile
56− hClose outFile
53+
54+ where
55+ hPutTextBuilder h = BU.hPutBuilder h . TL.encodeUtf8Builder . TL.toLazyText
57
56
58
57
59 -- I'm pretty sure there's a certain amount of oversimplification in CabalPackageInfo, so I doubt this is fully robust.
58 -- I'm pretty sure there's a certain amount of oversimplification in CabalPackageInfo, so I doubt this is fully robust.
@@ -87,7 +86,7 @@ generateHeader origPath packageInfo =
87 <> TL.fromText " #-}\n"
86 <> TL.fromText " #-}\n"
88 else mempty
87 else mempty
89 optList = map TL.fromString
88 optList = map TL.fromString
90− $ filter (\x -> not (isPrefixOf "-O" x))
89+ $ filter (not . isPrefixOf "-O")
91 $ fromMaybe []
90 $ fromMaybe []
92 $ lookup GHC (_cabalPackageInfo_compilerOptions packageInfo)
91 $ lookup GHC (_cabalPackageInfo_compilerOptions packageInfo)
93
92
lib/command/src/Obelisk/Command/Project.hs+43−28
@@ -10,11 +10,9 @@ module Obelisk.Command.Project
10 , nixShellRunConfig
10 , nixShellRunConfig
11 , nixShellRunProc
11 , nixShellRunProc
12 , nixShellWithHoogle
12 , nixShellWithHoogle
13− , nixShellWithPkgs
13+ , nixShellWithoutPkgs
14 , obeliskDirName
14 , obeliskDirName
15− , projectShell
16 , toImplDir
15 , toImplDir
17− , toNixPath
18 , toObeliskDir
16 , toObeliskDir
19 , withProjectRoot
17 , withProjectRoot
20 ) where
18 ) where
@@ -29,7 +27,6 @@ import Data.Bits
29import qualified Data.ByteString.Lazy as BSL
27import qualified Data.ByteString.Lazy as BSL
30import Data.Default (def)
28import Data.Default (def)
31import Data.Function ((&), on)
29import Data.Function ((&), on)
32−import Data.List (isInfixOf)
33import Data.Map (Map)
30import Data.Map (Map)
34import Data.Text (Text)
31import Data.Text (Text)
35import qualified Data.Text as T
32import qualified Data.Text as T
@@ -50,7 +47,7 @@ import Obelisk.App (MonadObelisk)
50import Obelisk.CliApp
47import Obelisk.CliApp
51import Obelisk.Command.Nix
48import Obelisk.Command.Nix
52import Obelisk.Command.Thunk
49import Obelisk.Command.Thunk
53−import Obelisk.Command.Utils (nixExePath, nixBuildExePath)
50+import Obelisk.Command.Utils (nixBuildExePath, nixExePath, toNixPath)
54
51
55--TODO: Make this module resilient to random exceptions
52--TODO: Make this module resilient to random exceptions
56
53
@@ -96,16 +93,22 @@ initProject source force = withSystemTempDirectory "ob-init" $ \tmpDir -> do
96 | otherwise -> failWith "ob init requires an empty directory. Use the flag --force to init anyway, potentially overwriting files."
93 | otherwise -> failWith "ob init requires an empty directory. Use the flag --force to init anyway, potentially overwriting files."
97 skeleton <- withSpinner "Setting up obelisk" $ do
94 skeleton <- withSpinner "Setting up obelisk" $ do
98 liftIO $ createDirectory obDir
95 liftIO $ createDirectory obDir
96+ -- Clone the git source and repack it with the init source obelisk
97+ -- The purpose of this is to ensure we use the correct thunk spec.
98+ let cloneAndRepack src = do
99+ putLog Debug $ "Cloning obelisk into " <> T.pack implDir <> " and repacking using itself"
100+ commit <- getLatestRev src
101+ gitCloneForThunkUnpack (thunkSourceToGitSource src) (_thunkRev_commit commit) implDir
102+ callHandoffOb implDir ["thunk", "pack", implDir]
99 case source of
103 case source of
100− InitSource_Default -> createThunkWithLatest implDir obeliskSource
104+ InitSource_Default -> cloneAndRepack obeliskSource
101− InitSource_Branch branch -> createThunkWithLatest implDir $ obeliskSourceWithBranch branch
105+ InitSource_Branch branch -> cloneAndRepack $ obeliskSourceWithBranch branch
102 InitSource_Symlink path -> do
106 InitSource_Symlink path -> do
103 let symlinkPath = if isAbsolute path
107 let symlinkPath = if isAbsolute path
104 then path
108 then path
105 else ".." </> path
109 else ".." </> path
106 liftIO $ createSymbolicLink symlinkPath implDir
110 liftIO $ createSymbolicLink symlinkPath implDir
107 _ <- nixBuildAttrWithCache implDir "command"
111 _ <- nixBuildAttrWithCache implDir "command"
108− --TODO: We should probably handoff to the impl here
109 skel <- nixBuildAttrWithCache implDir "skeleton" --TODO: I don't think there's actually any reason to cache this
112 skel <- nixBuildAttrWithCache implDir "skeleton" --TODO: I don't think there's actually any reason to cache this
110
113
111 callProcessAndLogOutput (Notice, Error) $
114 callProcessAndLogOutput (Notice, Error) $
@@ -131,6 +134,24 @@ initProject source force = withSystemTempDirectory "ob-init" $ \tmpDir -> do
131 createDirectoryIfMissing False configDir
134 createDirectoryIfMissing False configDir
132 mapM_ (createDirectoryIfMissing False . (configDir </>)) ["backend", "common", "frontend"]
135 mapM_ (createDirectoryIfMissing False . (configDir </>)) ["backend", "common", "frontend"]
133
136
137+callHandoffOb
138+ :: MonadObelisk m
139+ => FilePath -- ^ Directory of the obelisk we want to handoff to
140+ -> [String] -- ^ Arguments to pass to ob
141+ -> m ()
142+callHandoffOb dir args = do
143+ obeliskCommandPkg <- nixCmd $ NixCmd_Build $ def
144+ & nixBuildConfig_outLink .~ OutLink_None
145+ & nixCmdConfig_target .~ Target
146+ { _target_path = Just dir
147+ , _target_attr = Just "command"
148+ , _target_expr = Nothing
149+ }
150+ let impl = obeliskCommandPkg </> "bin" </> "ob"
151+ -- Invoke the real implementation, using --no-handoff to prevent infinite recursion
152+ putLog Debug $ "Running '" <> T.pack (unwords args) <> "' with " <> T.pack impl
153+ callProcessAndLogOutput (Debug, Warning) (proc impl ("--no-handoff" : args))
154+
134--TODO: Allow the user to ignore our security concerns
155--TODO: Allow the user to ignore our security concerns
135-- | Find the Obelisk implementation for the project at the given path
156-- | Find the Obelisk implementation for the project at the given path
136findProjectObeliskCommand :: MonadObelisk m => FilePath -> m (Maybe FilePath)
157findProjectObeliskCommand :: MonadObelisk m => FilePath -> m (Maybe FilePath)
@@ -249,13 +270,6 @@ filePermissionIsSafe s umask = not fileWorldWritable && fileGroupWritable <= uma
249 fileGroupWritable = fileMode s .&. 0o020 == 0o020
270 fileGroupWritable = fileMode s .&. 0o020 == 0o020
250 umaskGroupWritable = umask .&. 0o020 == 0
271 umaskGroupWritable = umask .&. 0o020 == 0
251
272
252−-- | Nix syntax requires relative paths to be prefixed by @./@ or
253−-- @../@. This will make a 'FilePath' that can be embedded in a Nix
254−-- expression.
255−toNixPath :: FilePath -> FilePath
256−toNixPath root | "/" `isInfixOf` root = root
257− | otherwise = "./" <> root
258−
259nixShellRunConfig :: MonadObelisk m => FilePath -> Bool -> Maybe String -> m NixShellConfig
273nixShellRunConfig :: MonadObelisk m => FilePath -> Bool -> Maybe String -> m NixShellConfig
260nixShellRunConfig root isPure command = do
274nixShellRunConfig root isPure command = do
261 nixpkgsPath <- fmap T.strip $ readProcessAndLogStderr Debug $ setCwd (Just root) $
275 nixpkgsPath <- fmap T.strip $ readProcessAndLogStderr Debug $ setCwd (Just root) $
@@ -273,19 +287,28 @@ nixShellRunConfig root isPure command = do
273nixShellRunProc :: NixShellConfig -> ProcessSpec
287nixShellRunProc :: NixShellConfig -> ProcessSpec
274nixShellRunProc cfg = setDelegateCtlc True $ proc "nix-shell" $ runNixShellConfig cfg
288nixShellRunProc cfg = setDelegateCtlc True $ proc "nix-shell" $ runNixShellConfig cfg
275
289
276−nixShellWithPkgs :: MonadObelisk m => FilePath -> Bool -> Bool -> Map Text FilePath -> Maybe String -> m ()
290+nixShellWithoutPkgs
291+ :: MonadObelisk m
292+ => FilePath -- ^ Path to project root
293+ -> Bool -- ^ Should this be a pure shell?
294+ -> Bool -- ^ Should we chdir to the package root in the shell?
295+ -> Map Text FilePath -- ^ Package names mapped to their paths
296+ -> String -- ^ Shell attribute to use (e.g. @"ghc"@, @"ghcjs"@, etc.)
297+ -> Maybe String -- ^ If 'Just' run the given command; otherwise just open the interactive shell
298+ -> m ()
277−nixShellWithPkgs root isPure chdirToRoot packageNamesAndPaths command = do
299+nixShellWithoutPkgs root isPure chdirToRoot packageNamesAndPaths shellAttr command = do
278 packageNamesAndAbsPaths <- liftIO $ for packageNamesAndPaths makeAbsolute
300 packageNamesAndAbsPaths <- liftIO $ for packageNamesAndPaths makeAbsolute
279 defShellConfig <- nixShellRunConfig root isPure command
301 defShellConfig <- nixShellRunConfig root isPure command
280 let setCwd_ = if chdirToRoot then setCwd (Just root) else id
302 let setCwd_ = if chdirToRoot then setCwd (Just root) else id
281− (_, _, _, ph) <- createProcess_ "nixShellWithPkgs" $ setCwd_ $ nixShellRunProc $ defShellConfig
303+ (_, _, _, ph) <- createProcess_ "nixShellWithoutPkgs" $ setCwd_ $ nixShellRunProc $ defShellConfig
282 & nixShellConfig_common . nixCmdConfig_target . target_expr ?~
304 & nixShellConfig_common . nixCmdConfig_target . target_expr ?~
283− "{root, pkgs}: ((import root {}).passthru.__unstable__.self.extend (_: _: {\
305+ "{root, pkgs, shell}: ((import root {}).passthru.__unstable__.self.extend (_: _: {\
284 \shellPackages = builtins.fromJSON pkgs;\
306 \shellPackages = builtins.fromJSON pkgs;\
285− \})).project.shells.ghc"
307+ \})).project.shells.${shell}"
286 & nixShellConfig_common . nixCmdConfig_args .~
308 & nixShellConfig_common . nixCmdConfig_args .~
287 [ rawArg "root" $ toNixPath $ if chdirToRoot then "." else root
309 [ rawArg "root" $ toNixPath $ if chdirToRoot then "." else root
288 , strArg "pkgs" (T.unpack $ decodeUtf8 $ BSL.toStrict $ Json.encode packageNamesAndAbsPaths)
310 , strArg "pkgs" (T.unpack $ decodeUtf8 $ BSL.toStrict $ Json.encode packageNamesAndAbsPaths)
311+ , strArg "shell" shellAttr
289 ]
312 ]
290 void $ waitForProcess ph
313 void $ waitForProcess ph
291
314
@@ -300,14 +323,6 @@ nixShellWithHoogle root isPure shell' command = do
300 & nixShellConfig_common . nixCmdConfig_args .~ [ strArg "shell" shell' ]
323 & nixShellConfig_common . nixCmdConfig_args .~ [ strArg "shell" shell' ]
301 void $ waitForProcess ph
324 void $ waitForProcess ph
302
325
303−projectShell :: MonadObelisk m => FilePath -> Bool -> String -> Maybe String -> m ()
304−projectShell root isPure shellName command = do
305− defShellConfig <- nixShellRunConfig root isPure command
306− (_, _, _, ph) <- createProcess_ "runNixShellAttr" $ setCwd (Just root) $ nixShellRunProc $ defShellConfig
307− & nixShellConfig_common . nixCmdConfig_target . target_path ?~ "default.nix"
308− & nixShellConfig_common . nixCmdConfig_target . target_attr ?~ ("shells." <> shellName)
309− void $ waitForProcess ph
310−
311findProjectAssets :: MonadObelisk m => FilePath -> m Text
326findProjectAssets :: MonadObelisk m => FilePath -> m Text
312findProjectAssets root = do
327findProjectAssets root = do
313 isDerivation <- readProcessAndLogStderr Debug $ setCwd (Just root) $
328 isDerivation <- readProcessAndLogStderr Debug $ setCwd (Just root) $
lib/command/src/Obelisk/Command/Run.hs+223−74
@@ -1,10 +1,14 @@
1+{-# LANGUAGE DeriveFoldable #-}
2+{-# LANGUAGE DeriveFunctor #-}
3+{-# LANGUAGE DeriveTraversable #-}
1{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE LambdaCase #-}
5{-# LANGUAGE LambdaCase #-}
3{-# LANGUAGE MultiParamTypeClasses #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE OverloadedStrings #-}
7{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE QuasiQuotes #-}
5{-# LANGUAGE ScopedTypeVariables #-}
9{-# LANGUAGE ScopedTypeVariables #-}
6{-# LANGUAGE TupleSections #-}
10{-# LANGUAGE TupleSections #-}
7−{-# LANGUAGE QuasiQuotes #-}
11+{-# LANGUAGE ViewPatterns #-}
8module Obelisk.Command.Run where
12module Obelisk.Command.Run where
9
13
10import Control.Arrow ((&&&))
14import Control.Arrow ((&&&))
@@ -14,15 +18,22 @@ import Control.Monad (filterM, unless, void)
14import Control.Monad.Except (runExceptT, throwError)
18import Control.Monad.Except (runExceptT, throwError)
15import Control.Monad.IO.Class (liftIO)
19import Control.Monad.IO.Class (liftIO)
16import Control.Monad.Reader (MonadIO)
20import Control.Monad.Reader (MonadIO)
21+import Data.Bifoldable (bifoldr1)
22+import Data.Bifunctor (bimap)
17import Data.Coerce (coerce)
23import Data.Coerce (coerce)
18import Data.Default (def)
24import Data.Default (def)
19−import Data.Either
25+import Data.Either (partitionEithers)
20−import Data.Foldable (for_, toList)
26+import Data.Foldable (fold, for_, toList)
27+import Data.Functor.Identity (runIdentity)
28+import Data.List.NonEmpty (NonEmpty)
21import qualified Data.List.NonEmpty as NE
29import qualified Data.List.NonEmpty as NE
22import Data.Map (Map)
30import Data.Map (Map)
23import qualified Data.Map as Map
31import qualified Data.Map as Map
32+import qualified Data.Map.Monoidal as MMap
24import Data.Maybe
33import Data.Maybe
34+import Data.Set (Set)
25import qualified Data.Set as Set
35import qualified Data.Set as Set
36+import Data.String.Here.Interpolated (i)
26import Data.Text (Text)
37import Data.Text (Text)
27import qualified Data.Text as T
38import qualified Data.Text as T
28import Data.Time.Clock (getCurrentTime)
39import Data.Time.Clock (getCurrentTime)
@@ -65,7 +76,7 @@ import Obelisk.CliApp (
65 withSpinner,
76 withSpinner,
66 )
77 )
67import Obelisk.Command.Nix
78import Obelisk.Command.Nix
68−import Obelisk.Command.Project (nixShellWithPkgs, toImplDir, withProjectRoot, findProjectAssets)
79+import Obelisk.Command.Project (nixShellWithoutPkgs, withProjectRoot, findProjectAssets)
69import Obelisk.Command.Thunk (attrCacheFileName)
80import Obelisk.Command.Thunk (attrCacheFileName)
70import Obelisk.Command.Utils (findExePath, ghcidExePath)
81import Obelisk.Command.Utils (findExePath, ghcidExePath)
71
82
@@ -84,6 +95,31 @@ data CabalPackageInfo = CabalPackageInfo
84 -- ^ List of compiler-specific options (e.g., the "ghc-options" field of the cabal file)
95 -- ^ List of compiler-specific options (e.g., the "ghc-options" field of the cabal file)
85 }
96 }
86
97
98+-- | 'Bool' with a better name for it's purpose.
99+data Interpret = Interpret_Interpret | Interpret_NoInterpret deriving (Eq, Ord, Show)
100+
101+textInterpret :: Interpret -> Text
102+textInterpret = \case
103+ Interpret_Interpret -> "Interpret"
104+ Interpret_NoInterpret -> "NoInterpret"
105+
106+-- | Describe a set of 'FilePath's as a tree to facilitate merging them in a convenient way.
107+data PathTree a = PathTree_Node
108+ (Maybe a) -- An optional leaf at this point in the tree
109+ (Map FilePath (PathTree a)) -- Branches to deeper leaves
110+ deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
111+
112+-- | 2D ASCII drawing of a 'PathTree'. Adapted from Data.Tree.draw.
113+drawPathTree :: (a -> Text) -> PathTree a -> Text
114+drawPathTree showA (PathTree_Node _ ts0) = T.intercalate "\n" $ goForest (Map.toList ts0)
115+ where
116+ annotated ma = maybe id (\a b -> b <> " [" <> showA a <> "]") ma . T.pack
117+ goTree (fp, PathTree_Node ma forest) = annotated ma fp : goForest (Map.toList forest)
118+ goForest [] = []
119+ goForest [tree] = shift "└─ " " " (goTree tree)
120+ goForest (tree:forest) = shift "├─ " "│ " (goTree tree) <> goForest forest
121+ shift first other = zipWith (<>) (first : repeat other)
122+
87-- | Used to signal to obelisk that it's being invoked as a preprocessor
123-- | Used to signal to obelisk that it's being invoked as a preprocessor
88preprocessorIdentifier :: String
124preprocessorIdentifier :: String
89preprocessorIdentifier = "__preprocessor-apply-packages"
125preprocessorIdentifier = "__preprocessor-apply-packages"
@@ -122,16 +158,15 @@ profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
122 <> [ "-RTS" ]
158 <> [ "-RTS" ]
123 void $ waitForProcess ph
159 void $ waitForProcess ph
124
160
125−run
126− :: MonadObelisk m
161+run :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
127− => m ()
162+run root interpretPaths = do
128−run = withProjectRoot "." $ \root -> do
163+ pkgs <- getParsedLocalPkgs root interpretPaths
129− pkgs <- fmap toList . parsePackagesOrFail =<< getLocalPkgs root
130− withGhciScript pkgs root $ \dotGhciPath -> do
164+ withGhciScript pkgs $ \dotGhciPath -> do
131− freePort <- getFreePort
132 assets <- findProjectAssets root
165 assets <- findProjectAssets root
133 putLog Debug $ "Assets impurely loaded from: " <> assets
166 putLog Debug $ "Assets impurely loaded from: " <> assets
167+ ghciArgs <- getGhciSessionSettings pkgs root True
168+ freePort <- getFreePort
134− runGhcid root True dotGhciPath pkgs $ Just $ unwords
169+ runGhcid root True (ghciArgs <> mkGhciScriptArg dotGhciPath) pkgs $ Just $ unwords
135 [ "Obelisk.Run.run"
170 [ "Obelisk.Run.run"
136 , show freePort
171 , show freePort
137 , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
172 , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
@@ -139,39 +174,87 @@ run = withProjectRoot "." $ \root -> do
139 , "Frontend.frontend"
174 , "Frontend.frontend"
140 ]
175 ]
141
176
142−runRepl :: MonadObelisk m => m ()
177+runRepl :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
143−runRepl = withProjectRoot "." $ \root -> do
178+runRepl root interpretPaths = do
144− pkgs <- fmap toList . parsePackagesOrFail =<< getLocalPkgs root
179+ pkgs <- getParsedLocalPkgs root interpretPaths
180+ ghciArgs <- getGhciSessionSettings pkgs "." True
145− withGhciScript pkgs "." $ \dotGhciPath ->
181+ withGhciScript pkgs $ \dotGhciPath ->
146− runGhciRepl root pkgs dotGhciPath
182+ runGhciRepl root pkgs (ghciArgs <> mkGhciScriptArg dotGhciPath)
183+
184+runWatch :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
185+runWatch root interpretPaths = do
186+ pkgs <- getParsedLocalPkgs root interpretPaths
187+ ghciArgs <- getGhciSessionSettings pkgs root True
188+ withGhciScript pkgs $ \dotGhciPath ->
189+ runGhcid root True (ghciArgs <> mkGhciScriptArg dotGhciPath) pkgs Nothing
147
190
148−runWatch :: MonadObelisk m => m ()
191+exportGhciConfig :: MonadObelisk m => Bool -> FilePath -> PathTree Interpret -> m [String]
149−runWatch = withProjectRoot "." $ \root -> do
192+exportGhciConfig useRelativePaths root interpretPaths = do
193+ pkgs <- getParsedLocalPkgs root interpretPaths
194+ getGhciSessionSettings pkgs "." useRelativePaths
195+
196+nixShellForInterpretPaths :: MonadObelisk m => Bool -> String -> FilePath -> PathTree Interpret -> Maybe String -> m ()
197+nixShellForInterpretPaths isPure shell root interpretPaths cmd = do
198+ pkgs <- getParsedLocalPkgs root interpretPaths
199+ nixShellWithoutPkgs root isPure False (packageInfoToNamePathMap pkgs) shell cmd
200+
201+-- | Like 'getLocalPkgs' but also parses them and fails if any of them can't be parsed.
202+getParsedLocalPkgs :: MonadObelisk m => FilePath -> PathTree Interpret -> m (NonEmpty CabalPackageInfo)
150− pkgs <- fmap toList . parsePackagesOrFail =<< getLocalPkgs root
203+getParsedLocalPkgs root interpretPaths = parsePackagesOrFail =<< getLocalPkgs root interpretPaths
151− withGhciScript pkgs root $ \dotGhciPath ->
152− runGhcid root True dotGhciPath pkgs Nothing
153
204
154-- | Relative paths to local packages of an obelisk project.
205-- | Relative paths to local packages of an obelisk project.
155--
206--
156-- These are a combination of the obelisk predefined local packages,
207-- These are a combination of the obelisk predefined local packages,
157-- and any packages that the user has set with the @packages@ argument
208-- and any packages that the user has set with the @packages@ argument
158-- to the Nix @project@ function.
209-- to the Nix @project@ function.
159−getLocalPkgs :: MonadObelisk m => FilePath -> m [FilePath]
210+getLocalPkgs :: forall m. MonadObelisk m => FilePath -> PathTree Interpret -> m (Set FilePath)
160−getLocalPkgs root = do
211+getLocalPkgs root interpretPaths = do
212+ putLog Debug $ [i|Finding packages with root ${root} and interpret paths:|] <> "\n" <> drawPathTree textInterpret interpretPaths
161− obeliskPaths <- runFind ["-L", root, "-name", ".obelisk", "-type", "d"]
213+ obeliskPackagePaths <- runFind ["-L", root, "-name", ".obelisk", "-type", "d"]
162
214
163 -- We do not want to find packages that are embedded inside other obelisk projects, unless that
215 -- We do not want to find packages that are embedded inside other obelisk projects, unless that
164 -- obelisk project is our own.
216 -- obelisk project is our own.
217+ obeliskPackageExclusions <- liftIO $ fmap Set.fromList $ traverse canonicalizePath $
165− let exclusions = filter (/= root) $ map takeDirectory obeliskPaths
218+ filter (/= root) $ map takeDirectory obeliskPackagePaths
166− fmap (map (makeRelative ".")) $ runFind $
219+ putLog Debug [i|Excluding obelisk packages: ${T.pack $ unwords $ Set.toList obeliskPackageExclusions}|]
220+ let rootsAndExclusions = calcIntepretFinds "" interpretPaths
221+
222+ fmap fold $ for (MMap.toAscList rootsAndExclusions) $ \(interpretPathRoot, exclusions) ->
223+ let allExclusions = obeliskPackageExclusions <> exclusions <> Set.singleton ("*" </> attrCacheFileName)
224+ in fmap (Set.fromList . map normalise) $ runFind $
167− ["-L", root, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
225+ ["-L", interpretPathRoot, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
168− <> concat [["-not", "-path", p </> "*"] | p <- (toImplDir "*" </> attrCacheFileName) : exclusions]
226+ <> concat [["-not", "-path", p </> "*"] | p <- toList allExclusions]
169 where
227 where
170 runFind args = do
228 runFind args = do
171 (_exitCode, out, err) <- readCreateProcessWithExitCode $ proc findExePath args
229 (_exitCode, out, err) <- readCreateProcessWithExitCode $ proc findExePath args
172 putLog Debug $ T.strip $ T.pack err
230 putLog Debug $ T.strip $ T.pack err
173 pure $ map T.unpack $ T.lines $ T.strip $ T.pack out
231 pure $ map T.unpack $ T.lines $ T.strip $ T.pack out
174
232
233+-- | Calculates a set of root 'FilePath's along with each one's corresponding set of exclusions.
234+-- This is used when constructing a set of @find@ commands to run to produce a set of packages
235+-- that matches the user's @--interpret@/@--no-interpret@ settings.
236+calcIntepretFinds :: FilePath -> PathTree Interpret -> MMap.MonoidalMap FilePath (Set FilePath)
237+calcIntepretFinds treeRoot0 tree0 = runIdentity $ go treeRoot0 tree0
238+ where
239+ go treeRoot tree = foldPathTreeFor (== Interpret_Interpret) treeRoot tree $ \parent children -> do
240+ exclusions <- foldPathTreeFor (== Interpret_NoInterpret) parent children $ \parent' children' ->
241+ pure $ Map.singleton parent' children'
242+ deeperFinds <- Map.traverseWithKey go exclusions
243+ pure $ MMap.singleton parent (Map.keysSet exclusions) <> fold (MMap.MonoidalMap deeperFinds)
244+
245+-- | Traverses a 'PathTree' and folds all leaves matching a given predicate.
246+foldPathTreeFor
247+ :: forall m a b. (Applicative m, Monoid b)
248+ => (a -> Bool)
249+ -> FilePath
250+ -> PathTree a
251+ -> (FilePath -> PathTree a -> m b)
252+ -> m b
253+foldPathTreeFor predicate parent children f = case children of
254+ PathTree_Node (Just x) children' | predicate x -> f parent (PathTree_Node Nothing children')
255+ PathTree_Node _ children' -> fmap fold $ flip Map.traverseWithKey children' $ \k children'' ->
256+ foldPathTreeFor predicate (parent </> k) children'' f
257+
175data GuessPackageFileError = GuessPackageFileError_Ambiguous [FilePath] | GuessPackageFileError_NotFound
258data GuessPackageFileError = GuessPackageFileError_Ambiguous [FilePath] | GuessPackageFileError_NotFound
176 deriving (Eq, Ord, Show)
259 deriving (Eq, Ord, Show)
177instance Exception GuessPackageFileError
260instance Exception GuessPackageFileError
@@ -272,46 +355,56 @@ parseCabalPackage' pkg = runExceptT $ do
272 Left (_, errors) ->
355 Left (_, errors) ->
273 throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
356 throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
274
357
275−parsePackagesOrFail :: MonadObelisk m => [FilePath] -> m (NE.NonEmpty CabalPackageInfo)
358+parsePackagesOrFail :: (MonadObelisk m, Foldable f) => f FilePath -> m (NE.NonEmpty CabalPackageInfo)
276−parsePackagesOrFail dirs = do
359+parsePackagesOrFail dirs' = do
277 (pkgDirErrs, packageInfos') <- fmap partitionEithers $ for dirs $ \dir -> do
360 (pkgDirErrs, packageInfos') <- fmap partitionEithers $ for dirs $ \dir -> do
278 flip fmap (parseCabalPackage dir) $ \case
361 flip fmap (parseCabalPackage dir) $ \case
279 Just packageInfo
362 Just packageInfo
280 | _cabalPackageInfo_buildable packageInfo -> Right packageInfo
363 | _cabalPackageInfo_buildable packageInfo -> Right packageInfo
281 _ -> Left dir
364 _ -> Left dir
282
365
366+ -- Sort duplicate packages such that we prefer shorter paths, but fall back to alphabetical ordering.
367+ let packagesByName = Map.map (NE.sortBy $ comparing $ \p -> let n = _cabalPackageInfo_packageFile p in (length n, n))
283− let packagesByName = Map.fromListWith (<>) [(_cabalPackageInfo_packageName p, p NE.:| []) | p <- packageInfos']
368+ $ Map.fromListWith (<>) [(_cabalPackageInfo_packageName p, p NE.:| []) | p <- packageInfos']
284 unambiguous <- ifor packagesByName $ \packageName ps -> case ps of
369 unambiguous <- ifor packagesByName $ \packageName ps -> case ps of
285 p NE.:| [] -> pure p -- No ambiguity here
370 p NE.:| [] -> pure p -- No ambiguity here
286 p NE.:| _ -> do
371 p NE.:| _ -> do
372+ let chosenText = " [Chosen] "
373+ prefix p'
374+ | _cabalPackageInfo_packageFile p' == _cabalPackageInfo_packageFile p = chosenText
375+ | otherwise = T.map (const ' ') chosenText
287− putLog Warning $ T.pack $
376+ putLog Warning $ T.unlines $
288− "Packages named '" <> T.unpack packageName <> "' appear in " <> show (length ps) <> " different locations: "
377+ "Packages named '" <> packageName <> "' appear in " <> T.pack (show $ length ps) <> " different locations: "
289− <> intercalate ", " (map _cabalPackageInfo_packageFile $ toList ps)
378+ : map (\p' -> prefix p' <> T.pack (_cabalPackageInfo_packageFile p')) (toList ps)
290− <> "; Picking " <> _cabalPackageInfo_packageFile p
291 pure p
379 pure p
292
380
293 packageInfos <- case NE.nonEmpty $ toList unambiguous of
381 packageInfos <- case NE.nonEmpty $ toList unambiguous of
382+ Nothing -> failWith $ T.pack $
294− Nothing -> failWith $ T.pack $ "No valid, buildable packages found in " <> intercalate ", " dirs
383+ "No valid, buildable packages found" <> (if null dirs then "" else " in " <> intercalate ", " dirs)
295 Just xs -> pure xs
384 Just xs -> pure xs
296
385
297 unless (null pkgDirErrs) $
386 unless (null pkgDirErrs) $
298 putLog Warning $ T.pack $ "Failed to find buildable packages in " <> intercalate ", " pkgDirErrs
387 putLog Warning $ T.pack $ "Failed to find buildable packages in " <> intercalate ", " pkgDirErrs
299
388
300 pure packageInfos
389 pure packageInfos
390+ where
391+ dirs = toList dirs'
301
392
302−packageInfoToNamePathMap :: [CabalPackageInfo] -> Map Text FilePath
393+packageInfoToNamePathMap :: Foldable f => f CabalPackageInfo -> Map Text FilePath
303−packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot)
394+packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot) . toList
304
395
305-- | Create ghci configuration to load the given packages
396-- | Create ghci configuration to load the given packages
306withGhciScript
397withGhciScript
307− :: MonadObelisk m
398+ :: (MonadObelisk m, Foldable f)
308− => [CabalPackageInfo] -- ^ List of packages to load into ghci
399+ => f CabalPackageInfo -- ^ List of packages to load into ghci
309− -> FilePath -- ^ All paths written to the .ghci file will be relative to this path
310 -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
400 -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
311 -> m ()
401 -> m ()
312−withGhciScript packageInfos pathBase f = do
402+withGhciScript (toList -> packageInfos) f =
313− selfExe <- liftIO getExecutablePath
403+ withSystemTempDirectory "ob-ghci" $ \fp -> do
314− let
404+ let dotGhciPath = fp </> ".ghci"
405+ liftIO $ writeFile dotGhciPath dotGhci
406+ f dotGhciPath
407+ where
315 packageNames = Set.fromList $ map _cabalPackageInfo_packageName packageInfos
408 packageNames = Set.fromList $ map _cabalPackageInfo_packageName packageInfos
316 modulesToLoad = mconcat
409 modulesToLoad = mconcat
317 [ [ "Obelisk.Run" | "obelisk-run" `Set.member` packageNames ]
410 [ [ "Obelisk.Run" | "obelisk-run" `Set.member` packageNames ]
@@ -319,66 +412,88 @@ withGhciScript packageInfos pathBase f = do
319 , [ "Frontend" | "frontend" `Set.member` packageNames ]
412 , [ "Frontend" | "frontend" `Set.member` packageNames ]
320 ]
413 ]
321 dotGhci = unlines
414 dotGhci = unlines
322− -- TODO: Shell escape
323− [ ":set -F -pgmF " <> selfExe <> " -optF " <> preprocessorIdentifier <> " " <> unwords (map (("-optF " <>) . makeRelative pathBase . _cabalPackageInfo_packageFile) packageInfos)
324− , ":set -i" <> intercalate ":" (packageInfos >>= rootedSourceDirs)
325− , if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
415+ [ if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
326 , "import qualified Obelisk.Run"
416 , "import qualified Obelisk.Run"
327 , "import qualified Frontend"
417 , "import qualified Frontend"
328− , "import qualified Backend" ]
418+ , "import qualified Backend"
329− withSystemTempDirectory "ob-ghci" $ \fp -> do
419+ ]
330− let dotGhciPath = fp </> ".ghci"
420+
331− liftIO $ writeFile dotGhciPath dotGhci
421+-- | Builds a list of options to pass to ghci or set in .ghci file that configures
332− f dotGhciPath
422+-- the preprocessor and source includes.
423+getGhciSessionSettings
424+ :: (MonadObelisk m, Foldable f)
425+ => f CabalPackageInfo -- ^ List of packages to load into ghci
426+ -> FilePath -- ^ All paths will be relative to this path
427+ -> Bool -- ^ Use relative paths
428+ -> m [String]
429+getGhciSessionSettings (toList -> packageInfos) pathBase useRelativePaths = do
430+ -- N.B. ghci settings do NOT support escaping in any way. To minimize the likelihood that
431+ -- paths-with-spaces ruin our day, we first canonicalize everything, and then relativize
432+ -- all paths to 'pathBase'.
433+ selfExe <- liftIO $ canonicalizePath =<< getExecutablePath
434+ canonicalPathBase <- liftIO $ canonicalizePath pathBase
435+
436+ (pkgFiles, pkgSrcPaths :: [NonEmpty FilePath]) <- fmap unzip $ liftIO $ for packageInfos $ \pkg -> do
437+ canonicalSrcDirs <- traverse canonicalizePath $ (_cabalPackageInfo_packageRoot pkg </>) <$> _cabalPackageInfo_sourceDirs pkg
438+ canonicalPkgFile <- canonicalizePath $ _cabalPackageInfo_packageFile pkg
439+ pure (canonicalPkgFile `relativeTo'` canonicalPathBase, (`relativeTo'` canonicalPathBase) <$> canonicalSrcDirs)
333
440
441+ pure
442+ $ baseGhciOptions
443+ <> ["-F", "-pgmF", selfExe, "-optF", preprocessorIdentifier]
444+ <> concatMap (\p -> ["-optF", p]) pkgFiles
445+ <> [ "-i" <> intercalate ":" (concatMap toList pkgSrcPaths) ]
334 where
446 where
335− rootedSourceDirs pkg = NE.toList $
447+ relativeTo' = if useRelativePaths then relativeTo else const
336− makeRelative pathBase . (_cabalPackageInfo_packageRoot pkg </>) <$> _cabalPackageInfo_sourceDirs pkg
448+
449+baseGhciOptions :: [String]
450+baseGhciOptions =
451+ [ "-ignore-dot-ghci"
452+ , "-no-user-package-db"
453+ , "-package-env", "-"
454+ ]
337
455
338-- | Run ghci repl
456-- | Run ghci repl
339runGhciRepl
457runGhciRepl
340− :: MonadObelisk m
458+ :: (MonadObelisk m, Foldable f)
341 => FilePath -- ^ Path to project root
459 => FilePath -- ^ Path to project root
342− -> [CabalPackageInfo]
460+ -> f CabalPackageInfo -- ^ Packages to keep unbuilt
343− -> FilePath -- ^ Path to .ghci
461+ -> [String] -- ^ GHCi arguments
344 -> m ()
462 -> m ()
345−runGhciRepl root packages dotGhci =
463+runGhciRepl root (toList -> packages) ghciArgs =
346 -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
464 -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
347 -- ghc that is provided by the shell in the user's project.
465 -- ghc that is provided by the shell in the user's project.
348− nixShellWithPkgs root True False (packageInfoToNamePathMap packages) $ Just $ "ghci " <> makeBaseGhciOptions dotGhci -- TODO: Shell escape
466+ nixShellWithoutPkgs root True False (packageInfoToNamePathMap packages) "ghc" $
467+ Just $ unwords $ "ghci" : ghciArgs -- TODO: Shell escape
349
468
350-- | Run ghcid
469-- | Run ghcid
351runGhcid
470runGhcid
352− :: MonadObelisk m
471+ :: (MonadObelisk m, Foldable f)
353 => FilePath -- ^ Path to project root
472 => FilePath -- ^ Path to project root
354 -> Bool -- ^ Should we chdir to root when running this process?
473 -> Bool -- ^ Should we chdir to root when running this process?
355− -> FilePath -- ^ Path to .ghci
474+ -> [String] -- ^ GHCi arguments
356− -> [CabalPackageInfo]
475+ -> f CabalPackageInfo -- ^ Packages to keep unbuilt
357 -> Maybe String -- ^ Optional command to run at every reload
476 -> Maybe String -- ^ Optional command to run at every reload
358 -> m ()
477 -> m ()
359−runGhcid root chdirToRoot dotGhci packages mcmd =
478+runGhcid root chdirToRoot ghciArgs (toList -> packages) mcmd =
360− nixShellWithPkgs root True chdirToRoot (packageInfoToNamePathMap packages) (Just $ unwords $ ghcidExePath : opts) -- TODO: Shell escape
479+ nixShellWithoutPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $
480+ Just $ unwords $ ghcidExePath : opts -- TODO: Shell escape
361 where
481 where
362 opts =
482 opts =
363 [ "-W"
483 [ "-W"
364− , "--command='ghci -ignore-dot-ghci " <> makeBaseGhciOptions dotGhci <> "' "
365 , "--outputfile=ghcid-output.txt"
484 , "--outputfile=ghcid-output.txt"
366 ] <> map (\x -> "--reload='" <> x <> "'") reloadFiles
485 ] <> map (\x -> "--reload='" <> x <> "'") reloadFiles
367 <> map (\x -> "--restart='" <> x <> "'") restartFiles
486 <> map (\x -> "--restart='" <> x <> "'") restartFiles
368 <> testCmd
487 <> testCmd
488+ <> ["--command='" <> unwords ("ghci" : ghciArgs) <> "'"] -- TODO: Shell escape
369 testCmd = maybeToList (flip fmap mcmd $ \cmd -> "--test='" <> cmd <> "'") -- TODO: Shell escape
489 testCmd = maybeToList (flip fmap mcmd $ \cmd -> "--test='" <> cmd <> "'") -- TODO: Shell escape
370
490
371 adjustRoot x = if chdirToRoot then makeRelative root x else x
491 adjustRoot x = if chdirToRoot then makeRelative root x else x
372 reloadFiles = map adjustRoot [root </> "config"]
492 reloadFiles = map adjustRoot [root </> "config"]
373 restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
493 restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
374
494
375−makeBaseGhciOptions :: FilePath -> String
495+mkGhciScriptArg :: FilePath -> [String]
376−makeBaseGhciOptions dotGhci =
377− unwords
378− [ "-no-user-package-db"
379− , "-package-env -"
380− , "-ghci-script " <> dotGhci
496+mkGhciScriptArg dotGhci = ["-ghci-script", dotGhci]
381− ]
382
497
383getFreePort :: MonadIO m => m PortNumber
498getFreePort :: MonadIO m => m PortNumber
384getFreePort = liftIO $ withSocketsDo $ do
499getFreePort = liftIO $ withSocketsDo $ do
@@ -389,3 +504,37 @@ getFreePort = liftIO $ withSocketsDo $ do
389 sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
504 sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
390 bind sock (addrAddress addr)
505 bind sock (addrAddress addr)
391 return sock
506 return sock
507+
508+
509+-- | Convert a 'FilePath' into a 'PathTree'.
510+pathToTree :: a -> FilePath -> PathTree a
511+pathToTree a p = go $ splitDirectories p
512+ where
513+ go [] = PathTree_Node (Just a) mempty
514+ go (x : xs) = PathTree_Node Nothing $ Map.singleton x $ go xs
515+
516+-- | Like 'zipWith' but pads with a padding value instead of stopping on the shortest list.
517+zipDefaultWith :: a -> b -> (a -> b -> c) -> [a] -> [b] -> [c]
518+zipDefaultWith _da _db _f [] [] = []
519+zipDefaultWith da db f (a:as) [] = f a db : zipDefaultWith da db f as []
520+zipDefaultWith da db f [] (b:bs) = f da b : zipDefaultWith da db f [] bs
521+zipDefaultWith da db f (a:as) (b:bs) = f a b : zipDefaultWith da db f as bs
522+
523+-- | Makes the first absolute path relative to the second absolute path.
524+--
525+-- Both input paths MUST be absolute.
526+--
527+-- Unlike 'makeRelative' this does not merely strip prefixes. It will introduce
528+-- enough @..@ paths to make the resulting path truly relative in virtually every
529+-- case. The only exception is on Windows when the two paths are on different
530+-- drives. In this case the resulting path may be absolute.
531+relativeTo :: FilePath -> FilePath -> FilePath
532+relativeTo dir base
533+ = bifoldr1 (</>)
534+ $ bimap (collapse . (".." <$) . catMaybes) (collapse . catMaybes)
535+ $ unzip
536+ $ dropWhile (\(a,b) -> a == b)
537+ $ zipDefaultWith Nothing Nothing (,)
538+ (map Just $ splitDirectories base)
539+ (map Just $ splitDirectories dir)
540+ where collapse = foldr (</>) ""
lib/command/src/Obelisk/Command/Thunk.hs+396−277
@@ -5,67 +5,48 @@
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
11− ( GitHubSource (..)
12− , GitUri (..)
13− , ReadThunkError (..)
14− , ThunkConfig (..)
15− , ThunkData (..)
16− , ThunkPackConfig (..)
17− , ThunkPtr (..)
18− , ThunkRev (..)
19− , ThunkSource (..)
20− , ThunkUpdateConfig (..)
21− , attrCacheFileName
22− , createThunk
23− , createThunkWithLatest
24− , getLatestRev
25− , getThunkGitBranch
26− , getThunkPtr
27− , gitUriToText
28− , nixBuildAttrWithCache
29− , nixBuildThunkAttrWithCache
30− , packThunk
31− , parseGitUri
32− , readThunk
33− , unpackThunk
34− , updateThunk
35− , updateThunkToLatest
36− , uriThunkPtr
37− ) where
38
12
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)
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
48import Data.Aeson.Encode.Pretty
22import Data.Aeson.Encode.Pretty
49import qualified Data.Aeson.Types as Aeson
23import qualified Data.Aeson.Types as Aeson
24+import Data.Bifunctor (first)
50import qualified Data.ByteString.Lazy as LBS
25import qualified Data.ByteString.Lazy as LBS
51import Data.Containers.ListUtils (nubOrd)
26import Data.Containers.ListUtils (nubOrd)
52import Data.Default
27import Data.Default
53import Data.Either.Combinators (fromRight', rightToMaybe)
28import Data.Either.Combinators (fromRight', rightToMaybe)
29+import Data.Foldable (toList)
30+import Data.Function ((&))
31+import Data.Functor ((<&>))
54import Data.Git.Ref (Ref)
32import Data.Git.Ref (Ref)
55import qualified Data.Git.Ref as Ref
33import qualified Data.Git.Ref as Ref
56import qualified Data.List as L
34import qualified Data.List as L
57−import Data.List.NonEmpty (NonEmpty (..))
35+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
58import qualified Data.List.NonEmpty as NonEmpty
36import qualified Data.List.NonEmpty as NonEmpty
59import Data.Map (Map)
37import Data.Map (Map)
60import qualified Data.Map as Map
38import qualified Data.Map as Map
61import Data.Maybe
39import Data.Maybe
62import Data.Set (Set)
40import Data.Set (Set)
63import qualified Data.Set as Set
41import qualified Data.Set as Set
42+import Data.String.Here.Interpolated (i)
43+import Data.String.Here.Uninterpolated (here)
64import Data.Text (Text)
44import Data.Text (Text)
65import qualified Data.Text as T
45import qualified Data.Text as T
66import Data.Text.Encoding
46import Data.Text.Encoding
67import qualified Data.Text.IO as T
47import qualified Data.Text.IO as T
68import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
48import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
49+import Data.Traversable (for)
69import Data.Yaml (parseMaybe)
50import Data.Yaml (parseMaybe)
70import GitHub
51import GitHub
71import GitHub.Data.Name
52import GitHub.Data.Name
@@ -84,11 +65,10 @@ import Obelisk.Command.Utils
84
65
85--TODO: Support symlinked thunk data
66--TODO: Support symlinked thunk data
86data ThunkData
67data ThunkData
87− = ThunkData_Packed ThunkPtr
68+ = ThunkData_Packed ThunkSpec ThunkPtr
88 -- ^ Packed thunk
69 -- ^ Packed thunk
89− | ThunkData_Checkout (Maybe ThunkPtr)
70+ | ThunkData_Checkout
90 -- ^ Checked out thunk that was unpacked from this pointer
71 -- ^ Checked out thunk that was unpacked from this pointer
91− deriving (Show, Eq, Ord)
92
72
93-- | A reference to the exact data that a thunk should translate into
73-- | A reference to the exact data that a thunk should translate into
94data ThunkPtr = ThunkPtr
74data ThunkPtr = ThunkPtr
@@ -114,6 +94,11 @@ data ThunkSource
114 | ThunkSource_Git GitSource
94 | ThunkSource_Git GitSource
115 deriving (Show, Eq, Ord)
95 deriving (Show, Eq, Ord)
116
96
97+thunkSourceToGitSource :: ThunkSource -> GitSource
98+thunkSourceToGitSource = \case
99+ ThunkSource_GitHub s -> forgetGithub False s
100+ ThunkSource_Git s -> s
101+
117data GitHubSource = GitHubSource
102data GitHubSource = GitHubSource
118 { _gitHubSource_owner :: Name Owner
103 { _gitHubSource_owner :: Name Owner
119 , _gitHubSource_repo :: Name Repo
104 , _gitHubSource_repo :: Name Repo
@@ -213,96 +198,117 @@ nixPrefetchGit uri rev fetchSubmodules =
213
198
214--TODO: Pretty print these
199--TODO: Pretty print these
215data ReadThunkError
200data ReadThunkError
216− = ReadThunkError_UnrecognizedFiles
201+ = ReadThunkError_UnrecognizedThunk
217− | ReadThunkError_AmbiguousFiles
202+ | ReadThunkError_UnrecognizedPaths (NonEmpty FilePath)
218− | ReadThunkError_UnrecognizedLoader Text
203+ | ReadThunkError_MissingPaths (NonEmpty FilePath)
219− | ReadThunkError_UnparseablePtr LBS.ByteString
204+ | ReadThunkError_UnparseablePtr FilePath String
205+ | ReadThunkError_FileError IOError
206+ | ReadThunkError_FileDoesNotMatch FilePath Text
207+ | ReadThunkError_UnrecognizedState String
208+ | ReadThunkError_AmbiguousPackedState ThunkPtr ThunkPtr
220− deriving (Show)
209+ deriving (Show)
221−
210+
222−-- | Read a thunk and validate that it is only a thunk, either packed or unpacked.
211+unpackedDirName :: FilePath
223−-- If the thunk is packed and additional data is present, fail.
212+unpackedDirName = "."
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
234
213
235attrCacheFileName :: FilePath
214attrCacheFileName :: FilePath
236attrCacheFileName = ".attr-cache"
215attrCacheFileName = ".attr-cache"
237
216
238−data ThunkType = ThunkType
217+-- | Specification for how a file in a thunk version works.
239− { _thunkType_loader :: FilePath
218+data ThunkFileSpec
240− , _thunkType_json :: FilePath
219+ = ThunkFileSpec_Ptr (LBS.ByteString -> Either String ThunkPtr) -- ^ This file specifies 'ThunkPtr' data
241− , _thunkType_optional :: Set FilePath
220+ | ThunkFileSpec_FileMatches Text -- ^ This file must match the given content exactly
242− , _thunkType_loaderVersions :: NonEmpty Text
221+ | ThunkFileSpec_CheckoutIndicator -- ^ Existence of this directory indicates that the thunk is unpacked
243− , _thunkType_parser :: Aeson.Object -> Aeson.Parser ThunkPtr
222+ | ThunkFileSpec_AttrCache -- ^ This directory is an attribute cache
244− }
223+
245−
224+-- | Specification for how a set of files in a thunk version work.
246−gitHubThunkType :: ThunkType
225+data ThunkSpec = ThunkSpec
247−gitHubThunkType = ThunkType
226+ { _thunkSpec_name :: !Text
248− { _thunkType_loader = "default.nix"
227+ , _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
254− }
255−
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
263 }
228 }
264
229
265−thunkTypes :: [ThunkType]
230+thunkSpecTypes :: NonEmpty (NonEmpty ThunkSpec)
266−thunkTypes = [gitThunkType, gitHubThunkType]
231+thunkSpecTypes = gitThunkSpecs :| [gitHubThunkSpecs]
267−
232+
268−findThunkType :: [ThunkType] -> FilePath -> IO (Either ReadThunkError ThunkType)
233+-- | Attempts to match a 'ThunkSpec' to a given directory.
269−findThunkType types thunkDir = do
234+matchThunkSpecToDir
270− matches <- fmap catMaybes $ forM types $ \thunkType -> do
235+ :: (MonadError ReadThunkError m, MonadIO m, MonadCatch m)
271− let
236+ => ThunkSpec -- ^ 'ThunkSpec' to match against the given files/directory
272− expectedContents = Set.fromList $ (thunkDir </>) <$>
237+ -> FilePath -- ^ Path to directory
273− [ _thunkType_loader thunkType
238+ -> Set FilePath -- ^ Set of file paths relative to the given directory
274− , _thunkType_json thunkType
239+ -> m ThunkData
275− ]
240+matchThunkSpecToDir thunkSpec dir dirFiles = do
276− optionalContents = Set.map (thunkDir </>) (_thunkType_optional thunkType)
241+ case nonEmpty (toList $ dirFiles `Set.difference` expectedPaths) of
277−
242+ Just fs -> throwError $ ReadThunkError_UnrecognizedPaths $ (dir </>) <$> fs
278− -- Ensure that there aren't any other files in the thunk
243+ Nothing -> pure ()
279− -- NB: System.Directory.listDirectory returns the contents without the directory path
244+ case nonEmpty (toList $ requiredPaths `Set.difference` dirFiles) of
280− files <- liftIO $ Set.fromList . fmap (thunkDir </>) <$> listDirectory thunkDir
245+ Just fs -> throwError $ ReadThunkError_MissingPaths $ (dir </>) <$> fs
281− let unexpectedContents = files `Set.difference` (expectedContents `Set.union` optionalContents)
246+ Nothing -> pure ()
282− missingContents = expectedContents `Set.difference` files
247+ datas <- fmap toList $ flip Map.traverseMaybeWithKey (_thunkSpec_files thunkSpec) $ \expectedPath -> \case
283− pure $ if Set.null unexpectedContents && Set.null missingContents
248+ ThunkFileSpec_AttrCache -> Nothing <$ dirMayExist expectedPath
284− then Just thunkType
249+ ThunkFileSpec_CheckoutIndicator -> liftIO (doesDirectoryExist (dir </> expectedPath)) <&> \case
285− else Nothing
250+ False -> Nothing
286−
251+ True -> Just ThunkData_Checkout
287− pure $ case matches of
252+ ThunkFileSpec_FileMatches expectedContents -> handle (\(e :: IOError) -> throwError $ ReadThunkError_FileError e) $ do
288− [singleMatch] -> Right singleMatch
253+ actualContents <- liftIO (T.readFile $ dir </> expectedPath)
289− [] -> Left ReadThunkError_UnrecognizedFiles
254+ case T.strip expectedContents == T.strip actualContents of
290− _ -> Left ReadThunkError_AmbiguousFiles
255+ True -> pure Nothing
256+ False -> throwError $ ReadThunkError_FileDoesNotMatch (dir </> expectedPath) expectedContents
257+ ThunkFileSpec_Ptr parser -> handle (\(e :: IOError) -> throwError $ ReadThunkError_FileError e) $ do
258+ let path = dir </> expectedPath
259+ liftIO (doesFileExist path) >>= \case
260+ False -> pure Nothing
261+ True -> do
262+ actualContents <- liftIO $ LBS.readFile path
263+ case parser actualContents of
264+ Right v -> pure $ Just (ThunkData_Packed thunkSpec v)
265+ Left e -> throwError $ ReadThunkError_UnparseablePtr (dir </> expectedPath) e
266+
267+ case nonEmpty datas of
268+ Nothing -> throwError ReadThunkError_UnrecognizedThunk
269+ Just xs -> fold1WithM xs $ \a b -> either throwError pure (mergeThunkData a b)
270+ where
271+ rootPathsOnly = Set.fromList . mapMaybe takeRootDir . Map.keys
272+ takeRootDir = fmap NonEmpty.head . nonEmpty . splitPath
273+
274+ expectedPaths = rootPathsOnly $ _thunkSpec_files thunkSpec
275+
276+ requiredPaths = rootPathsOnly $ Map.filter isRequiredFileSpec $ _thunkSpec_files thunkSpec
277+ isRequiredFileSpec = \case
278+ ThunkFileSpec_FileMatches _ -> True
279+ _ -> False
280+
281+ dirMayExist expectedPath = liftIO (doesFileExist (dir </> expectedPath)) >>= \case
282+ True -> throwError $ ReadThunkError_UnrecognizedPaths $ expectedPath :| []
283+ False -> pure ()
284+
285+ -- Combine 'ThunkData' from different files, preferring "Checkout" over "Packed"
286+ mergeThunkData ThunkData_Checkout ThunkData_Checkout = Right ThunkData_Checkout
287+ mergeThunkData ThunkData_Checkout ThunkData_Packed{} = Left bothPackedAndUnpacked
288+ mergeThunkData ThunkData_Packed{} ThunkData_Checkout = Left bothPackedAndUnpacked
289+ mergeThunkData a@(ThunkData_Packed _ ptrA) (ThunkData_Packed _ ptrB) =
290+ if ptrA == ptrB then Right a else Left $ ReadThunkError_AmbiguousPackedState ptrA ptrB
291+
292+ bothPackedAndUnpacked = ReadThunkError_UnrecognizedState "Both packed data and checkout present"
293+
294+ fold1WithM (x :| xs) f = foldM f x xs
295+
296+readThunkWith
297+ :: (MonadObelisk m)
298+ => NonEmpty (NonEmpty ThunkSpec) -> FilePath -> m (Either ReadThunkError ThunkData)
299+readThunkWith specTypes dir = do
300+ dirFiles <- Set.fromList <$> liftIO (listDirectory dir)
301+ let specs = concatMap toList $ toList $ NonEmpty.transpose specTypes -- Interleave spec types so we try each one in a "fair" ordering
302+ flip fix specs $ \loop -> \case
303+ [] -> pure $ Left ReadThunkError_UnrecognizedThunk
304+ spec:rest -> runExceptT (matchThunkSpecToDir spec dir dirFiles) >>= \case
305+ Left e -> putLog Debug [i|Thunk specification ${_thunkSpec_name spec} did not match ${dir}: ${e}|] *> loop rest
306+ x@(Right _) -> x <$ putLog Debug [i|Thunk specification ${_thunkSpec_name spec} matched ${dir}|]
291
307
292-- | Read a thunk and validate that it is exactly a packed thunk.
308-- | Read a thunk and validate that it is exactly a packed thunk.
293-- If additional data is present, fail.
309-- If additional data is present, fail.
294−readPackedThunk :: FilePath -> IO (Either ReadThunkError ThunkPtr)
310+readThunk :: (MonadObelisk m) => FilePath -> m (Either ReadThunkError ThunkData)
295−readPackedThunk thunkDir = runExceptT $ do
311+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
301−
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
306
312
307parseThunkPtr :: (Aeson.Object -> Aeson.Parser ThunkSource) -> Aeson.Object -> Aeson.Parser ThunkPtr
313parseThunkPtr :: (Aeson.Object -> Aeson.Parser ThunkSource) -> Aeson.Object -> Aeson.Parser ThunkPtr
308parseThunkPtr parseSrc v = do
314parseThunkPtr parseSrc v = do
@@ -346,16 +352,18 @@ parseGitSource v = do
346overwriteThunk :: MonadObelisk m => FilePath -> ThunkPtr -> m ()
352overwriteThunk :: MonadObelisk m => FilePath -> ThunkPtr -> m ()
347overwriteThunk target thunk = do
353overwriteThunk target thunk = do
348 -- Ensure that this directory is a valid thunk (i.e. so we aren't losing any data)
354 -- Ensure that this directory is a valid thunk (i.e. so we aren't losing any data)
349− Right _ <- readThunk target
355+ readThunk target >>= \case
356+ Left e -> failWith [i|Invalid thunk at ${target}: ${e}|]
357+ Right _ -> pure ()
350
358
351 --TODO: Is there a safer way to do this overwriting?
359 --TODO: Is there a safer way to do this overwriting?
352− liftIO $ removeDirectoryRecursive target
360+ liftIO $ removePathForcibly target
353− liftIO $ createThunk target thunk
361+ createThunk target $ Right thunk
354
362
355−thunkPtrLoader :: ThunkPtr -> Text
363+thunkPtrToSpec :: ThunkPtr -> ThunkSpec
356−thunkPtrLoader thunk = case _thunkPtr_source thunk of
364+thunkPtrToSpec thunk = case _thunkPtr_source thunk of
357− ThunkSource_GitHub _ -> NonEmpty.head gitHubStandaloneLoaders
365+ ThunkSource_GitHub _ -> NonEmpty.head gitHubThunkSpecs
358− ThunkSource_Git _ -> NonEmpty.head plainGitStandaloneLoaders
366+ ThunkSource_Git _ -> NonEmpty.head gitThunkSpecs
359
367
360-- It's important that formatting be very consistent here, because
368-- It's important that formatting be very consistent here, because
361-- otherwise when people update thunks, their patches will be messy
369-- otherwise when people update thunks, their patches will be messy
@@ -402,35 +410,41 @@ encodeThunkPtrData (ThunkPtr rev src) = case src of
402 , confTrailingNewline = True
410 , confTrailingNewline = True
403 }
411 }
404
412
405−createThunk :: MonadIO m => FilePath -> ThunkPtr -> m ()
413+createThunk :: MonadObelisk m => FilePath -> Either ThunkSpec ThunkPtr -> m ()
406−createThunk target thunk = liftIO $ do
414+createThunk target ptrInfo =
407− createDirectoryIfMissing True (target </> attrCacheFileName)
415+ ifor_ (_thunkSpec_files spec) $ \path -> \case
408− T.writeFile (target </> "default.nix") (thunkPtrLoader thunk)
416+ ThunkFileSpec_FileMatches content -> withReadyPath path $ \p -> liftIO $ T.writeFile p content
409− let
417+ ThunkFileSpec_Ptr _ -> case ptrInfo of
410− jsonFileName = case _thunkPtr_source thunk of
418+ 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)
419+ Right ptr -> withReadyPath path $ \p -> liftIO $ LBS.writeFile p (encodeThunkPtrData ptr)
420+ _ -> pure ()
421+ where
422+ spec = either id thunkPtrToSpec ptrInfo
423+ withReadyPath path f = do
424+ let fullPath = target </> path
425+ putLog Debug $ "Writing thunk file " <> T.pack fullPath
426+ liftIO $ createDirectoryIfMissing True $ takeDirectory fullPath
427+ f fullPath
414
428
415createThunkWithLatest :: MonadObelisk m => FilePath -> ThunkSource -> m ()
429createThunkWithLatest :: MonadObelisk m => FilePath -> ThunkSource -> m ()
416createThunkWithLatest target s = do
430createThunkWithLatest target s = do
417 rev <- getLatestRev s
431 rev <- getLatestRev s
418− createThunk target $ ThunkPtr
432+ createThunk target $ Right $ ThunkPtr
419 { _thunkPtr_source = s
433 { _thunkPtr_source = s
420 , _thunkPtr_rev = rev
434 , _thunkPtr_rev = rev
421 }
435 }
422
436
423updateThunkToLatest :: MonadObelisk m => ThunkUpdateConfig -> FilePath -> m ()
437updateThunkToLatest :: 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
438+updateThunkToLatest (ThunkUpdateConfig mBranch thunkConfig) target = spinner $ do
425− checkThunkDirectory "ob thunk update directory cannot be '.'" target
439+ checkThunkDirectory target
426 -- check to see if thunk should be updated to a specific branch or just update it's current branch
440 -- check to see if thunk should be updated to a specific branch or just update it's current branch
427 case mBranch of
441 case mBranch of
428 Nothing -> do
442 Nothing -> do
429 (overwrite, ptr) <- readThunk target >>= \case
443 (overwrite, ptr) <- readThunk target >>= \case
430− Left err -> failWith $ T.pack $ "thunk update: " <> show err
444+ Left err -> failWith [i|Thunk update: ${err}|]
431 Right c -> case c of
445 Right c -> case c of
432− ThunkData_Packed t -> return (target, t)
446+ ThunkData_Packed _ t -> return (target, t)
433− ThunkData_Checkout _ -> failWith "cannot update an unpacked thunk"
447+ ThunkData_Checkout -> failWith "cannot update an unpacked thunk"
434 let src = _thunkPtr_source ptr
448 let src = _thunkPtr_source ptr
435 rev <- getLatestRev src
449 rev <- getLatestRev src
436 overwriteThunk overwrite $ modifyThunkPtrByConfig thunkConfig $ ThunkPtr
450 overwriteThunk overwrite $ modifyThunkPtrByConfig thunkConfig $ ThunkPtr
@@ -438,14 +452,12 @@ updateThunkToLatest (ThunkUpdateConfig mBranch thunkConfig) target = withSpinner
438 , _thunkPtr_rev = rev
452 , _thunkPtr_rev = rev
439 }
453 }
440 Just branch -> readThunk target >>= \case
454 Just branch -> readThunk target >>= \case
441− Left err -> failWith $ T.pack $ "thunk update: " <> show err
455+ Left err -> failWith [i|Thunk update: ${err}|]
442 Right c -> case c of
456 Right c -> case c of
443− ThunkData_Packed t -> case _thunkPtr_source t of
457+ ThunkData_Packed _ t -> setThunk thunkConfig target (thunkSourceToGitSource $ _thunkPtr_source t) branch
444− ThunkSource_Git tsg -> setThunk thunkConfig target tsg branch
445− ThunkSource_GitHub tsgh -> do
446− let tsg = forgetGithub False tsgh
447− 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."
458+ 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.|]
459+ where
460+ spinner = withSpinner' ("Updating thunk " <> T.pack target <> " to latest") (pure $ const $ "Thunk " <> T.pack target <> " updated to latest")
449
461
450setThunk :: MonadObelisk m => ThunkConfig -> FilePath -> GitSource -> String -> m ()
462setThunk :: MonadObelisk m => ThunkConfig -> FilePath -> GitSource -> String -> m ()
451setThunk thunkConfig target gs branch = do
463setThunk thunkConfig target gs branch = do
@@ -455,21 +467,21 @@ setThunk thunkConfig target gs branch = do
455
467
456-- | All recognized github standalone loaders, ordered from newest to oldest.
468-- | 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.
469-- This tool will only ever produce the newest one when it writes a thunk.
458−gitHubStandaloneLoaders :: NonEmpty Text
470+gitHubThunkSpecs :: NonEmpty ThunkSpec
459−gitHubStandaloneLoaders =
471+gitHubThunkSpecs =
460− gitHubStandaloneLoaderV4 :|
472+ gitHubThunkSpecV5 :|
461− [ gitHubStandaloneLoaderV3
473+ [ gitHubThunkSpecV4
462− , gitHubStandaloneLoaderV2
474+ , gitHubThunkSpecV3
463− , gitHubStandaloneLoaderV1
475+ , gitHubThunkSpecV2
476+ , gitHubThunkSpecV1
464 ]
477 ]
465
478
466−gitHubStandaloneLoaderV1 :: Text
479+gitHubThunkSpecV1 :: ThunkSpec
467−gitHubStandaloneLoaderV1 = T.unlines
480+gitHubThunkSpecV1 = legacyGitHubThunkSpec "github-v1"
468− [ "import ((import <nixpkgs> {}).fetchFromGitHub (builtins.fromJSON (builtins.readFile ./github.json)))"
481+ "import ((import <nixpkgs> {}).fetchFromGitHub (builtins.fromJSON (builtins.readFile ./github.json)))"
469− ]
470
482
471−gitHubStandaloneLoaderV2 :: Text
483+gitHubThunkSpecV2 :: ThunkSpec
472−gitHubStandaloneLoaderV2 = T.unlines
484+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.
485 [ "# DO NOT HAND-EDIT THIS FILE" --TODO: Add something about how to get more info on Obelisk, etc.
474 , "import ((import <nixpkgs> {}).fetchFromGitHub ("
486 , "import ((import <nixpkgs> {}).fetchFromGitHub ("
475 , " let json = builtins.fromJSON (builtins.readFile ./github.json);"
487 , " let json = builtins.fromJSON (builtins.readFile ./github.json);"
@@ -479,8 +491,8 @@ gitHubStandaloneLoaderV2 = T.unlines
479 , "))"
491 , "))"
480 ]
492 ]
481
493
482−gitHubStandaloneLoaderV3 :: Text
494+gitHubThunkSpecV3 :: ThunkSpec
483−gitHubStandaloneLoaderV3 = T.unlines
495+gitHubThunkSpecV3 = legacyGitHubThunkSpec "github-v3" $ T.unlines
484 [ "# DO NOT HAND-EDIT THIS FILE"
496 [ "# DO NOT HAND-EDIT THIS FILE"
485 , "let"
497 , "let"
486 , " fetch = { private ? false, ... }@args: if private && builtins.hasAttr \"fetchGit\" builtins"
498 , " fetch = { private ? false, ... }@args: if private && builtins.hasAttr \"fetchGit\" builtins"
@@ -499,8 +511,8 @@ gitHubStandaloneLoaderV3 = T.unlines
499 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
511 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
500 ]
512 ]
501
513
502−gitHubStandaloneLoaderV4 :: Text
514+gitHubThunkSpecV4 :: ThunkSpec
503−gitHubStandaloneLoaderV4 = T.unlines
515+gitHubThunkSpecV4 = legacyGitHubThunkSpec "github-v4" $ T.unlines
504 [ "# DO NOT HAND-EDIT THIS FILE"
516 [ "# DO NOT HAND-EDIT THIS FILE"
505 , "let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:"
517 , "let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:"
506 , " if !fetchSubmodules && !private then builtins.fetchTarball {"
518 , " if !fetchSubmodules && !private then builtins.fetchTarball {"
@@ -511,24 +523,50 @@ gitHubStandaloneLoaderV4 = T.unlines
511 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
523 , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
512 ]
524 ]
513
525
514−plainGitStandaloneLoaders :: NonEmpty Text
526+legacyGitHubThunkSpec :: Text -> Text -> ThunkSpec
515−plainGitStandaloneLoaders =
527+legacyGitHubThunkSpec name loader = ThunkSpec name $ Map.fromList
516− plainGitStandaloneLoaderV4 :|
528+ [ ("default.nix", ThunkFileSpec_FileMatches $ T.strip loader)
517− [ plainGitStandaloneLoaderV1
529+ , ("github.json" , ThunkFileSpec_Ptr parseGitHubJsonBytes)
518− , plainGitStandaloneLoaderV2
530+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
519− , plainGitStandaloneLoaderV3
531+ , (".git", ThunkFileSpec_CheckoutIndicator)
520 ]
532 ]
521
533
522−plainGitStandaloneLoaderV1 :: Text
534+gitHubThunkSpecV5 :: ThunkSpec
523−plainGitStandaloneLoaderV1 = T.unlines
535+gitHubThunkSpecV5 = mkThunkSpec "github-v5" "github.json" parseGitHubJsonBytes [here|
536+# DO NOT HAND-EDIT THIS FILE
537+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
538+ if !fetchSubmodules && !private then builtins.fetchTarball {
539+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
540+ } else (import <nixpkgs> {}).fetchFromGitHub {
541+ inherit owner repo rev sha256 fetchSubmodules private;
542+ };
543+ json = builtins.fromJSON (builtins.readFile ./github.json);
544+in fetch json
545+|]
546+
547+parseGitHubJsonBytes :: LBS.ByteString -> Either String ThunkPtr
548+parseGitHubJsonBytes = parseJsonObject $ parseThunkPtr $ \v ->
549+ ThunkSource_GitHub <$> parseGitHubSource v <|> ThunkSource_Git <$> parseGitSource v
550+
551+gitThunkSpecs :: NonEmpty ThunkSpec
552+gitThunkSpecs =
553+ gitThunkSpecV5 :|
554+ [ gitThunkSpecV4
555+ , gitThunkSpecV3
556+ , gitThunkSpecV2
557+ , gitThunkSpecV1
558+ ]
559+
560+gitThunkSpecV1 :: ThunkSpec
561+gitThunkSpecV1 = legacyGitThunkSpec "git-v1" $ T.unlines
524 [ "# DO NOT HAND-EDIT THIS FILE"
562 [ "# DO NOT HAND-EDIT THIS FILE"
525 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
563 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
526 , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
564 , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
527 , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
565 , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
528 ]
566 ]
529
567
530−plainGitStandaloneLoaderV2 :: Text
568+gitThunkSpecV2 :: ThunkSpec
531−plainGitStandaloneLoaderV2 = T.unlines
569+gitThunkSpecV2 = legacyGitThunkSpec "git-v2" $ T.unlines
532 [ "# DO NOT HAND-EDIT THIS FILE"
570 [ "# DO NOT HAND-EDIT THIS FILE"
533 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
571 , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
534 , " if builtins.hasAttr \"fetchGit\" builtins"
572 , " if builtins.hasAttr \"fetchGit\" builtins"
@@ -539,8 +577,8 @@ plainGitStandaloneLoaderV2 = T.unlines
539
577
540-- This loader has a bug because @builtins.fetchGit@ is not given a @ref@
578-- 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.
579-- and will fail to find commits without this because it does shallow clones.
542−plainGitStandaloneLoaderV3 :: Text
580+gitThunkSpecV3 :: ThunkSpec
543−plainGitStandaloneLoaderV3 = T.unlines
581+gitThunkSpecV3 = legacyGitThunkSpec "git-v3" $ T.unlines
544 [ "# DO NOT HAND-EDIT THIS FILE"
582 [ "# DO NOT HAND-EDIT THIS FILE"
545 , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
583 , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
546 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
584 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
@@ -555,8 +593,8 @@ plainGitStandaloneLoaderV3 = T.unlines
555 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
593 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
556 ]
594 ]
557
595
558−plainGitStandaloneLoaderV4 :: Text
596+gitThunkSpecV4 :: ThunkSpec
559−plainGitStandaloneLoaderV4 = T.unlines
597+gitThunkSpecV4 = legacyGitThunkSpec "git-v4" $ T.unlines
560 [ "# DO NOT HAND-EDIT THIS FILE"
598 [ "# DO NOT HAND-EDIT THIS FILE"
561 , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
599 , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
562 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
600 , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
@@ -572,10 +610,52 @@ plainGitStandaloneLoaderV4 = T.unlines
572 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
610 , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
573 ]
611 ]
574
612
575−thunkFileNames :: [FilePath]
613+legacyGitThunkSpec :: Text -> Text -> ThunkSpec
576−thunkFileNames = ["default.nix", "github.json", "git.json"]
614+legacyGitThunkSpec name loader = ThunkSpec name $ Map.fromList
615+ [ ("default.nix", ThunkFileSpec_FileMatches $ T.strip loader)
616+ , ("git.json" , ThunkFileSpec_Ptr parseGitJsonBytes)
617+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
618+ , (".git", ThunkFileSpec_CheckoutIndicator)
619+ ]
620+
621+gitThunkSpecV5 :: ThunkSpec
622+gitThunkSpecV5 = mkThunkSpec "git-v5" "git.json" parseGitJsonBytes [here|
623+# DO NOT HAND-EDIT THIS FILE
624+let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:
625+ let realUrl = let firstChar = builtins.substring 0 1 url; in
626+ if firstChar == "/" then /. + url
627+ else if firstChar == "." then ./. + url
628+ else url;
629+ in if !fetchSubmodules && private then builtins.fetchGit {
630+ url = realUrl; inherit rev;
631+ ${if branch == null then null else "ref"} = branch;
632+ } else (import <nixpkgs> {}).fetchgit {
633+ url = realUrl; inherit rev sha256;
634+ };
635+ json = builtins.fromJSON (builtins.readFile ./git.json);
636+in fetch json
637+|]
638+
639+parseGitJsonBytes :: LBS.ByteString -> Either String ThunkPtr
640+parseGitJsonBytes = parseJsonObject $ parseThunkPtr $ fmap ThunkSource_Git . parseGitSource
641+
642+mkThunkSpec :: Text -> FilePath -> (LBS.ByteString -> Either String ThunkPtr) -> Text -> ThunkSpec
643+mkThunkSpec name jsonFileName parser srcNix = ThunkSpec name $ Map.fromList
644+ [ ("default.nix", ThunkFileSpec_FileMatches defaultNixViaSrc)
645+ , ("thunk.nix", ThunkFileSpec_FileMatches srcNix)
646+ , (jsonFileName, ThunkFileSpec_Ptr parser)
647+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
648+ , (normalise $ unpackedDirName </> ".git", ThunkFileSpec_CheckoutIndicator)
649+ ]
650+ where
651+ defaultNixViaSrc = [here|
652+# DO NOT HAND-EDIT THIS FILE
653+import (import ./thunk.nix)
654+|]
577
655
578−--TODO: when checking something out, make a shallow clone
656+
657+parseJsonObject :: (Aeson.Object -> Aeson.Parser a) -> LBS.ByteString -> Either String a
658+parseJsonObject p bytes = Aeson.parseEither p =<< Aeson.eitherDecode bytes
579
659
580-- | Checks a cache directory to see if there is a fresh symlink
660-- | Checks a cache directory to see if there is a fresh symlink
581-- to the result of building an attribute of a thunk.
661-- to the result of building an attribute of a thunk.
@@ -583,44 +663,49 @@ thunkFileNames = ["default.nix", "github.json", "git.json"]
583-- and the result is symlinked into the cache.
663-- and the result is symlinked into the cache.
584nixBuildThunkAttrWithCache
664nixBuildThunkAttrWithCache
585 :: MonadObelisk m
665 :: MonadObelisk m
666+ => ThunkSpec
586− => FilePath
667+ -> FilePath
587 -- ^ Path to directory containing Thunk
668 -- ^ Path to directory containing Thunk
588 -> String
669 -> String
589 -- ^ Attribute to build
670 -- ^ Attribute to build
590− -> m FilePath
671+ -> m (Maybe FilePath)
591 -- ^ Symlink to cached or built nix output
672 -- ^ Symlink to cached or built nix output
592-- WARNING: If the thunk uses an impure reference such as '<nixpkgs>'
673-- WARNING: If the thunk uses an impure reference such as '<nixpkgs>'
593-- the caching mechanism will fail as it merely measures the modification
674-- the caching mechanism will fail as it merely measures the modification
594-- time of the cache link and the expression to build.
675-- time of the cache link and the expression to build.
595−nixBuildThunkAttrWithCache thunkDir attr = do
676+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
677 latestChange <- liftIO $ do
604− createDirectoryIfMissing False cacheDir
678+ let
605− let getModificationTimeMaybe = fmap rightToMaybe . try @IOError . getModificationTime
679+ getModificationTimeMaybe = fmap rightToMaybe . try @IOError . getModificationTime
680+ thunkFileNames = Map.keys $ _thunkSpec_files thunkSpec
606− maximum . catMaybes <$> mapM (getModificationTimeMaybe . (thunkDir </>)) thunkFileNames
681+ maximum . catMaybes <$> traverse (getModificationTimeMaybe . (thunkDir </>)) thunkFileNames
682+
683+ let cachePaths' = nonEmpty $ Map.keys $ Map.filter (\case ThunkFileSpec_AttrCache -> True; _ -> False) $
684+ _thunkSpec_files thunkSpec
685+ for cachePaths' $ \cachePaths ->
686+ fmap NonEmpty.head $ for cachePaths $ \cacheDir -> do
687+ let
688+ cachePath = thunkDir </> cacheDir </> attr <.> "out"
689+ cacheErrHandler e
690+ | isDoesNotExistError e = pure Nothing -- expected from a cache miss
691+ | otherwise = Nothing <$ putLog Error (T.pack $ displayException e)
607− cacheHit <- handle cacheErrHandler $ do
692+ cacheHit <- handle cacheErrHandler $ do
608− cacheTime <- liftIO $ posixSecondsToUTCTime . realToFrac . modificationTime <$> getSymbolicLinkStatus cachePath
693+ cacheTime <- liftIO $ posixSecondsToUTCTime . realToFrac . modificationTime <$> getSymbolicLinkStatus cachePath
609− return $ if latestChange <= cacheTime
694+ pure $ if latestChange <= cacheTime
610− then Just cachePath
695+ then Just cachePath
611− else Nothing
696+ else Nothing
612− case cacheHit of
697+ case cacheHit of
613− Just c -> return c
698+ Just c -> pure c
614− Nothing -> do
699+ Nothing -> do
615− putLog Warning $ T.pack $ mconcat [thunkDir, ": ", attr, " not cached, building ..."]
700+ putLog Warning $ T.pack $ mconcat [thunkDir, ": ", attr, " not cached, building ..."]
701+ liftIO $ createDirectoryIfMissing True (takeDirectory cachePath)
616− _ <- nixCmd $ NixCmd_Build $ def
702+ (cachePath <$) $ nixCmd $ NixCmd_Build $ def
617− Lens.& nixBuildConfig_outLink Lens..~ OutLink_IndirectRoot cachePath
703+ & nixBuildConfig_outLink .~ OutLink_IndirectRoot cachePath
618− Lens.& nixCmdConfig_target Lens..~ Target
704+ & nixCmdConfig_target .~ Target
619− { _target_path = Just thunkDir
705+ { _target_path = Just thunkDir
620− , _target_attr = Just attr
706+ , _target_attr = Just attr
621− , _target_expr = Nothing
707+ , _target_expr = Nothing
622− }
708+ }
623− return cachePath
624
709
625-- | Build a nix attribute, and cache the result if possible
710-- | Build a nix attribute, and cache the result if possible
626nixBuildAttrWithCache
711nixBuildAttrWithCache
@@ -631,13 +716,15 @@ nixBuildAttrWithCache
631 -- ^ Attribute to build
716 -- ^ Attribute to build
632 -> m FilePath
717 -> m FilePath
633 -- ^ Symlink to cached or built nix output
718 -- ^ Symlink to cached or built nix output
634−nixBuildAttrWithCache exprPath attr = do
719+nixBuildAttrWithCache exprPath attr = readThunk exprPath >>= \case
635− readThunk exprPath >>= \case
636− -- Only packed thunks are cached. in particular, checkouts are not
720+ -- Only packed thunks are cached. In particular, checkouts are not.
721+ Right (ThunkData_Packed spec _) ->
637− Right (ThunkData_Packed _) -> nixBuildThunkAttrWithCache exprPath attr
722+ maybe build pure =<< nixBuildThunkAttrWithCache spec exprPath attr
723+ _ -> build
724+ where
638− _ -> nixCmd $ NixCmd_Build $ def
725+ build = nixCmd $ NixCmd_Build $ def
639− Lens.& nixBuildConfig_outLink Lens..~ OutLink_None
726+ & nixBuildConfig_outLink .~ OutLink_None
640− Lens.& nixCmdConfig_target Lens..~ Target
727+ & nixCmdConfig_target .~ Target
641 { _target_path = Just exprPath
728 { _target_path = Just exprPath
642 , _target_attr = Just attr
729 , _target_attr = Just attr
643 , _target_expr = Nothing
730 , _target_expr = Nothing
@@ -658,7 +745,7 @@ updateThunk p f = withSystemTempDirectory "obelisk-thunkptr-" $ \tmpDir -> do
658 where
745 where
659 copyThunkToTmp tmpDir thunkDir = readThunk thunkDir >>= \case
746 copyThunkToTmp tmpDir thunkDir = readThunk thunkDir >>= \case
660 Left err -> failWith $ "withThunkUnpacked: " <> T.pack (show err)
747 Left err -> failWith $ "withThunkUnpacked: " <> T.pack (show err)
661− Right (ThunkData_Packed _) -> do
748+ Right ThunkData_Packed{} -> do
662 let tmpThunk = tmpDir </> "thunk"
749 let tmpThunk = tmpDir </> "thunk"
663 callProcessAndLogOutput (Notice, Error) $
750 callProcessAndLogOutput (Notice, Error) $
664 proc cp ["-r", "-T", thunkDir, tmpThunk]
751 proc cp ["-r", "-T", thunkDir, tmpThunk]
@@ -672,62 +759,81 @@ updateThunk p f = withSystemTempDirectory "obelisk-thunkptr-" $ \tmpDir -> do
672finalMsg :: Bool -> (a -> Text) -> Maybe (a -> Text)
759finalMsg :: Bool -> (a -> Text) -> Maybe (a -> Text)
673finalMsg noTrail s = if noTrail then Nothing else Just s
760finalMsg noTrail s = if noTrail then Nothing else Just s
674
761
675−unpackThunk :: MonadObelisk m => FilePath -> m ()
676−unpackThunk = unpackThunk' False
677−
678-- | Check that we are not somewhere inside the thunk directory
762-- | Check that we are not somewhere inside the thunk directory
679−checkThunkDirectory :: MonadObelisk m => Text -> FilePath -> m ()
763+checkThunkDirectory :: MonadObelisk m => FilePath -> m ()
680−checkThunkDirectory msg thunkDir = do
764+checkThunkDirectory thunkDir = do
681 currentDir <- liftIO getCurrentDirectory
765 currentDir <- liftIO getCurrentDirectory
682 thunkDir' <- liftIO $ canonicalizePath thunkDir
766 thunkDir' <- liftIO $ canonicalizePath thunkDir
683− when (thunkDir' `L.isInfixOf` currentDir) $ failWith msg
767+ when (thunkDir' `L.isInfixOf` currentDir) $
768+ failWith [i|Can't perform thunk operations from within the thunk directory: ${thunkDir}|]
769+
770+ -- Don't let thunk commands work when directly given an unpacked repo
771+ when (takeFileName thunkDir == unpackedDirName) $
772+ readThunk (takeDirectory thunkDir) >>= \case
773+ Right _ -> failWith [i|Refusing to perform thunk operation on ${thunkDir} because it is a thunk's unpacked source|]
774+ Left _ -> pure ()
775+
776+unpackThunk :: MonadObelisk m => FilePath -> m ()
777+unpackThunk = unpackThunk' False
684
778
685unpackThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
779unpackThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
686−unpackThunk' noTrail thunkDir = checkThunkDirectory "Can't pack/unpack from within the thunk directory" thunkDir >> readThunk thunkDir >>= \case
780+unpackThunk' noTrail thunkDir = checkThunkDirectory thunkDir *> readThunk thunkDir >>= \case
687− Left err -> failWith $ "thunk unpack: " <> T.pack (show err)
781+ 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
782 --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"
783+ Right ThunkData_Checkout -> failWith [i|Thunk at ${thunkDir} is already unpacked|]
690− Right (ThunkData_Packed tptr) -> do
784+ Right (ThunkData_Packed _ tptr) -> do
691 let (thunkParent, thunkName) = splitFileName thunkDir
785 let (thunkParent, thunkName) = splitFileName thunkDir
692− withTempDirectory thunkParent thunkName $ \tmpRepo -> do
786+ withTempDirectory thunkParent thunkName $ \tmpThunk -> do
693− let obGitDir = tmpRepo </> ".git" </> "obelisk"
787+ let
788+ gitSrc = thunkSourceToGitSource $ _thunkPtr_source tptr
694− s = case _thunkPtr_source tptr of
789+ newSpec = case _thunkPtr_source tptr of
695− ThunkSource_GitHub s' -> forgetGithub False s'
790+ ThunkSource_GitHub _ -> NonEmpty.head gitHubThunkSpecs
696− ThunkSource_Git s' -> s'
791+ ThunkSource_Git _ -> NonEmpty.head gitThunkSpecs
697 withSpinner' ("Fetching thunk " <> T.pack thunkName)
792 withSpinner' ("Fetching thunk " <> T.pack thunkName)
698 (finalMsg noTrail $ const $ "Fetched thunk " <> T.pack thunkName) $ do
793 (finalMsg noTrail $ const $ "Fetched thunk " <> T.pack thunkName) $ do
794+ let unpackedPath = tmpThunk </> unpackedDirName
795+ gitCloneForThunkUnpack gitSrc (_thunkRev_commit $ _thunkPtr_rev tptr) unpackedPath
796+
797+ let normalizeMore = dropTrailingPathSeparator . normalise
798+ when (normalizeMore unpackedPath /= normalizeMore tmpThunk) $ -- Only write meta data if the checkout is not inplace
799+ createThunk tmpThunk $ Left newSpec
800+
801+ liftIO $ do
802+ removePathForcibly thunkDir
803+ renameDirectory tmpThunk thunkDir
804+
805+gitCloneForThunkUnpack
806+ :: MonadObelisk m
807+ => GitSource -- ^ Git source to use
808+ -> Ref hash -- ^ Commit hash to reset to
809+ -> FilePath -- ^ Directory to clone into
810+ -> m ()
811+gitCloneForThunkUnpack gitSrc commit dir = do
699− let git = callProcessAndLogOutput (Notice, Notice) . gitProc tmpRepo
812+ let git = callProcessAndLogOutput (Notice, Notice) . gitProc dir
700− git $ [ "clone" ]
813+ git $ [ "clone" ]
701− ++ ("--recursive" <$ guard (_gitSource_fetchSubmodules s))
814+ ++ ["--recursive" | _gitSource_fetchSubmodules gitSrc]
702− ++ [ T.unpack $ gitUriToText $ _gitSource_url s ]
815+ ++ [ T.unpack $ gitUriToText $ _gitSource_url gitSrc ]
703− ++ do branch <- maybeToList $ _gitSource_branch s
816+ ++ do branch <- maybeToList $ _gitSource_branch gitSrc
704− [ "--branch", T.unpack $ untagName branch ]
817+ [ "--branch", T.unpack $ untagName branch ]
705− git ["reset", "--hard", Ref.toHexString $ _thunkRev_commit $ _thunkPtr_rev tptr]
818+ git ["reset", "--hard", Ref.toHexString commit]
706− when (_gitSource_fetchSubmodules s) $
819+ when (_gitSource_fetchSubmodules gitSrc) $
707− git ["submodule", "update", "--recursive", "--init"]
820+ git ["submodule", "update", "--recursive", "--init"]
708−
709− liftIO $ createDirectory obGitDir
710− callProcessAndLogOutput (Notice, Error) $
711− proc cp ["-r", "-T", thunkDir </> ".", obGitDir </> "orig-thunk"]
712− callProcessAndLogOutput (Notice, Error) $
713− proc "rm" ["-r", thunkDir]
714− callProcessAndLogOutput (Notice, Error) $
715− proc "mv" ["-T", tmpRepo, thunkDir]
716
821
717--TODO: add a rollback mode to pack to the original thunk
822--TODO: add a rollback mode to pack to the original thunk
718packThunk :: MonadObelisk m => ThunkPackConfig -> FilePath -> m ThunkPtr
823packThunk :: MonadObelisk m => ThunkPackConfig -> FilePath -> m ThunkPtr
719packThunk = packThunk' False
824packThunk = packThunk' False
720
825
721packThunk' :: MonadObelisk m => Bool -> ThunkPackConfig -> FilePath -> m ThunkPtr
826packThunk' :: 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
827+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"
828+ Right ThunkData_Packed{} -> failWith [i|Thunk at ${thunkDir} is is already packed|]
725− Right (ThunkData_Checkout _) -> do
829+ _ -> withSpinner'
726− withSpinner' ("Packing thunk " <> T.pack thunkDir)
830+ ("Packing thunk " <> T.pack thunkDir)
727− (finalMsg noTrail $ const $ "Packed thunk " <> T.pack thunkDir) $ do
831+ (finalMsg noTrail $ const $ "Packed thunk " <> T.pack thunkDir) $
832+ do
833+ let checkClean = if force then CheckClean_NoCheck else CheckClean_FullCheck
728− thunkPtr <- modifyThunkPtrByConfig thunkConfig <$> getThunkPtr (not force) thunkDir (_thunkConfig_private thunkConfig)
834+ thunkPtr <- modifyThunkPtrByConfig thunkConfig <$> getThunkPtr checkClean thunkDir (_thunkConfig_private thunkConfig)
729− callProcessAndLogOutput (Debug, Error) $ proc "rm" ["-rf", thunkDir]
835+ liftIO $ removePathForcibly thunkDir
730− liftIO $ createThunk thunkDir thunkPtr
836+ createThunk thunkDir $ Right thunkPtr
731 pure thunkPtr
837 pure thunkPtr
732
838
733modifyThunkPtrByConfig :: ThunkConfig -> ThunkPtr -> ThunkPtr
839modifyThunkPtrByConfig :: ThunkConfig -> ThunkPtr -> ThunkPtr
@@ -738,29 +844,43 @@ modifyThunkPtrByConfig (ThunkConfig markPrivate') ptr = case markPrivate' of
738 ThunkSource_GitHub s -> ThunkSource_GitHub $ s { _gitHubSource_private = markPrivate }
844 ThunkSource_GitHub s -> ThunkSource_GitHub $ s { _gitHubSource_private = markPrivate }
739 }
845 }
740
846
847+data CheckClean
848+ = CheckClean_FullCheck
849+ -- ^ Check that the repo is clean, including .gitignored files
850+ | CheckClean_NotIgnored
851+ -- ^ Check that the repo is clean, not including .gitignored files
852+ | CheckClean_NoCheck
853+ -- ^ Don't check that the repo is clean
854+
741−getThunkPtr :: forall m. MonadObelisk m => Bool -> FilePath -> Maybe Bool -> m ThunkPtr
855+getThunkPtr :: forall m. MonadObelisk m => CheckClean -> FilePath -> Maybe Bool -> m ThunkPtr
742−getThunkPtr checkClean thunkDir mPrivate = do
856+getThunkPtr gitCheckClean dir mPrivate = do
857+ let repoLocations = nubOrd $ map (first normalise)
858+ [(".git", "."), (unpackedDirName </> ".git", unpackedDirName)]
859+ repoLocation' <- liftIO $ flip findM repoLocations $ doesDirectoryExist . (dir </>) . fst
860+ thunkDir <- case repoLocation' of
861+ Nothing -> failWith [i|Can't find an unpacked thunk in ${dir}|]
862+ Just (_, path) -> pure $ normalise $ dir </> path
863+
864+ let (checkClean, checkIgnored) = case gitCheckClean of
865+ CheckClean_FullCheck -> (True, True)
866+ CheckClean_NotIgnored -> (True, False)
867+ CheckClean_NoCheck -> (False, False)
743− when checkClean $ ensureCleanGitRepo thunkDir True
868+ when checkClean $ ensureCleanGitRepo thunkDir checkIgnored
744 "thunk pack: thunk checkout contains unsaved modifications"
869 "thunk pack: thunk checkout contains unsaved modifications"
745
870
746 -- Check whether there are any stashes
871 -- Check whether there are any stashes
872+ when checkClean $ do
747− stashOutput <- readGitProcess thunkDir ["stash", "list"]
873+ stashOutput <- readGitProcess thunkDir ["stash", "list"]
748− when checkClean $ case T.null stashOutput of
874+ unless (T.null stashOutput) $
749− False -> do
750 failWith $ T.unlines $
875 failWith $ T.unlines $
751 [ "thunk pack: thunk checkout has stashes"
876 [ "thunk pack: thunk checkout has stashes"
752 , "git stash list:"
877 , "git stash list:"
753 ] ++ T.lines stashOutput
878 ] ++ T.lines stashOutput
754− True -> return ()
755
879
756 -- Get current branch
880 -- Get current branch
757 (mCurrentBranch, mCurrentCommit) <- do
881 (mCurrentBranch, mCurrentCommit) <- do
758− b <- listToMaybe
759− <$> T.lines
760− <$> readGitProcess thunkDir ["rev-parse", "--abbrev-ref", "HEAD"]
882+ b <- listToMaybe . T.lines <$> readGitProcess thunkDir ["rev-parse", "--abbrev-ref", "HEAD"]
761− c <- listToMaybe
762− <$> T.lines
763− <$> readGitProcess thunkDir ["rev-parse", "HEAD"]
883+ c <- listToMaybe . T.lines <$> readGitProcess thunkDir ["rev-parse", "HEAD"]
764 case b of
884 case b of
765 (Just "HEAD") -> failWith $ T.unlines
885 (Just "HEAD") -> failWith $ T.unlines
766 [ "thunk pack: You are in 'detached HEAD' state."
886 [ "thunk pack: You are in 'detached HEAD' state."
@@ -771,7 +891,7 @@ getThunkPtr checkClean thunkDir mPrivate = do
771
891
772 -- Get information on all branches and their (optional) designated upstream
892 -- Get information on all branches and their (optional) designated upstream
773 -- correspondents
893 -- correspondents
774− (headDump :: [Text]) <- T.lines <$> readGitProcess thunkDir
894+ headDump :: [Text] <- T.lines <$> readGitProcess thunkDir
775 [ "for-each-ref"
895 [ "for-each-ref"
776 , "--format=%(refname:short) %(upstream:short) %(upstream:remotename)"
896 , "--format=%(refname:short) %(upstream:short) %(upstream:remotename)"
777 , "refs/heads/"
897 , "refs/heads/"
@@ -817,7 +937,7 @@ getThunkPtr checkClean thunkDir mPrivate = do
817 ]
937 ]
818
938
819 -- loosely by https://stackoverflow.com/questions/7773939/show-git-ahead-and-behind-info-for-all-branches-including-remotes
939 -- 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
940+ stats <- ifor headUpstream $ \branch (upstream, _remote) -> do
821 (stat :: [Text]) <- T.lines <$> readGitProcess thunkDir
941 (stat :: [Text]) <- T.lines <$> readGitProcess thunkDir
822 [ "rev-list", "--left-right"
942 [ "rev-list", "--left-right"
823 , T.unpack branch <> "..." <> T.unpack upstream
943 , T.unpack branch <> "..." <> T.unpack upstream
@@ -841,8 +961,9 @@ getThunkPtr checkClean thunkDir mPrivate = do
841 \pushed but this repo's remote tracking branches don't know it.)"
961 \pushed but this repo's remote tracking branches don't know it.)"
842 ]
962 ]
843
963
964+ when checkClean $ do
844− -- We assume it's safe to pack the thunk at this point
965+ -- 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."
966+ putLog Informational "All changes safe in git remotes. OK to pack thunk."
846
967
847 let remote = maybe "origin" snd $ flip Map.lookup headUpstream =<< mCurrentBranch
968 let remote = maybe "origin" snd $ flip Map.lookup headUpstream =<< mCurrentBranch
848
969
@@ -860,9 +981,7 @@ getThunkPtr checkClean thunkDir mPrivate = do
860-- | Get the latest revision available from the given source
981-- | Get the latest revision available from the given source
861getLatestRev :: MonadObelisk m => ThunkSource -> m ThunkRev
982getLatestRev :: MonadObelisk m => ThunkSource -> m ThunkRev
862getLatestRev os = do
983getLatestRev os = do
863− let gitS = case os of
984+ let gitS = thunkSourceToGitSource os
864− ThunkSource_GitHub s -> forgetGithub False s
865− ThunkSource_Git s -> s
866 (_, commit) <- gitGetCommitBranch (_gitSource_url gitS) (untagName <$> _gitSource_branch gitS)
985 (_, commit) <- gitGetCommitBranch (_gitSource_url gitS) (untagName <$> _gitSource_branch gitS)
867 case os of
986 case os of
868 ThunkSource_GitHub s -> githubThunkRev s commit
987 ThunkSource_GitHub s -> githubThunkRev s commit
lib/command/src/Obelisk/Command/Upgrade/Hash.hsdeleted−114
@@ -1,114 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE ScopedTypeVariables #-}
5−{-# LANGUAGE TupleSections #-}
6−-- | Hash a git repo or arbitrary directory using nix-hash.
7−module Obelisk.Command.Upgrade.Hash
8− ( getDirectoryHash
9− , getHashAtGitRevision
10− ) where
11−
12−import Control.Monad (forM, forM_)
13−import Control.Monad.IO.Class (liftIO)
14−import Data.Bool (bool)
15−import Data.Maybe (catMaybes)
16−import Data.Semigroup ((<>))
17−import Data.Text (Text)
18−import qualified Data.Text as T
19−import System.Directory
20−import System.FilePath
21−import System.IO.Temp
22−import System.Process (cwd, proc)
23−
24−import Obelisk.App (MonadObelisk)
25−import Obelisk.CliApp
26−import Obelisk.Command.Utils
27−
28−import Obelisk.Migration
29−
30−-- | Get the unique hash of the given directory
31−--
32−-- Excludes the following before computing the hash:
33−-- * the specified top-level files/ directories.
34−-- * .git directory
35−-- * untracked Git files
36−-- * ignored Git files
37−-- * empty directories
38−--
39−-- Uses the same predictive algorithm as that of Nix (`nix-hash`).
40−--
41−-- This function will do a full copy of the directory to a temporary location before
42−-- computing the hash. Because it will be deleting the files in exclude list, and
43−-- other files if the directory is a git repo, which needs to be done as `nix-hash`
44−-- doesn't support taking an excludes list.
45−getDirectoryHash :: MonadObelisk m => [FilePath] -> FilePath -> m Hash
46−getDirectoryHash excludes dir = withSystemTempDirectory "obelisk-hash-" $ \tmpDir -> do
47− withSpinnerNoTrail (T.pack $ "Copying " <> dir <> " to " <> tmpDir) $ do
48− runProc $ copyDir dir tmpDir
49− getDirectoryHashDestructive excludes tmpDir
50−
51−getDirectoryHashDestructive :: MonadObelisk m => [FilePath] -> FilePath -> m Hash
52−getDirectoryHashDestructive excludes dir = do
53− liftIO (doesDirectoryExist $ dir </> ".git") >>= \case
54− True -> do
55− tidyUpGitWorkingCopy dir
56− withSpinnerNoTrail "Removing .git directory" $
57− liftIO $ removePathForcibly $ dir </> ".git"
58− False -> pure ()
59− withSpinnerNoTrail "Removing excluded paths" $ do
60− forM_ (fmap (dir </>) excludes) $
61− liftIO . removePathForcibly
62− nixHash dir
63−
64−getHashAtGitRevision :: MonadObelisk m => [Text] -> [FilePath] -> FilePath -> m [Hash]
65−getHashAtGitRevision revs excludes dir = withSystemTempDirectory "obelisk-hashrev-" $ \tmpDir -> do
66− withSpinnerNoTrail (T.pack $ "Copying " <> dir <> " to " <> tmpDir) $ do
67− runProc $ copyDir dir tmpDir
68− tidyUpGitWorkingCopy tmpDir
69− -- Discard changes to tracked files
70− runProcSilently $ gitProc tmpDir ["reset", "--hard"]
71− forM revs $ \rev -> do
72− runProcSilently $ gitProc tmpDir ["checkout", T.unpack rev]
73− -- Checking out an arbitrary revision can leave untracked files (from
74− -- previous revison) around, so tidy them up.
75− tidyUpGitWorkingCopy tmpDir
76− withFilesStashed tmpDir (excludes <> [".git"]) $
77− nixHash tmpDir
78− where
79− withFilesStashed base fs m = withSystemTempDirectory "obelisk-hashrev-stash-" $ \stashDir -> do
80− existingPaths <- fmap catMaybes $ forM fs $ \p -> do
81− liftIO (doesPathExist $ base </> p) >>= pure . bool Nothing (Just p)
82− forM_ existingPaths $ \p ->
83− liftIO $ renamePath (base </> p) (stashDir </> p)
84− result <- m
85− forM_ existingPaths $ \p ->
86− liftIO $ renamePath (stashDir </> p) (base </> p)
87− return result
88−
89−nixHash :: MonadObelisk m => FilePath -> m Hash
90−nixHash dir = withSpinnerNoTrail "Running `nix-hash`" $
91− readProc $ proc "nix-hash" [dir]
92−
93−-- | Clean up the following files in the git working copy
94−--
95−-- * Paths ignored by .gitignore, and still present
96−-- * Untracked files (not added to git index)
97−-- * Any empty directories (these are not tracked by git)
98−--
99−-- Note that this leaves modified (staged or unstaged) files as they are.
100−tidyUpGitWorkingCopy :: MonadObelisk m => FilePath -> m ()
101−tidyUpGitWorkingCopy dir = withSpinnerNoTrail "Tidying up git working copy" $ do
102− ignored <- gitLsFiles dir ["--ignored", "--exclude-standard", "--others"]
103− untracked <- gitLsFiles dir ["--exclude-standard", "--others"]
104− putLog Debug $ "Ignored: " <> T.pack (show $ length ignored) <> " files."
105− putLog Debug $ "Untracked files:\n" <> T.unlines untracked
106− withSpinnerNoTrail "Removing untracked and ignored files" $ do
107− forM_ (fmap ((dir </>) . T.unpack) $ ignored <> untracked) $
108− liftIO . removePathForcibly
109− -- Empty directories won't be included in these lists. Git doesn't track them
110− -- So we must delete these separately.
111− runProc $ proc "find" [dir, "-depth", "-empty", "-type", "d", "-delete"]
112− where
113− gitLsFiles pwd opts = fmap T.lines $ readProc $
114− (proc "git" $ ["ls-files", "."] <> opts) { cwd = Just pwd }
lib/command/src/Obelisk/Command/Utils.hs+17−2
@@ -10,19 +10,20 @@ module Obelisk.Command.Utils where
10import Control.Applicative hiding (many)
10import Control.Applicative hiding (many)
11import Control.Monad.Except
11import Control.Monad.Except
12import Data.Bool (bool)
12import Data.Bool (bool)
13−import qualified Text.Megaparsec.Char.Lexer as ML
14import Data.Bifunctor
13import Data.Bifunctor
15import Data.Char
14import Data.Char
16import Data.Either
15import Data.Either
17−import Data.Semigroup ((<>))
16+import Data.List (isInfixOf)
18import Data.Map (Map)
17import Data.Map (Map)
19import qualified Data.Map as M
18import qualified Data.Map as M
20import Data.Maybe (maybeToList)
19import Data.Maybe (maybeToList)
20+import Data.Semigroup ((<>))
21import Data.Text (Text)
21import Data.Text (Text)
22import qualified Data.Text as T
22import qualified Data.Text as T
23import Data.Void (Void)
23import Data.Void (Void)
24import System.Exit (ExitCode)
24import System.Exit (ExitCode)
25import System.Which (staticWhich)
25import System.Which (staticWhich)
26+import qualified Text.Megaparsec.Char.Lexer as ML
26import Text.Megaparsec as MP
27import Text.Megaparsec as MP
27import Text.Megaparsec.Char as MP
28import Text.Megaparsec.Char as MP
28
29
@@ -32,6 +33,12 @@ import Obelisk.CliApp
32cp :: FilePath
33cp :: FilePath
33cp = $(staticWhich "cp")
34cp = $(staticWhich "cp")
34
35
36+mvPath :: FilePath
37+mvPath = $(staticWhich "mv")
38+
39+rmPath :: FilePath
40+rmPath = $(staticWhich "rm")
41+
35ghcidExePath :: FilePath
42ghcidExePath :: FilePath
36ghcidExePath = $(staticWhich "ghcid")
43ghcidExePath = $(staticWhich "ghcid")
37
44
@@ -47,6 +54,14 @@ nixBuildExePath = $(staticWhich "nix-build")
47jreKeyToolPath :: FilePath
54jreKeyToolPath :: FilePath
48jreKeyToolPath = $(staticWhich "keytool")
55jreKeyToolPath = $(staticWhich "keytool")
49
56
57+-- | Nix syntax requires relative paths to be prefixed by @./@ or
58+-- @../@. This will make a 'FilePath' that can be embedded in a Nix
59+-- expression.
60+toNixPath :: FilePath -> FilePath
61+toNixPath root | "/" `isInfixOf` root = root
62+ | otherwise = "./" <> root
63+
64+
50-- Check whether the working directory is clean
65-- Check whether the working directory is clean
51checkGitCleanStatus :: MonadObelisk m => FilePath -> Bool -> m Bool
66checkGitCleanStatus :: MonadObelisk m => FilePath -> Bool -> m Bool
52checkGitCleanStatus repo withIgnored = do
67checkGitCleanStatus repo withIgnored = do
lib/command/src/Obelisk/Command/VmBuilder.hs+2−1
@@ -21,6 +21,7 @@ import qualified System.Info
21
21
22import Obelisk.App (MonadObelisk, getObeliskUserStateDir)
22import Obelisk.App (MonadObelisk, getObeliskUserStateDir)
23import Obelisk.CliApp
23import Obelisk.CliApp
24+import Obelisk.Command.Utils (rmPath)
24
25
25-- | Generate the `--builders` argument string to enable the VM builder after ensuring it is available.
26-- | Generate the `--builders` argument string to enable the VM builder after ensuring it is available.
26getNixBuildersArg :: MonadObelisk m => m String
27getNixBuildersArg :: MonadObelisk m => m String
@@ -95,7 +96,7 @@ setupNixDocker stateDir = withSpinner ("Creating Docker container named " <> con
95
96
96 -- Create new SSH keys for this container
97 -- Create new SSH keys for this container
97 callProcessAndLogOutput (Debug, Error) $
98 callProcessAndLogOutput (Debug, Error) $
98− proc "rm" ["-f", stateDir </> sshKeyFileName, stateDir </> sshKeyFileName <.> "pub"]
99+ proc rmPath ["-f", stateDir </> sshKeyFileName, stateDir </> sshKeyFileName <.> "pub"]
99 callProcessAndLogOutput (Debug, Error) $
100 callProcessAndLogOutput (Debug, Error) $
100 proc "ssh-keygen" ["-t", "ed25519", "-f", stateDir </> sshKeyFileName, "-P", ""]
101 proc "ssh-keygen" ["-t", "ed25519", "-f", stateDir </> sshKeyFileName, "-P", ""]
101
102
lib/executable-config/default.nix+25−18
@@ -2,26 +2,33 @@
2# configuration information into a canonical location. It also provides a haskell
2# configuration information into a canonical location. It also provides a haskell
3# package that can be used to retrieve the injected configuration on each supported
3# package that can be used to retrieve the injected configuration on each supported
4# platform.
4# platform.
5−{ nixpkgs
5+{ lib
6−, filterGitSource # TODO define this in obelisk
6+, runCommand
7+, obeliskCleanSource
7}:
8}:
9+
10+let
8−let injectConfig = config: assets: nixpkgs.runCommand "inject-config" {} (''
11+ injectConfig = config: assets: runCommand "inject-config" {} (''
9− set -x
12+ set -x
10− mkdir -p $out
13+ mkdir -p $out
11− cp --no-preserve=mode -Lr "${assets}" $out/static
14+ cp --no-preserve=mode -Lr "${assets}" $out/static
12− chmod +w "$out"
15+ chmod +w "$out"
13− '' + nixpkgs.lib.optionalString (!(builtins.isNull config)) ''
16+ '' + lib.optionalString (!(builtins.isNull config)) ''
14− if ! mkdir $out/config; then
17+ if ! mkdir $out/config; then
15− 2>&1 echo config directory already exists or could not be created
18+ 2>&1 echo config directory already exists or could not be created
16− exit 1
19+ exit 1
17− fi
20+ fi
18− cp -a "${config}"/* "$out/config"
21+ cp -a "${config}"/* "$out/config"
22+ # Needed for android deployments
19− find "$out/config" -type f -printf '%P\0' >"$out/config.files"
23+ find "$out/config" -type f -printf '%P\0' > "$out/config.files"
20− '');
24+ '');
21−in with nixpkgs.haskell.lib; {
25+in
26+
27+{
22 haskellOverlay = self: super: {
28 haskellOverlay = self: super: {
23− obelisk-executable-config-lookup = self.callCabal2nix "obelisk-executable-config-lookup" (filterGitSource ./lookup) {};
29+ obelisk-executable-config-lookup = self.callCabal2nix "obelisk-executable-config-lookup" (obeliskCleanSource ./lookup) {};
24 };
30 };
31+
25 platforms = {
32 platforms = {
26 android = {
33 android = {
27 # Inject the given config directory into an android assets folder
34 # Inject the given config directory into an android assets folder
@@ -32,7 +39,7 @@ in with nixpkgs.haskell.lib; {
32 inject = injectConfig;
39 inject = injectConfig;
33 };
40 };
34 web = {
41 web = {
35− inject = self: self.callCabal2nix "obelisk-executable-config-inject" (filterGitSource ./inject) {};
42+ inject = self: self.callCabal2nix "obelisk-executable-config-inject" (obeliskCleanSource ./inject) {};
36 };
43 };
37 };
44 };
38}
45}
lib/frontend/src/Obelisk/Frontend.hs+1−1
@@ -182,7 +182,7 @@ runFrontendWithConfigsAndCurrentRoute
182 -> Frontend (R frontendRoute)
182 -> Frontend (R frontendRoute)
183 -> JSM ()
183 -> JSM ()
184runFrontendWithConfigsAndCurrentRoute mode configs validFullEncoder frontend = do
184runFrontendWithConfigsAndCurrentRoute mode configs validFullEncoder frontend = do
185− let ve = validFullEncoder . hoistParse errorLeft (prismEncoder (rPrism $ _FullRoute_Frontend . _ObeliskRoute_App))
185+ let ve = validFullEncoder . hoistParse errorLeft (reviewEncoder (rPrism $ _FullRoute_Frontend . _ObeliskRoute_App))
186 errorLeft = \case
186 errorLeft = \case
187 Left _ -> error "runFrontend: Unexpected non-app ObeliskRoute reached the frontend. This shouldn't happen."
187 Left _ -> error "runFrontend: Unexpected non-app ObeliskRoute reached the frontend. This shouldn't happen."
188 Right x -> Identity x
188 Right x -> Identity x
lib/route/src/Obelisk/Route.hs+77−32
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
1{-# LANGUAGE ApplicativeDo #-}
2{-# LANGUAGE ApplicativeDo #-}
2{-# LANGUAGE ConstraintKinds #-}
3{-# LANGUAGE ConstraintKinds #-}
3{-# LANGUAGE EmptyCase #-}
4{-# LANGUAGE EmptyCase #-}
@@ -50,6 +51,7 @@ module Obelisk.Route
50 , pathParamEncoder
51 , pathParamEncoder
51 , pathLiteralEncoder
52 , pathLiteralEncoder
52 , singletonListEncoder
53 , singletonListEncoder
54+ , packTextEncoder
53 , unpackTextEncoder
55 , unpackTextEncoder
54 , prefixTextEncoder
56 , prefixTextEncoder
55 , unsafeTshowEncoder
57 , unsafeTshowEncoder
@@ -60,6 +62,7 @@ module Obelisk.Route
60 , justEncoder
62 , justEncoder
61 , nothingEncoder
63 , nothingEncoder
62 , isoEncoder
64 , isoEncoder
65+ , viewEncoder
63 , wrappedEncoder
66 , wrappedEncoder
64 , unwrappedEncoder
67 , unwrappedEncoder
65 , listToNonEmptyEncoder
68 , listToNonEmptyEncoder
@@ -68,6 +71,7 @@ module Obelisk.Route
68 , toListMapEncoder
71 , toListMapEncoder
69 , shadowEncoder
72 , shadowEncoder
70 , prismEncoder
73 , prismEncoder
74+ , reviewEncoder
71 , rPrism
75 , rPrism
72 , _R
76 , _R
73 , obeliskRouteEncoder
77 , obeliskRouteEncoder
@@ -132,6 +136,7 @@ import Control.Lens
132 , Prism'
136 , Prism'
133 , prism'
137 , prism'
134 , re
138 , re
139+ , review
135 , view
140 , view
136 , Wrapped (..)
141 , Wrapped (..)
137 )
142 )
@@ -159,6 +164,7 @@ import Data.Set (Set)
159import qualified Data.Set as Set
164import qualified Data.Set as Set
160import Data.Some (Some(Some))
165import Data.Some (Some(Some))
161import Data.Text (Text)
166import Data.Text (Text)
167+import Data.Text.Lens (IsText, packed, unpacked)
162import qualified Data.Text as T
168import qualified Data.Text as T
163import qualified Data.Text.Encoding as T
169import qualified Data.Text.Encoding as T
164import Data.Universe
170import Data.Universe
@@ -219,7 +225,19 @@ hoistR f (x :=> Identity y) = f x :/ y
219infixr 5 :.
225infixr 5 :.
220type (:.) = (,)
226type (:.) = (,)
221
227
228+#ifdef __GLASGOW_HASKELL__
229+#if __GLASGOW_HASKELL__ >= 810
222{-# COMPLETE (:.) #-}
230{-# COMPLETE (:.) #-}
231+#else
232+{-# WARNING (:.)
233+ [ "Use of this pattern in GHC < 8.10 will result in spurious non-exhaustive warnings at every use site."
234+ , "We cannot provide a COMPLETE pragma to silence these due to a GHC bug: https://gitlab.haskell.org/ghc/ghc/issues/17729."
235+ , "The bug hides incompleteness warnings for all two tuples when the COMPLETE pattern is in scope."
236+ , "Instead, you should use (,) directly until you can switch to GHC >= 8.10, where the COMPLETE pragma is reinstated."
237+ ]
238+ #-}
239+#endif
240+#endif
223pattern (:.) :: a -> b -> a :. b
241pattern (:.) :: a -> b -> a :. b
224pattern a :. b = (a, b)
242pattern a :. b = (a, b)
225
243
@@ -338,7 +356,7 @@ instance Monad parse => Bifunctor (,) (EncoderImpl parse) (EncoderImpl parse) (E
338 }
356 }
339
357
340instance (Monad parse, Applicative check) => Braided (Encoder check parse) (,) where
358instance (Monad parse, Applicative check) => Braided (Encoder check parse) (,) where
341− braid = isoEncoder (iso swap swap)
359+ braid = viewEncoder (iso swap swap)
342
360
343
361
344instance (Applicative check, Monad parse) => PFunctor (,) (Encoder check parse) (Encoder check parse) where
362instance (Applicative check, Monad parse) => PFunctor (,) (Encoder check parse) (Encoder check parse) where
@@ -374,11 +392,11 @@ instance (Monad parse, Applicative check) => Bifunctor Either (Encoder check par
374 bimap f g = Encoder $ liftA2 bimap (unEncoder f) (unEncoder g)
392 bimap f g = Encoder $ liftA2 bimap (unEncoder f) (unEncoder g)
375
393
376instance (Applicative check, Monad parse) => Associative (Encoder check parse) Either where
394instance (Applicative check, Monad parse) => Associative (Encoder check parse) Either where
377− associate = isoEncoder (iso (associate @(->) @Either) disassociate)
395+ associate = viewEncoder (iso (associate @(->) @Either) disassociate)
378− disassociate = isoEncoder (iso disassociate associate)
396+ disassociate = viewEncoder (iso disassociate associate)
379
397
380instance (Monad parse, Applicative check) => Braided (Encoder check parse) Either where
398instance (Monad parse, Applicative check) => Braided (Encoder check parse) Either where
381− braid = isoEncoder (iso swap swap)
399+ braid = viewEncoder (iso swap swap)
382
400
383
401
384
402
@@ -432,17 +450,17 @@ instance (Applicative check, Monad parse) => Monoidal (Encoder check parse) (,)
432--------------------------------------------------------------------------------
450--------------------------------------------------------------------------------
433
451
434-- | Given a valid 'Iso' from lens, construct an 'Encoder'
452-- | Given a valid 'Iso' from lens, construct an 'Encoder'
435−isoEncoder :: (Applicative check, Applicative parse) => Iso' a b -> Encoder check parse a b
453+viewEncoder :: (Applicative check, Applicative parse) => Iso' a b -> Encoder check parse a b
436−isoEncoder f = unsafeMkEncoder $ EncoderImpl
454+viewEncoder f = unsafeMkEncoder $ EncoderImpl
437 { _encoderImpl_encode = view f
455 { _encoderImpl_encode = view f
438 , _encoderImpl_decode = pure . view (from f)
456 , _encoderImpl_decode = pure . view (from f)
439 }
457 }
440
458
441wrappedEncoder :: (Wrapped a, Applicative check, Applicative parse) => Encoder check parse (Unwrapped a) a
459wrappedEncoder :: (Wrapped a, Applicative check, Applicative parse) => Encoder check parse (Unwrapped a) a
442−wrappedEncoder = isoEncoder $ from _Wrapped'
460+wrappedEncoder = viewEncoder $ from _Wrapped'
443
461
444unwrappedEncoder :: (Wrapped a, Applicative check, Applicative parse) => Encoder check parse a (Unwrapped a)
462unwrappedEncoder :: (Wrapped a, Applicative check, Applicative parse) => Encoder check parse a (Unwrapped a)
445−unwrappedEncoder = isoEncoder _Wrapped'
463+unwrappedEncoder = viewEncoder $ _Wrapped'
446
464
447maybeToEitherEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Maybe a) (Either () a)
465maybeToEitherEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Maybe a) (Either () a)
448maybeToEitherEncoder = unsafeMkEncoder $ EncoderImpl
466maybeToEitherEncoder = unsafeMkEncoder $ EncoderImpl
@@ -467,11 +485,11 @@ maybeEncoder f g = shadowEncoder f g . maybeToEitherEncoder
467
485
468-- | Encode a value by simply applying 'Just'
486-- | Encode a value by simply applying 'Just'
469justEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse a (Maybe a)
487justEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse a (Maybe a)
470−justEncoder = prismEncoder _Just
488+justEncoder = reviewEncoder _Just
471
489
472-- | Encode () to 'Nothing'.
490-- | Encode () to 'Nothing'.
473nothingEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse () (Maybe a)
491nothingEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse () (Maybe a)
474−nothingEncoder = prismEncoder _Nothing
492+nothingEncoder = reviewEncoder _Nothing
475
493
476someConstEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Some (Const a)) a
494someConstEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Some (Const a)) a
477someConstEncoder = unsafeMkEncoder $ EncoderImpl
495someConstEncoder = unsafeMkEncoder $ EncoderImpl
@@ -756,11 +774,11 @@ prefixNonemptyTextEncoder p = Encoder $ pure $ EncoderImpl
756 Just stripped -> pure stripped
774 Just stripped -> pure stripped
757 }
775 }
758
776
759−unpackTextEncoder :: (Applicative check, Applicative parse) => Encoder check parse Text String
777+packTextEncoder :: (Applicative check, Applicative parse, IsText text) => Encoder check parse String text
760−unpackTextEncoder = Encoder $ pure $ EncoderImpl
778+packTextEncoder = isoEncoder packed
761− { _encoderImpl_encode = T.unpack
779+
762− , _encoderImpl_decode = pure . T.pack
780+unpackTextEncoder :: (Applicative check, Applicative parse, IsText text) => Encoder check parse text String
763− }
781+unpackTextEncoder = isoEncoder unpacked
764
782
765toListMapEncoder :: (Applicative check, Applicative parse, Ord k) => Encoder check parse (Map k v) [(k, v)]
783toListMapEncoder :: (Applicative check, Applicative parse, Ord k) => Encoder check parse (Map k v) [(k, v)]
766toListMapEncoder = Encoder $ pure $ EncoderImpl
784toListMapEncoder = Encoder $ pure $ EncoderImpl
@@ -825,12 +843,19 @@ _R variant = dSumGEqPrism variant . iso runIdentity Identity
825
843
826-- | An encoder that only works on the items available via the prism. An error will be thrown in the parse monad
844-- | An encoder that only works on the items available via the prism. An error will be thrown in the parse monad
827-- if the prism doesn't match.
845-- if the prism doesn't match.
846+--
847+-- Note that a 'Prism' from @a@ to @b@ will produce an 'Encoder' from @b@ to @a@
848+-- (i.e. 'reviewEncoder' is a contravariant functor from the category of prisms to the category of encoders),
849+-- just like 'review' produces a function @b -> a@. This is because 'Prism's extract values, in a way that might
850+-- fail, in their forward direction and inject values, in a way that cannot fail, in their reverse direction;
851+-- whereas 'Encoder's encode, which cannot fail, in their forward direction, and decode, which can fail, in their
852+-- reverse direction. In short @reviewEncoder (f . g) = reviewEncoder g . reviewEncoder f@.
828−prismEncoder :: (Applicative check, MonadError Text parse) => Prism' b a -> Encoder check parse a b
853+reviewEncoder :: (Applicative check, MonadError Text parse) => Prism' b a -> Encoder check parse a b
829−prismEncoder p = unsafeMkEncoder $ EncoderImpl
854+reviewEncoder p = unsafeMkEncoder $ EncoderImpl
830− { _encoderImpl_encode = (^. re p)
855+ { _encoderImpl_encode = review p
831 , _encoderImpl_decode = \r -> case r ^? p of
856 , _encoderImpl_decode = \r -> case r ^? p of
832 Just a -> pure a
857 Just a -> pure a
833− Nothing -> throwError "prismEncoder: value is not present in the prism"
858+ Nothing -> throwError "reviewEncoder: value is not present in the prism"
834 }
859 }
835
860
836-- | A URL path and query string, in which trailing slashes don't matter in the path
861-- | A URL path and query string, in which trailing slashes don't matter in the path
@@ -1026,17 +1051,6 @@ void1Encoder = Encoder $ pure $ EncoderImpl
1026instance GShow Void1 where
1051instance GShow Void1 where
1027 gshowsPrec _ = \case {}
1052 gshowsPrec _ = \case {}
1028
1053
1029−concat <$> mapM deriveRouteComponent
1030− [ ''ResourceRoute
1031− , ''JSaddleWarpRoute
1032− , ''IndexOnlyRoute
1033− ]
1034−
1035−makePrisms ''ObeliskRoute
1036−makePrisms ''FullRoute
1037−deriveGEq ''Void1
1038−deriveGCompare ''Void1
1039−
1040-- | Given a backend route and a checked route encoder, render the route (path
1054-- | Given a backend route and a checked route encoder, render the route (path
1041-- and query string). See 'checkEncoder' for how to produce a checked encoder.
1055-- and query string). See 'checkEncoder' for how to produce a checked encoder.
1042renderBackendRoute
1056renderBackendRoute
@@ -1069,11 +1083,11 @@ readShowEncoder :: (MonadError Text parse, Read a, Show a, Applicative check) =>
1069readShowEncoder = singlePathSegmentEncoder . unsafeTshowEncoder
1083readShowEncoder = singlePathSegmentEncoder . unsafeTshowEncoder
1070
1084
1071integralEncoder :: (MonadError Text parse, Applicative check, Integral a) => Encoder check parse a Integer
1085integralEncoder :: (MonadError Text parse, Applicative check, Integral a) => Encoder check parse a Integer
1072−integralEncoder = prismEncoder (Numeric.Lens.integral)
1086+integralEncoder = reviewEncoder (Numeric.Lens.integral)
1073
1087
1074pathSegmentEncoder :: (MonadError Text parse, Applicative check, Cons as as a a) =>
1088pathSegmentEncoder :: (MonadError Text parse, Applicative check, Cons as as a a) =>
1075 Encoder check parse (a, (as, b)) (as, b)
1089 Encoder check parse (a, (as, b)) (as, b)
1076−pathSegmentEncoder = first (prismEncoder _Cons) . disassociate
1090+pathSegmentEncoder = first (reviewEncoder _Cons) . disassociate
1077
1091
1078newtype Decoder check parse b a = Decoder { toEncoder :: Encoder check parse a b }
1092newtype Decoder check parse b a = Decoder { toEncoder :: Encoder check parse a b }
1079
1093
@@ -1180,3 +1194,34 @@ byteStringsToPageName p q =
1180 in decode pageNameEncoder' (T.unpack (T.decodeUtf8 p), T.unpack (T.decodeUtf8 q))
1194 in decode pageNameEncoder' (T.unpack (T.decodeUtf8 p), T.unpack (T.decodeUtf8 q))
1181
1195
1182--TODO: decodeURIComponent as appropriate
1196--TODO: decodeURIComponent as appropriate
1197+
1198+
1199+{-# DEPRECATED isoEncoder "Instead of 'isoEncoder f', use 'viewEncoder f'" #-}
1200+-- | Given a valid 'Iso' from lens, construct an 'Encoder'
1201+isoEncoder :: (Applicative check, Applicative parse) => Iso' a b -> Encoder check parse a b
1202+isoEncoder = viewEncoder
1203+
1204+{-# DEPRECATED prismEncoder "Instead of 'prismEncoder f', use 'reviewEncoder f'" #-}
1205+-- | An encoder that only works on the items available via the prism. An error will be thrown in the parse monad
1206+-- if the prism doesn't match.
1207+--
1208+-- Note that a 'Prism' from @a@ to @b@ will produce an 'Encoder' from @b@ to @a@
1209+-- (i.e. 'prismEncoder' is a contravariant functor from the category of prisms to the category of encoders),
1210+-- just like 'review' produces a function @b -> a@. This is because 'Prism's extract values, in a way that might
1211+-- fail, in their forward direction and inject values, in a way that cannot fail, in their reverse direction;
1212+-- whereas 'Encoder's encode, which cannot fail, in their forward direction, and decode, which can fail, in their
1213+-- reverse direction. In short @prismEncoder (f . g) = prismEncoder g . prismEncoder f@.
1214+prismEncoder :: (Applicative check, MonadError Text parse) => Prism' b a -> Encoder check parse a b
1215+prismEncoder = reviewEncoder
1216+
1217+
1218+concat <$> mapM deriveRouteComponent
1219+ [ ''ResourceRoute
1220+ , ''JSaddleWarpRoute
1221+ , ''IndexOnlyRoute
1222+ ]
1223+
1224+makePrisms ''ObeliskRoute
1225+makePrisms ''FullRoute
1226+deriveGEq ''Void1
1227+deriveGCompare ''Void1
lib/selftest/obelisk-selftest.cabal+2−1
@@ -9,6 +9,8 @@ library
9 hs-source-dirs: src
9 hs-source-dirs: src
10 build-depends:
10 build-depends:
11 base
11 base
12+ , bytestring
13+ , aeson
12 , containers
14 , containers
13 , directory
15 , directory
14 , filepath
16 , filepath
@@ -17,7 +19,6 @@ library
17 , http-types
19 , http-types
18 , HUnit
20 , HUnit
19 , network
21 , network
20− , obelisk-cliapp
21 , obelisk-executable-config-lookup
22 , obelisk-executable-config-lookup
22 , obelisk-run
23 , obelisk-run
23 , which
24 , which
lib/selftest/src/Obelisk/SelfTest.hs+400−230
@@ -4,39 +4,45 @@
4{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE PatternGuards #-}
5{-# LANGUAGE PatternGuards #-}
6{-# LANGUAGE ScopedTypeVariables #-}
6{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE TemplateHaskell #-}
8+{-# LANGUAGE TypeApplications #-}
7{-# LANGUAGE ViewPatterns #-}
9{-# LANGUAGE ViewPatterns #-}
8−{-# LANGUAGE TemplateHaskell #-}
9module Obelisk.SelfTest where
10module Obelisk.SelfTest where
10
11
12+import Control.Concurrent (threadDelay)
11−import Control.Exception (bracket, throw)
13+import Control.Exception (bracket, throw, try)
12import Control.Monad
14import Control.Monad
13import Control.Monad.IO.Class
15import Control.Monad.IO.Class
16+import qualified Data.Aeson as Aeson
17+import qualified Data.Aeson.Types as Aeson
14import Data.Bool (bool)
18import Data.Bool (bool)
19+import qualified Data.ByteString.Lazy as LBS
20+import Data.Foldable (for_)
15import Data.Function (fix)
21import Data.Function (fix)
22+import qualified Data.Map as Map
16import Data.Semigroup ((<>))
23import Data.Semigroup ((<>))
17import qualified Data.Set as Set
24import qualified Data.Set as Set
18import Data.String
25import Data.String
19import Data.Text (Text)
26import Data.Text (Text)
20−import Data.Void
21import qualified Data.Text as T
27import qualified Data.Text as T
28+import qualified Data.Text.Encoding as T
22import qualified Data.Text.IO as T
29import qualified Data.Text.IO as T
23import qualified Network.HTTP.Client as HTTP
30import qualified Network.HTTP.Client as HTTP
24import qualified Network.HTTP.Types as HTTP
31import qualified Network.HTTP.Types as HTTP
25import qualified Network.Socket as Socket
32import qualified Network.Socket as Socket
26−import Shelly hiding (cp)
33+import Shelly
27import System.Directory (getCurrentDirectory, withCurrentDirectory, getDirectoryContents)
34import System.Directory (getCurrentDirectory, withCurrentDirectory, getDirectoryContents)
28import System.Environment
35import System.Environment
29import System.Exit (ExitCode (..))
36import System.Exit (ExitCode (..))
30−import System.Which (staticWhich)
37+import System.FilePath (addTrailingPathSeparator)
31import qualified System.Info
38import qualified System.Info
32import System.IO (Handle, hClose, hIsEOF, hGetContents)
39import System.IO (Handle, hClose, hIsEOF, hGetContents)
33import System.IO.Temp
40import System.IO.Temp
34−import System.Process (readProcessWithExitCode, CreateProcess(cwd), readCreateProcessWithExitCode, proc)
41+import System.Process (readProcessWithExitCode)
42+import System.Which (staticWhich)
35import Test.Hspec
43import Test.Hspec
36import Test.HUnit.Base
44import Test.HUnit.Base
37
45
38−import Obelisk.CliApp hiding (runCli, readCreateProcessWithExitCode)
39−import qualified Obelisk.CliApp as CliApp
40import Obelisk.ExecutableConfig.Lookup (getConfigs)
46import Obelisk.ExecutableConfig.Lookup (getConfigs)
41import Obelisk.Run (getConfigRoute)
47import Obelisk.Run (getConfigRoute)
42
48
@@ -46,8 +52,8 @@ data ObRunState
46 | ObRunState_BackendStarted
52 | ObRunState_BackendStarted
47 deriving (Eq, Show)
53 deriving (Eq, Show)
48
54
49−cp :: FilePath
55+cpPath :: FilePath
50−cp = $(staticWhich "cp")
56+cpPath = $(staticWhich "cp")
51
57
52cabalPath :: FilePath
58cabalPath :: FilePath
53cabalPath = $(staticWhich "cabal")
59cabalPath = $(staticWhich "cabal")
@@ -64,15 +70,24 @@ chmodPath = $(staticWhich "chmod")
64whoamiPath :: FilePath
70whoamiPath :: FilePath
65whoamiPath = $(staticWhich "whoami")
71whoamiPath = $(staticWhich "whoami")
66
72
73+nixInstantiatePath :: FilePath
74+nixInstantiatePath = $(staticWhich "nix-instantiate")
75+
67nixBuildPath :: FilePath
76nixBuildPath :: FilePath
68nixBuildPath = $(staticWhich "nix-build")
77nixBuildPath = $(staticWhich "nix-build")
69
78
79+nixPrefetchGitPath :: FilePath
80+nixPrefetchGitPath = $(staticWhich "nix-prefetch-git")
81+
70lnPath :: FilePath
82lnPath :: FilePath
71lnPath = $(staticWhich "ln")
83lnPath = $(staticWhich "ln")
72
84
73rmPath :: FilePath
85rmPath :: FilePath
74rmPath = $(staticWhich "rm")
86rmPath = $(staticWhich "rm")
75
87
88+rsyncPath :: FilePath
89+rsyncPath = $(staticWhich "rsync")
90+
76gitUserConfig :: [Text]
91gitUserConfig :: [Text]
77gitUserConfig = ["-c", "user.name=Obelisk Selftest", "-c", "user.email=noreply@example.com"]
92gitUserConfig = ["-c", "user.name=Obelisk Selftest", "-c", "user.email=noreply@example.com"]
78
93
@@ -84,12 +99,6 @@ commit msg = void $ run gitPath $ gitUserConfig <> [ "commit"
84 , msg
99 , msg
85 ]
100 ]
86
101
87−-- TODO replace Void and stop using loosely typed synchronous exceptions
88−runCli :: MonadIO m => CliT Void IO a -> m a
89−runCli f = liftIO $ do
90− c <- newCliConfig Notice False False (\case {})
91− CliApp.runCli c f
92−
93tshow :: Show a => a -> Text
102tshow :: Show a => a -> Text
94tshow = T.pack . show
103tshow = T.pack . show
95
104
@@ -106,228 +115,268 @@ ob = "ob"
106augmentWithVerbosity :: (String -> [Text] -> a) -> String -> Bool -> [Text] -> a
115augmentWithVerbosity :: (String -> [Text] -> a) -> String -> Bool -> [Text] -> a
107augmentWithVerbosity runner executable isVerbose args = runner executable $ (if isVerbose then ("-v" :) else id) args
116augmentWithVerbosity runner executable isVerbose args = runner executable $ (if isVerbose then ("-v" :) else id) args
108
117
118+isolatedGitShell :: Bool -> FilePath -> (([Text] -> Sh Text) -> Sh a) -> IO a
119+isolatedGitShell isVerbose dir f = shelly $ bool silently verbosely isVerbose $ do
120+ setenv "HOME" "/dev/null"
121+ setenv "GIT_CONFIG_NOSYSTEM" "1"
122+ _ <- git ["init"]
123+ _ <- git ["config", "user.name", "SelfTest"]
124+ _ <- git ["config", "user.email", "self@test"]
125+ f git
126+ where
127+ git args = run gitPath $ ["-C", toTextIgnore dir] <> args
128+
129+-- | Copies a git repo to a new location and "resets" the git history to include
130+-- exactly one commit with all files added. It then restricts writing and reading
131+-- for group and user to make the repo ideal for being a valid git remote for thunks.
132+--
133+-- Using this allows dirty repos to be used as git remotes during the test since 'git clone'ing
134+-- a dirty repo will not include the uncommitted changes.
135+copyForGitRemote :: Bool -> FilePath -> FilePath -> IO ()
136+copyForGitRemote isVerbose origDir copyDir = isolatedGitShell isVerbose copyDir $ \git -> do
137+ run_ rsyncPath
138+ [ "-r", "--no-perms", "--no-owner", "--no-group", "--exclude", ".git"
139+ , toTextIgnore (addTrailingPathSeparator origDir), toTextIgnore copyDir
140+ ]
141+ _ <- git ["add", "--all"]
142+ _ <- git ["commit", "-m", "Copy repo"]
143+ run_ chmodPath ["-R", "u-w,g-rw,o-rw", toTextIgnore copyDir] -- Freeze this state
144+
109main :: IO ()
145main :: IO ()
110main = do
146main = do
111 -- Note: you can pass hspec arguments as well, eg: `-m <pattern>`
147 -- Note: you can pass hspec arguments as well, eg: `-m <pattern>`
112 isVerbose <- elem "-v" <$> getArgs
148 isVerbose <- elem "-v" <$> getArgs
113 unless isVerbose $
149 unless isVerbose $
114 putStrLn "Tests may take longer to run if there are unbuilt derivations: use -v for verbose output"
150 putStrLn "Tests may take longer to run if there are unbuilt derivations: use -v for verbose output"
115− let verbosity = bool silently verbosely isVerbose
151+
116− nixBuild args = run nixBuildPath ("--no-out-link" : args)
152+ obeliskImplDirtyReadOnly <- getCurrentDirectory
117− obeliskImplDirtyReadOnly <- fromString <$> getCurrentDirectory
153+ httpManager <- HTTP.newManager HTTP.defaultManagerSettings
118− let runOb_ = augmentWithVerbosity run_ ob isVerbose
154+
119− let runOb = augmentWithVerbosity run ob isVerbose
155+ withSystemTempDirectory "obelisk-repo-git-remote" $ \copyDir -> do
120− let testObRunInDir' = augmentWithVerbosity testObRunInDir ob isVerbose ["run"]
156+ copyForGitRemote isVerbose obeliskImplDirtyReadOnly copyDir
121− let testThunkPack' = augmentWithVerbosity testThunkPack ob isVerbose []
157+ main' isVerbose httpManager copyDir
158+
159+main' :: Bool -> HTTP.Manager -> FilePath -> IO ()
160+main' isVerbose httpManager obeliskRepoReadOnly = withInitCache $ \initCache -> hspec $ parallel $ do
122 let
161 let
162+ inTmpObInit' dirname f = inTmp' dirname $ \dir -> do
163+ run_ cpPath ["-rT", fromString initCache, toTextIgnore dir]
164+ f dir
165+ inTmpObInit = inTmpObInit' defaultTmpDirName
166+
167+ -- To be used in tests that change the obelisk impl directory
168+ inTmpObInitWithImplCopy f = inTmpObInit $ \dir ->
123− withObeliskImplClean f =
169+ withObeliskImplClean $ \(fromString -> implClean) -> do
170+ run_ rmPath [thunk]
171+ run_ lnPath ["-s", implClean, thunk]
172+ f dir
173+
174+ describe "ob init" $ parallel $ do
175+ it "works with default impl" $ inTmp $ \_ -> runOb ["init"]
176+ it "works with master branch impl" $ inTmp $ \_ -> runOb ["init", "--branch", "master"]
177+ it "works with symlink" $ inTmp $ \_ -> runOb ["init", "--symlink", toTextIgnore obeliskRepoReadOnly]
178+ it "doesn't silently overwrite existing files" $ inTmp $ \_ -> do
179+ let p force = errExit False $ do
180+ run_ ob $ "--no-handoff" : "-v" : "init" : ["--force"|force]
181+ (== 0) <$> lastExitCode
182+
183+ True <- p False
184+ False <- p False
185+ True <- p True
186+ pure ()
187+
188+ it "doesn't create anything when given an invalid impl" $ inTmp $ \tmp -> do
189+ void $ errExit False $ runOb ["init", "--symlink", "/dev/null"]
190+ ls tmp >>= liftIO . assertEqual "" []
191+
192+ it "produces a valid route config" $ inTmpObInit $ \tmp -> liftIO $
193+ withCurrentDirectory (T.unpack $ toTextIgnore tmp) $ do
194+ configs <- getConfigs
195+ return (either (const Nothing) Just $ getConfigRoute configs) `shouldNotReturn` Nothing
196+
197+ it "can unpack and repack .obelisk/impl after init with master branch impl" $ inTmp $ \_ -> do
198+ runOb_ ["init", "--branch", "master"]
199+ runOb_ ["thunk", "unpack", ".obelisk/impl"]
200+ runOb_ ["thunk", "pack", ".obelisk/impl"]
201+
202+ -- These tests fail with "Could not find module 'Obelisk.Generated.Static'"
203+ -- when not run by 'nix-build --attr selftest'
204+ describe "ob run" $ {- NOT parallel $ -} do
205+ it "works in root directory" $ inTmpObInit $ \_ -> testObRunInDir' Nothing httpManager
206+ it "works in sub directory" $ inTmpObInit $ \_ -> testObRunInDir' (Just "frontend") httpManager
207+
208+ describe "obelisk project" $ parallel $ do
209+ it "can build obelisk command" $ inTmpObInit $ \_ -> nixBuild ["-A", "command" , toTextIgnore obeliskRepoReadOnly]
210+ it "can build obelisk skeleton" $ inTmpObInit $ \_ -> nixBuild ["-A", "skeleton", toTextIgnore obeliskRepoReadOnly]
211+ it "can build obelisk shell" $ inTmpObInit $ \_ -> nixBuild ["-A", "shell", toTextIgnore obeliskRepoReadOnly]
212+ it "can build everything" $ inTmpObInit $ \_ -> nixBuild [toTextIgnore obeliskRepoReadOnly]
213+
214+ describe "blank initialized project" $ parallel $ do
215+
216+ it "can build ghc.backend" $ inTmpObInit $ \_ -> nixBuild ["-A", "ghc.backend"]
217+ it "can build ghcjs.frontend" $ inTmpObInit $ \_ -> nixBuild ["-A", "ghcjs.frontend"]
218+
219+ if System.Info.os == "darwin"
220+ then it "can build ios" $ inTmpObInit $ \_ -> nixBuild ["-A", "ios.frontend"]
221+ else it "can build android after accepting license" $ inTmpObInit $ \dir -> do
222+ let defaultNixPath = dir </> ("default.nix" :: FilePath)
223+ writefile defaultNixPath
224+ =<< T.replace
225+ "# config.android_sdk.accept_license = false;"
226+ "config.android_sdk.accept_license = true;"
227+ <$> readfile defaultNixPath
228+ nixBuild ["-A", "android.frontend"]
229+
230+ forM_ ["ghc", "ghcjs"] $ \compiler -> do
231+ let
232+ shellName = "shells." <> compiler
233+ inShell cmd' = run_ "nix-shell" ["default.nix", "-A", fromString shellName, "--run", cmd']
234+ it ("can enter " <> shellName) $ inTmpObInit $ \_ -> inShell "exit"
235+ -- NOTE: We override the temporary directory name because cabal has a bug preventing new-build from working
236+ -- in a path that has unicode characters.
237+ it ("can build in " <> shellName) $ inTmpObInit' "test" $ \_ -> inShell $
238+ T.pack cabalPath <> " --version; " <> T.pack cabalPath <> " new-build --" <> T.pack compiler <> " all"
239+
240+ it "has idempotent thunk update" $ inTmpObInitWithImplCopy $ \_ -> do
241+ _ <- pack
242+ u <- update
243+ uu <- update
244+ assertRevEQ u uu
245+
246+ it "can run 'ob doc'" $ inTmpObInit $ \_ -> runOb ["doc", "reflex"]
247+
248+ describe "ob thunk pack/unpack" $ parallel $ do
249+ it "has thunk pack and unpack inverses" $ inTmpObInitWithImplCopy $ \_ -> do
250+
251+ _ <- pack
252+ e <- commitAll
253+ eu <- unpack
254+ eup <- pack
255+ eupu <- unpack
256+ _ <- pack
257+
258+ assertRevEQ e eup
259+ assertRevEQ eu eupu
260+ assertRevNE e eu
261+
262+ it "unpacks the correct branch" $ withTmp $ \dir -> do
263+ let branch = "master"
264+ run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch]
265+ runOb_ ["thunk", "pack", toTextIgnore dir]
266+ runOb_ ["thunk", "unpack", toTextIgnore dir]
267+ branch' <- run gitPath ["-C", toTextIgnore $ dir </> unpackedDirName, "rev-parse", "--abbrev-ref", "HEAD"]
268+ liftIO $ assertEqual "" branch (T.strip branch')
269+
270+ it "can pack and unpack plain git repos" $
124− withSystemTempDirectory "obelisk-impl-clean" $ \(fromString -> obeliskImpl) -> do
271+ shelly_ $ withSystemTempDirectory "git-repo" $ \dir -> do
125− void . shellyOb verbosity $ chdir obeliskImpl $ do
272+ let repo = toTextIgnore $ dir </> ("repo" :: FilePath)
126− run_ gitPath ["clone", "file://" <> toTextIgnore obeliskImplDirtyReadOnly, toTextIgnore obeliskImpl]
273+ run_ gitPath ["clone", "https://github.com/haskell/process.git", repo]
127− f obeliskImpl
274+ origHash <- chdir (fromText repo) revParseHead
275+
276+ runOb_ ["thunk", "pack", repo]
277+ packedFiles <- Set.fromList <$> ls (fromText repo)
278+ liftIO $ assertEqual "" packedFiles $ Set.fromList $ (repo </>) <$>
279+ ["default.nix", "thunk.nix", "github.json" :: FilePath]
280+
281+ runOb_ ["thunk", "unpack", repo]
282+ chdir (fromText repo </> unpackedDirName) $ do
283+ unpackHash <- revParseHead
284+ assertRevEQ origHash unpackHash
285+
286+ testThunkPack' $ fromText repo
287+
288+ it "aborts thunk pack when there are uncommitted files" $ inTmpObInitWithImplCopy $ \dir -> do
289+ testThunkPack' (dir </> thunk)
290+
291+ it "works on legacy git thunks" $ testLegacyGitThunks isVerbose
292+
293+ describe "ob thunk update --branch" $ parallel $ do
294+ it "can change a thunk to the latest version of a desired branch" $ withTmp $ \dir -> do
295+ let branch1 = "master"
296+ branch2 = "develop"
297+ run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch1]
298+ runOb_ ["thunk" , "pack", toTextIgnore dir]
299+ runOb_ ["thunk", "update", toTextIgnore dir, "--branch", branch2]
300+
301+ it "doesn't create anything when given an invalid branch" $ withTmp $ \dir -> do
302+ let checkDir dir' = liftIO $ getDirectoryContents $ T.unpack $ toTextIgnore dir'
303+ run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", "master"]
304+ runOb_ ["thunk" , "pack", toTextIgnore dir]
305+ startingContents <- checkDir dir
306+ void $ errExit False $ runOb ["thunk", "update", toTextIgnore dir, "--branch", "dumble-palooza"]
307+ checkDir dir >>= liftIO . assertEqual "" startingContents
308+
309+ describe "ob hoogle" $ {- NOT parallel -} do
310+ it "starts a hoogle server on the given port" $ inTmpObInit $ \_ -> do
311+ [p0] <- liftIO $ getFreePorts 1
312+ maskExitSuccess $ runHandle "ob" ["hoogle", "--port", T.pack (show p0)] $ \stdout -> flip fix Nothing $ \loop -> \case
313+ Nothing -> do -- Still waiting for initial signal that the server has started
314+ ln <- liftIO $ T.hGetLine stdout
315+ let search = "Server starting on port " <> T.pack (show p0)
316+ case search `T.isInfixOf` ln of
317+ False -> loop Nothing -- keep waiting
318+ True -> loop $ Just 10
319+ Just (n :: Int) -> do -- Server has started and we have n attempts left
320+ let req uri = liftIO $ try @HTTP.HttpException $ HTTP.parseRequest uri >>= flip HTTP.httpLbs httpManager
321+ req ("http://127.0.0.1:" <> show p0) >>= \case
322+ Right r | HTTP.responseStatus r == HTTP.ok200 -> exit 0
323+ e -> if n <= 0
324+ then errorExit $ "Request to hoogle server failed: " <> T.pack (show e)
325+ else liftIO (threadDelay (1*10^(6 :: Int))) *> loop (Just $ n - 1)
326+ where
327+ verbosity = bool silently verbosely isVerbose
328+ nixBuild args = run nixBuildPath ("--no-out-link" : args)
128
329
129− withObeliskImplDirty f =
330+ runOb_ = augmentWithVerbosity run_ ob isVerbose
331+ runOb = augmentWithVerbosity run ob isVerbose
332+ testObRunInDir' = augmentWithVerbosity testObRunInDir ob isVerbose ["run"]
333+ testThunkPack' = augmentWithVerbosity testThunkPack ob isVerbose []
334+
335+ withObeliskImplClean f =
130− withSystemTempDirectory "obelisk-impl-copy" $ \(fromString -> obeliskImpl) -> do
336+ withSystemTempDirectory "obelisk-impl-clean" $ \obeliskImpl -> do
131− void . shellyOb verbosity $ chdir obeliskImpl $ do
337+ void . shellyOb verbosity $ do
132− user <- T.strip <$> run whoamiPath []
338+ dirtyFiles <- T.strip <$> run gitPath ["-C", toTextIgnore obeliskRepoReadOnly, "diff", "--stat"]
133− run_ cp ["-rT", "--no-preserve=mode", toTextIgnore obeliskImplDirtyReadOnly, toTextIgnore obeliskImpl]
339+ () <- when (dirtyFiles /= "") $ error "SelfTest does not work correctly with dirty obelisk repos as remote"
134− run_ chownPath ["-R", user, toTextIgnore obeliskImpl]
135− run_ chmodPath ["-R", "g-rw,o-rw", toTextIgnore obeliskImpl]
340+ run_ gitPath ["clone", "file://" <> toTextIgnore obeliskRepoReadOnly, toTextIgnore obeliskImpl]
136 f obeliskImpl
341 f obeliskImpl
137
342
138− withInitCache f obeliskImpl =
343+ withInitCache f =
139 withSystemTempDirectory "init Cache λ" $ \initCache -> do
344 withSystemTempDirectory "init Cache λ" $ \initCache -> do
140 -- Setup the ob init cache
345 -- Setup the ob init cache
141 void . shellyOb verbosity $ chdir initCache $ do
346 void . shellyOb verbosity $ chdir initCache $ do
142− runOb_ ["init", "--symlink", toTextIgnore obeliskImpl]
347+ runOb_ ["init", "--symlink", toTextIgnore obeliskRepoReadOnly]
143 run_ gitPath ["init"]
348 run_ gitPath ["init"]
144
349
145 f initCache
350 f initCache
146
351
147− withObeliskImplDirtyAndInitCache f =
352+ shelly_ = void . shellyOb verbosity
148− withObeliskImplDirty $ \impl -> withInitCache (f impl) impl
149
353
150− httpManager <- HTTP.newManager HTTP.defaultManagerSettings
354+ defaultTmpDirName = "test λ"
355+
356+ inTmp' :: FilePath -> (FilePath -> Sh a) -> IO ()
357+ inTmp' dirname f = withTmp' dirname (chdir <*> f)
358+ inTmp = inTmp' defaultTmpDirName
359+
360+ withTmp' dirname f = shelly_ . withSystemTempDirectory dirname $ f . fromString
361+ withTmp = withTmp' defaultTmpDirName
362+
363+ assertRevEQ a b = liftIO . assertEqual "" "" =<< diff a b
364+ assertRevNE a b = liftIO . assertBool "" . (/= "") =<< diff a b
365+
366+ revParseHead = T.strip <$> run gitPath ["rev-parse", "HEAD"]
367+
368+ commitAll = do
369+ run_ gitPath ["add", "."]
370+ commit "checkpoint"
371+ revParseHead
372+
373+ thunk = ".obelisk/impl"
374+ update = runOb ["thunk", "update", thunk] *> commitAll
375+ pack = runOb ["thunk", "pack", thunk] *> commitAll
376+ unpack = runOb ["thunk", "unpack", thunk] *> commitAll
377+
378+ diff a b = run gitPath ["diff", a, b]
151
379
152− withObeliskImplDirtyAndInitCache $ \obeliskImplDirty initCache ->
153− hspec $ parallel $ do
154− let shelly_ = void . shellyOb verbosity
155−
156− defaultTmpDirName = "test λ"
157−
158− inTmp' :: FilePath -> (FilePath -> Sh a) -> IO ()
159− inTmp' dirname f = withTmp' dirname (chdir <*> f)
160− inTmp = inTmp' defaultTmpDirName
161−
162− withTmp' dirname f = shelly_ . withSystemTempDirectory dirname $ f . fromString
163− withTmp = withTmp' defaultTmpDirName
164−
165− inTmpObInit' dirname f = inTmp' dirname $ \dir -> do
166− run_ cp ["-rT", fromString initCache, toTextIgnore dir]
167− f dir
168− inTmpObInit = inTmpObInit' defaultTmpDirName
169−
170− -- To be used in tests that change the obelisk impl directory
171− inTmpObInitWithImplCopy f = inTmpObInit $ \dir ->
172− withObeliskImplClean $ \(fromString -> implClean) -> do
173− run_ rmPath [thunk]
174− run_ lnPath ["-s", implClean, thunk]
175− f dir
176−
177− assertRevEQ a b = liftIO . assertEqual "" "" =<< diff a b
178− assertRevNE a b = liftIO . assertBool "" . (/= "") =<< diff a b
179−
180− revParseHead = T.strip <$> run gitPath ["rev-parse", "HEAD"]
181−
182− commitAll = do
183− run_ gitPath ["add", "."]
184− commit "checkpoint"
185− revParseHead
186−
187− thunk = ".obelisk/impl"
188− update = runOb ["thunk", "update", thunk] >> commitAll
189− pack = runOb ["thunk", "pack", thunk] >> commitAll
190− unpack = runOb ["thunk", "unpack", thunk] >> commitAll
191−
192− diff a b = run gitPath ["diff", a, b]
193−
194− describe "ob init" $ parallel $ do
195− it "works with default impl" $ inTmp $ \_ -> runOb ["init"]
196− it "works with master branch impl" $ inTmp $ \_ -> runOb ["init", "--branch", "master"]
197− it "works with symlink" $ inTmp $ \_ -> runOb ["init", "--symlink", toTextIgnore obeliskImplDirty]
198− it "doesn't silently overwrite existing files" $ withSystemTempDirectory "ob-init λ" $ \dir -> do
199− let p force = (System.Process.proc ob $ "--no-handoff" : "-v" : "init" : ["--force"|force]) { cwd = Just dir }
200− (ExitSuccess, _, _) <- readCreateProcessWithExitCode (p False) ""
201− (ExitFailure _, _, _) <- readCreateProcessWithExitCode (p False) ""
202− (ExitSuccess, _, _) <- readCreateProcessWithExitCode (p True) ""
203− pure ()
204−
205− it "doesn't create anything when given an invalid impl" $ inTmp $ \tmp -> do
206− void $ errExit False $ runOb ["init", "--symlink", "/dev/null"]
207− ls tmp >>= liftIO . assertEqual "" []
208−
209− it "produces a valid route config" $ inTmpObInit $ \tmp -> liftIO $
210− withCurrentDirectory (T.unpack $ toTextIgnore tmp) $ do
211− configs <- getConfigs
212− return (either (const Nothing) Just $ getConfigRoute configs) `shouldNotReturn` Nothing
213−
214− -- These tests fail with "Could not find module 'Obelisk.Generated.Static'"
215− -- when not run by 'nix-build --attr selftest'
216− describe "ob run" $ {- NOT parallel $ -} do
217− it "works in root directory" $ inTmpObInit $ \_ -> testObRunInDir' Nothing httpManager
218− it "works in sub directory" $ inTmpObInit $ \_ -> testObRunInDir' (Just "frontend") httpManager
219−
220− describe "obelisk project" $ parallel $ do
221− it "can build obelisk command" $ inTmpObInit $ \_ -> nixBuild ["-A", "command" , toTextIgnore obeliskImplDirty]
222− it "can build obelisk skeleton" $ inTmpObInit $ \_ -> nixBuild ["-A", "skeleton", toTextIgnore obeliskImplDirty]
223− it "can build obelisk shell" $ inTmpObInit $ \_ -> nixBuild ["-A", "shell", toTextIgnore obeliskImplDirty]
224− it "can build everything" $ inTmpObInit $ \_ -> nixBuild [toTextIgnore obeliskImplDirty]
225−
226− describe "blank initialized project" $ parallel $ do
227−
228− it "can build ghc.backend" $ inTmpObInit $ \_ -> nixBuild ["-A", "ghc.backend"]
229− it "can build ghcjs.frontend" $ inTmpObInit $ \_ -> nixBuild ["-A", "ghcjs.frontend"]
230−
231− if System.Info.os == "darwin"
232− then it "can build ios" $ inTmpObInit $ \_ -> nixBuild ["-A", "ios.frontend"]
233− else it "can build android after accepting license" $ inTmpObInit $ \dir -> do
234− let defaultNixPath = dir </> ("default.nix" :: FilePath)
235− writefile defaultNixPath
236− =<< T.replace
237− "# config.android_sdk.accept_license = false;"
238− "config.android_sdk.accept_license = true;"
239− <$> readfile defaultNixPath
240− nixBuild ["-A", "android.frontend"]
241−
242− forM_ ["ghc", "ghcjs"] $ \compiler -> do
243− let
244− shellName = "shells." <> compiler
245− inShell cmd' = run_ "nix-shell" ["default.nix", "-A", fromString shellName, "--run", cmd']
246− it ("can enter " <> shellName) $ inTmpObInit $ \_ -> inShell "exit"
247− -- NOTE: We override the temporary directory name because cabal has a bug preventing new-build from working
248− -- in a path that has unicode characters.
249− it ("can build in " <> shellName) $ inTmpObInit' "test" $ \_ -> inShell $
250− T.pack cabalPath <> " --version; " <> T.pack cabalPath <> " new-build --" <> T.pack compiler <> " all"
251−
252− it "has idempotent thunk update" $ inTmpObInitWithImplCopy $ \_ -> do
253− _ <- pack
254− u <- update
255− uu <- update
256− assertRevEQ u uu
257−
258− describe "ob thunk pack/unpack" $ parallel $ do
259− it "has thunk pack and unpack inverses" $ inTmpObInitWithImplCopy $ \_ -> do
260−
261− _ <- pack
262− e <- commitAll
263− eu <- unpack
264− eup <- pack
265− eupu <- unpack
266− _ <- pack
267−
268− assertRevEQ e eup
269− assertRevEQ eu eupu
270− assertRevNE e eu
271−
272− it "unpacks the correct branch" $ withTmp $ \dir -> do
273− let branch = "master"
274− run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch]
275− runOb_ ["thunk", "pack", toTextIgnore dir]
276− runOb_ ["thunk", "unpack", toTextIgnore dir]
277− branch' <- chdir dir $ run gitPath ["rev-parse", "--abbrev-ref", "HEAD"]
278− liftIO $ assertEqual "" branch (T.strip branch')
279−
280− it "can pack and unpack plain git repos" $
281− shelly_ $ withSystemTempDirectory "git-repo" $ \dir -> do
282− let repo = toTextIgnore $ dir </> ("repo" :: String)
283− run_ gitPath ["clone", "https://github.com/haskell/process.git", repo]
284− origHash <- chdir (fromText repo) revParseHead
285−
286− runOb_ ["thunk", "pack", repo]
287− packedFiles <- Set.fromList <$> ls (fromText repo)
288− liftIO $ assertEqual "" packedFiles $ Set.fromList $ (repo </>) <$>
289− ["default.nix", "github.json", ".attr-cache" :: String]
290−
291− runOb_ ["thunk", "unpack", repo]
292− chdir (fromText repo) $ do
293− unpackHash <- revParseHead
294− assertRevEQ origHash unpackHash
295−
296− testThunkPack' $ fromText repo
297−
298− it "aborts thunk pack when there are uncommitted files" $ inTmpObInitWithImplCopy $ \dir -> do
299− testThunkPack' (dir </> thunk)
300−
301− describe "ob thunk update --branch" $ parallel $ do
302− it "can change a thunk to the latest version of a desired branch" $ withTmp $ \dir -> do
303− let branch1 = "master"
304− branch2 = "develop"
305− run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch1]
306− runOb_ ["thunk" , "pack", toTextIgnore dir]
307− runOb_ ["thunk", "update", toTextIgnore dir, "--branch", branch2]
308−
309− it "doesn't create anything when given an invalid branch" $ withTmp $ \dir -> do
310− let checkDir dir' = liftIO $ getDirectoryContents $ T.unpack $ toTextIgnore dir'
311− run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", "master"]
312− runOb_ ["thunk" , "pack", toTextIgnore dir]
313− startingContents <- checkDir dir
314− void $ errExit False $ runOb ["thunk", "update", toTextIgnore dir, "--branch", "dumble-palooza"]
315− checkDir dir >>= liftIO . assertEqual "" startingContents
316−
317− describe "ob hoogle" $ {- NOT parallel -} do
318− it "starts a hoogle server on the given port" $ inTmpObInit $ \_ -> do
319− [p0] <- liftIO $ getFreePorts 1
320− maskExitSuccess $ runHandle "ob" ["hoogle", "--port", T.pack (show p0)] $ \stdout -> fix $ \loop -> do
321− ln <- liftIO $ T.hGetLine stdout
322− echo ln
323− let search = "Server starting on port " <> T.pack (show p0)
324− case search `T.isInfixOf` ln of
325− False -> loop -- keep waiting
326− True -> do
327− let req uri = liftIO $ HTTP.parseRequest uri >>= flip HTTP.httpLbs httpManager
328− req ("http://127.0.0.1:" <> show p0) >>= \r -> case HTTP.responseStatus r == HTTP.ok200 of
329− False -> errorExit $ "Request to hoogle server failed: " <> T.pack (show r)
330− True -> exit 0
331
380
332maskExitSuccess :: Sh () -> Sh ()
381maskExitSuccess :: Sh () -> Sh ()
333maskExitSuccess = handle_sh (\case ExitSuccess -> pure (); e -> throw e)
382maskExitSuccess = handle_sh (\case ExitSuccess -> pure (); e -> throw e)
@@ -350,28 +399,31 @@ testObRunInDir executable extraArgs mdir httpManager = maskExitSuccess $ do
350 else exit 0
399 else exit 0
351
400
352testThunkPack :: String -> [Text] -> FilePath -> Sh ()
401testThunkPack :: String -> [Text] -> FilePath -> Sh ()
353−testThunkPack executable args path' = withTempFile (T.unpack $ toTextIgnore path') "test-file" $ \file handle -> do
402+testThunkPack executable args path' = withTempFile repoDir "test-file" $ \file handle -> do
403+ let
354− let pack' = readProcessWithExitCode executable (T.unpack <$> ["thunk", "pack", toTextIgnore path'] ++ args) ""
404+ pack' = readProcessWithExitCode executable (["thunk", "pack", path'] ++ map T.unpack args) ""
355− ensureThunkPackFails q = liftIO $ pack' >>= \case
405+ ensureThunkPackFails q = liftIO $ pack' >>= \case
356− (code, out, err)
406+ (code, out, err)
357− | code == ExitSuccess -> fail $ "ob thunk pack succeeded when it should have failed with error '" <> show q <> "'"
407+ | code == ExitSuccess -> fail $ "ob thunk pack succeeded when it should have failed with error '" <> show q <> "'"
358− | q `T.isInfixOf` T.pack (out <> err) -> pure ()
408+ | q `T.isInfixOf` T.pack (out <> err) -> pure ()
359− | otherwise -> fail $ "ob thunk pack failed for an unexpected reason, expecting '" <> show q <> "', received: " <> show out <> "\nstderr: " <> err
409+ | otherwise -> fail $ "ob thunk pack failed for an unexpected reason, expecting '" <> show q <> "', received: " <> show out <> "\nstderr: " <> err
360− git = chdir path' . run gitPath
410+ git = chdir repoDir . run_ gitPath
361 -- Untracked files
411 -- Untracked files
362 ensureThunkPackFails "Untracked files"
412 ensureThunkPackFails "Untracked files"
363− void $ git ["add", T.pack file]
413+ git ["add", T.pack file]
364 -- Uncommitted files (staged)
414 -- Uncommitted files (staged)
365 ensureThunkPackFails "unsaved"
415 ensureThunkPackFails "unsaved"
366− chdir path' $ commit "test commit"
416+ chdir repoDir $ commit "test commit"
367 -- Non-pushed commits in any branch
417 -- Non-pushed commits in any branch
368 ensureThunkPackFails "not yet pushed"
418 ensureThunkPackFails "not yet pushed"
369 -- Uncommitted files (unstaged)
419 -- Uncommitted files (unstaged)
370 liftIO $ T.hPutStrLn handle "test file" >> hClose handle
420 liftIO $ T.hPutStrLn handle "test file" >> hClose handle
371 ensureThunkPackFails "modified"
421 ensureThunkPackFails "modified"
372 -- Existing stashes
422 -- Existing stashes
373− void $ git $ gitUserConfig <> [ "stash" ]
423+ git $ gitUserConfig <> [ "stash" ]
374 ensureThunkPackFails "has stashes"
424 ensureThunkPackFails "has stashes"
425+ where
426+ repoDir = path' </> unpackedDirName
375
427
376-- | Blocks until a non-empty line is available
428-- | Blocks until a non-empty line is available
377hGetLineSkipBlanks :: MonadIO m => Handle -> m Text
429hGetLineSkipBlanks :: MonadIO m => Handle -> m Text
@@ -432,3 +484,121 @@ getFreePorts n = Socket.withSocketsDo $ do
432 sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
484 sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
433 Socket.bind sock (Socket.addrAddress addr)
485 Socket.bind sock (Socket.addrAddress addr)
434 pure sock
486 pure sock
487+
488+testLegacyGitThunks :: Bool -> IO ()
489+testLegacyGitThunks isVerbose = withSystemTempDirectory "test-git-repo" $ \gitDir -> do
490+ isolatedGitShell isVerbose gitDir $ \git -> do
491+ writefile (gitDir </> ("default.nix" :: FilePath)) "{}: \"hello\""
492+ _ <- git ["add", "--all"]
493+ _ <- git ["commit", "-m", "Initial commit"]
494+ rev <- T.strip <$> git ["rev-parse", "HEAD"]
495+ sha256 :: Text
496+ <- either error pure
497+ =<< (Aeson.parseEither (Aeson..: "sha256") <=< Aeson.eitherDecodeStrict . T.encodeUtf8)
498+ <$> run nixPrefetchGitPath [toTextIgnore gitDir]
499+
500+ for_ (legacyGitThunks (GitThunkParams gitDir rev sha256)) $ \mkFiles ->
501+ withSystemTempDirectory "test-thunks" $ \thunkDir -> do
502+ liftIO $ mkFiles thunkDir
503+ run_ "ob" ["thunk", "unpack", toTextIgnore thunkDir]
504+ run_ "ob" ["thunk", "pack", toTextIgnore thunkDir]
505+
506+data GitThunkParams = GitThunkParams
507+ { _gitThunkParams_repo :: !FilePath
508+ , _gitThunkParams_rev :: !Text
509+ , _gitThunkParams_sha256 :: !Text
510+ } deriving Show
511+
512+legacyGitThunks :: GitThunkParams -> [FilePath -> IO ()]
513+legacyGitThunks (GitThunkParams repo' rev sha256) =
514+ [ mkLegacyIO
515+ (T.unlines
516+ [ "# DO NOT HAND-EDIT THIS FILE"
517+ , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
518+ , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
519+ , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
520+ ]
521+ )
522+ (Map.fromList
523+ [ ("url", repo)
524+ , ("rev", rev)
525+ , ("branch", "master")
526+ , ("sha256", sha256)
527+ ]
528+ )
529+ , mkLegacyIO
530+ (T.unlines
531+ [ "# DO NOT HAND-EDIT THIS FILE"
532+ , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
533+ , " if builtins.hasAttr \"fetchGit\" builtins"
534+ , " then builtins.fetchGit ({ inherit url rev; } // (if branch == null then {} else { ref = branch; }))"
535+ , " else abort \"Plain Git repositories are only supported on nix 2.0 or higher.\";"
536+ , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
537+ ]
538+ )
539+ (Map.fromList
540+ [ ("url", repo)
541+ , ("rev", rev)
542+ , ("branch", "master")
543+ , ("sha256", sha256)
544+ ]
545+ )
546+ , mkLegacyIO
547+ (T.unlines
548+ [ "# DO NOT HAND-EDIT THIS FILE"
549+ , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
550+ , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
551+ , " if firstChar == \"/\" then /. + url"
552+ , " else if firstChar == \".\" then ./. + url"
553+ , " else url;"
554+ , " in if !fetchSubmodules && private then builtins.fetchGit {"
555+ , " url = realUrl; inherit rev;"
556+ , " } else (import <nixpkgs> {}).fetchgit {"
557+ , " url = realUrl; inherit rev sha256;"
558+ , " };"
559+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
560+ ]
561+ )
562+ (Map.fromList
563+ [ ("url", Aeson.String repo)
564+ , ("rev", Aeson.String rev)
565+ , ("branch", Aeson.String "master")
566+ , ("sha256", Aeson.String sha256)
567+ , ("private", Aeson.Bool False)
568+ ]
569+ )
570+ , mkLegacyIO
571+ (T.unlines
572+ [ "# DO NOT HAND-EDIT THIS FILE"
573+ , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
574+ , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
575+ , " if firstChar == \"/\" then /. + url"
576+ , " else if firstChar == \".\" then ./. + url"
577+ , " else url;"
578+ , " in if !fetchSubmodules && private then builtins.fetchGit {"
579+ , " url = realUrl; inherit rev;"
580+ , " ${if branch == null then null else \"ref\"} = branch;"
581+ , " } else (import <nixpkgs> {}).fetchgit {"
582+ , " url = realUrl; inherit rev sha256;"
583+ , " };"
584+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
585+ ]
586+ )
587+ (Map.fromList
588+ [ ("url", Aeson.String repo)
589+ , ("rev", Aeson.String rev)
590+ , ("branch", Aeson.String "master")
591+ , ("sha256", Aeson.String sha256)
592+ , ("private", Aeson.Bool False)
593+ ]
594+ )
595+ ]
596+ where
597+ repo = T.pack repo'
598+ mkLegacyIO :: Aeson.ToJSON v => Text -> Map.Map Text v -> FilePath -> IO ()
599+ mkLegacyIO defaultNix gitJson dir = do
600+ T.writeFile (dir </> ("default.nix" :: FilePath)) defaultNix
601+ LBS.writeFile (dir </> ("git.json" :: FilePath)) (Aeson.encode gitJson)
602+
603+unpackedDirName :: FilePath
604+unpackedDirName = "."
nixpkgs-overlays/default.nixnew file+15
@@ -0,0 +1,15 @@
1+self: super:
2+
3+let
4+ inherit (self) lib;
5+ inherit (import ../dep/gitignore.nix { inherit lib; }) gitignoreSource;
6+in {
7+ obeliskCleanSource = src:
8+ # WARNING: The order of application here seems to matter a great deal to
9+ # how quickly `ghcid` is able to reload changes. As a rule of thumb,
10+ # always apply `gitignoreSource` first.
11+ # See https://github.com/obsidiansystems/obelisk/pull/666 and related.
12+ lib.cleanSource (gitignoreSource src);
13+
14+ obeliskExecutableConfig = self.callPackage ../lib/executable-config {};
15+}