on master help sign in
.gitattributesnew file+1
since splitsnapshots
unifiedsplit
@@ -0,0 +1 @@
1+migration/* linguist-vendored linguist-generated=true
.github/pull_request_template.mdnew file+10
@@ -0,0 +1,10 @@
1+<!-- Provide a clear overview of your changes. -->
2+
3+I have:
4+
5+ - [ ] Based work on latest `develop` branch
6+ - [ ] Followed the [contribution guide](https://github.com/obsidiansystems/obelisk/blob/develop/CONTRIBUTING.md#submitting-changes)
7+ - [ ] Looked for lint in my changes with `hlint .` (lint found code you did not write can be left alone)
8+ - [ ] Run the test suite: `$(nix-build -A selftest --no-out-link)`
9+ - [ ] [Updated the changelog](https://github.com/obsidiansystems/obelisk/blob/develop/CONTRIBUTING.md#in-the-changelog)
10+ - [ ] (Optional) Run CI tests locally: `nix-build release.nix -A build.x86_64-linux --no-out-link` (or `x86_64-darwin` on macOS)
.gitignore+3−2
@@ -2,12 +2,13 @@
2**/.cabal-sandbox
2**/.cabal-sandbox
3**/cabal.sandbox.config
3**/cabal.sandbox.config
4result
4result
5+result-*
5*.o
6*.o
6*.hi
7*.hi
7−
8TAGS
8TAGS
9tags
9tags
10ctags
10ctags
11dist-newstyle
11dist-newstyle
12cabal.project.local
12cabal.project.local
13−.ghc.environment.*
13+.ghc.environment.*
14+**/ghcid-output.txt
.hlint.yamlnew file+65
@@ -0,0 +1,65 @@
1+# HLint configuration file
2+# https://github.com/ndmitchell/hlint
3+##########################
4+
5+# This file contains a template configuration file, which is typically
6+# placed as .hlint.yaml in the root of your project
7+
8+
9+# Specify additional command line arguments
10+#
11+# - arguments: [--color, --cpp-simple, -XQuasiQuotes]
12+
13+
14+# Control which extensions/flags/modules/functions can be used
15+#
16+# - extensions:
17+# - default: false # all extension are banned by default
18+# - name: [PatternGuards, ViewPatterns] # only these listed extensions can be used
19+# - {name: CPP, within: CrossPlatform} # CPP can only be used in a given module
20+#
21+# - flags:
22+# - {name: -w, within: []} # -w is allowed nowhere
23+#
24+# - modules:
25+# - {name: [Data.Set, Data.HashSet], as: Set} # if you import Data.Set qualified, it must be as 'Set'
26+# - {name: Control.Arrow, within: []} # Certain modules are banned entirely
27+#
28+# - functions:
29+# - {name: unsafePerformIO, within: []} # unsafePerformIO can only appear in no modules
30+
31+
32+# Add custom hints for this project
33+#
34+# Will suggest replacing "wibbleMany [myvar]" with "wibbleOne myvar"
35+# - error: {lhs: "wibbleMany [x]", rhs: wibbleOne x}
36+
37+
38+# Turn on hints that are off by default
39+#
40+# Ban "module X(module X) where", to require a real export list
41+# - warn: {name: Use explicit module export list}
42+#
43+# Replace a $ b $ c with a . b $ c
44+# - group: {name: dollar, enabled: true}
45+#
46+# Generalise map to fmap, ++ to <>
47+# - group: {name: generalise, enabled: true}
48+
49+
50+# Ignore some builtin hints
51+- ignore: {name: Redundant do}
52+- ignore: {name: Redundant flip}
53+- ignore: {name: Use <$>}
54+- ignore: {name: Use camelCase}
55+- ignore: {name: Use if}
56+- ignore: {name: Use unless}
57+# - ignore: {name: Use const, within: SpecialModule} # Only within certain modules
58+
59+
60+# Define some custom infix operators
61+# - fixity: infixr 3 ~^#^~
62+
63+
64+# To generate a suitable file for HLint do:
65+# $ hlint --default > .hlint.yaml
CONTRIBUTING.md+125−3
@@ -1,9 +1,131 @@
1−## Contributing to Obelisk
1+# Contribution Guide
2
2
3−Thanks for taking the time to contribute!
3+Contributions and issue reports are encouraged and appreciated!
4
4
5−Before submitting a pull request, please run the tests:
5+- [Opening Issues](#opening-issues)
6+- [Submitting Changes](#submitting-changes)
7+ - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
8+ - [Guidelines for Pull Requests](#guidelines-for-pull-requests)
9+ - [Code Quality](#code-quality)
10+ - [Documentation](#documentation)
11+- [Development Environment](#development-environment)
6
12
13+## Opening Issues
14+
15+Before opening an issue, please check whether your issue has already been reported. Assuming it has not:
16+
17+* Describe the issue you're encountering or the suggestion you're making
18+* Include any relevant steps to reproduce or code samples you can. It's always easier for us to debug if we have something that demonstrates the error.
19+* Let us know what version of this project you were using. If you're using a github checkout, provide the git hash.
20+
21+## Submitting Changes
22+
23+Most pull requests should target the `develop` branch. `master` is the release branch. `develop` is periodically merged into master after a period of testing.
24+
25+### Guidelines for Commit Messages
26+
27+#### Summary Line
28+The summary line of your commit message should summarize the changes being made. Commit messages should be written in the imperative mood and should describe what happens when the commit is applied. If your commit modifies one of the in-tree haskell packages (found in `./lib`), please prefix your commit summary with the name of the package being modified.
29+
30+One way to think about it is that your commit message should be able to complete the sentence:
31+"When applied, this commit will..."
32+
33+##### Note on bumping dependencies
34+Commits that update a dependency should include some information about why the dependency was updated in the commit message.
35+
36+#### Body
37+For breaking changes, new features, refactors, or other major changes, the body of the commit message should describe the motivation behind the change in greater detail and may include references to the issue tracker. The body shouldn't repeat code/comments from the diff.
38+
39+### Guidelines for Pull Requests
40+
41+Wherever possible, pull requests should add a single feature or fix a single bug. Pull requests should not bundle several unrelated changes.
42+
43+
44+### Code Quality
45+
46+#### Warnings
47+
48+Your pull request should add no new warnings to the project. It should also generally not disable any warnings.
49+
50+#### Build and Test
51+
52+Make sure the project builds and that the tests pass! This will generally also be checked by CI before merge, but trying it yourself first means you'll catch problems earlier and your contribution can be merged that much sooner!
53+
54+You can run the tests like this:
7```bash
55```bash
8$(nix-build -A selftest --no-out-link)
56$(nix-build -A selftest --no-out-link)
9```
57```
58+
59+To test that your changes build across platforms, you can also try to build release.nix, like this:
60+```bash
61+nix-build release.nix
62+```
63+
64+Note, however, that to build release.nix you must accept the android license agreement and your machine must be configured to build both ios and android executables (usually via remote builders).
65+
66+
67+### Documentation
68+
69+#### In the code
70+We're always striving to improve documentation. Please include [haddock](https://haskell-haddock.readthedocs.io/en/latest/index.html) documentation for any added code, and update the documentation for any code you modify.
71+
72+#### In the [Changelog](ChangeLog.md)
73+Add an entry to the changelog when your PR:
74+* Adds a feature
75+* Deprecates something
76+* Includes a breaking change
77+* Makes any other change that will impact users
78+
79+#### In the [Readme](README.md)
80+The readme is the first place a lot of people look for information about the repository. Update any parts of the readme that are affected by your PR.
81+
82+
83+## Development Environment
84+
85+There are two ways to get live compiler feedback while developing Obelisk libraries. For libraries that are dependencies of the `skeleton` application, the easiest way to get feedback is to
86+
87+```bash
88+cd skeleton
89+ob run
90+```
91+
92+This `ob run` session only loads modules that are dependencies of the skeleton and `obelisk-run`. For example, `obelisk-asset` and `obelisk-route` are used by the skeleton.
93+
94+For other libraries like `obelisk-command` you can use `ghcid`. To launch `ghcid` for `lib/command` you can run
95+
96+```bash
97+nix-shell -A obeliskEnvs.obelisk-command --run "cd lib/command && ghcid"
98+```
99+
100+### Building `ob` for testing
101+
102+To re-install `ob` from source globally you can do
103+
104+```bash
105+nix-env -f /path/to/obelisk -iA command
106+```
107+
108+You can also open a shell with the local version of `ob` available on your `$PATH`:
109+
110+```bash
111+nix run -f /path/to/obelisk command
112+```
113+
114+### Hacking on Obelisk from within an Obelisk project
115+
116+`ob` will defer to the version found in your project's `.obelisk/impl` directory. To work on that version specifically:
117+
118+```bash
119+ob thunk unpack ./.obelisk/impl
120+cd ./.obelisk/impl
121+# apply your changes
122+```
123+
124+If you want to commit your changes, first push them to your fork of obelisk and then
125+
126+```bash
127+cd /your/project/root
128+ob thunk pack .obelisk/impl
129+git add .obelisk/impl
130+git commit -m "Bump obelisk"
131+```
ChangeLog.mdnew file+156
@@ -0,0 +1,156 @@
1+# Revision history for obelisk
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.
4+
5+## v0.9.1.0
6+
7+* [#801](https://github.com/obsidiansystems/obelisk/pull/801): Remove errors and warning for local packages without a library component
8+* [#812](https://github.com/obsidiansystems/obelisk/pull/812): Add support for `NoImplicitPrelude` and other extensions disabled via `No`
9+* Pinned version bumps:
10+ * reflex-platform [0.7.0.0](https://github.com/reflex-frp/reflex-platform/releases/tag/v0.7.0.0)
11+ * hnix 0.8.0
12+* [#787](https://github.com/obsidiansystems/obelisk/pull/787): Set `immutable` cache control directive when serving content-addressed static assets
13+* Use iOS SDK 13.2
14+
15+
16+## v0.9.0.1
17+
18+* ([#810](https://github.com/obsidiansystems/obelisk/pull/810)) Fix loading of `all.js` in fully compiled web apps.
19+
20+## v0.9.0.0
21+
22+* **(Breaking change)** Backport nixpkgs upgrades to ACME/Let's Encrypt handling so that HTTPS deployments continue to work flawlessly. If your deployment is having trouble renewing [Let's Encrypt](https://letsencrypt.org/) certificates, upgrade to this version.
23+ * **IMPORTANT:** In order to use [Let's Encrypt](https://letsencrypt.org/) you must now accept their [terms of service](https://letsencrypt.org/repository/). To do that, add `terms.security.acme.acceptTerms = true;` to the `import ./.obelisk/impl {` section in your `default.nix`. The new skeleton application may serve as an [example](https://github.com/obsidiansystems/obelisk/blob/4759342ab3570888c027d4c58cb5694cb832d624/skeleton/default.nix#L13).
24+* Update reflex-platform dependency to v0.6.0.0
25+* ([#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`.
26+* ([#739](https://github.com/obsidiansystems/obelisk/pull/739)) Improve `ob shell` by allowing commands to be passed verbatim after a `--` argument. For example, `ob shell 'run command'` can now be written `ob shell -- run command`.
27+* ([#735](https://github.com/obsidiansystems/obelisk/pull/735)) Fix regression causing custom `Prelude`s to break `ob run`/`ob watch`/`ob repl`.
28+* ([#737](https://github.com/obsidiansystems/obelisk/pull/737)) Fix bug causing custom `Prelude`s to break `ob profile`.
29+* ([#752](https://github.com/obsidiansystems/obelisk/pull/752)) Fix the `ob` command-line tool to return non-zero exit code when underlying processes fail.
30+* ([#742](https://github.com/obsidiansystems/obelisk/pull/742), [#57](https://github.com/obsidiansystems/obelisk/pull/57), [#406](https://github.com/obsidiansystems/obelisk/pull/406)) Enable `-dedupe` and `-DGHCJS_BROWSER` in GHCJS builds to make JavaScript output considerably smaller leading to faster load/parse times and faster build times.
31+ * **Migration:** New Obelisk projects will automatically benefit from this change, but existing projects need to apply a change similar to [this one](https://github.com/obsidiansystems/obelisk/blob/371cb3302085601c5ec73e9574d51c8b95e3e493/skeleton/frontend/frontend.cabal#L32-L34).
32+* ([#742](https://github.com/obsidiansystems/obelisk/pull/742)) Update `reflex-platform` which includes:
33+ * A new version of GHCJS where `-dedupe` is fixed.
34+
35+## v0.8.0.0
36+
37+* ([#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 thin wrapper around that.
38+* ([#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.
39+
40+ **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.
41+* ([#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.
42+* ([#705](https://github.com/obsidiansystems/obelisk/pull/705)) Add `Obelisk.Route.packTextEncoder` and generalize `Obelisk.Route.unpackTextEncoder` over any `Data.Text.Lens.IsText`.
43+* ([#712](https://github.com/obsidiansystems/obelisk/pull/712)) Update [`reflex-platform`](https://github.com/reflex-frp/reflex-platform) to version 0.5.3.0.
44+* ([#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 its own `.obelisk/impl`.
45+* ([#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`.
46+* ([#709](https://github.com/obsidiansystems/obelisk/pull/709)) Fix a bug in obelisk's preprocessor causing it to incorrectly skip files in some circumstances.
47+* ([#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.
48+* ([#714](https://github.com/obsidiansystems/obelisk/pull/714)) Miscellaneous improvements to CLI help and logging.
49+
50+## v0.7.0.1
51+
52+* Fix the version number for `ob` the command-line tool. ([#679](https://github.com/obsidiansystems/obelisk/pull/679))
53+
54+## v0.7.0.0
55+
56+* 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))
57+* Support non-EC2 deployments. ([#658](https://github.com/obsidiansystems/obelisk/pull/658))
58+* Fix `ob deploy test android` to work. ([#645](https://github.com/obsidiansystems/obelisk/pull/645))
59+* 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.)
60+* Add `Obelisk.Backend.runBackendWith` to allow several customizations. ([#668](https://github.com/obsidiansystems/obelisk/pull/668), [#644](https://github.com/obsidiansystems/obelisk/pull/644))
61+* 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))
62+* 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))
63+* Bump reflex-platform to v0.5.2.0. ([#671](https://github.com/obsidiansystems/obelisk/pull/671))
64+
65+## v0.6.0.0 - 2020-02-21
66+
67+* Fix a bug in `Obelisk.Route.Frontend` where `routeLink`, `routeLinkDynAttr`, and `dynRouteLink` would not behave exactly like `<a href="...">` when run by JavaScript. These functions now scroll to the top of the page when the link is clicked. ([#540](https://github.com/obsidiansystems/obelisk/pull/540))
68+* Fix a bug in `ob run`/`ob watch`/`ob repl` where nested Obelisk projects would also be loaded into the session. These are now ignored. ([#652](https://github.com/obsidiansystems/obelisk/pull/652))
69+* Improve behavior of `ob run`/`ob watch`/`ob repl` when multiple packages with the same name are encountered. Obelisk now issues a warning and tells you which one it will use. ([#653](https://github.com/obsidiansystems/obelisk/pull/653))
70+* Removed `Obelisk.Backend.mkRouteToUrl` since it is easily written in terms of `Obelisk.Route.renderObeliskRoute`:
71+
72+ mkRouteToUrl validFullEncoder (k :/ v) = renderObeliskRoute validFullEncoder (FullRoute_Frontend (ObeliskRoute_App k) :/ v)
73+
74+* Add `Obelisk.Backend.renderAllJsPath` to expose URL path to `ghcjs/all.js`. ([#545](https://github.com/obsidiansystems/obelisk/pull/545))
75+* Add argument to `serveDefaultObeliskApp`, `serveObeliskApp`, and `serveGhcjsApp` to take the path to `all.js` instead of hard-coding it. ([#545](https://github.com/obsidiansystems/obelisk/pull/545))
76+
77+## v0.5.0.0 - 2020-02-07
78+
79+* Add `Obelisk.Route.(?/)`, a convenience function for constructing routes nested in `Maybe`. ([#457](https://github.com/obsidiansystems/obelisk/pull/457))
80+* Add local unpacked packages to the `ob run`, `ob watch`, and `ob repl` sessions. Any `.cabal` or hpack package inside the current obelisk project will be loaded into the session. For `ob run`/`ob watch` this means the session will automatically reload when you save a source file in any of those packages. For `ob repl` it means that `:r` will reload changes to any of those packages. There are some edge cases where this integration is still rough. Report any issues you encounter. ([#489](https://github.com/obsidiansystems/obelisk/pull/489))
81+* Add `ob hoogle` command to start a local [Hoogle](https://hoogle.haskell.org/) server for the project. ([#628](https://github.com/obsidiansystems/obelisk/pull/628))
82+* `ob thunk pack` will now attempt to automatically detect if the thunk is a private or public repo. To avoid this detection, specify `--private` or `--public` manually. ([#607](https://github.com/obsidiansystems/obelisk/pull/607))
83+* Fix a bug in the plain git thunk loader for thunks marked as 'private' when the revision is not in the default branch. ([#648](https://github.com/obsidiansystems/obelisk/pull/648))
84+* Improve handling of runtime nix dependencies. This may fix some issues encountered particularly by users on systems other than NixOS.
85+
86+## v0.4.0.0 - 2020-01-10
87+
88+* Bump reflex-platform which, notably, bumps nixpkgs to 19.09. ([#585](https://github.com/obsidiansystems/obelisk/pull/585))
89+* Add new thunk loader for Git repositories that supports `file://` Git remotes and supports private repositories via `builtins.fetchGit` for private repositories (when the `git.json` file specifies `"private": true`). ([#594](https://github.com/obsidiansystems/obelisk/pull/594))
90+* Add a new thunk loader for GitHub repositories that uses `builtins.fetchTarball` for public repositories to increase loader performance and uses `fetchFromGitHub` for private repositories (when the `github.json` file specifies `"private": true`). Note that `fetchFromGitHub` requires some Nix configuration for the Nix builder to access the repository. If `ob thunk pack` fails in this case, use `-v` to see Nix's helpful message. ([#594](https://github.com/obsidiansystems/obelisk/pull/594))
91+* Add `--public`/`--private` options to `ob thunk pack` to specify if a repository should be treated as a public or private. ([#594](https://github.com/obsidiansystems/obelisk/pull/594))
92+* Improve error messaging when a dependency doesn't have the expected `.cabal` or `package.yaml` file. ([#597](https://github.com/obsidiansystems/obelisk/pull/597))
93+* Improve the skeleton in small ways. ([#593](https://github.com/obsidiansystems/obelisk/pull/593), [#589](https://github.com/obsidiansystems/obelisk/pull/589))
94+* Fix `ob` commands to again support running from any subdirectory of an obelisk project ([#591](https://github.com/obsidiansystems/obelisk/pull/591))
95+* Add `reflex-platform-func` argument to Obelisk's `default.nix`. It defaults to its prior behavior of using the reflex-platform in in `dep`. ([#612](https://github.com/obsidiansystems/obelisk/pull/612))
96+
97+## v0.3.0.0 - 2019-12-20
98+
99+* Change the structure of Obelisk routes to use a designated
100+ `FullRoute` type. This combines frontend and backend routes into one
101+ structure. This is a **breaking** change which requires Obelisk apps
102+ to take specific migrations. They are:
103+ * Rewrite the implementation of `_backend_routeEncoder` in
104+ `Backend` to use `mkFullRouteEncoder` instead of
105+ `handleEncoder`. Specifically, the backend and frontend cases of
106+ the top-level `pathComponentEncoder` become the second and third
107+ arguments of `mkFullRouteEncoder` respectively, while the
108+ missing route becomes the first argument. An example of how to
109+ do this is available in [a reflex-examples
110+ commit](https://github.com/reflex-frp/reflex-examples/commits/28f566c3e7dc615578dc74297b7c620c1f13683e).
111+ * Replace type constructions of `InL` with `FullRoute_Backend` and
112+ `InR` with `FullRoute_Frontend`.
113+* Generalised `pathSegmentEncoder`, added `pathFieldEncoder`.
114+* Added some `Prism`s to the encoder library for manipulating `DSum`s.
115+* Add `ob doc` command, which lists paths to haddock documentation for specified packages.
116+* Bump reflex-platform so that obelisk now uses GHC 8.6.5 and the nixos-19.03 nixpkgs set.
117+* Add support in `obelisk-route` for single parameters in URL paths.
118+* Bump reflex-platform so that obelisk now uses reflex-dom 0.5.2.0.
119+* Use a `--pure` nix shell in `ob run` for parity with `ob repl` and more resilience against "works on my machine".
120+* Pin usages of `<nixpkgs>` in obelisk thunks, etc. to the nixpkgs used by the project's obelisk impl.
121+* Backport ACMEv2 support in obelisk server to regain LetsEncrypt account creation.
122+* Enable HTTPS in `ob run`.
123+* `ob run` now handles `ghci` errors better, and includes a custom `ghcid`
124+ version. As a result, you no longer need to have ghcid installed to
125+ use `ob run`, as we provide one for you.
126+* `ob` commands now complain less on systems with umasks other than `0022`.
127+* Ignore package environment files in `ob run` and `ob repl`.
128+* Add `Obelisk.Route.Frontend.routeLinkDynAttr`.
129+
130+## v0.2.0.0 - 2019-8-17
131+
132+* Configs become ByteStrings.
133+* FrontendConfigsT has been changed into ConfigsT and configs are made available via getConfig/getConfigs
134+ * The frontend will still only have access to configs that are placed in config/frontend and config/common, while the backend has access to the entire contents of the config directory via `Obelisk.ExecutableConfig.Lookup.getConfigs`.
135+* The backend no longer runs in BackendConfigsT.
136+* Add tabulation package. See Data.Tabulation for details.
137+* Add encoders for `DMap`, `HasFields` (cf. Data.Tabulation), and JSON.
138+* Use IP address for nginx proxy pass instead of localhost
139+
140+## v0.1.1.0 - 2019-05-17
141+
142+* Fix crashes of Android apps on 32-bit ARM devices.
143+* Provide a way to indicate acceptance of the Android SDK license by passing `config.android_sdk.accept_license = true;` in the arguments to the import of `.obelisk/impl` in the project's `default.nix`.
144+* Add `COMPLETE` pragma to `(:/)`. Using this pattern synonym should no longer generate spurious warnings about non-exhaustive pattern matching.
145+* Make asset path hashing strict (see `Obelisk.Asset.Gather`)
146+* Add the `ob shell` command to enter a nix shell for an obelisk project
147+* Allow skeleton's obelisk to be overridden. This changes the skeleton's default.nix interface: the arguments that it used to take are now part of the new "obelisk" argument.
148+* Removed `MonadIO` from `ObeliskWidget` to prevent accidental IO during prerendering. If you need to do IO in a widget it should be on the right hand side of a `prerender`.
149+* Significantly changed the interface to the "executable config" packages. `obelisk-executable-config-lookup` is a new internal package which looks up all configs in a platform-specific way. `obelisk-executable-frontend` and `obelisk-executable-backend` provide MTL-style monad classes (`HasFrontendConfigs` and `HasBackendConfigs`) which the frontend and backend, respectively, can use to look up configs. This replaces the old `get` function which ran in `IO`.
150+* Add a flag to force thunk packing even if there are unpushed changes in the unpacked thunk.
151+
152+
153+## v0.1.0.0 - 2019-03-29
154+
155+* Use reflex-dom's `HydrationDomBuilder` to "hydrate" statically rendered DOM served by the Obelisk backend (rather than re-creating DOM and replacing it all).
156+* Add `HasCookies` and `CookiesT` to allow `ObeliskWidget`s to access cookies during static and "hydrated" DOM rendering.
FAQ.mdnew file+117
@@ -0,0 +1,117 @@
1+# Frequently Asked Questions
2+
3+1. [How do I declare a new Haskell dependency?](#how-do-i-declare-a-new-haskell-dependency)
4+1. [How do I add or override Haskell dependencies in the package set?](#how-do-i-add-or-override-haskell-dependencies-in-the-package-set)
5+1. [How do I extend my Obelisk application with more local packages?](#how-do-i-extend-my-obelisk-application-with-more-local-packages)
6+1. [How do I use `ob run` over HTTPS?](#how-do-i-use-ob-run-over-https)
7+1. [How do I fix invalid entitlements?](#how-do-i-fix-invalid-entitlements)
8+1. [`ob thunk update` or `ob deploy update` fails](#ob-thunk-update-or-ob-deploy-update-fails)
9+1. [How do I fix `Ambiguous module name` errors?](#how-do-i-fix-ambiguous-module-name-errors)
10+
11+### How do I declare a new Haskell dependency?
12+
13+Every component of your Obelisk application is a standard [cabal](https://www.haskell.org/cabal/) package. That means declaring new Haskell dependencies simply involves updating the `build-depends` field in the appropriate cabal file (`backend.cabal` for example). By default, Obelisk will use its curated package set to choose which version of each package you get. It's possible that the package you need is not already in the curated set or the curated version isn't the one you want. See [How do I add or override Haskell dependencies in the package set?](#how-do-i-add-or-override-haskell-dependencies-in-the-package-set) for a solution to this.
14+
15+### How do I add or override Haskell dependencies in the package set?
16+
17+To add a Haskell package that doesn't exist in Obelisk's package set or to override the version of a package, use the `overrides` attribute in your project's `default.nix`. For example, to use a specific version of the `aeson` package fetched from GitHub and a specific version of the `waargonaut` package fetched from Hackage, your `default.nix` will look like:
18+
19+```nix
20+# ...
21+project ./. ({ pkgs, ... }: {
22+# ...
23+ overrides = self: super: let
24+ aesonSrc = pkgs.fetchFromGitHub {
25+ owner = "obsidiansystems";
26+ repo = "aeson-gadt-th";
27+ rev = "ed573c2cccf54d72aa6279026752a3fecf9c1383";
28+ sha256 = "08q6rnz7w9pn76jkrafig6f50yd0f77z48rk2z5iyyl2jbhcbhx3";
29+ };
30+ in
31+ {
32+ aeson = self.callCabal2nix "aeson" aesonSrc {};
33+ waargonaut = self.callHackageDirect {
34+ pkg = "waargonaut";
35+ ver = "0.8.0.1";
36+ sha256 = "1zv28np3k3hg378vqm89v802xr0g8cwk7gy3mr77xrzy5jbgpa39";
37+ } {};
38+ };
39+# ...
40+```
41+
42+For further information see [the Haskell section](https://nixos.org/nixpkgs/manual/#users-guide-to-the-haskell-infrastructure) of nixpkgs "Contributors Guide".
43+
44+### How do I extend my Obelisk application with more local packages?
45+
46+If the standard packages (`frontend`, `backend`, and `common`) are not enough, you may add more local packages by defining them with the `packages` attribute in your `default.nix`. The sources of these packages will be automatically loaded by `ob run`/`ob repl`/etc.
47+
48+```nix
49+# ...
50+project ./. ({ pkgs, ... }: {
51+# ...
52+ packages = {
53+ another = ./dep/another;
54+ };
55+# ...
56+```
57+
58+### How do I use `ob run` over HTTPS?
59+
60+To run your app locally over HTTPS, update the protocol in `config/common/route` to `https`, and then use `ob run` as normal.
61+
62+Obelisk generates a self-signed certificate for running HTTPS so 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.
63+
64+
65+### How do I fix invalid entitlements?
66+
67+You probably did not set `ios.bundleIdentifier` correctly in `default.nix`. When this happens you'll see an error something like this:
68+
69+```
70+2018-11-25 09:34:22.438 ios-deploy[58106:8521046] [ !! ] Error 0xe8008016: The executable was signed with invalid entitlements. AMDeviceSecureInstallApplication(0, device, url, options, install_callback, 0)
71+```
72+
73+Fixing the value of `ios.bundleIdentifier` should fix the error.
74+
75+### `ob thunk update` or `ob deploy update` fails
76+Whenever an `ob` command fails, try re-running it with `-v`.
77+
78+If you're using a private repo, and you get a failure in `nix-prefetch-url`, you may need to unpack and repack the thunk. Here's some example output that shows this issue:
79+
80+```
81+Starting Obelisk </nix/store/j8wls8a89xr6s1a47lg6g83gnbdrfd0l-obelisk-command-0.1/bin/.ob-wrapped> args=["deploy","update","-v"] logging-level=Debug
82+Creating process: 'nix-build' './.obelisk/impl' '-A' 'command' '--no-out-link'
83+✔ Built on ./.obelisk/impl [command]
84+Handing off to /nix/store/j8wls8a89xr6s1a47lg6g83gnbdrfd0l-obelisk-command-0.1/bin/ob
85+Starting Obelisk </nix/store/j8wls8a89xr6s1a47lg6g83gnbdrfd0l-obelisk-command-0.1/bin/.ob-wrapped> args=["--no-handoff","deploy","update","-v"] logging-level=Debug
86+Creating process: 'git' 'ls-remote' '--exit-code' '--symref' 'https://github.com/obsidiansystems/some-private-repo.git' 'refs/heads/master'
87+git ls-remote maps: (fromList [],fromList [(GitRef_Branch "master","8546dfc8be9653f20bb26214e0991dbb957cb290")])
88+Latest commit in branch master from remote repo https://github.com/obsidiansystems/some-private-repo.git is 8546dfc8be9653f20bb26214e0991dbb957cb290
89+Creating process: 'nix-prefetch-url' '--unpack' '--type' 'sha256' 'https://github.com/obsidiansystems/some-private-repo/archive/8546dfc8be9653f20bb26214e0991dbb957cb290.tar.gz'
90+error: unable to download 'https://github.com/obsidiansystems/some-private-repo/archive/8546dfc8be9653f20bb26214e0991dbb957cb290.tar.gz': HTTP error 404
91+Process exited with code 1; 'nix-prefetch-url' '--unpack' '--type' 'sha256' 'https://github.com/obsidiansystems/some-private-repo/archive/8546dfc8be9653f20bb26214e0991dbb957cb290.tar.gz'
92+nix-prefetch-url: Failed to determine sha256 hash of URL https://github.com/obsidiansystems/some-private-repo/archive/8546dfc8be9653f20bb26214e0991dbb957cb290.tar.gz
93+✖ Updating thunk ./src to latest
94+```
95+
96+And here's how you can fix it:
97+
98+```bash
99+ob thunk unpack $SOME_THUNK
100+ob thunk pack $SOME_THUNK
101+```
102+Substitute the directory of your thunk for `$SOME_THUNK`. In the case of `ob deploy update`, `$SOME_THUNK` will be `src` in the deployment directory.
103+
104+(Based on issue #351).
105+
106+### How do I fix `Ambiguous module name` errors?
107+Since obelisk places the common/backend/frontend modules packages into the same ghci, and ghci doesn't "sandbox" them, it is possible to have conflicting module errors inside `ob repl/watch/run` that do not appear when doing a cabal build.
108+
109+You can disambiguate this via [PackageImports](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#package-qualified-imports). For instance, if you see
110+```
111+error:
112+ Ambiguous module name ‘Crypto.Hash’:
113+ it was found in multiple packages:
114+ cryptohash-0.11.9 cryptonite-0.25
115+```
116+then specify the package you want in the import, e.g:
117+`import "cryptonite" Crypto.Hash`
LICENSEnew file+30
@@ -0,0 +1,30 @@
1+Copyright (c) 2020 Obsidian Systems
2+
3+All rights reserved.
4+
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
7+
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
10+
11+ * Redistributions in binary form must reproduce the above
12+ copyright notice, this list of conditions and the following
13+ disclaimer in the documentation and/or other materials provided
14+ with the distribution.
15+
16+ * Neither the name of Elliot Cameron nor the names of other
17+ contributors may be used to endorse or promote products derived
18+ from this software without specific prior written permission.
19+
20+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.md+306−35
@@ -1,55 +1,326 @@
1−## Installation
1+# Obelisk
2+
3+[![Haskell Programming Language](https://img.shields.io/badge/language-Haskell-blue.svg)](http://www.haskell.org)
4+[![BSD3 License](http://img.shields.io/badge/license-BSD3-brightgreen.svg)](https://github.com/obsidiansystems/obelisk/blob/master/LICENSE)
5+
6+<p align="center"><img src="docs/obelisk-logo-640.png" width="50%" alt="Obelisk Logo"></p>
7+
8+Functional reactive web and mobile applications, with batteries included. Obelisk's goal is to represent a cohesive, highly-curated set of choices that [Obsidian Systems](https://obsidian.systems/) has made for building these types of applications in a way that is extremely fast but does not compromise on production readiness.
9+
10+- [Overview](#overview)
11+ - [Who should consider using it?](#who-should-consider-using-it)
12+- [Installing Obelisk](#installing-obelisk)
13+- [Developing an Obelisk project](#developing-an-obelisk-project)
14+ - [IDE Support](#ide-support)
15+- [Deploying](#deploying)
16+ - [Default EC2 Deployment](#default-ec2-deployment)
17+ - [Custom Non-EC2 Deployment](#custom-non-ec2-deployment)
18+ - [VirtualBox Deployment](#virtualbox-deployment)
19+ - [Locally](#locally)
20+ - [From macOS](#from-macos)
21+ - [Deploying an updated version](#deploying-an-updated-version)
22+- [Mobile](#mobile)
23+ - [iOS](#ios)
24+ - [Android](#android)
25+- [Frequently Asked Questions (FAQ)](#frequently-asked-questions-faq)
26+- [Contributing](#contributing)
27+
28+## Overview
29+
30+Obelisk allows you to build high-quality web and mobile applications very quickly using [Reflex](https://reflex-frp.org/). In minutes you can go from an empty directory to an interactive application that works on web, iOS, and Android, all sharing the same Haskell codebase! Obelisk's development environment also enables extremely rapid development and feedback. You can take advantage of Haskell's type system across the frontend and backend boundary. This means changes to your backend that would break your frontend are immediately detected during development and vice versa. Obelisk uses Haskell's compiler to give you a complete "TODO list" of what needs to be updated.
31+
32+Obelisk is targeted primarily at Haskell developers who want to build high-quality web and/or mobile applications in Haskell, without the distractions of manually choosing and integrating technology for every piece of the system.
33+
34+### Who should consider using it?
35+
36+Obelisk assumes basic knowledge of [Haskell](https://www.haskell.org/) and [Reflex/Reflex-DOM](https://reflex-frp.org/), web technologies like [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) and [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS), and a terminal shell like [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)). Knowledge of [Nix](https://nixos.org/) helps but is not strictly necessary.
37+
38+
39+## Installing Obelisk
40+
41+1. [Install Nix](https://nixos.org/nix/).
42+ If you already have Nix installed, make sure you have version 2.0 or higher. To check your current version, run `nix-env --version`.
21. Set up nix caches
431. Set up nix caches
3− 1. Add this to `/etc/nixos/configuration.nix`:
44+ 1. If you are running NixOS, add this to `/etc/nixos/configuration.nix`:
4− ```
45+ ```nix
5 nix.binaryCaches = [ "https://nixcache.reflex-frp.org" ];
46 nix.binaryCaches = [ "https://nixcache.reflex-frp.org" ];
6 nix.binaryCachePublicKeys = [ "ryantrinkle.com-1:JJiAKaRv9mWgpVAz8dwewnZe0AzzEAzPkagE9SP5NWI=" ];
47 nix.binaryCachePublicKeys = [ "ryantrinkle.com-1:JJiAKaRv9mWgpVAz8dwewnZe0AzzEAzPkagE9SP5NWI=" ];
7 ```
48 ```
8−1. Get set up to access private repositories
49+ and rebuild your NixOS configuration (e.g. `sudo nixos-rebuild switch`).
9− 1. [Get set up to connect to GitHub with SSH](https://help.github.com/articles/connecting-to-github-with-ssh/)
50+ 1. If you are using another operating system or Linux distribution, ensure that these lines are present in your Nix configuration file (`/etc/nix/nix.conf` on most systems; [see full list](https://nixos.org/nix/manual/#sec-conf-file)):
10− 1. [Create a GitHub personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/)
51+ ```nix
11− 1. Add this to `/etc/nixos/configuration.nix`:
52+ binary-caches = https://cache.nixos.org https://nixcache.reflex-frp.org
53+ binary-cache-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= ryantrinkle.com-1:JJiAKaRv9mWgpVAz8dwewnZe0AzzEAzPkagE9SP5NWI=
54+ binary-caches-parallel-connections = 40
12 ```
55 ```
13− nix.envVars = {
56+ * If you're on a Linux distribution other than NixOS, enable sandboxing (see these [issue 172](https://github.com/obsidiansystems/obelisk/issues/172#issuecomment-411507818) or [issue 6](https://github.com/obsidiansystems/obelisk/issues/6) if you run into build problems) by adding the following:
14− NIX_GITHUB_PRIVATE_USERNAME = "your-github-username";
57+ ```nix
15− NIX_GITHUB_PRIVATE_PASSWORD = "your-github-personal-access-token";
58+ sandbox = true
16− };
59+ ```
17− ```
60+ * If you're on MacOS, disable sandboxing (there are still some impure dependencies for now) by adding the following:
18− 1. `nix-env -i hub` OR `nix-env -iA nixos.gitAndTools.hub`
61+ ```nix
19− 1. `hub clone obsidiansystems/obelisk`
62+ sandbox = false
20− * NOTE: you must authenticate with hub at least once, because the `ob` command uses `hub` for authentication
63+ ```
21− #TODO: Make ob do this itself (either invoke hub automatically or not depend on hub)
64+ then restart the nix daemon
65+ ```bash
66+ sudo launchctl stop org.nixos.nix-daemon
67+ sudo launchctl start org.nixos.nix-daemon
68+ ```
69+1. Install obelisk:
70+ ```bash
22−1. Install `ob`: `nix-env -f obelisk -iA command`.
71+ nix-env -f https://github.com/obsidiansystems/obelisk/archive/master.tar.gz -iA command
23− Alternatively, if you prefer not to install to your user nix environment, you can
72+ ```
24− enter a shell with the `ob` command available: `nix-shell -A shell`.
73+
74+### Accessing private repositories
75+
76+To allow the Nix builder to access private git repositories, you must be set up
77+to access them via SSH. Follow these steps depending on the platform you need
78+access to:
79+
80+- [GitHub](https://help.github.com/articles/connecting-to-github-with-ssh/)
81+- [GitLab](https://docs.gitlab.com/ee/gitlab-basics/create-your-ssh-keys.html)
82+
83+## Developing an Obelisk project
84+
85+To create a new Obelisk project, go to an empty directory and run:
86+
87+```bash
88+ob init
89+```
90+
91+Obelisk leverages ghcid to provide a live-reloading server that handles both frontend and backend. To run your Obelisk app and monitor the source for changes:
92+
93+```bash
94+ob run
95+```
25
96
26−## Building
97+Now, with an appropriate browser, go to http://localhost:8000 (or the address/port specified in `config/common/route`) to access your app.
27−Build the frontend by running
98+Firefox will not be able to properly run the development website due to [issue 460](https://github.com/obsidiansystems/obelisk/issues/460). Fortunately, this problem does not occur on a fully built website.
99+
100+Every time you change the Haskell source files in frontend, common or backend, `ob run` will automatically recompile the modified files and reload the server. Furthermore, it will display on screen compilation errors and warnings if any.
101+
102+### IDE Support
103+
104+Obelisk officially supports terminal-based feedback (akin to [`ghcid`](https://github.com/ndmitchell/ghcid)) in `ob run` and `ob watch`.
105+
106+## Deploying
107+
108+### Default EC2 Deployment
109+
110+In this section we will demonstrate how to deploy your Obelisk app to an Amazon EC2 instance. Obelisk deployments are configured for EC2 by default (see [Custom Non-EC2 Deployment](#custom-non-ec2-deployment)).
111+
112+First create a new EC2 instance:
113+
114+1. Launch a NixOS 19.09 EC2 instance (we recommend [this AMI](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#LaunchInstanceWizard:ami=ami-00a8eeaf232a74f84))
115+1. In the instance configuration wizard ensure that your instance has at least 1GB RAM and 10GB disk space.
116+1. When prompted save your AWS private key (`~/myaws.pem`) somewhere safe. We'll need it later during deployment.
117+1. Go to "Security Groups", select your instance's security group and under "Inbound" tab add a new rule for HTTP port 80 and HTTPS port 443.
118+
119+At this stage your instance should be booting and become accessible shortly. Note down the hostname of your EC2 instance.
120+
121+Now go to your Obelisk project directory (`~/code/myapp`), and initialize a deployment config (`~/code/myapp-deploy`):
122+Your project directory must be "thunkable", i.e. something on which `ob thunk pack` can be called. Usually it will be a git repository whose current revision has been pushed upstream.
28
123
29```bash
124```bash
30−nix-build -A ghcjs.frontend --out-link frontend-js
125+cd ~/code/myapp
126+SERVER=ec2-35-183-22-197.ca-central-1.compute.amazonaws.com
127+ROUTE=https://myapp.com # Publicly accessible route to your app
128+EMAIL=myname@myapp.com
129+ob deploy init \
130+ --ssh-key ~/myaws.pem \
131+ --hostname $SERVER \
132+ --route $ROUTE \
133+ --admin-email $EMAIL \
134+ ~/code/myapp-deploy
31```
135```
32
136
33−Now you can try running the backend in GHCi by running
137+HTTPS is enabled by default; to disable HTTPS pass `--disable-https` to the `ob deploy init` command above.
138+
139+This step will also require that you manually verify the authenticity of the host `$SERVER`. Obelisk will save the fingerprint in a deployment-specific configuration. **Obelisk deployments do *not* rely on the `known_hosts` of your local machine.** This is because, in the event that you need to switch from one deploy machine / bastion host to another, you want to be absolutely sure that you're still connecting to the machines you think you are, even if that deploy machine / bastion host has never connected to them before. Obelisk explicitly avoids a workflow that encourages people to accept host keys without checking them, since that could result in leaking production secrets to anyone who manages to MITM you, e.g. via DNS spoofing or cache poisoning. (Note that an active attack is a circumstance where you may need to quickly switch bastion hosts, e.g. because the attacker has taken one down or you have taken it down in case it was compromised. In this circumstance you might need to deploy to production to fix an exploit or rotate keys, etc.) When you run `ob deploy` later it will rely on the saved verification in this step.
140+
141+Next, go to the deployment directory that you just initialized and deploy!
34
142
35```bash
143```bash
36−ob repl backend
144+cd ~/code/myapp-deploy
145+ob deploy push
146+```
147+
148+`ob deploy push` will locally build your app and then transfer it, along with all the Nix package dependencies, via ssh to the EC2 instance. The backend will live in `/var/lib/backend`.
149+
150+At this point you are done. Your app will be accessible at `${ROUTE}`. The currently deployed version - the git commit hash of the source repo - can be found at `${ROUTE}/version`.
151+
152+### Custom Non-EC2 Deployment
153+
154+By default Obelisk deployments are configured for NixOS machines running on AWS EC2. To provide your own configuration, you need to write a custom `module.nix` in the deployment repository. This still requires that your server is running NixOS.
155+
156+`module.nix` must contain a Nix *function* that produces a [NixOS module function](https://nixos.org/nixos/manual/index.html#sec-writing-modules). The top-level function takes deployment configuration as arguments: `hostName`, `adminEmail`, `routeHost`, `enableHttps`, `version`, `exe`, `nixosPkgs`. Most of these are the values you specified during `ob deploy init` and are stored in the deployment repository. `version` is a `git` hash for the app that you're deploying. `exe` is the Linux build of the app (as seen in [Deploying Locally](#locally)). `nixosPkgs` is the package set used to construct the NixOS VM.
157+
158+The [VirtualBox Deployment](#virtualbox-deployment) section provides an example.
159+
160+#### VirtualBox Deployment
161+
162+Here's a `module.nix` that is configured for deployment to a VirtualBox VM (running NixOS):
163+
164+```nix
165+{ nixosPkgs, ... }: {...}: {
166+ imports = [ (nixosPkgs.path + /nixos/modules/virtualisation/virtualbox-image.nix) ];
167+}
37```
168```
38−and then typing
169+
170+The `{...}:` and following is the [NixOS module](https://nixos.org/nixos/manual/index.html#sec-writing-modules) definition.
171+
172+### Locally
173+
174+If you want deploy your application locally or test a production-oriented build you can build and deploy the app as described below.
175+
176+Build the application:
39
177
40```bash
178```bash
41−backend
179+nix-build -A exe --no-out-link
42```
180```
43
181
44−at the GHCi prompt.
182+Copy the result to a new directory, add configuration, and run!
183+
184+```bash
185+mkdir test-app
186+ln -s $(nix-build -A exe --no-out-link)/* test-app/
187+cp -r config test-app
188+(cd test-app && ./backend)
189+```
190+
191+### From macOS
192+
193+Deploying from macOS requires some extra setup:
194+
195+- [Install nix-darwin](https://github.com/LnL7/nix-darwin)
196+- [Install docker](https://docs.docker.com/)
197+
198+Running `ob deploy push` will give you additional setup instructions.
199+
200+### Deploying an updated version
201+
202+If you'd like to deploy an updated version (with new commits) of your Obelisk app: simply go to the configuration directory, update the source thunk and push:
203+
204+```bash
205+cd ~/code/myapp-deploy
206+ob deploy update
207+ob deploy push
208+```
209+
210+## Mobile
211+Until Obelisk offers a `ob deploy` equivalent for mobile apps, you are recommended to do it manually as follows.
212+
213+### iOS
214+
215+#### First time setup
216+Development on iOS requires a computer running macOS and an iOS developer account.
217+Your account must also belong to an Apple Developer Team, if you want to access developer portal links (otherwise they'll redirect to your account page).
218+
219+##### iPhone
220+1. Connect the iPhone on which you'd like to run builds - this will open up iTunes.
221+1. Click accept to authorize on both the computer and the iPhone.
222+
223+##### Xcode
224+Install Xcode 11.2 (contains iOS SDK 13.2) and open it so that it runs its post install tool setup.
225+
226+These versions will work out of the box but iOS SDKs prior to 11.3 should also work. You can choose another installed version in `default.nix`
227+
228+More recent Xcodes should also work, as long as one of the SDKs mentioned above has been used.
229+To add another SDK to your current Xcode, [download](https://developer.apple.com/download/more/) the corresponding Xcode, extract it and copy its SDK folder next to the installed one, e.g.
230+```bash
231+open -W Xcode_9.2.xip
232+sudo cp -R Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.2.sdk
233+```
234+
235+
236+You can verify that you have correct versions by running
237+```bash
238+xcodebuild -showsdks
239+```
240+
241+##### Certificates
242+To deploy and/or package apps, you'll need to inform Apple of your development devices and permissions by
243+adding credentials to the correct provisioning profile via the Apple Developer portal.
244+
245+1. Open up XCode and go to Preferences - Accounts. Select the organization
246+Member role, click Manage Certificates, and add an iOS Development
247+certificate.
248+1. Go to [developer portal - devices](https://developer.apple.com/account/ios/device/) and add your device.
249+To find your device's UDID, select it in iTunes and click the serial number.
250+1. Go to [developer portal - development profiles](https://developer.apple.com/account/ios/profile/limited).
251+Create a development profile and add your certificate and device.
252+Click "Generate" and then download and open the profile.
253+
254+#### Building
255+1. In your project's `default.nix` set values for `ios.bundleIdentifier` and `ios.bundleName`.
256+Ensure that `bundleIdentifier` matches the App ID of the development profile, or that you are using a wildcard profile.
257+1. Run `nix-build -A ios.frontend -o result-ios` to build the app. Find it at `result-ios/frontend.app`
258+
259+#### Deploying
260+1. Connect the registered iPhone.
261+1. Find your Apple Team ID in the [developer portal](https://developer.apple.com/account/#/membership).
262+1. Run the deploy command with your Team ID:
263+```bash
264+result-ios/bin/deploy [TEAM_ID]
265+# or in debug mode via lldb:
266+result-ios/bin/deploy [TEAM_ID] -d
267+```
268+
269+#### Packaging
270+1. Go to [developer portal - distribution profiles](https://developer.apple.com/account/ios/profile/production).
271+Create and download a distribution profile.
272+1. Run the package script with your TEAM ID and your distribution profile to create a `.ipa`:
273+```bash
274+result-ios/bin/package [TEAM_ID] /path/to/output/.ipa /path/to/profile/file
275+```
276+
277+#### Debugging
278+It's also possible to inspect iOS WkWebView apps once they are installed in the iPhone:
279+1. On the desktop, go to Safari > Preferences > Advanced and enable Develop menu.
280+1. On the iPhone go to Settings > Safari > Advanced and enable Web Inspector.
281+1. Open the app on the iPhone while it is connected to the desktop.
282+1. In the desktop's Safari Develop menu, you should see your iPhone. Select the screen under the name of the app.
283+
284+### Android
285+
286+NOTE: Currently Android builds are only supported on Linux.
287+
288+1. In your project's `default.nix` set a suitable value for `android.applicationId` and `android.displayName`.
289+1. In your project's `default.nix` pass `config.android_sdk.accept_license = true;` in the arguments to the import of of `.obelisk/impl` to indicate your acceptance of the [Android Software Development Kit License Agreement](https://developer.android.com/studio/terms), which is required to build Android apps.
290+1. Run `nix-build -A android.frontend -o result-android` to build the Android app.
291+1. A debug version of the app should be generated at `result-android/android-app-debug.apk`
292+
293+Now deploy the built apk file to your Android device:
294+
295+1. Enable *USB debugging* in your Android device ([instructions here](https://developer.android.com/studio/debug/dev-options))
296+1. Connect the device using USB (be sure to confirm any security prompts on the device)
297+1. Run the deploy script: `result-android/bin/deploy`
298+
299+Alternatively, you can deploy from an obelisk deployment directory (a directory generated post `ob deploy init ...` command) using the `ob deploy test android` command.
300+This command will accomplish the following:
301+
302+1. Create a key store and apk signing key (`android_keystore.jks`)
303+1. Build a Signed Android apk for your application
304+1. Deploy the Signed apk to your connected Android device
305+
306+In the event that you change your key or keystore password, you will have to update your credentials within the JSON object found in `android_keytool_config.json`.
307+
308+Additional documentation on Java key stores can be found [here](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html).
309+
310+This should copy over and install the application on your device (if you see a "*signatures do not match*" error, simply uninstall the previous app from the device before retrying the deploy). The name of the installed application will be what you have specified for `android.displayName` in the `default.nix`.
311+
312+#### Releasing to Play Store
313+
314+##### Build a release version
315+
316+After having configured signing for your app, you may proceed to build a release version of the app. This is no different to how you build the non-release version, so consult the section [Android](#android) further above for exact instructions on building and deploying to your device.
317+
318+
319+## Frequently Asked Questions (FAQ)
320+
321+Refer to [FAQ](FAQ.md).
45
322
46−Point your web browser at [localhost:8000](localhost:8000) and everything should work.
47
323
48−Feel free to edit the frontend and backend directories as you see fit.
324+## Contributing
49
325
50−## Developer Tools
326+Contributions and issue reports are encouraged and appreciated! Refer to the [Contributing](CONTRIBUTING.md) guide for information about getting started.
51−To increase developer productivity it is highly recommended to make use of the
52−`ob watch` command. This will open a live repl that
53−will compile and refresh itself showing you the latest possible syntax or type errors
54−as well as any other ghc warnings whenever files within their respective directories
55−are saved and updated.
acme.nixnew file+430
@@ -0,0 +1,430 @@
1+# Copied from https://github.com/NixOS/nixpkgs-channels/blob/70717a337f7ae4e486ba71a500367cad697e5f09/nixos/modules/security/acme.nix # MODIFIED
2+# Lines marked '# MODIFIED' have been added or modified from the original. # MODIFIED
3+{ config, lib, pkgs, ... }:
4+with lib;
5+let
6+
7+ cfg = config.security.acme;
8+
9+ certOpts = { name, ... }: {
10+ options = {
11+ webroot = mkOption {
12+ type = types.nullOr types.str;
13+ default = null;
14+ example = "/var/lib/acme/acme-challenges";
15+ description = ''
16+ Where the webroot of the HTTP vhost is located.
17+ <filename>.well-known/acme-challenge/</filename> directory
18+ will be created below the webroot if it doesn't exist.
19+ <literal>http://example.org/.well-known/acme-challenge/</literal> must also
20+ be available (notice unencrypted HTTP).
21+ '';
22+ };
23+
24+ server = mkOption {
25+ type = types.nullOr types.str;
26+ default = null;
27+ description = ''
28+ ACME Directory Resource URI. Defaults to let's encrypt
29+ production endpoint,
30+ https://acme-v02.api.letsencrypt.org/directory, if unset.
31+ '';
32+ };
33+
34+ domain = mkOption {
35+ type = types.str;
36+ default = name;
37+ description = "Domain to fetch certificate for (defaults to the entry name)";
38+ };
39+
40+ email = mkOption {
41+ type = types.nullOr types.str;
42+ default = cfg.email;
43+ description = "Contact email address for the CA to be able to reach you.";
44+ };
45+
46+ user = mkOption {
47+ type = types.str;
48+ default = "root";
49+ description = "User running the ACME client.";
50+ };
51+
52+ group = mkOption {
53+ type = types.str;
54+ default = "root";
55+ description = "Group running the ACME client.";
56+ };
57+
58+ allowKeysForGroup = mkOption {
59+ type = types.bool;
60+ default = false;
61+ description = ''
62+ Give read permissions to the specified group
63+ (<option>security.acme.cert.&lt;name&gt;.group</option>) to read SSL private certificates.
64+ '';
65+ };
66+
67+ postRun = mkOption {
68+ type = types.lines;
69+ default = "";
70+ example = "systemctl reload nginx.service";
71+ description = ''
72+ Commands to run after new certificates go live. Typically
73+ the web server and other servers using certificates need to
74+ be reloaded.
75+ Executed in the same directory with the new certificate.
76+ '';
77+ };
78+
79+ directory = mkOption {
80+ type = types.str;
81+ readOnly = true;
82+ default = "/var/lib/acme/${name}";
83+ description = "Directory where certificate and other state is stored.";
84+ };
85+
86+ extraDomains = mkOption {
87+ type = types.attrsOf (types.nullOr types.str);
88+ default = {};
89+ example = literalExample ''
90+ {
91+ "example.org" = null;
92+ "mydomain.org" = null;
93+ }
94+ '';
95+ description = ''
96+ A list of extra domain names, which are included in the one certificate to be issued.
97+ Setting a distinct server root is deprecated and not functional in 20.03+
98+ '';
99+ };
100+
101+ keyType = mkOption {
102+ type = types.str;
103+ default = "ec256";
104+ description = ''
105+ Key type to use for private keys.
106+ For an up to date list of supported values check the --key-type option
107+ at https://go-acme.github.io/lego/usage/cli/#usage.
108+ '';
109+ };
110+
111+ dnsProvider = mkOption {
112+ type = types.nullOr types.str;
113+ default = null;
114+ example = "route53";
115+ description = ''
116+ DNS Challenge provider. For a list of supported providers, see the "code"
117+ field of the DNS providers listed at https://go-acme.github.io/lego/dns/.
118+ '';
119+ };
120+
121+ credentialsFile = mkOption {
122+ type = types.path;
123+ description = ''
124+ Path to an EnvironmentFile for the cert's service containing any required and
125+ optional environment variables for your selected dnsProvider.
126+ To find out what values you need to set, consult the documentation at
127+ https://go-acme.github.io/lego/dns/ for the corresponding dnsProvider.
128+ '';
129+ example = "/var/src/secrets/example.org-route53-api-token";
130+ };
131+
132+ dnsPropagationCheck = mkOption {
133+ type = types.bool;
134+ default = true;
135+ description = ''
136+ Toggles lego DNS propagation check, which is used alongside DNS-01
137+ challenge to ensure the DNS entries required are available.
138+ '';
139+ };
140+ };
141+ };
142+
143+in
144+
145+{
146+
147+ ###### interface
148+ imports = [
149+ (mkRemovedOptionModule [ "security" "acme" "production" ] ''
150+ Use security.acme.server to define your staging ACME server URL instead.
151+ To use the let's encrypt staging server, use security.acme.server =
152+ "https://acme-staging-v02.api.letsencrypt.org/directory".
153+ ''
154+ )
155+ # (mkRemovedOptionModule [ "security" "acme" "directory"] "ACME Directory is now hardcoded to /var/lib/acme and its permisisons are managed by systemd. See https://github.com/NixOS/nixpkgs/issues/53852 for more info.") # MODIFIED
156+ # (mkRemovedOptionModule [ "security" "acme" "preDelay"] "This option has been removed. If you want to make sure that something executes before certificates are provisioned, add a RequiredBy=acme-\${cert}.service to the service you want to execute before the cert renewal") # MODIFIED
157+ # (mkRemovedOptionModule [ "security" "acme" "activationDelay"] "This option has been removed. If you want to make sure that something executes before certificates are provisioned, add a RequiredBy=acme-\${cert}.service to the service you want to execute before the cert renewal") # MODIFIED
158+ (mkChangedOptionModule [ "security" "acme" "validMin"] [ "security" "acme" "validMinDays"] (config: config.security.acme.validMin / (24 * 3600)))
159+ ];
160+ options = {
161+ security.acme = {
162+
163+ validMinDays = mkOption {
164+ type = types.int;
165+ default = 30;
166+ description = "Minimum remaining validity before renewal in days.";
167+ };
168+
169+ email = mkOption {
170+ type = types.nullOr types.str;
171+ default = null;
172+ description = "Contact email address for the CA to be able to reach you.";
173+ };
174+
175+ renewInterval = mkOption {
176+ type = types.str;
177+ default = "daily";
178+ description = ''
179+ Systemd calendar expression when to check for renewal. See
180+ <citerefentry><refentrytitle>systemd.time</refentrytitle>
181+ <manvolnum>7</manvolnum></citerefentry>.
182+ '';
183+ };
184+
185+ server = mkOption {
186+ type = types.nullOr types.str;
187+ default = null;
188+ description = ''
189+ ACME Directory Resource URI. Defaults to let's encrypt
190+ production endpoint,
191+ <literal>https://acme-v02.api.letsencrypt.org/directory</literal>, if unset.
192+ '';
193+ };
194+
195+ preliminarySelfsigned = mkOption {
196+ type = types.bool;
197+ default = true;
198+ description = ''
199+ Whether a preliminary self-signed certificate should be generated before
200+ doing ACME requests. This can be useful when certificates are required in
201+ a webserver, but ACME needs the webserver to make its requests.
202+ With preliminary self-signed certificate the webserver can be started and
203+ can later reload the correct ACME certificates.
204+ '';
205+ };
206+
207+ acceptTerms = mkOption {
208+ type = types.bool;
209+ default = false;
210+ description = ''
211+ Accept the CA's terms of service. The default provier is Let's Encrypt,
212+ you can find their ToS at https://letsencrypt.org/repository/
213+ '';
214+ };
215+
216+ certs = mkOption {
217+ default = { };
218+ type = with types; attrsOf (submodule certOpts);
219+ description = ''
220+ Attribute set of certificates to get signed and renewed. Creates
221+ <literal>acme-''${cert}.{service,timer}</literal> systemd units for
222+ each certificate defined here. Other services can add dependencies
223+ to those units if they rely on the certificates being present,
224+ or trigger restarts of the service if certificates get renewed.
225+ '';
226+ example = literalExample ''
227+ {
228+ "example.com" = {
229+ webroot = "/var/www/challenges/";
230+ email = "foo@example.com";
231+ extraDomains = { "www.example.com" = null; "foo.example.com" = null; };
232+ };
233+ "bar.example.com" = {
234+ webroot = "/var/www/challenges/";
235+ email = "bar@example.com";
236+ };
237+ }
238+ '';
239+ };
240+ };
241+ };
242+
243+ ###### implementation
244+ config = mkMerge [
245+ (mkIf (cfg.certs != { }) {
246+
247+ assertions = let
248+ certs = (mapAttrsToList (k: v: v) cfg.certs);
249+ in [
250+ {
251+ assertion = all (certOpts: certOpts.dnsProvider == null || certOpts.webroot == null) certs;
252+ message = ''
253+ Options `security.acme.certs.<name>.dnsProvider` and
254+ `security.acme.certs.<name>.webroot` are mutually exclusive.
255+ '';
256+ }
257+ {
258+ assertion = cfg.email != null || all (certOpts: certOpts.email != null) certs;
259+ message = ''
260+ You must define `security.acme.certs.<name>.email` or
261+ `security.acme.email` to register with the CA.
262+ '';
263+ }
264+ {
265+ assertion = cfg.acceptTerms;
266+ message = ''
267+ You must accept the CA's terms of service before using
268+ the ACME module by setting `security.acme.acceptTerms`
269+ to `true`. For Let's Encrypt's ToS see https://letsencrypt.org/repository/
270+ '';
271+ }
272+ ];
273+
274+ systemd.services = let
275+ services = concatLists servicesLists;
276+ servicesLists = mapAttrsToList certToServices cfg.certs;
277+ certToServices = cert: data:
278+ let
279+ # StateDirectory must be relative, and will be created under /var/lib by systemd
280+ lpath = "acme/${cert}";
281+ apath = "/var/lib/${lpath}";
282+ spath = "/var/lib/acme/.lego/${cert}";
283+ fileMode = if data.allowKeysForGroup then "640" else "600";
284+ globalOpts = [ "-d" data.domain "--email" data.email "--path" "." "--key-type" data.keyType ]
285+ ++ optionals (cfg.acceptTerms) [ "--accept-tos" ]
286+ ++ optionals (data.dnsProvider != null && !data.dnsPropagationCheck) [ "--dns.disable-cp" ]
287+ ++ concatLists (mapAttrsToList (name: root: [ "-d" name ]) data.extraDomains)
288+ ++ (if data.dnsProvider != null then [ "--dns" data.dnsProvider ] else [ "--http" "--http.webroot" data.webroot ])
289+ ++ optionals (cfg.server != null || data.server != null) ["--server" (if data.server == null then cfg.server else data.server)];
290+ runOpts = escapeShellArgs (globalOpts ++ [ "run" ]);
291+ renewOpts = escapeShellArgs (globalOpts ++ [ "renew" "--days" (toString cfg.validMinDays) ]);
292+ acmeService = {
293+ description = "Renew ACME Certificate for ${cert}";
294+ after = [ "network.target" "network-online.target" ];
295+ wants = [ "network-online.target" ];
296+ wantedBy = mkIf (!config.boot.isContainer) [ "multi-user.target" ];
297+ serviceConfig = {
298+ Type = "oneshot";
299+ User = data.user;
300+ Group = data.group;
301+ PrivateTmp = true;
302+ StateDirectory = "acme/.lego/${cert} acme/.lego/accounts ${lpath}";
303+ StateDirectoryMode = if data.allowKeysForGroup then "750" else "700";
304+ WorkingDirectory = spath;
305+ # Only try loading the credentialsFile if the dns challenge is enabled
306+ EnvironmentFile = if data.dnsProvider != null then data.credentialsFile else null;
307+ ExecStart = pkgs.writeScript "acme-start" ''
308+ #!${pkgs.runtimeShell} -e
309+ test -L ${spath}/accounts -o -d ${spath}/accounts || ln -s ../accounts ${spath}/accounts
310+ ${pkgs.lego}/bin/lego ${renewOpts} || ${pkgs.lego}/bin/lego ${runOpts}
311+ '';
312+ ExecStartPost =
313+ let
314+ keyName = builtins.replaceStrings ["*"] ["_"] data.domain;
315+ script = pkgs.writeScript "acme-post-start" ''
316+ #!${pkgs.runtimeShell} -e
317+ cd ${apath}
318+ # Test that existing cert is older than new cert
319+ KEY=${spath}/certificates/${keyName}.key
320+ KEY_CHANGED=no
321+ if [ -e $KEY -a $KEY -nt key.pem ]; then
322+ KEY_CHANGED=yes
323+ cp -p ${spath}/certificates/${keyName}.key key.pem
324+ cp -p ${spath}/certificates/${keyName}.crt fullchain.pem
325+ cp -p ${spath}/certificates/${keyName}.issuer.crt chain.pem
326+ ln -sf fullchain.pem cert.pem
327+ cat key.pem fullchain.pem > full.pem
328+ fi
329+ chmod ${fileMode} *.pem
330+ chown '${data.user}:${data.group}' *.pem
331+ if [ "$KEY_CHANGED" = "yes" ]; then
332+ : # noop in case postRun is empty
333+ ${data.postRun}
334+ fi
335+ '';
336+ in
337+ "+${script}";
338+ };
339+
340+ };
341+ selfsignedService = {
342+ description = "Create preliminary self-signed certificate for ${cert}";
343+ path = [ pkgs.openssl ];
344+ script =
345+ ''
346+ workdir="$(mktemp -d)"
347+ # Create CA
348+ openssl genrsa -des3 -passout pass:xxxx -out $workdir/ca.pass.key 2048
349+ openssl rsa -passin pass:xxxx -in $workdir/ca.pass.key -out $workdir/ca.key
350+ openssl req -new -key $workdir/ca.key -out $workdir/ca.csr \
351+ -subj "/C=UK/ST=Warwickshire/L=Leamington/O=OrgName/OU=Security Department/CN=example.com"
352+ openssl x509 -req -days 1 -in $workdir/ca.csr -signkey $workdir/ca.key -out $workdir/ca.crt
353+ # Create key
354+ openssl genrsa -des3 -passout pass:xxxx -out $workdir/server.pass.key 2048
355+ openssl rsa -passin pass:xxxx -in $workdir/server.pass.key -out $workdir/server.key
356+ openssl req -new -key $workdir/server.key -out $workdir/server.csr \
357+ -subj "/C=UK/ST=Warwickshire/L=Leamington/O=OrgName/OU=IT Department/CN=example.com"
358+ openssl x509 -req -days 1 -in $workdir/server.csr -CA $workdir/ca.crt \
359+ -CAkey $workdir/ca.key -CAserial $workdir/ca.srl -CAcreateserial \
360+ -out $workdir/server.crt
361+ # Copy key to destination
362+ cp $workdir/server.key ${apath}/key.pem
363+ # Create fullchain.pem (same format as "simp_le ... -f fullchain.pem" creates)
364+ cat $workdir/{server.crt,ca.crt} > "${apath}/fullchain.pem"
365+ # Create full.pem for e.g. lighttpd
366+ cat $workdir/{server.key,server.crt,ca.crt} > "${apath}/full.pem"
367+ # Give key acme permissions
368+ chown '${data.user}:${data.group}' "${apath}/"{key,fullchain,full}.pem
369+ chmod ${fileMode} "${apath}/"{key,fullchain,full}.pem
370+ '';
371+ serviceConfig = {
372+ Type = "oneshot";
373+ PrivateTmp = true;
374+ StateDirectory = lpath;
375+ User = data.user;
376+ Group = data.group;
377+ };
378+ unitConfig = {
379+ # Do not create self-signed key when key already exists
380+ ConditionPathExists = "!${apath}/key.pem";
381+ };
382+ };
383+ in (
384+ [ { name = "acme-${cert}"; value = acmeService; } ]
385+ ++ optional cfg.preliminarySelfsigned { name = "acme-selfsigned-${cert}"; value = selfsignedService; }
386+ );
387+ servicesAttr = listToAttrs services;
388+ in
389+ servicesAttr;
390+
391+ systemd.tmpfiles.rules =
392+ map (data: "d ${data.webroot}/.well-known/acme-challenge - ${data.user} ${data.group}") (filter (data: data.webroot != null) (attrValues cfg.certs));
393+
394+ systemd.timers = let
395+ # Allow systemd to pick a convenient time within the day
396+ # to run the check.
397+ # This allows the coalescing of multiple timer jobs.
398+ # We divide by the number of certificates so that if you
399+ # have many certificates, the renewals are distributed over
400+ # the course of the day to avoid rate limits.
401+ numCerts = length (attrNames cfg.certs);
402+ _24hSecs = 60 * 60 * 24;
403+ AccuracySec = "${toString (_24hSecs / numCerts)}s";
404+ in flip mapAttrs' cfg.certs (cert: data: nameValuePair
405+ ("acme-${cert}")
406+ ({
407+ description = "Renew ACME Certificate for ${cert}";
408+ wantedBy = [ "timers.target" ];
409+ timerConfig = {
410+ OnCalendar = cfg.renewInterval;
411+ Unit = "acme-${cert}.service";
412+ Persistent = "yes";
413+ inherit AccuracySec;
414+ # Skew randomly within the day, per https://letsencrypt.org/docs/integration-guide/.
415+ RandomizedDelaySec = "24h";
416+ };
417+ })
418+ );
419+
420+ systemd.targets.acme-selfsigned-certificates = mkIf cfg.preliminarySelfsigned {};
421+ systemd.targets.acme-certificates = {};
422+ })
423+
424+ ];
425+
426+ meta = {
427+ maintainers = with lib.maintainers; [ abbradar fpletz globin m1cr0man ];
428+ # doc = ./acme.xml; # MODIFIED
429+ };
430+}
all-builds.nixnew file+113
@@ -0,0 +1,113 @@
1+{ self-args ? {
2+ config.android_sdk.accept_license = true;
3+ iosSdkVersion = "13.2";
4+ }
5+, local-self ? import ./. self-args
6+, supportedSystems ? [ builtins.currentSystem ]
7+}:
8+
9+let
10+ inherit (local-self.nixpkgs) lib runCommand nix;
11+ cacheBuildSystems = supportedSystems;
12+
13+ obeliskPackagesCommon = [
14+ "obelisk-frontend"
15+ "obelisk-route"
16+ "obelisk-executable-config-lookup"
17+ ];
18+
19+ obeliskPackagesBackend = obeliskPackagesCommon ++ [
20+ "obelisk-asset-manifest"
21+ "obelisk-asset-serve-snap"
22+ "obelisk-backend"
23+ "obelisk-cliapp"
24+ "obelisk-command"
25+ "obelisk-executable-config-inject"
26+ "obelisk-frontend"
27+ "obelisk-run"
28+ "obelisk-route"
29+ "obelisk-selftest"
30+ "obelisk-snap-extras"
31+ ];
32+
33+ pnameToAttrs = pkgsSet: pnames:
34+ lib.listToAttrs (map
35+ (name: { inherit name; value = pkgsSet.${name}; })
36+ pnames);
37+
38+ collect = v:
39+ if lib.isDerivation v then [v]
40+ else if lib.isAttrs v then lib.concatMap collect (builtins.attrValues v)
41+ else if lib.isList v then lib.concatMap collect v
42+ else [];
43+
44+ perPlatform = lib.genAttrs cacheBuildSystems (system: let
45+ reflex-platform = import ./dep/reflex-platform { inherit system; };
46+
47+ mkPerProfiling = profiling: let
48+ obelisk = import ./. (self-args // { inherit system profiling; });
49+ ghc = pnameToAttrs
50+ obelisk.haskellPackageSets.ghc
51+ obeliskPackagesBackend;
52+ ghcjs = pnameToAttrs
53+ obelisk.haskellPackageSets.ghcjs
54+ obeliskPackagesCommon;
55+ command = obelisk.command;
56+
57+ withSkeletonOptions = skel: options: (skel.passthru.__unstable__.self.extend (self: super: {
58+ userSettings = super.userSettings // options;
59+ })).project;
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+
66+ serverSkeletonExe = rawSkeleton.exe;
67+ # TODO fix nixpkgs so it doesn't try to run the result of haskell shells as setup hooks.
68+ serverSkeletonShell = local-self.nixpkgs.runCommand "shell-safe-for-dep" {} ''
69+ touch "$out"
70+ echo "return" >> "$out"
71+ cat "${skeleton.shells.ghc}" >> "$out"
72+ '';
73+ androidSkeleton = skeleton.android.frontend;
74+ iosSkeleton = skeleton.ios.frontend;
75+ nameSuffix = if profiling then "profiled" else "unprofiled";
76+ packages = {
77+ skeletonProfiledObRun = rawSkeleton.__unstable__.profiledObRun;
78+ inherit
79+ command
80+ serverSkeletonShell
81+ ghc
82+ ;
83+ } // lib.optionalAttrs (!profiling) {
84+ inherit
85+ ghcjs
86+ serverSkeletonExe
87+ ;
88+ } // lib.optionalAttrs reflex-platform.androidSupport {
89+ inherit androidSkeleton;
90+ } // lib.optionalAttrs reflex-platform.iosSupport {
91+ inherit iosSkeleton;
92+ };
93+ in packages // {
94+ cache = reflex-platform.pinBuildInputs
95+ "obelisk-${system}-${nameSuffix}"
96+ (collect packages);
97+ };
98+
99+ perProfiling = {
100+ profiled = mkPerProfiling true;
101+ unprofiled = mkPerProfiling false;
102+ };
103+ in perProfiling // {
104+ cache = reflex-platform.pinBuildInputs
105+ "obelisk-${system}"
106+ (map (p: p.cache) (builtins.attrValues perProfiling));
107+ });
108+
109+ metaCache = local-self.reflex-platform.pinBuildInputs
110+ "obelisk-everywhere"
111+ (map (a: a.cache) (builtins.attrValues perPlatform));
112+
113+in perPlatform // { inherit metaCache; }
all-tests.nixnew file+145
@@ -0,0 +1,145 @@
1+{
2+ supportedSystems ? [ builtins.currentSystem ]
3+}:
4+let
5+ nginxRoot = "/run/nginx";
6+ obelisk = import ./default.nix {};
7+ # Get NixOS a pre-release 20.03 that contains the python based tests and recursive nix
8+ pkgs = import (builtins.fetchTarball https://github.com/nixos/nixpkgs/archive/3de5266.tar.gz) {};
9+ sshKeys = import (pkgs.path + /nixos/tests/ssh-keys.nix) pkgs;
10+ make-test = import (pkgs.path + /nixos/tests/make-test-python.nix);
11+ obelisk-everywhere = (import ./all-builds.nix { inherit supportedSystems; }).x86_64-linux.cache;
12+ snakeOilPrivateKey = sshKeys.snakeOilPrivateKey.text;
13+ snakeOilPublicKey = sshKeys.snakeOilPublicKey;
14+in
15+ make-test ({...}: {
16+ name = "obelisk";
17+ nodes = {
18+ githost = {
19+ networking.firewall.allowedTCPPorts = [ 22 80 ];
20+ services.openssh = {
21+ enable = true;
22+ };
23+ environment.systemPackages = [
24+ pkgs.git
25+ ];
26+ users.users.root.openssh.authorizedKeys.keys = [
27+ snakeOilPublicKey
28+ ];
29+ };
30+
31+ client = {
32+ imports = [
33+ (pkgs.path + /nixos/modules/installer/cd-dvd/channel.nix)
34+ ];
35+ nix.useSandbox = false;
36+ nix.binaryCaches = [];
37+ environment.systemPackages = [
38+ obelisk.command
39+ obelisk.shell
40+ obelisk-everywhere
41+ pkgs.git
42+ ];
43+ };
44+ };
45+
46+ testScript =
47+ let
48+ privateKeyFile = pkgs.writeText "id_rsa" ''${snakeOilPrivateKey}'';
49+ thunkableSample = pkgs.writeText "default.nix" ''
50+ let pkgs = import <nixpkgs> {}; in pkgs.git
51+ '';
52+ invalidThunkableSample = pkgs.writeText "default.nix" ''
53+ let pkgs = import <nixpkgs> {}; in pkgtypo.git
54+ '';
55+ sshConfigFile = pkgs.writeText "ssh_config" ''
56+ Host *
57+ StrictHostKeyChecking no
58+ UserKnownHostsFile=/dev/null
59+ ConnectionAttempts=1
60+ ConnectTimeout=1
61+ IdentityFile=~/.ssh/id_rsa
62+ User=root
63+ '';
64+ in ''
65+ start_all()
66+
67+ with subtest("obelisk is installed and git is configured"):
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")
73+
74+ with subtest("the client can access the server via ssh"):
75+ client.succeed("mkdir -p ~/.ssh/")
76+ client.succeed(
77+ "cp ${privateKeyFile} ~/.ssh/id_rsa"
78+ )
79+ client.succeed("chmod 600 ~/.ssh/id_rsa")
80+ client.wait_until_succeeds(
81+ "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa githost true"
82+ )
83+ client.succeed(
84+ "cp ${sshConfigFile} ~/.ssh/config"
85+ )
86+ client.wait_until_succeeds("ssh githost true")
87+
88+ with subtest("a remote bare repo can be started"):
89+ githost.succeed("mkdir -p ~/myorg/myapp.git")
90+ githost.succeed("cd ~/myorg/myapp.git && git init --bare")
91+
92+ with subtest("a git project can be configured with a remote using ssh"):
93+ client.succeed("mkdir -p ~/code/myapp")
94+ client.succeed("cd ~/code/myapp && git init")
95+ client.succeed(
96+ "cp ${thunkableSample} ~/code/myapp/default.nix"
97+ )
98+ client.succeed("cd ~/code/myapp && git add .")
99+
100+ client.succeed('cd ~/code/myapp && git commit -m "Initial"')
101+ client.succeed(
102+ "cd ~/code/myapp && git remote add origin root@githost:/root/myorg/myapp.git"
103+ )
104+
105+
106+ with subtest("pushing code to the remote"):
107+ client.succeed("cd ~/code/myapp && git push -u origin master")
108+ client.succeed("cd ~/code/myapp && git status")
109+
110+ with subtest("obelisk can pack"):
111+ client.succeed("ob -v thunk pack ~/code/myapp")
112+ client.succeed("grep -qF 'git.json' ~/code/myapp/thunk.nix")
113+ client.succeed("grep -qF 'myorg' ~/code/myapp/git.json")
114+ client.succeed("ob -v thunk unpack ~/code/myapp")
115+
116+ with subtest("obelisk can set the public / private flag"):
117+ client.succeed("ob -v thunk pack ~/code/myapp --private")
118+ client.fail("""grep -qF '"private": practice' ~/code/myapp/git.json""")
119+ client.succeed("""grep -qF '"private": true' ~/code/myapp/git.json""")
120+ client.succeed("nix-build ~/code/myapp")
121+ client.succeed("ob -v thunk unpack ~/code/myapp")
122+ client.succeed("ob -v thunk pack ~/code/myapp --public")
123+ client.succeed("""grep -qF '"private": false' ~/code/myapp/git.json""")
124+ client.succeed("nix-build ~/code/myapp")
125+ client.succeed("ob -v thunk unpack ~/code/myapp")
126+
127+ with subtest("building an invalid thunk fails"):
128+ client.succeed("cd ~/code/myapp && git checkout -b bad")
129+ client.succeed(
130+ "cp ${invalidThunkableSample} ~/code/myapp/default.nix"
131+ )
132+ client.succeed("cd ~/code/myapp && git add .")
133+ client.succeed('cd ~/code/myapp && git commit -m "Bad commit"')
134+ client.succeed("cd ~/code/myapp && git push -u origin bad")
135+ client.succeed("ob -v thunk pack ~/code/myapp --public")
136+ client.fail("nix-build ~/code/myapp")
137+ client.succeed("ob -v thunk unpack ~/code/myapp")
138+ client.succeed("cd ~/code/myapp && git checkout master")
139+
140+ with subtest("obelisk can detect private repos"):
141+ client.succeed("ob -v thunk pack ~/code/myapp")
142+ client.succeed("""grep -qF '"private": true' ~/code/myapp/git.json""")
143+ client.succeed("ob -v thunk unpack ~/code/myapp")
144+ '';
145+ }) {}
default.nix+344−212
@@ -1,260 +1,392 @@
1{ system ? builtins.currentSystem
1{ system ? builtins.currentSystem
2, profiling ? false
2, profiling ? false
3+, iosSdkVersion ? "13.2"
4+, config ? {}
5+, terms ? { # Accepted terms, conditions, and licenses
6+ security.acme.acceptTerms = false;
7+ }
8+, reflex-platform-func ? import ./dep/reflex-platform
3}:
9}:
10+let
4−let reflex-platform = import ./dep/reflex-platform { inherit system; };
11+ reflex-platform = getReflexPlatform { inherit system; };
5− inherit (reflex-platform) hackGet;
12+ inherit (reflex-platform) hackGet nixpkgs;
6− pkgs = reflex-platform.nixpkgs;
13+ pkgs = nixpkgs;
7−in with pkgs.haskell.lib; with pkgs.lib;
8−let #TODO: Upstream
9− # Modify a Haskell package to add completion scripts for the given
10− # executable produced by it. These completion scripts will be picked up
11− # automatically if the resulting derivation is installed, e.g. by
12− # `nix-env -i`.
13−
14− # TODO: Remove this after updating nixpkgs: https://github.com/NixOS/nixpkgs/issues/37750
15− justStaticExecutables' = drv: let
16− drv' = justStaticExecutables drv;
17− in if pkgs.stdenv.isDarwin
18− then removeConfigureFlag drv' "--ghc-option=-optl=-dead_strip"
19− else drv';
20−
21−
22− addOptparseApplicativeCompletionScripts = exeName: pkg: overrideCabal pkg (drv: {
23− postInstall = (drv.postInstall or "") + ''
24− BASH_COMP_DIR="$out/share/bash-completion/completions"
25− mkdir -p "$BASH_COMP_DIR"
26− "$out/bin/${exeName}" --bash-completion-script "$out/bin/${exeName}" >"$BASH_COMP_DIR/ob"
27−
28− ZSH_COMP_DIR="$out/share/zsh/vendor-completions"
29− mkdir -p "$ZSH_COMP_DIR"
30− "$out/bin/${exeName}" --zsh-completion-script "$out/bin/${exeName}" >"$ZSH_COMP_DIR/_ob"
31−
32− FISH_COMP_DIR="$out/share/fish/vendor_completions.d"
33− mkdir -p "$FISH_COMP_DIR"
34− "$out/bin/${exeName}" --fish-completion-script "$out/bin/${exeName}" >"$FISH_COMP_DIR/ob.fish"
35− '';
36− });
37−
38− # The haskell environment used to build Obelisk itself, e.g. the 'ob' command
39− ghcObelisk = reflex-platform.ghc.override {
40− overrides = composeExtensions defaultHaskellOverrides (self: super: {
41− mkDerivation = args: super.mkDerivation (args // {
42− enableLibraryProfiling = profiling;
43− });
44−
45− #TODO: Eliminate this when https://github.com/phadej/github/pull/307 makes its way to reflex-platform
46− github = overrideCabal super.github (drv: {
47− src = pkgs.fetchFromGitHub {
48− owner = "ryantrinkle";
49− repo = "github";
50− rev = "8f543cdc07876bfb7b924d3722e3dbc1df4b02ca";
51− sha256 = "0vcnx9cxqd821kmjx1r4cvj95zs742qm1pwqnb52vw3djplbqd86";
52− };
53− sha256 = null;
54− revision = null;
55− editedCabalFile = null;
56− });
57
14
58− # Dynamic linking with split objects dramatically increases startup time (about 0.5 seconds on a decent machine with SSD)
15+ inherit (import dep/gitignore.nix { inherit (nixpkgs) lib; }) gitignoreSource;
59− obelisk-command = addOptparseApplicativeCompletionScripts "ob" (justStaticExecutables' super.obelisk-command);
60
16
61− optparse-applicative = self.callHackage "optparse-applicative" "0.14.0.0" {};
17+ getReflexPlatform = { system, enableLibraryProfiling ? profiling }: reflex-platform-func {
62− });
18+ inherit iosSdkVersion config system enableLibraryProfiling;
63− };
64
19
65− fixUpstreamPkgs = self: super: {
20+ nixpkgsOverlays = [
66− heist = doJailbreak super.heist; #TODO: Move up to reflex-platform; create tests for r-p supported packages
21+ (import ./nixpkgs-overlays)
67− network-transport = self.callHackage "network-transport" "0.5.2" {};
68− network-transport-tcp = self.callHackage "network-transport-tcp" "0.6.0" {};
69− };
22+ ];
70
23
71− cleanSource = builtins.filterSource (name: _: let baseName = builtins.baseNameOf name; in !(
24+ haskellOverlays = [
72− builtins.match "^\\.ghc\\.environment.*" baseName != null ||
25+ (import ./haskell-overlays/misc-deps.nix { inherit hackGet; })
73− baseName == "cabal.project.local"
26+ pkgs.obeliskExecutableConfig.haskellOverlay
74− ));
27+ (import ./haskell-overlays/obelisk.nix)
75−
28+ (import ./haskell-overlays/tighten-ob-exes.nix)
76− addLibs = self: super: {
29+ ];
77− obelisk-asset-manifest = self.callCabal2nix "obelisk-asset-manifest" (hackGet ./lib/asset + "/manifest") {};
30+ };
78− obelisk-asset-serve-snap = self.callCabal2nix "obelisk-asset-serve-snap" (hackGet ./lib/asset + "/serve-snap") {};
31+
79− obelisk-backend = self.callCabal2nix "obelisk-backend" (cleanSource ./lib/backend) {};
32+ # The haskell environment used to build Obelisk itself, e.g. the 'ob' command
80− obelisk-command = (self.callCabal2nix "obelisk-command" (cleanSource ./lib/command) {}).override { Cabal = super.Cabal_2_0_0_2; };
33+ ghcObelisk = reflex-platform.ghc;
81− obelisk-run-frontend = self.callCabal2nix "obelisk-run-frontend" (cleanSource ./lib/run-frontend) {};
82− obelisk-selftest = self.callCabal2nix "obelisk-selftest" (cleanSource ./lib/selftest) {};
83− obelisk-snap = self.callCabal2nix "obelisk-snap" (cleanSource ./lib/snap) {};
84− obelisk-snap-extras = self.callCabal2nix "obelisk-snap-extras" (cleanSource ./lib/snap-extras) {};
85− };
86
34
87− defaultHaskellOverrides = composeExtensions fixUpstreamPkgs addLibs;
35+ # Development environments for obelisk packages.
88−in
36+ ghcObeliskEnvs = pkgs.lib.mapAttrs (n: v: reflex-platform.workOn ghcObelisk v) ghcObelisk;
89−with pkgs.lib;
37+
38+ inherit (import ./lib/asset/assets.nix { inherit nixpkgs; }) mkAssets;
39+
40+ haskellLib = pkgs.haskell.lib;
41+
90−rec {
42+in rec {
91 inherit reflex-platform;
43 inherit reflex-platform;
92− inherit (reflex-platform) nixpkgs;
44+ inherit (reflex-platform) nixpkgs pinBuildInputs;
45+ inherit (nixpkgs) lib;
46+ pathGit = ./.; # Used in CI by the migration graph hash algorithm to correctly ignore files.
93 path = reflex-platform.filterGit ./.;
47 path = reflex-platform.filterGit ./.;
48+ obelisk = ghcObelisk;
49+ obeliskEnvs = pkgs.lib.filterAttrs (k: _: k == "tabulation" || pkgs.lib.strings.hasPrefix "obelisk-" k) ghcObeliskEnvs; #TODO: use thunkSet https://github.com/reflex-frp/reflex-platform/pull/671
94 command = ghcObelisk.obelisk-command;
50 command = ghcObelisk.obelisk-command;
95− shell = nixpkgs.stdenv.mkDerivation {
51+ shell = pinBuildInputs "obelisk-shell" ([command] ++ command.commandRuntimeDeps);
96− name = "obelisk-shell";
97− src = null;
98− nativeBuildInputs = [command];
99− };
100
52
101 selftest = pkgs.writeScript "selftest" ''
53 selftest = pkgs.writeScript "selftest" ''
102− #!/usr/bin/env bash
54+ #!${pkgs.runtimeShell}
103 set -euo pipefail
55 set -euo pipefail
104
56
105− PATH="${ghcObelisk.obelisk-command}/bin:$PATH"
57+ PATH="${command}/bin:$PATH"
106− export OBELISK_IMPL="${hackGet ./.}"
58+ cd ${./.}
107− "${justStaticExecutables' ghcObelisk.obelisk-selftest}/bin/obelisk-selftest"
59+ "${ghcObelisk.obelisk-selftest}/bin/obelisk-selftest" +RTS -N -RTS "$@"
108 '';
60 '';
109− #TODO: Why can't I build ./skeleton directly as a derivation? `nix-build -E ./.` doesn't work
110 skeleton = pkgs.runCommand "skeleton" {
61 skeleton = pkgs.runCommand "skeleton" {
111 dir = builtins.filterSource (path: type: builtins.trace path (baseNameOf path != ".obelisk")) ./skeleton;
62 dir = builtins.filterSource (path: type: builtins.trace path (baseNameOf path != ".obelisk")) ./skeleton;
112 } ''
63 } ''
113 ln -s "$dir" "$out"
64 ln -s "$dir" "$out"
114 '';
65 '';
115− nullIfAbsent = p: if pathExists p then p else null;
66+ nullIfAbsent = p: if lib.pathExists p then p else null;
116− haskellOverrides = addLibs;
117 #TODO: Avoid copying files within the nix store. Right now, obelisk-asset-manifest-generate copies files into a big blob so that the android/ios static assets can be imported from there; instead, we should get everything lined up right before turning it into an APK, so that copies, if necessary, only exist temporarily.
67 #TODO: Avoid copying files within the nix store. Right now, obelisk-asset-manifest-generate copies files into a big blob so that the android/ios static assets can be imported from there; instead, we should get everything lined up right before turning it into an APK, so that copies, if necessary, only exist temporarily.
118− processAssets = { src, packageName ? "static", moduleName ? "Static" }: pkgs.runCommand "asset-manifest" {
68+ processAssets = { src, packageName ? "obelisk-generated-static", moduleName ? "Obelisk.Generated.Static" }: pkgs.runCommand "asset-manifest" {
119 inherit src;
69 inherit src;
120 outputs = [ "out" "haskellManifest" "symlinked" ];
70 outputs = [ "out" "haskellManifest" "symlinked" ];
121− buildInputs = [
71+ nativeBuildInputs = [ ghcObelisk.obelisk-asset-manifest ];
122− (reflex-platform.ghc.callCabal2nix "obelisk-asset-manifest" (hackGet ./lib/asset + "/manifest") {})
123− ];
124 } ''
72 } ''
125 set -euo pipefail
73 set -euo pipefail
126 touch "$out"
74 touch "$out"
75+ mkdir -p "$symlinked"
127 obelisk-asset-manifest-generate "$src" "$haskellManifest" ${packageName} ${moduleName} "$symlinked"
76 obelisk-asset-manifest-generate "$src" "$haskellManifest" ${packageName} ${moduleName} "$symlinked"
128 '';
77 '';
78+
79+ compressedJs = frontend: optimizationLevel: pkgs.runCommand "compressedJs" {} ''
80+ set -euo pipefail
81+ cd '${haskellLib.justStaticExecutables frontend}'
82+ shopt -s globstar
83+ for f in **/all.js; do
84+ dir="$out/$(basename "$(dirname "$f")")"
85+ mkdir -p "$dir"
86+ ln -s "$(realpath "$f")" "$dir/all.unminified.js"
87+ ${if optimizationLevel == null then ''
88+ ln -s "$dir/all.unminified.js" "$dir/all.js"
89+ '' else ''
90+ '${pkgs.closurecompiler}/bin/closure-compiler' --externs '${reflex-platform.ghcjsExternsJs}' -O '${optimizationLevel}' --jscomp_warning=checkVars --create_source_map="$dir/all.js.map" --source_map_format=V3 --js_output_file="$dir/all.js" "$dir/all.unminified.js"
91+ echo '//# sourceMappingURL=all.js.map' >> "$dir/all.js"
92+ ''}
93+ done
94+ '';
95+
96+ serverModules = {
97+ mkBaseEc2 = { nixosPkgs, ... }: {...}: {
98+ imports = [
99+ (nixosPkgs.path + /nixos/modules/virtualisation/amazon-image.nix)
100+ ];
101+ ec2.hvm = true;
102+ };
103+
104+ mkDefaultNetworking = { adminEmail, enableHttps, hostName, routeHost, ... }: {...}: {
105+ networking = {
106+ inherit hostName;
107+ firewall.allowedTCPPorts = if enableHttps then [ 80 443 ] else [ 80 ];
108+ };
109+
110+ # `amazon-image.nix` already sets these but if the user provides their own module then
111+ # forgetting these can cause them to lose access to the server!
112+ # https://github.com/NixOS/nixpkgs/blob/fab05f17d15e4e125def4fd4e708d205b41d8d74/nixos/modules/virtualisation/amazon-image.nix#L133-L136
113+ services.openssh.enable = true;
114+ services.openssh.permitRootLogin = "prohibit-password";
115+
116+ security.acme.certs = if enableHttps then {
117+ "${routeHost}".email = adminEmail;
118+ } else {};
119+
120+ security.acme.${if enableHttps && (terms.security.acme.acceptTerms or false) then "acceptTerms" else null} = true;
121+ };
122+
123+ mkObeliskApp =
124+ { exe
125+ , routeHost
126+ , enableHttps
127+ , name ? "backend"
128+ , user ? name
129+ , group ? user
130+ , baseUrl ? "/"
131+ , internalPort ? 8000
132+ , backendArgs ? "--port=${toString internalPort}"
133+ , ...
134+ }: {...}: {
135+ services.nginx = {
136+ enable = true;
137+ recommendedProxySettings = true;
138+ virtualHosts."${routeHost}" = {
139+ enableACME = enableHttps;
140+ forceSSL = enableHttps;
141+ locations.${baseUrl} = {
142+ proxyPass = "http://127.0.0.1:" + toString internalPort;
143+ proxyWebsockets = true;
144+ extraConfig = ''
145+ access_log off;
146+ '';
147+ };
148+ };
149+ };
150+ systemd.services.${name} = {
151+ wantedBy = [ "multi-user.target" ];
152+ after = [ "network.target" ];
153+ restartIfChanged = true;
154+ path = [ pkgs.gnutar ];
155+ script = ''
156+ ln -sft . '${exe}'/*
157+ mkdir -p log
158+ exec ./backend ${backendArgs} </dev/null
159+ '';
160+ serviceConfig = {
161+ User = user;
162+ KillMode = "process";
163+ WorkingDirectory = "~";
164+ Restart = "always";
165+ RestartSec = 5;
166+ };
167+ };
168+ users = {
169+ users.${user} = {
170+ description = "${user} service";
171+ home = "/var/lib/${user}";
172+ createHome = true;
173+ isSystemUser = true;
174+ group = group;
175+ };
176+ groups.${group} = {};
177+ };
178+ };
179+ };
180+
181+ inherit mkAssets;
182+
129− serverExe = backend: frontend: assets: config:
183+ serverExe = backend: frontend: assets: optimizationLevel: version:
130 pkgs.runCommand "serverExe" {} ''
184 pkgs.runCommand "serverExe" {} ''
131 mkdir $out
185 mkdir $out
132 set -eux
186 set -eux
133− ln -s "${backend}"/bin/backend $out/backend
187+ ln -s '${if profiling then backend else haskellLib.justStaticExecutables backend}'/bin/* $out/
134− ln -s ${frontend}/bin/frontend.jsexe $out/frontend.jsexe
135− ln -s "${assets}" $out/static
188+ ln -s '${mkAssets assets}' $out/static.assets
136− ln -s "${config}" $out/config
189+ for d in '${mkAssets (compressedJs frontend optimizationLevel)}'/*/; do
190+ ln -s "$d" "$out"/"$(basename "$d").assets"
191+ done
192+ echo ${version} > $out/version
137 '';
193 '';
138− server = exe: hostName:
194+
139− let system = "x86_64-linux";
195+ server = { exe, hostName, adminEmail, routeHost, enableHttps, version, module ? serverModules.mkBaseEc2 }@args:
196+ let
140− nixos = import (pkgs.path + /nixos);
197+ nixos = import (pkgs.path + /nixos);
141− https = import (pkgs.fetchFromGitHub {
142− owner = "obsidiansystems";
143− repo = "obelisk-https";
144− rev = "999e36b4ab14cbe31be6815cdbc3a1223a7b4617";
145− sha256 = "0qxi7hg751ikkp4r5j7d706gjrsl26lzlrnh905havij10plcg1l";
146− private = true;
147− } + "/module.nix") {} {
148− backendPort = 8000; # TODO read from config
149− # sslConfig = {
150− # hostName = "example.com";
151− # adminEmail = "webmaster@example.com";
152− # subdomains = [ "www" ];
153− # };
154− };
155 in nixos {
198 in nixos {
156− inherit system;
199+ system = "x86_64-linux";
157− configuration = args: {
200+ configuration = {
158 imports = [
201 imports = [
202+ (module { inherit exe hostName adminEmail routeHost enableHttps version; nixosPkgs = pkgs; })
203+ (serverModules.mkDefaultNetworking args)
204+ (serverModules.mkObeliskApp args)
205+ ./acme.nix # Backport of ACME upgrades from 20.03
206+ ];
207+
208+ # Backport of ACME upgrades from 20.03
209+ disabledModules = [
159− (pkgs.path + /nixos/modules/virtualisation/amazon-image.nix)
210+ (pkgs.path + /nixos/modules/security/acme.nix)
160− https
211+ ];
212+ nixpkgs.overlays = [
213+ (self: super: {
214+ lego = (import (builtins.fetchTarball {
215+ url = https://github.com/NixOS/nixpkgs-channels/archive/70717a337f7ae4e486ba71a500367cad697e5f09.tar.gz;
216+ sha256 = "1sbmqn7yc5iilqnvy9nvhsa9bx6spfq1kndvvis9031723iyymd1";
217+ }) {}).lego;
218+ })
161 ];
219 ];
162− networking = { inherit hostName; };
163− systemd.services.backend = {
164− wantedBy = [ "multi-user.target" ];
165− after = [ "network.target" ];
166− restartIfChanged = true;
167− script = ''
168− ln -sft . "${exe}"/*
169− mkdir -p log
170− exec ./backend >>backend.out 2>>backend.err </dev/null
171− '';
172− serviceConfig = {
173− User = "backend";
174− KillMode = "process";
175− WorkingDirectory = "~";
176− Restart = "always";
177− RestartSec = 5;
178− };
179− };
180− users.extraUsers.backend = {
181− description = "backend service";
182− home = "/var/lib/backend";
183− createHome = true;
184− isSystemUser = true;
185− group = "backend";
186− };
187− ec2.hvm = true;
188 };
220 };
189 };
221 };
190
222
191−
192 # An Obelisk project is a reflex-platform project with a predefined layout and role for each component
223 # An Obelisk project is a reflex-platform project with a predefined layout and role for each component
193− project = base: projectDefinition:
224+ project = base': projectDefinition:
194− let assets = processAssets { src = base + "/static"; };
225+ let
195− configPath = base + "/config";
226+ projectOut = { system, enableLibraryProfiling ? profiling }: let reflexPlatformProject = (getReflexPlatform { inherit system enableLibraryProfiling; }).project; in reflexPlatformProject (args@{ nixpkgs, ... }:
196− projectOut = reflex-platform.project (args@{ nixpkgs, ... }:
227+ let
228+ inherit (lib.strings) hasPrefix;
229+ mkProject =
197− let mkProject = { android ? null #TODO: Better error when missing
230+ { android ? null #TODO: Better error when missing
198− , ios ? null #TODO: Better error when missing
231+ , ios ? null #TODO: Better error when missing
199− , packages ? {}
232+ , packages ? {}
200− , overrides ? _: _: {}
233+ , overrides ? _: _: {}
234+ , staticFiles ? null
235+ , tools ? _: []
236+ , shellToolOverrides ? _: _: {}
237+ , withHoogle ? false # Setting this to `true` makes shell reloading far slower
238+ , __closureCompilerOptimizationLevel ? "ADVANCED" # Set this to `null` to skip the closure-compiler step
239+ , __withGhcide ? false
201− }:
240+ }:
241+ let
242+ allConfig = nixpkgs.lib.makeExtensible (self: {
243+ base = base';
244+ inherit args;
245+ userSettings = {
246+ inherit android ios packages overrides tools shellToolOverrides withHoogle __closureCompilerOptimizationLevel __withGhcide;
247+ staticFiles = if staticFiles == null then self.base + /static else staticFiles;
248+ };
202− let frontendName = "frontend";
249+ frontendName = "frontend";
203− backendName = "backend";
250+ backendName = "backend";
204− commonName = "common";
251+ commonName = "common";
205− staticName = "static";
252+ staticName = "obelisk-generated-static";
206− staticPath = base + "/static";
253+ staticFilesImpure = let fs = self.userSettings.staticFiles; in if lib.isDerivation fs then fs else toString fs;
207− assets = processAssets { src = base + "/static"; };
254+ processedStatic = processAssets { src = self.userSettings.staticFiles; };
208− # The packages whose names and roles are defined by this package
255+ # The packages whose names and roles are defined by this package
209− predefinedPackages = filterAttrs (_: x: x != null) {
256+ predefinedPackages = lib.filterAttrs (_: x: x != null) {
210− ${frontendName} = nullIfAbsent (base + "/frontend");
257+ ${self.frontendName} = nullIfAbsent (self.base + "/frontend");
211− ${commonName} = nullIfAbsent (base + "/common");
258+ ${self.commonName} = nullIfAbsent (self.base + "/common");
212− ${backendName} = nullIfAbsent (base + "/backend");
259+ ${self.backendName} = nullIfAbsent (self.base + "/backend");
213− };
260+ };
261+ shellPackages = {};
214− combinedPackages = predefinedPackages // packages;
262+ combinedPackages = self.predefinedPackages // self.userSettings.packages // self.shellPackages;
215− projectOverrides = self: super: {
263+ projectOverrides = self': super': {
216− ${staticName} = dontHaddock (self.callCabal2nix "static" assets.haskellManifest {});
264+ ${self.staticName} = haskellLib.dontHaddock (self'.callCabal2nix self.staticName self.processedStatic.haskellManifest {});
217− frontend = if self.ghc.isGhcjs or false then super.frontend.override { obelisk-run-frontend = null; } else super.frontend;
265+ ${self.backendName} = haskellLib.addBuildDepend super'.${self.backendName} self'.obelisk-run;
218− };
219− totalOverrides = composeExtensions (composeExtensions defaultHaskellOverrides projectOverrides) overrides;
220− ghcDevPackages = ["obelisk-run-frontend"];
221− in {
222− overrides = totalOverrides;
223− packages = combinedPackages;
224− shells = {
225− ghc = (filter (x: hasAttr x combinedPackages) [
226− backendName
227− commonName
228− frontendName
229− ]);
230− ghcjs = filter (x: hasAttr x combinedPackages) [
231− frontendName
232− commonName
233− ];
234 };
266 };
235− withHoogle = false; # Setting this to `true` makes shell reloading far slower
267+ totalOverrides = lib.composeExtensions self.projectOverrides self.userSettings.overrides;
236− android = {
268+ privateConfigDirs = ["config/backend"];
269+ injectableConfig = builtins.filterSource (path: _:
270+ !(lib.lists.any (x: hasPrefix (toString self.base + "/" + toString x) (toString path)) self.privateConfigDirs)
271+ );
272+ __androidWithConfig = configPath: {
237− ${if android == null then null else frontendName} = {
273+ ${if self.userSettings.android == null then null else self.frontendName} = {
238 executableName = "frontend";
274 executableName = "frontend";
239− ${if builtins.pathExists staticPath then "assets" else null} = assets.symlinked;
275+ ${if builtins.pathExists self.userSettings.staticFiles then "assets" else null} =
276+ nixpkgs.obeliskExecutableConfig.platforms.android.inject
277+ (self.injectableConfig configPath)
278+ self.processedStatic.symlinked;
240− } // android;
279+ } // self.userSettings.android;
241 };
280 };
242− ios = {
281+ __iosWithConfig = configPath: {
243− ${if ios == null then null else frontendName} = {
282+ ${if self.userSettings.ios == null then null else self.frontendName} = {
244 executableName = "frontend";
283 executableName = "frontend";
245− ${if builtins.pathExists staticPath then "staticSrc" else null} = assets.symlinked;
284+ ${if builtins.pathExists self.userSettings.staticFiles then "staticSrc" else null} =
246− } // ios;
285+ nixpkgs.obeliskExecutableConfig.platforms.ios.inject
286+ (self.injectableConfig configPath)
287+ self.processedStatic.symlinked;
288+ } // self.userSettings.ios;
247 };
289 };
290+
291+ shells-ghc = builtins.attrNames (self.predefinedPackages // self.shellPackages);
292+
293+ shells-ghcjs = [
294+ self.frontendName
295+ self.commonName
296+ ];
297+
298+ shells-ghcSavedSplices = [
299+ self.commonName
300+ self.frontendName
301+ ];
302+
303+ shellToolOverrides = lib.composeExtensions
304+ self.userSettings.shellToolOverrides
305+ (if self.userSettings.__withGhcide
306+ then (import ./haskell-overlays/ghcide.nix)
307+ else (_: _: {})
308+ );
309+
310+ project = reflexPlatformProject ({...}: self.projectConfig);
311+ projectConfig = {
312+ inherit (self) shellToolOverrides;
313+ inherit (self.userSettings) tools withHoogle;
314+ overrides = self.totalOverrides;
315+ packages = self.combinedPackages;
316+ shells = {
317+ ${if self.userSettings.android == null && self.userSettings.ios == null then null else "ghcSavedSplices"} =
318+ lib.filter (x: lib.hasAttr x self.combinedPackages) self.shells-ghcSavedSplices;
319+ ghc = lib.filter (x: lib.hasAttr x self.combinedPackages) self.shells-ghc;
320+ ghcjs = lib.filter (x: lib.hasAttr x self.combinedPackages) self.shells-ghcjs;
321+ };
322+ android = self.__androidWithConfig (self.base + "/config");
323+ ios = self.__iosWithConfig (self.base + "/config");
324+
325+ passthru = {
326+ __unstable__.self = allConfig;
327+ inherit (self)
328+ staticFilesImpure processedStatic
329+ __iosWithConfig __androidWithConfig
330+ ;
331+ inherit (self.userSettings)
332+ android ios overrides packages shellToolOverrides staticFiles tools withHoogle
333+ __closureCompilerOptimizationLevel
334+ ;
335+ };
336+ };
248− };
337+ });
338+ in allConfig;
249− in mkProject (projectDefinition args));
339+ in (mkProject (projectDefinition args)).projectConfig);
250− in projectOut //
340+ mainProjectOut = projectOut { inherit system; };
251− { server = { hostName }:
341+ serverOn = projectInst: version: serverExe
252− let exe = serverExe projectOut.ghc.backend projectOut.ghcjs.frontend assets.symlinked configPath;
342+ projectInst.ghc.backend
253− in server exe hostName;
343+ mainProjectOut.ghcjs.frontend
254− };
344+ projectInst.passthru.staticFiles
255− haskellPackageSets = {
345+ projectInst.passthru.__closureCompilerOptimizationLevel
256− ghc = reflex-platform.ghc.override {
346+ version;
257− overrides = defaultHaskellOverrides;
347+ linuxExe = serverOn (projectOut { system = "x86_64-linux"; });
348+ dummyVersion = "Version number is only available for deployments";
349+ in mainProjectOut // {
350+ __unstable__.profiledObRun = let
351+ profiled = projectOut { inherit system; enableLibraryProfiling = true; };
352+ exeSource = builtins.toFile "ob-run.hs" ''
353+ {-# LANGUAGE NoImplicitPrelude #-}
354+ {-# LANGUAGE PackageImports #-}
355+ module Main where
356+
357+ -- Explicitly import Prelude from base lest there be multiple modules called Prelude
358+ import "base" Prelude (IO, (++), read)
359+
360+ import "base" Control.Exception (finally)
361+ import "reflex" Reflex.Profiled (writeProfilingData)
362+ import "base" System.Environment (getArgs)
363+
364+ import qualified "obelisk-run" Obelisk.Run
365+ import qualified Frontend
366+ import qualified Backend
367+
368+ main :: IO ()
369+ main = do
370+ [portStr, assets, profFileName] <- getArgs
371+ Obelisk.Run.run (read portStr) (Obelisk.Run.runServeAsset assets) Backend.backend Frontend.frontend
372+ `finally` writeProfilingData (profFileName ++ ".rprof")
373+ '';
374+ in nixpkgs.runCommand "ob-run" {
375+ buildInputs = [ (profiled.ghc.ghcWithPackages (p: [p.backend p.frontend])) ];
376+ } ''
377+ cp ${exeSource} ob-run.hs
378+ mkdir -p $out/bin
379+ ghc -x hs -prof -fno-prof-auto -threaded ob-run.hs -o $out/bin/ob-run
380+ '';
381+
382+ linuxExeConfigurable = linuxExe;
383+ linuxExe = linuxExe dummyVersion;
384+ exe = serverOn mainProjectOut dummyVersion;
385+ server = args@{ hostName, adminEmail, routeHost, enableHttps, version, module ? serverModules.mkBaseEc2 }:
386+ server (args // { exe = linuxExe version; });
387+ obelisk = import (base' + "/.obelisk/impl") {};
258 };
388 };
389+ haskellPackageSets = {
390+ inherit (reflex-platform) ghc ghcjs;
259 };
391 };
260}
392}
lib/https/default.nix → dep/ghcid/default.nixrenamed

The content is the same.

dep/ghcid/github.jsonnew file+7
@@ -0,0 +1,7 @@
1+{
2+ "owner": "ndmitchell",
3+ "repo": "ghcid",
4+ "branch": "master",
5+ "rev": "f572318f32b1617f6054248e5888af68222f8e50",
6+ "sha256": "1icg3r70lg2kmd9gdc024ih1n9nrja98yav74z9nvykqygvv5w0n"
7+}
dep/gitignore.nix/default.nixnew file+8
@@ -0,0 +1,8 @@
1+# DO NOT HAND-EDIT THIS FILE
2+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3+ if !fetchSubmodules && !private then builtins.fetchTarball {
4+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5+ } else (import <nixpkgs> {}).fetchFromGitHub {
6+ inherit owner repo rev sha256 fetchSubmodules private;
7+ };
8+in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))
dep/gitignore.nix/github.jsonnew file+8
@@ -0,0 +1,8 @@
1+{
2+ "owner": "hercules-ci",
3+ "repo": "gitignore.nix",
4+ "branch": "master",
5+ "private": false,
6+ "rev": "7415c4feb127845553943a3856cbc5cb967ee5e0",
7+ "sha256": "1zd1ylgkndbb5szji32ivfhwh04mr1sbgrnvbrqpmfb67g2g3r9i"
8+}
dep/hnix/default.nixnew file+7
@@ -0,0 +1,7 @@
1+# DO NOT HAND-EDIT THIS FILE
2+import ((import <nixpkgs> {}).fetchFromGitHub (
3+ let json = builtins.fromJSON (builtins.readFile ./github.json);
4+ in { inherit (json) owner repo rev sha256;
5+ private = json.private or false;
6+ }
7+))
dep/hnix/github.jsonnew file+7
@@ -0,0 +1,7 @@
1+{
2+ "owner": "haskell-nix",
3+ "repo": "hnix",
4+ "branch": "master",
5+ "rev": "6c9c7c310c54372b3db0fdf5a0137b395cde1bdb",
6+ "sha256": "1i5903b7lxqn2s3jarb14h6wdq8bxiik1hp0xy43w5w1hgvvq0g5"
7+}
dep/reflex-platform/default.nix+1−6
@@ -1,7 +1,2 @@
1# DO NOT HAND-EDIT THIS FILE
1# DO NOT HAND-EDIT THIS FILE
2−import ((import <nixpkgs> {}).fetchFromGitHub (
2+import (import ./thunk.nix)
3− let json = builtins.fromJSON (builtins.readFile ./github.json);
4− in { inherit (json) owner repo rev sha256;
5− private = json.private or false;
6− }
7−))
dep/reflex-platform/github.json+4−3
@@ -1,7 +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.7.0.0",
5− "rev": "f70d210a59a2817293d3b6c3d960b5710aae5c03",
5+ "private": false,
6− "sha256": "0hm4im0865j1vxdqhy987dp2v0wcqy5xfx2nzxq625slnsf458p1"
6+ "rev": "27a7851a780ff21472d85f9a02fb84635ef9027a",
7+ "sha256": "1m4zlw91dpjlbdchjyxhvhv3k7lilm0qa17dhhww868xxc27sann"
7}
8}
dep/reflex-platform/thunk.nixnew file+9
@@ -0,0 +1,9 @@
1+# DO NOT HAND-EDIT THIS FILE
2+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3+ if !fetchSubmodules && !private then builtins.fetchTarball {
4+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5+ } else (import <nixpkgs> {}).fetchFromGitHub {
6+ inherit owner repo rev sha256 fetchSubmodules private;
7+ };
8+ json = builtins.fromJSON (builtins.readFile ./github.json);
9+in fetch json
dep/snap-core/default.nixnew file+8
@@ -0,0 +1,8 @@
1+# DO NOT HAND-EDIT THIS FILE
2+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3+ if !fetchSubmodules && !private then builtins.fetchTarball {
4+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5+ } else (import <nixpkgs> {}).fetchFromGitHub {
6+ inherit owner repo rev sha256 fetchSubmodules private;
7+ };
8+in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))
dep/snap-core/github.jsonnew file+8
@@ -0,0 +1,8 @@
1+{
2+ "owner": "obsidiansystems",
3+ "repo": "snap-core",
4+ "branch": "ts-expose-fileserve-internals",
5+ "private": false,
6+ "rev": "e015fc484e38dd9389c58b277b1884395e553bdf",
7+ "sha256": "1793x1h4lw9vnrii5akhfxx1x9yrgxf3052jf6bs8f1mhaic6mxx"
8+}
docs/obelisk-logo-640.pngnew file

Binary file not shown.

guides/app-deploy/README.mdnew file+324
@@ -0,0 +1,324 @@
1+# Obelisk Application Deployment Guide
2+
3+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.
4+
5+> **Note:** This guide can be completed on a Linux host with Nix installed or a macOS host with Nix installed. Each section is labeled regarding which operating system hosts it supports. When going through the guide, start at the beginning and go through all sections that are supported on your host and merely skip sections that are not supported. The sections for iOS deployments require an iPhone or iPad device and the sections for Android deployments require an Android device. This guide assumes that you have Nix correctly set up and that your system is configured 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.
6+>
7+> 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.
8+
9+## a) Get Obelisk (Linux, Mac)
10+
11+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 its GitHub repository and start a project that uses that local check out.
12+
13+Open a terminal and run the following:
14+
15+```bash
16+export WORKDIR=~/obelisk-guide
17+mkdir -p "$WORKDIR"
18+```
19+
20+Then let's get Obelisk from GitHub using a specific branch:
21+
22+```bash
23+export OBELISK_BRANCH=develop
24+git clone https://github.com/obsidiansystems/obelisk.git -b "$OBELISK_BRANCH" "$WORKDIR/obelisk"
25+```
26+
27+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.
28+
29+```bash
30+alias ob=$(nix-build "$WORKDIR/obelisk" -A command --no-out-link)/bin/ob
31+```
32+
33+In order to start an Obelisk project, we need initialize it in a new directory. Let's call it `myapp`:
34+
35+```bash
36+mkdir -p "$WORKDIR/myapp"
37+cd "$WORKDIR/myapp"
38+ob init --branch "$OBELISK_BRANCH"
39+```
40+
41+> **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.
42+
43+## b) Run the Obelisk app on localhost (Linux, Mac)
44+
45+Let's test that we can run a server on localhost. This is quite easy:
46+
47+```bash
48+cd "$WORKDIR/myapp"
49+ob run
50+```
51+
52+Now open a browser and point it to http://localhost:8000 (or just click on this link). You should see the following:
53+
54+![](assets/app-deploy.png)
55+
56+## c) Prepare a VirtualBox deploy target (Linux, Mac)
57+
58+### Import the NixOS VirtualBox appliance
59+
60+Install [VirtualBox](https://www.virtualbox.org/) on your machine.
61+
62+On NixOS, do this by adding the following line to your `/etc/nixos/configuration.nix` before the last line containing `}`:
63+
64+```nix
65+ virtualisation.virtualbox.host.enable = true;
66+```
67+
68+then `sudo nixos-rebuild switch`.
69+
70+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.
71+
72+With the downloaded file, open VirtualBox and import the `.ova` file:
73+
74+![](assets/virtualbox-appliance-import.png)
75+
76+Leave the default settings and finish the import. That will take a few minutes:
77+
78+![](assets/virtualbox-appliance-import-loading.png)
79+
80+You should now see a NixOS machine in the dashboard:
81+
82+![](assets/virtualbox-dashboard-nixos.png)
83+
84+If you are on a network with DHCP on your wireless or network card then right-click on the "NixOS" image and click "Settings". Go to the "Network" section and make "Attached to:" set to "Bridged Adapter".
85+
86+![](assets/virtualbox-image-settings-network.png)
87+
88+Finally, double-click on the "NixOS" machine and wait for it boot up. If it asks for a password, use `demo`.
89+
90+![](assets/virtualbox-nioxs-after-boot.png)
91+
92+### Configure the virtual machine for SSH
93+
94+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.
95+
96+Change the system configuration using `sudo` to enable SSH access:
97+
98+```bash
99+sudo nano /etc/nixos/configuration.nix
100+```
101+
102+This will ask you to enter your password. Enter `demo`.
103+
104+![](assets/nano-edit-nixos-configuration.png)
105+
106+You need to add the following snippet right before the final line containing `}`.
107+
108+```nix
109+ services.openssh.enable = true;
110+ services.openssh.permitRootLogin = "yes";
111+```
112+
113+Save and close the editor by typing <kbd>Ctrl</kbd>+<kbd>O</kbd>, <kbd>Enter</kbd>, and then <kbd>Ctrl</kbd>+<kbd>X</kbd>.
114+
115+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.
116+
117+To get the virtual machine's IP address go back to the terminal on your *host* machine (not the virtual machine) and run:
118+
119+```bash
120+export VM_ID=$(VBoxManage list runningvms | grep "NixOS" | awk -F'[{}]' '{print $2}')
121+echo "$VM_ID"
122+```
123+
124+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.)
125+
126+Now get the IP address for that machine:
127+
128+```bash
129+export VM_IP=$(VBoxManage guestproperty enumerate "$VM_ID" | grep /V4/IP | awk '{print $4}' | sed 's/,//')
130+echo "$VM_IP"
131+```
132+
133+You should see an IP like `192.168.7.86`.
134+
135+With that you will be able to SSH into that machine from a terminal, using the username `root`.
136+
137+```bash
138+ssh root@$VM_IP echo "Access granted"
139+```
140+
141+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>.
142+
143+> **Note:** If instead you see an error like this
144+>
145+> ```
146+> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
147+> @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
148+> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
149+> IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
150+> Someone could be eavesdropping on you right now (man-in-the-middle attack)!
151+> It is also possible that a host key has just been changed.
152+> ```
153+>
154+> you need to remove the old fingerprint for this IP. Run the following:
155+>
156+> ```bash
157+> sed -i "/^$VM_IP /d" ~/.ssh/known_hosts
158+> ```
159+>
160+> and then try the previous `ssh` command again.
161+
162+Now we'll allow access with an SSH key instead of a password. Create a new SSH key with `ssh-keygen`:
163+
164+```bash
165+ssh-keygen -t ed25519 -f "$WORKDIR/obkey" -P ""
166+```
167+
168+Now copy your local SSH key to the server:
169+
170+```bash
171+ssh-copy-id -i "$WORKDIR/obkey.pub" root@$VM_IP
172+```
173+
174+This will ask you for your password again.
175+
176+Now test login with your key instead:
177+
178+```bash
179+ssh -i "$WORKDIR/obkey" root@$VM_IP echo "Access granted"
180+```
181+
182+This should print `Access granted` *without* asking for a password.
183+
184+### Configure the git remote
185+
186+Before the project can be deployed, it needs to be a valid `git` repository.
187+
188+> **Note:** You need `git` installed and configured. You can do that with:
189+>
190+> ```bash
191+> nix-env -i git
192+> git config --global user.name "John Doe"
193+> git config --global user.email johndoe@example.com
194+> ```
195+
196+```bash
197+git init --bare "$WORKDIR/myapp-git-remote"
198+cd "$WORKDIR/myapp"
199+git init
200+git add --all
201+git commit -m "initial commit"
202+git remote add origin "$WORKDIR/myapp-git-remote"
203+git push -u origin master
204+```
205+
206+### Initialize deployment directory
207+
208+With that, we can come back to the Obelisk app and initialize the deployment:
209+
210+```bash
211+cd "$WORKDIR/myapp"
212+ob deploy init --ssh-key "$WORKDIR/obkey" --admin-email a@a.a --hostname $VM_IP --route https://$VM_IP "$WORKDIR/myappdeploy" --disable-https
213+```
214+
215+Then configure the deployment for VirtualBox:
216+
217+```bash
218+echo '{nixosPkgs, ...}: {...}: { imports = [ (nixosPkgs.path + /nixos/modules/virtualisation/virtualbox-image.nix) ]; }' > "$WORKDIR/myappdeploy/module.nix"
219+```
220+
221+## d) Deploy to VirtualBox target (Linux only)
222+
223+> Deploying requires a Linux host in order to build the Linux binaries.
224+
225+Now we can deploy to the VirtualBox VM.
226+
227+```bash
228+cd "$WORKDIR/myappdeploy"
229+ob deploy push -v
230+```
231+
232+Once that is complete, open the webpage with
233+
234+```bash
235+xdg-open http://$VM_IP
236+```
237+
238+If that fails, just get the URL by running
239+
240+```bash
241+echo http://$VM_IP
242+```
243+
244+and copy/paste that URL into your browser navigation input.
245+
246+It should look like this:
247+
248+![](assets/app-deploy-2.png)
249+
250+Congratulations! You have deployed an Obelisk application to a remote server via SSH.
251+
252+## e) Deploy an Android app (Linux only)
253+
254+> **Note:** This section requires that you be running a Linux *host*.
255+
256+Modify `$WORKDIR/myapp/default.nix` to set `config.android_sdk.accept_license = true;` and then update your app.
257+
258+```bash
259+cd "$WORKDIR/myapp"
260+sed -i 's/# config.android_sdk.accept_license = false;/config.android_sdk.accept_license = true;/g' default.nix
261+git add default.nix
262+git commit -m"Accept license"
263+git push
264+```
265+
266+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.
267+
268+Now update your deployment and deploy to Android:
269+
270+```bash
271+cd "$WORKDIR/myappdeploy"
272+ob deploy update
273+ob deploy test android -v
274+```
275+
276+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:
277+
278+```
279+Is CN=a, OU=b, O=c, L=d, ST=e, C=f correct?
280+ [no]:
281+```
282+
283+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.
284+
285+When connecting your Android device you may be asked to "Allow USB debugging". You need to allow it.
286+![](assets/android-confirm-usb-debugging.jpg)
287+
288+
289+When the deployment is complete opening the app should look something like
290+
291+![](assets/android-app.jpg)
292+
293+Congratulations! You have deployed an Obelisk Android app via USB.
294+
295+## f) Deploy an iOS app (Mac only)
296+
297+> **Note:** This section requires that you be running a macOS *host*.
298+
299+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.
300+
301+![](assets/xcode-devices.png)
302+
303+Find your `Team ID` at the following URL (Apple Developer Membership details): https://developer.apple.com/account/#/membership/
304+
305+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:
306+
307+```bash
308+cd "$WORKDIR/myappdeploy"
309+ob deploy test ios <TEAM-ID> # Use your Team ID here
310+```
311+
312+![](assets/ios-deploy-keychain.png)
313+
314+![](assets/ios-deploy-example.png)
315+
316+If there are no errors and the last line says `100% Installed Package` you can open the device and look for the Obelisk app:
317+
318+![](assets/ios-obelisk-app-icon.jpg)
319+
320+![](assets/ios-obelisk-app-open.jpg)
321+
322+Congratulations, you have deployed an Obelisk app on an iOS device.
323+
324+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+40
@@ -0,0 +1,40 @@
1+self: super:
2+let
3+ pkgs = self.callPackage ({ pkgs }: pkgs) { };
4+ inherit (pkgs.haskell.lib) dontCheck justStaticExecutables;
5+ inherit (pkgs.haskellPackages) callHackageDirect callHackage;
6+
7+in {
8+ ghcide = justStaticExecutables (dontCheck (callHackageDirect {
9+ pkg = "ghcide";
10+ ver = "0.2.0";
11+ sha256 = "199l4qzrghhz6wbfkgqdl4gll4wvgpr190kinzhv88idnn9pxm96";
12+ } rec {
13+ ghc-check = callHackageDirect {
14+ pkg = "ghc-check";
15+ ver = "0.3.0.1";
16+ sha256 = "1dj909m09m24315x51vxvcl28936ahsw4mavbc53danif3wy09ns";
17+ } { };
18+ lsp-test = dontCheck (callHackage "lsp-test" "0.6.1.0" { });
19+ haddock-library = dontCheck (callHackage "haddock-library" "1.8.0" { });
20+ haskell-lsp = dontCheck (callHackageDirect {
21+ pkg = "haskell-lsp";
22+ ver = "0.22.0.0";
23+ sha256 = "1q3w46qcvzraxgmw75s7bl0qvb2fvff242r5vfx95sqska566b4m";
24+ } { inherit haskell-lsp-types; });
25+ haskell-lsp-types = dontCheck (callHackageDirect {
26+ pkg = "haskell-lsp-types";
27+ ver = "0.22.0.0";
28+ sha256 = "1apjclphi2v6ggrdnbc0azxbb1gkfj3x1vkwpc8qd6lsrbyaf0n8";
29+ } { });
30+ regex-tdfa = dontCheck (callHackage "regex-tdfa" "1.3.1.0" {
31+ regex-base = dontCheck (callHackage "regex-base" "0.94.0.0" { });
32+ });
33+ shake = dontCheck (callHackage "shake" "0.18.4" { });
34+ hie-bios = dontCheck (callHackageDirect {
35+ pkg = "hie-bios";
36+ ver = "0.5.0";
37+ sha256 = "116nmpva5jmlgc2dgy8cm5wv6cinhzmga1l0432p305074w720r2";
38+ } { });
39+ }));
40+}
haskell-overlays/misc-deps.nixnew file+26
@@ -0,0 +1,26 @@
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+ regex-base = self.callHackage "regex-base" "0.94.0.0" {};
13+ regex-posix = self.callHackage "regex-posix" "0.96.0.0" {};
14+ regex-tdfa = self.callHackage "regex-tdfa" "1.3.1.0" {};
15+ test-framework = haskellLib.dontCheck (self.callHackage "test-framework" "0.8.2.0" {});
16+ hnix = haskellLib.dontCheck (self.callHackage "hnix" "0.8.0" {});
17+ hnix-store-core = self.callHackage "hnix-store-core" "0.2.0.0" {};
18+
19+ aeson-gadt-th = self.callHackage "aeson-gadt-th" "0.2.4" {};
20+
21+ ghcid = self.callCabal2nix "ghcid" (hackGet ../dep/ghcid) {};
22+ # Exports more internals
23+ snap-core = haskellLib.dontCheck (self.callCabal2nix "snap-core" (hackGet ../dep/snap-core) {});
24+
25+ shelly = self.callHackage "shelly" "1.9.0" {};
26+}
haskell-overlays/obelisk.nixnew file+48
@@ -0,0 +1,48 @@
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.git
23+ pkgs.nix
24+ pkgs.nix-prefetch-git
25+ pkgs.openssh
26+ pkgs.rsync
27+ pkgs.which
28+ (haskellLib.justStaticExecutables self.ghcid)
29+ ];
30+ };
31+ obelisk-frontend = self.callCabal2nix "obelisk-frontend" (obeliskCleanSource ../lib/frontend) {};
32+ obelisk-run = onLinux (self.callCabal2nix "obelisk-run" (obeliskCleanSource ../lib/run) {}) (pkg:
33+ haskellLib.overrideCabal pkg (drv: { librarySystemDepends = [ pkgs.iproute ]; })
34+ );
35+ obelisk-route = self.callCabal2nix "obelisk-route" (obeliskCleanSource ../lib/route) {};
36+ obelisk-selftest = haskellLib.overrideCabal (self.callCabal2nix "obelisk-selftest" (obeliskCleanSource ../lib/selftest) {}) {
37+ librarySystemDepends = [
38+ pkgs.cabal-install
39+ pkgs.coreutils
40+ pkgs.git
41+ pkgs.nix
42+ pkgs.nix-prefetch-git
43+ pkgs.rsync
44+ ];
45+ };
46+ obelisk-snap-extras = self.callCabal2nix "obelisk-snap-extras" (obeliskCleanSource ../lib/snap-extras) {};
47+ tabulation = self.callCabal2nix "tabulation" (obeliskCleanSource ../lib/tabulation) {};
48+}
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+}
hydra.jsonnew file+29
@@ -0,0 +1,29 @@
1+{
2+ "enabled": 1,
3+ "hidden": true,
4+ "description": "Jobsets",
5+ "nixexprinput": "src",
6+ "nixexprpath": "jobsets.nix",
7+ "checkinterval": 300,
8+ "schedulingshares": 100,
9+ "enableemail": false,
10+ "emailoverride": "",
11+ "keepnr": 10,
12+ "inputs": {
13+ "src": {
14+ "type": "git",
15+ "value": "https://github.com/obsidiansystems/obelisk.git master",
16+ "emailresponsible": false
17+ },
18+ "nixpkgs": {
19+ "type": "git",
20+ "value": "https://github.com/NixOS/nixpkgs-channels nixos-unstable",
21+ "emailresponsible": false
22+ },
23+ "prs": {
24+ "type": "githubpulls",
25+ "value": "obsidiansystems obelisk",
26+ "emailresponsible": false
27+ }
28+ }
29+}
lib/README.md+3−1
@@ -1 +1,3 @@
1−Libraries provided by obelisk
1+# Obelisk libraries
2+
3+This directory contains libraries provided by obelisk. By convention they are prefixed with `obelisk-` and their module exports all lie within the `Obelisk` import namespace. For example, to include `cliapp` as a dependency you would add `obelisk-cliapp` to your cabal dependencies, and import `Obelisk.CliApp...` in the source files.
lib/asset/README.md+17−20
@@ -1,29 +1,26 @@
1−## obelisk-asset
1+# obelisk-asset
2
2
3−The 'assets.nix' file contains nix expressions that are a mutually
3+[![Haskell Programming Language](https://img.shields.io/badge/language-Haskell-blue.svg)](http://www.haskell.org)
4−recursive set of attributes used to create static asset directories
4+[![BSD3 License](http://img.shields.io/badge/license-BSD3-brightgreen.svg)](https://github.com/obsidiansystems/obelisk/blob/master/LICENSE)
5−with hashable file encodings. This file should be incorporated within
6−your project's 'default.nix' file. (See ./example/default.nix , line 2)
7−```
8−{assets ? import ./../assets.nix { inherit nixpkgs; }
9−}:
10−```
11
5
12−The 'mkAssets' and 'mkAssetsWith' functions within 'assets.nix' only
6+**Efficiently served, aggressively cached static web resources.**
13−need to be passed an encoding('zopfliEncodings', 'gzipEncodings',
14−'noEncodings') and a static directory of your choice as arguments.
15
7
16−In this example, 'mkAssets' is used on a directory that has a .png
8+The `assets.nix` file contains nix expressions that are a mutually recursive set of attributes used to create static asset directories with hashable file encodings. This file should be incorporated within your project's `default.nix` file. (See `example/default.nix`, line 2)
17−file inside of it. (See ./example/default.nix, line 11)
9+
10+```nix
11+{ assets ? import ./../assets.nix { inherit nixpkgs; } }:
18```
12```
13+
14+The `mkAssets` and `mkAssetsWith` functions within `assets.nix` only need to be passed an `encoding("zopfliEncodings", "gzipEncodings", "noEncodings")` and a static directory of your choice as arguments.
15+
16+In this example, `mkAssets` is used on a directory that has a `.png` file inside of it. (See `example/default.nix`, line 11)
17+
18+```nix
19−myAssets = assets.mkAssets ./static;
19+myAssets = assets.mkAssets ./static;
20```
20```
21
21
22−Once you have successfully incorporated 'assets.nix' into your
22+Once you have successfully incorporated `assets.nix` into your project's nix file(s), use `nix-build` to generate a symlink of your `mkAssets` expression. The following command from `example/run-example` (line 3) will generate an immutable symlink that holds hashed static assets.
23−project's nix file(s), use nix-build to generate a symlink of
23+
24−your 'mkAssets' expression. The following command from
25−example/run-example (line 3) will generate an immutable symlink
26−that holds hashed static assets.
27```bash
24```bash
28nix-build -o static.assets -A myAssets
25nix-build -o static.assets -A myAssets
29```
26```
lib/asset/assets.nix+28−5
@@ -20,7 +20,7 @@ zopfliEncodings = file:
20 nixpkgs.stdenv.mkDerivation {
20 nixpkgs.stdenv.mkDerivation {
21 name = "encodings";
21 name = "encodings";
22
22
23− input = file;
23+ input = mkPath file;
24
24
25 builder = builtins.toFile "builder.sh" ''
25 builder = builtins.toFile "builder.sh" ''
26 source "$stdenv/setup"
26 source "$stdenv/setup"
@@ -46,7 +46,7 @@ gzipEncodings = file:
46 nixpkgs.stdenv.mkDerivation {
46 nixpkgs.stdenv.mkDerivation {
47 name = "encodings";
47 name = "encodings";
48
48
49− input = file;
49+ input = mkPath file;
50
50
51 builder = builtins.toFile "builder.sh" ''
51 builder = builtins.toFile "builder.sh" ''
52 source "$stdenv/setup"
52 source "$stdenv/setup"
@@ -70,7 +70,7 @@ noEncodings = file:
70 nixpkgs.stdenv.mkDerivation {
70 nixpkgs.stdenv.mkDerivation {
71 name = "encodings";
71 name = "encodings";
72
72
73− input = file;
73+ input = mkPath file;
74
74
75 builder = builtins.toFile "builder.sh" ''
75 builder = builtins.toFile "builder.sh" ''
76 source "$stdenv/setup"
76 source "$stdenv/setup"
@@ -203,7 +203,7 @@ hashFile = path:
203 nixpkgs.nix
203 nixpkgs.nix
204 ];
204 ];
205 preferLocalBuild = true;
205 preferLocalBuild = true;
206− inherit path;
206+ path = mkPath path;
207 } ''
207 } ''
208 nix-hash --flat --base32 --type sha256 "$path" | tr -d '\n' >"$out"
208 nix-hash --flat --base32 --type sha256 "$path" | tr -d '\n' >"$out"
209 '');
209 '');
@@ -224,7 +224,30 @@ symlink = path: {
224 inherit path;
224 inherit path;
225};
225};
226
226
227+# Tests if a given character (string of length 1) is valid for a derivation path name.
228+# Passing a string of length other than 1 is undefined.
229+# :: Char -> Bool
230+isValidDrvNameChar = c: "a" <= c && c <= "z" || "A" <= c && c <= "Z" || "0" <= c && c <= "9" || c == "+" || c == "-" || c == "_" || c == "?" || c == "=" || c == ".";
231+
232+# Convert a string into a string that could be used in a derivation name.
233+# replacement lets you choose how to replace invalid characters. It may be any length.
234+# If it contains invalid characters then the result will also be invalid.
235+# :: { str :: String, replacement :: String } -> String
236+mkValidDrvName = { str, replacement ? "?" }:
237+ let
238+ newName = stringAsChars (c: if isValidDrvNameChar c then c else replacement) str;
239+ in if builtins.substring 0 1 newName == "." then "_" + newName else newName;
240+
241+# Like builtins.path but always ensures the name is valid.
242+mkPath = path:
243+ if builtins.typeOf path == "path" # Don't mess with non-paths
244+ then builtins.path {
245+ inherit path;
246+ name = mkValidDrvName { str = builtins.baseNameOf path; };
247+ }
248+ else path;
249+
227−# Given a encoding generation function and a file entry resulting from readDirRecursive in the form { name :: String, value: { path :: String } },
250+# Given an encoding generation function and a file entry resulting from readDirRecursive in the form { name :: String, value: { path :: String } },
228# build a DirEntry for dirToPath with the various encodings of the asset for dirToPath to build into a final directory tree.
251# build a DirEntry for dirToPath with the various encodings of the asset for dirToPath to build into a final directory tree.
229mkAsset = encodings: {name, value}:
252mkAsset = encodings: {name, value}:
230 let nameWithHash = "${hashFile value.path}-${name}";
253 let nameWithHash = "${hashFile value.path}-${name}";
lib/asset/manifest/obelisk-asset-manifest.cabal+5−2
@@ -17,13 +17,14 @@ library
17 base
17 base
18 , bytestring
18 , bytestring
19 , containers
19 , containers
20+ , deepseq
20 , directory
21 , directory
21 , SHA
22 , SHA
22 , filepath
23 , filepath
23 , template-haskell
24 , template-haskell
24 , text
25 , text
25 , transformers
26 , transformers
26− , unix
27+ , unix-compat
27 , vector
28 , vector
28 exposed-modules:
29 exposed-modules:
29 Obelisk.Asset.Gather
30 Obelisk.Asset.Gather
@@ -32,7 +33,9 @@ library
32 Obelisk.Asset.TH
33 Obelisk.Asset.TH
33
34
34 other-extensions: TemplateHaskell
35 other-extensions: TemplateHaskell
36+ ghc-options:
37+ -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O2
35− ghc-options: -Wall -Werror -fno-warn-unused-do-bind -fwarn-tabs -funbox-strict-fields -O2 -fprof-auto-calls
38+ -fno-warn-unused-do-bind -funbox-strict-fields -fprof-auto-calls
36
39
37executable obelisk-asset-manifest-generate
40executable obelisk-asset-manifest-generate
38 hs-source-dirs: src-bin
41 hs-source-dirs: src-bin
lib/asset/manifest/src/Obelisk/Asset/Gather.hs+5−3
@@ -1,10 +1,12 @@
1{-# LANGUAGE OverloadedStrings #-}
1{-# LANGUAGE OverloadedStrings #-}
2+{-# LANGUAGE BangPatterns #-}
2-- | Functions for collecting up files to be processed by the asset pipeline
3-- | Functions for collecting up files to be processed by the asset pipeline
3module Obelisk.Asset.Gather
4module Obelisk.Asset.Gather
4 ( gatherHashedPaths
5 ( gatherHashedPaths
5 , toHashedPath
6 , toHashedPath
6 ) where
7 ) where
7
8
9+import Control.DeepSeq
8import Control.Monad (forM)
10import Control.Monad (forM)
9import Data.Bits
11import Data.Bits
10import qualified Data.ByteString.Lazy as LBS
12import qualified Data.ByteString.Lazy as LBS
@@ -13,7 +15,6 @@ import Data.Char
13import Data.Digest.Pure.SHA
15import Data.Digest.Pure.SHA
14import Data.Map (Map)
16import Data.Map (Map)
15import qualified Data.Map as Map
17import qualified Data.Map as Map
16−import Data.Monoid
17import qualified Data.Text as T
18import qualified Data.Text as T
18import Data.Text.Encoding
19import Data.Text.Encoding
19import qualified Data.Vector.Unboxed as UV
20import qualified Data.Vector.Unboxed as UV
@@ -34,7 +35,7 @@ gatherHashedPaths root = go ""
34 let relativePath = subdir </> sub
35 let relativePath = subdir </> sub
35 isFile <- doesFileExist $ root </> relativePath
36 isFile <- doesFileExist $ root </> relativePath
36 if isFile
37 if isFile
37− then do hashedRelativePath <- toHashedPath root relativePath
38+ then do !hashedRelativePath <- force <$> toHashedPath root relativePath
38 return $ Map.singleton relativePath hashedRelativePath
39 return $ Map.singleton relativePath hashedRelativePath
39 else go relativePath
40 else go relativePath
40
41
@@ -48,7 +49,8 @@ toHashedPath root relativePath = do
48 contents <- LBS.readFile path
49 contents <- LBS.readFile path
49 let hashPrefix = T.unpack $ decodeUtf8 $ LBS.toStrict $ toNixBase32 $ bytestringDigest $ sha256 contents
50 let hashPrefix = T.unpack $ decodeUtf8 $ LBS.toStrict $ toNixBase32 $ bytestringDigest $ sha256 contents
50 (dir, filename) = splitFileName relativePath
51 (dir, filename) = splitFileName relativePath
51− return $ normalise $ dir </> (hashPrefix <> "-" <> filename)
52+ !hashedRelativePath = force $ normalise $ dir </> (hashPrefix <> "-" <> filename)
53+ return hashedRelativePath
52
54
53-- | Convert a ByteString to base 32 in the way that Nix does
55-- | Convert a ByteString to base 32 in the way that Nix does
54toNixBase32 :: LBS.ByteString -> LBS.ByteString
56toNixBase32 :: LBS.ByteString -> LBS.ByteString
lib/asset/manifest/src/Obelisk/Asset/Promoted.hs+15−5
@@ -10,6 +10,7 @@ module Obelisk.Asset.Promoted
10import Obelisk.Asset.Gather
10import Obelisk.Asset.Gather
11
11
12import Data.Foldable
12import Data.Foldable
13+import qualified Data.List as L
13import Language.Haskell.TH (runQ, pprint)
14import Language.Haskell.TH (runQ, pprint)
14import Language.Haskell.TH.Syntax hiding (lift)
15import Language.Haskell.TH.Syntax hiding (lift)
15import GHC.TypeLits
16import GHC.TypeLits
@@ -18,7 +19,6 @@ import qualified Data.Sequence as Seq
18import Control.Monad.Trans.Writer
19import Control.Monad.Trans.Writer
19import System.FilePath
20import System.FilePath
20import System.Directory
21import System.Directory
21−import Data.Monoid
22import Data.Text (Text)
22import Data.Text (Text)
23import qualified Data.Text as T
23import qualified Data.Text as T
24import qualified Data.Text.IO as T
24import qualified Data.Text.IO as T
@@ -32,11 +32,15 @@ data StaticConfig = StaticConfig
32
32
33writeStaticProject :: Map FilePath FilePath -> FilePath -> StaticConfig -> IO ()
33writeStaticProject :: Map FilePath FilePath -> FilePath -> StaticConfig -> IO ()
34writeStaticProject paths target cfg = do
34writeStaticProject paths target cfg = do
35− createDirectoryIfMissing True $ target </> "src"
35+ createDirectoryIfMissing True target
36 T.writeFile (target </> T.unpack (_staticConfig_packageName cfg) <.> "cabal") $ staticCabalFile cfg
36 T.writeFile (target </> T.unpack (_staticConfig_packageName cfg) <.> "cabal") $ staticCabalFile cfg
37 let modName = _staticConfig_moduleName cfg
37 let modName = _staticConfig_moduleName cfg
38+ (modName', moduleDirPath) = case L.uncons (reverse $ T.splitOn "." modName) of
39+ Nothing -> error $ "writeStaticProject: invalid module name " <> T.unpack modName
40+ Just (name, parents) -> (name, target </> "src" </> T.unpack (T.intercalate "/" $ reverse parents))
41+ createDirectoryIfMissing True moduleDirPath
38 modContents <- staticModuleFile modName paths
42 modContents <- staticModuleFile modName paths
39− T.writeFile (target </> "src" </> T.unpack modName <.> "hs") modContents
43+ T.writeFile (moduleDirPath </> T.unpack modName' <.> "hs") modContents
40
44
41staticCabalFile :: StaticConfig -> Text
45staticCabalFile :: StaticConfig -> Text
42staticCabalFile cfg = T.unlines
46staticCabalFile cfg = T.unlines
@@ -63,11 +67,17 @@ staticModuleFile moduleName paths = do
63 , "{-# LANGUAGE FlexibleInstances #-}"
67 , "{-# LANGUAGE FlexibleInstances #-}"
64 , "{-# LANGUAGE KindSignatures #-}"
68 , "{-# LANGUAGE KindSignatures #-}"
65 , "{-# LANGUAGE OverloadedStrings #-}"
69 , "{-# LANGUAGE OverloadedStrings #-}"
70+ , "{-# LANGUAGE ScopedTypeVariables #-}"
71+ , "{-# LANGUAGE TypeApplications #-}"
66 , "module " <> moduleName <> " where"
72 , "module " <> moduleName <> " where"
67 , ""
73 , ""
68 , "import qualified GHC.Types"
74 , "import qualified GHC.Types"
69− , "import Data.Text ()"
75+ , "import Data.Text (Text)"
70 , "import qualified Data.Text.Internal"
76 , "import qualified Data.Text.Internal"
77+ , "import Data.Monoid ((<>))"
78+ , ""
79+ , "static :: forall a. StaticFile a => Text"
80+ , "static = \"static/\" <> hashedPath @a" --TODO: Use obelisk-route to generate this in a more consistent way
71 , ""
81 , ""
72 , T.pack $ pprint decs
82 , T.pack $ pprint decs
73 ]
83 ]
@@ -96,7 +106,7 @@ staticClass :: WriterT (Seq Dec) Q StaticContext
96staticClass = do
106staticClass = do
97 let n x = Name (OccName x) NameS
107 let n x = Name (OccName x) NameS
98 className = n "StaticFile"
108 className = n "StaticFile"
99− methodName = n "static"
109+ methodName = n "hashedPath"
100 cls = ClassD [] className [KindedTV (n "s") (ConT ''Symbol)] [] [SigD methodName (ConT ''Text)]
110 cls = ClassD [] className [KindedTV (n "s") (ConT ''Symbol)] [] [SigD methodName (ConT ''Text)]
101 tell $ Seq.singleton cls
111 tell $ Seq.singleton cls
102 return $ StaticContext
112 return $ StaticContext
lib/asset/manifest/src/Obelisk/Asset/Symlink.hs+1−1
@@ -7,7 +7,7 @@ import Data.Map (Map)
7import qualified Data.Map as Map
7import qualified Data.Map as Map
8import System.Directory
8import System.Directory
9import System.FilePath.Posix
9import System.FilePath.Posix
10−import System.Posix.Files
10+import System.PosixCompat.Files
11
11
12-- | Copy the given hashed files from one location to hashed paths in another
12-- | Copy the given hashed files from one location to hashed paths in another
13-- location, and symlink the unhashed paths to the hashed ones
13-- location, and symlink the unhashed paths to the hashed ones
lib/asset/serve-snap/obelisk-asset-serve.cabal → lib/asset/serve-snap/obelisk-asset-serve-snap.cabalrenamed+4−2
@@ -23,10 +23,12 @@ library
23 , obelisk-snap-extras
23 , obelisk-snap-extras
24 , text
24 , text
25 , transformers
25 , transformers
26− , unix
26+ , unix-compat
27 exposed-modules:
27 exposed-modules:
28 Obelisk.Asset.Accept
28 Obelisk.Asset.Accept
29 Obelisk.Asset.Serve.Snap
29 Obelisk.Asset.Serve.Snap
30
30
31 other-extensions: TemplateHaskell
31 other-extensions: TemplateHaskell
32+ ghc-options:
33+ -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O2
32− ghc-options: -Wall -Werror -fno-warn-unused-do-bind -fwarn-tabs -funbox-strict-fields -O2 -fprof-auto-calls
34+ -fno-warn-unused-do-bind -funbox-strict-fields -fprof-auto-calls
lib/asset/serve-snap/src/Obelisk/Asset/Accept.hs+6−6
@@ -136,16 +136,16 @@ qvalue = do
136 skipMany lws
136 skipMany lws
137 q0 <|> q1
137 q0 <|> q1
138 where q0 = do
138 where q0 = do
139− char '0'
139+ _ <- char '0'
140 decimals <- option [] $ do
140 decimals <- option [] $ do
141− char '.'
141+ _ <- char '.'
142 starRule (Just 0) (Just numAllowedDigits) digit
142 starRule (Just 0) (Just numAllowedDigits) digit
143 return $ QValue $ MkFixed $ fromIntegral $ (read ('0' : decimals) :: Int) * 10 ^ (numAllowedDigits - length decimals)
143 return $ QValue $ MkFixed $ fromIntegral $ (read ('0' : decimals) :: Int) * 10 ^ (numAllowedDigits - length decimals)
144 q1 = do
144 q1 = do
145− char '1'
145+ _ <- char '1'
146 option () $ do
146 option () $ do
147− char '.'
147+ _ <- char '.'
148− starRule (Just 0) (Just numAllowedDigits) $ char '0'
148+ _ <- starRule (Just 0) (Just numAllowedDigits) $ char '0'
149 return ()
149 return ()
150 return $ QValue 1
150 return $ QValue 1
151 numAllowedDigits :: Int
151 numAllowedDigits :: Int
@@ -232,7 +232,7 @@ hashRule minNum maxNum element = do
232lws :: Parser ()
232lws :: Parser ()
233lws = do
233lws = do
234 option () $ cr >> lf
234 option () $ cr >> lf
235− starRule (Just 1) Nothing $ sp <|> ht
235+ _ <- starRule (Just 1) Nothing $ sp <|> ht
236 return ()
236 return ()
237
237
238-- | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
238-- | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
lib/asset/serve-snap/src/Obelisk/Asset/Serve/Snap.hs+22−11
@@ -12,13 +12,15 @@ import Obelisk.Asset.Accept (Encoding (..), acceptEncodingBody, chooseEncoding,
12import Obelisk.Snap.Extras
12import Obelisk.Snap.Extras
13
13
14import Snap
14import Snap
15− (MonadSnap, getHeader, getsRequest, modifyResponse, pass, redirect, sendFile, setContentLength, setContentType, setHeader, setResponseCode)
15+ (MonadSnap, getHeader, getRequest, getsRequest, modifyResponse, pass, redirect, sendFile, setContentLength, setContentType, setHeader, setResponseCode)
16import Snap.Util.FileServe (defaultMimeTypes, fileType, getSafePath, serveFile)
16import Snap.Util.FileServe (defaultMimeTypes, fileType, getSafePath, serveFile)
17+import Snap.Internal.Util.FileServe (checkRangeReq)
17
18
18import Control.Applicative ((<|>))
19import Control.Applicative ((<|>))
19import Control.Exception (handleJust, try, throwIO)
20import Control.Exception (handleJust, try, throwIO)
20−import Control.Monad (forM, liftM)
21+import Control.Monad (forM, liftM, unless)
21import Control.Monad.IO.Class (liftIO)
22import Control.Monad.IO.Class (liftIO)
23+import Control.Monad.Fail (MonadFail)
22import Data.Attoparsec.ByteString (parseOnly, endOfInput)
24import Data.Attoparsec.ByteString (parseOnly, endOfInput)
23import Data.ByteString (ByteString)
25import Data.ByteString (ByteString)
24import qualified Data.ByteString as BS
26import qualified Data.ByteString as BS
@@ -29,7 +31,7 @@ import Data.Text.Encoding (decodeUtf8, encodeUtf8)
29import System.Directory (getDirectoryContents)
31import System.Directory (getDirectoryContents)
30import System.FilePath ((</>), splitFileName, takeDirectory)
32import System.FilePath ((</>), splitFileName, takeDirectory)
31import System.IO.Error (isDoesNotExistError)
33import System.IO.Error (isDoesNotExistError)
32−import System.Posix (getFileStatus, fileSize)
34+import System.PosixCompat.Files (getFileStatus, fileSize)
33
35
34-- | Serve static assets from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
36-- | Serve static assets from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
35--
37--
@@ -38,7 +40,7 @@ import System.Posix (getFileStatus, fileSize)
38-- current version of the asset
40-- current version of the asset
39-- (e.g. @0rx5yvkkgkig2pcqf4ngi1l7vh89qqajdzc6aiayaibyhvj0d853-test.png@). Hashed
41-- (e.g. @0rx5yvkkgkig2pcqf4ngi1l7vh89qqajdzc6aiayaibyhvj0d853-test.png@). Hashed
40-- asset names will be sent with permanent caching headers.
42-- asset names will be sent with permanent caching headers.
41−serveAssets :: MonadSnap m => FilePath -> FilePath -> m ()
43+serveAssets :: (MonadSnap m, MonadFail m) => FilePath -> FilePath -> m ()
42serveAssets = serveAssets' True
44serveAssets = serveAssets' True
43
45
44-- | Serve static assets from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
46-- | Serve static assets from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
@@ -47,15 +49,15 @@ serveAssets = serveAssets' True
47-- browser for the logical asset name (e.g. @test.png@) but instead the current
49-- browser for the logical asset name (e.g. @test.png@) but instead the current
48-- version of the asset with to point the browser at the unique filename for the
50-- version of the asset with to point the browser at the unique filename for the
49-- current version of the asset.
51-- current version of the asset.
50−serveAssetsInPlace :: MonadSnap m => FilePath -> FilePath -> m ()
52+serveAssetsInPlace :: (MonadSnap m, MonadFail m) => FilePath -> FilePath -> m ()
51serveAssetsInPlace = serveAssets' False
53serveAssetsInPlace = serveAssets' False
52
54
53-- | Like 'serveAssets', but only serves a single specified asset
55-- | Like 'serveAssets', but only serves a single specified asset
54−serveAsset :: MonadSnap m => FilePath -> FilePath -> FilePath -> m ()
56+serveAsset :: (MonadSnap m, MonadFail m) => FilePath -> FilePath -> FilePath -> m ()
55serveAsset = serveAsset' True
57serveAsset = serveAsset' True
56
58
57-- | Like 'serveAssetsInPlace', but only serves a single specified asset
59-- | Like 'serveAssetsInPlace', but only serves a single specified asset
58−serveAssetInPlace :: MonadSnap m => FilePath -> FilePath -> FilePath -> m ()
60+serveAssetInPlace :: (MonadSnap m, MonadFail m) => FilePath -> FilePath -> FilePath -> m ()
59serveAssetInPlace = serveAsset' False
61serveAssetInPlace = serveAsset' False
60
62
61-- | Serve static assets from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
63-- | Serve static assets from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
@@ -63,13 +65,13 @@ serveAssetInPlace = serveAsset' False
63-- For assets generated from @assets.nix@, the @Bool@ argument @doRedirect@ controls whether redirects will be sent to the browser if a request is made for
65-- For assets generated from @assets.nix@, the @Bool@ argument @doRedirect@ controls whether redirects will be sent to the browser if a request is made for
64-- an unhashed asset name, e.g. @test.png@. For @True@, a redirect will be sent, yielding more round trips to the server but better caching behavior if the
66-- an unhashed asset name, e.g. @test.png@. For @True@, a redirect will be sent, yielding more round trips to the server but better caching behavior if the
65-- asset doesn't change often. Conversely for @False@, the asset will be served "in place" but made uncacheable.
67-- asset doesn't change often. Conversely for @False@, the asset will be served "in place" but made uncacheable.
66−serveAssets' :: MonadSnap m => Bool -> FilePath -> FilePath -> m ()
68+serveAssets' :: (MonadSnap m, MonadFail m) => Bool -> FilePath -> FilePath -> m ()
67serveAssets' doRedirect base fallback = do
69serveAssets' doRedirect base fallback = do
68 pRaw <- getSafePath
70 pRaw <- getSafePath
69 serveAsset' doRedirect base fallback $ if "/" `isSuffixOf` pRaw || pRaw == "" then pRaw <> "index.html" else pRaw
71 serveAsset' doRedirect base fallback $ if "/" `isSuffixOf` pRaw || pRaw == "" then pRaw <> "index.html" else pRaw
70
72
71-- | Serve a single static asset from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
73-- | Serve a single static asset from an asset directory generated via @assets.nix@ or, failing that, from a regular directory.
72−serveAsset' :: MonadSnap m => Bool -> FilePath -> FilePath -> FilePath -> m ()
74+serveAsset' :: (MonadFail m, MonadSnap m) => Bool -> FilePath -> FilePath -> FilePath -> m ()
73serveAsset' doRedirect base fallback p = do
75serveAsset' doRedirect base fallback p = do
74 assetType <- liftIO $ try $ BS.readFile $ base </> p </> "type"
76 assetType <- liftIO $ try $ BS.readFile $ base </> p </> "type"
75 case assetType of
77 case assetType of
@@ -93,8 +95,17 @@ serveAsset' doRedirect base fallback p = do
93 let finalFilename = base </> p </> "encodings" </> T.unpack (decodeUtf8 e)
95 let finalFilename = base </> p </> "encodings" </> T.unpack (decodeUtf8 e)
94 stat <- liftIO $ getFileStatus finalFilename
96 stat <- liftIO $ getFileStatus finalFilename
95 modifyResponse $ setHeader "Last-Modified" "Thu, 1 Jan 1970 00:00:00 GMT"
97 modifyResponse $ setHeader "Last-Modified" "Thu, 1 Jan 1970 00:00:00 GMT"
98+ . setHeader "Accept-Ranges" "bytes"
96− modifyResponse $ setResponseCode 200 . setContentLength (fromIntegral $ fileSize stat) . setContentType (fileType defaultMimeTypes p)
99+ . setContentType (fileType defaultMimeTypes p)
100+ let size = fromIntegral $ fileSize stat
101+ req <- getRequest
102+ -- Despite the name, this function actually does all of the work for
103+ -- responding to range requests. We only need to handle *none* range
104+ -- requests ourselves.
105+ wasRange <- checkRangeReq req finalFilename size
106+ unless wasRange $ do
107+ modifyResponse $ setResponseCode 200 . setContentLength size
97− sendFile finalFilename
108+ sendFile finalFilename
98 Just _ -> cachePermanently >> modifyResponse (setResponseCode 304)
109 Just _ -> cachePermanently >> modifyResponse (setResponseCode 304)
99 Right "redirect" -> do
110 Right "redirect" -> do
100 mtarget <- liftIO $ getAssetTarget $ base </> p
111 mtarget <- liftIO $ getAssetTarget $ base </> p
lib/backend/obelisk-backend.cabal+19−3
@@ -6,9 +6,25 @@ build-type: Simple
6library
6library
7 hs-source-dirs: src
7 hs-source-dirs: src
8 build-depends: base,
8 build-depends: base,
9− snap,
9+ bytestring,
10− snap-server,
10+ categories,
11+ containers,
12+ cookie,
11 data-default,
13 data-default,
14+ dependent-sum,
15+ dependent-sum-template,
16+ lens,
17+ mtl,
12 obelisk-asset-serve-snap,
18 obelisk-asset-serve-snap,
13− bytestring
19+ obelisk-executable-config-inject,
20+ obelisk-executable-config-lookup,
21+ obelisk-frontend,
22+ obelisk-route,
23+ obelisk-snap-extras,
24+ reflex-dom-core,
25+ snap,
26+ snap-server,
27+ text,
28+ universe
14 exposed-modules: Obelisk.Backend
29 exposed-modules: Obelisk.Backend
30+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
lib/backend/src/Obelisk/Backend.hs+278−21
@@ -1,41 +1,298 @@
1+{-# LANGUAGE DeriveFunctor #-}
2+{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE KindSignatures #-}
7+{-# LANGUAGE LambdaCase #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
1{-# LANGUAGE OverloadedStrings #-}
9{-# LANGUAGE OverloadedStrings #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# OPTIONS_GHC -fno-warn-orphans #-}
2module Obelisk.Backend
12module Obelisk.Backend
3− ( backend
13+ ( Backend (..)
4− , BackendConfig
14+ , BackendConfig (..)
15+ , defaultBackendConfig
16+ , StaticAssets (..)
17+ , defaultStaticAssets
18+ -- * Running a backend
19+ , runBackend
20+ , runBackendWith
21+ -- * Configuration of backend
22+ , GhcjsWidgets(..)
23+ , defaultGhcjsWidgets
24+ -- * all.js script loading functions
25+ , deferredGhcjsScript
26+ , delayedGhcjsScript
27+ -- * all.js preload functions
28+ , preloadGhcjs
29+ , renderAllJsPath
5 -- * Re-exports
30 -- * Re-exports
6 , Default (def)
31 , Default (def)
32+ , getPageName
33+ , getRouteWith
34+ , runSnapWithCommandLineArgs
35+ , runSnapWithConfig
36+ , serveDefaultObeliskApp
37+ , prettifyOutput
38+ , staticRenderContentType
39+ , getPublicConfigs
7 ) where
40 ) where
8
41
42+import Control.Monad
43+import Control.Monad.Except
44+import Control.Monad.Fail (MonadFail)
45+import Data.ByteString (ByteString)
9import qualified Data.ByteString.Char8 as BSC8
46import qualified Data.ByteString.Char8 as BSC8
10import Data.Default (Default (..))
47import Data.Default (Default (..))
48+import Data.Dependent.Sum
49+import Data.Functor.Identity
50+import Data.Map (Map)
51+import qualified Data.Map as Map
52+import Data.Monoid ((<>))
53+import Data.Text (Text)
54+import qualified Data.Text as T
55+import GHC.Generics (Generic)
11−import Obelisk.Asset.Serve.Snap (serveAssets)
56+import Obelisk.Asset.Serve.Snap (serveAsset)
12−import System.IO (hSetBuffering, stderr, BufferMode (..))
57+import qualified Obelisk.ExecutableConfig.Lookup as Lookup
13−import Snap (httpServe, defaultConfig, commandLineConfig, route)
58+import Obelisk.Frontend
59+import Obelisk.Route
60+import Obelisk.Snap.Extras (doNotCache, serveFileIfExistsAs)
61+import Reflex.Dom.Core
62+import Snap (MonadSnap, Snap, commandLineConfig, defaultConfig, getsRequest, httpServe, modifyResponse
63+ , rqPathInfo, rqQueryString, setContentType, writeBS, writeText
64+ , rqCookies, Cookie(..) , setHeader)
14import Snap.Internal.Http.Server.Config (Config (accessLog, errorLog), ConfigLog (ConfigIoLog))
65import Snap.Internal.Http.Server.Config (Config (accessLog, errorLog), ConfigLog (ConfigIoLog))
66+import System.IO (BufferMode (..), hSetBuffering, stderr, stdout)
15
67
16−--TODO: Add a link to a large explanation of the idea of using 'def'
68+data Backend backendRoute frontendRoute = Backend
17−-- | Configure the operation of the Obelisk backend. For reasonable defaults,
69+ { _backend_routeEncoder :: Encoder (Either Text) Identity (R (FullRoute backendRoute frontendRoute)) PageName
18−-- use 'def'.
70+ , _backend_run :: ((R backendRoute -> Snap ()) -> IO ()) -> IO ()
19−data BackendConfig = BackendConfig
71+ } deriving (Generic)
20
72
21−instance Default BackendConfig where
22− def = BackendConfig
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)
23
80
24−-- | Start an Obelisk backend
81+-- | The static assets provided must contain a compiled GHCJS app that corresponds exactly to the Frontend provided
25−backend :: BackendConfig -> IO ()
82+data GhcjsApp route = GhcjsApp
26−backend _ = do
83+ { _ghcjsApp_compiled :: !StaticAssets
84+ , _ghcjsApp_value :: !(Frontend route)
85+ } deriving (Generic)
86+
87+-- | Widgets used to load all.js on the frontend
88+data GhcjsWidgets a = GhcjsWidgets
89+ { _ghcjsWidgets_preload :: a
90+ -- ^ A preload widget, placed in the document head
91+ , _ghcjsWidgets_script :: a
92+ -- ^ A script widget, placed in the document body
93+ } deriving (Functor, Generic)
94+
95+
96+-- | Given the URL of all.js, return the widgets which are responsible for
97+-- loading the script. Defaults to 'preloadGhcjs' and 'deferredGhcjsScript'.
98+defaultGhcjsWidgets :: GhcjsWidgets (Text -> FrontendWidgetT r ())
99+defaultGhcjsWidgets = GhcjsWidgets
100+ { _ghcjsWidgets_preload = preloadGhcjs
101+ , _ghcjsWidgets_script = deferredGhcjsScript
102+ }
103+
104+-- | Serve a frontend, which must be the same frontend that Obelisk has built and placed in the default location
105+--TODO: The frontend should be provided together with the asset paths so that this isn't so easily breakable; that will probably make this function obsolete
106+serveDefaultObeliskApp
107+ :: (MonadSnap m, HasCookies m, MonadFail m)
108+ => (R appRoute -> Text)
109+ -> GhcjsWidgets (FrontendWidgetT (R appRoute) ())
110+ -> ([Text] -> m ())
111+ -> Frontend (R appRoute)
112+ -> Map Text ByteString
113+ -> R (ObeliskRoute appRoute)
114+ -> m ()
115+serveDefaultObeliskApp urlEnc ghcjsWidgets serveStaticAsset frontend =
116+ serveObeliskApp urlEnc ghcjsWidgets serveStaticAsset frontendApp
117+ where frontendApp = GhcjsApp
118+ { _ghcjsApp_compiled = defaultFrontendGhcjsAssets
119+ , _ghcjsApp_value = frontend
120+ }
121+
122+prettifyOutput :: IO ()
123+prettifyOutput = do
27 -- Make output more legible by decreasing the likelihood of output from
124 -- Make output more legible by decreasing the likelihood of output from
28 -- multiple threads being interleaved
125 -- multiple threads being interleaved
126+ hSetBuffering stdout LineBuffering
29 hSetBuffering stderr LineBuffering
127 hSetBuffering stderr LineBuffering
30
128
31− -- Get the web server configuration from the command line
129+defaultStaticAssets :: StaticAssets
32− cmdLineConf <- commandLineConfig defaultConfig
130+defaultStaticAssets = StaticAssets
131+ { _staticAssets_processed = "static.assets"
132+ , _staticAssets_unprocessed = "static"
133+ }
134+
135+defaultFrontendGhcjsAssets :: StaticAssets
136+defaultFrontendGhcjsAssets = StaticAssets
137+ { _staticAssets_processed = "frontend.jsexe.assets"
138+ , _staticAssets_unprocessed = "frontend.jsexe"
139+ }
140+
141+runSnapWithConfig :: MonadIO m => Config Snap a -> Snap () -> m ()
142+runSnapWithConfig conf a = do
33− let httpConf = cmdLineConf
143+ let httpConf = conf
34 { accessLog = Just $ ConfigIoLog BSC8.putStrLn
144 { accessLog = Just $ ConfigIoLog BSC8.putStrLn
35 , errorLog = Just $ ConfigIoLog BSC8.putStrLn
145 , errorLog = Just $ ConfigIoLog BSC8.putStrLn
36 }
146 }
37 -- Start the web server
147 -- Start the web server
38− httpServe httpConf $ route
148+ liftIO $ httpServe httpConf a
39− [ ("", serveAssets "frontend.jsexe.assets" "frontend.jsexe") --TODO: Can we prevent naming conflicts between frontend.jsexe and static?
149+
40− , ("", serveAssets "static.assets" "static")
150+-- Get the web server configuration from the command line
41− ]
151+runSnapWithCommandLineArgs :: MonadIO m => Snap () -> m ()
152+runSnapWithCommandLineArgs s = liftIO (commandLineConfig defaultConfig) >>= \c ->
153+ runSnapWithConfig c s
154+
155+getPageName :: (MonadSnap m) => m PageName
156+getPageName = do
157+ p <- getsRequest rqPathInfo
158+ q <- getsRequest rqQueryString
159+ return $ byteStringsToPageName p q
160+
161+getRouteWith :: (MonadSnap m) => Encoder Identity parse route PageName -> m (parse route)
162+getRouteWith e = do
163+ pageName <- getPageName
164+ return $ tryDecode e pageName
165+
166+renderAllJsPath :: Encoder Identity Identity (R (FullRoute a b)) PageName -> Text
167+renderAllJsPath validFullEncoder =
168+ renderObeliskRoute validFullEncoder $ FullRoute_Frontend (ObeliskRoute_Resource ResourceRoute_Ghcjs) :/ ["all.js"]
169+
170+serveObeliskApp
171+ :: (MonadSnap m, HasCookies m, MonadFail m)
172+ => (R appRoute -> Text)
173+ -> GhcjsWidgets (FrontendWidgetT (R appRoute) ())
174+ -> ([Text] -> m ())
175+ -> GhcjsApp (R appRoute)
176+ -> Map Text ByteString
177+ -> R (ObeliskRoute appRoute)
178+ -> m ()
179+serveObeliskApp urlEnc ghcjsWidgets serveStaticAsset frontendApp config = \case
180+ ObeliskRoute_App appRouteComponent :=> Identity appRouteRest -> serveGhcjsApp urlEnc ghcjsWidgets frontendApp config $ GhcjsAppRoute_App appRouteComponent :/ appRouteRest
181+ ObeliskRoute_Resource resComponent :=> Identity resRest -> case resComponent :=> Identity resRest of
182+ ResourceRoute_Static :=> Identity pathSegments -> serveStaticAsset pathSegments
183+ ResourceRoute_Ghcjs :=> Identity pathSegments -> serveGhcjsApp urlEnc ghcjsWidgets frontendApp config $ GhcjsAppRoute_Resource :/ pathSegments
184+ ResourceRoute_JSaddleWarp :=> Identity _ -> do
185+ let msg = "Error: Obelisk.Backend received jsaddle request"
186+ liftIO $ putStrLn $ T.unpack msg
187+ writeText msg
188+ ResourceRoute_Version :=> Identity () -> doNotCache >> serveFileIfExistsAs "text/plain" "version"
189+
190+serveStaticAssets :: (MonadSnap m, MonadFail m) => StaticAssets -> [Text] -> m ()
191+serveStaticAssets assets pathSegments = serveAsset (_staticAssets_processed assets) (_staticAssets_unprocessed assets) $ T.unpack $ T.intercalate "/" pathSegments
192+
193+data StaticAssets = StaticAssets
194+ { _staticAssets_processed :: !FilePath
195+ , _staticAssets_unprocessed :: !FilePath
196+ }
197+ deriving (Show, Read, Eq, Ord)
198+
199+data GhcjsAppRoute :: (* -> *) -> * -> * where
200+ GhcjsAppRoute_App :: appRouteComponent a -> GhcjsAppRoute appRouteComponent a
201+ GhcjsAppRoute_Resource :: GhcjsAppRoute appRouteComponent [Text]
202+
203+staticRenderContentType :: ByteString
204+staticRenderContentType = "text/html; charset=utf-8"
205+
206+--TODO: Don't assume we're being served at "/"
207+serveGhcjsApp
208+ :: (MonadSnap m, HasCookies m, MonadFail m)
209+ => (R appRouteComponent -> Text)
210+ -> GhcjsWidgets (FrontendWidgetT (R appRouteComponent) ())
211+ -> GhcjsApp (R appRouteComponent)
212+ -> Map Text ByteString
213+ -> R (GhcjsAppRoute appRouteComponent)
214+ -> m ()
215+serveGhcjsApp urlEnc ghcjsWidgets app config = \case
216+ GhcjsAppRoute_App appRouteComponent :=> Identity appRouteRest -> do
217+ modifyResponse $ setContentType staticRenderContentType
218+ modifyResponse $ setHeader "Cache-Control" "no-store private"
219+ writeBS <=< renderGhcjsFrontend urlEnc ghcjsWidgets (appRouteComponent :/ appRouteRest) config $ _ghcjsApp_value app
220+ GhcjsAppRoute_Resource :=> Identity pathSegments -> serveStaticAssets (_ghcjsApp_compiled app) pathSegments
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.
227+runBackend :: Backend backendRoute frontendRoute -> Frontend (R frontendRoute) -> IO ()
228+runBackend = runBackendWith defaultBackendConfig
229+
230+-- | Run an obelisk backend with the given configuration.
231+runBackendWith
232+ :: BackendConfig frontendRoute
233+ -> Backend backendRoute frontendRoute
234+ -> Frontend (R frontendRoute)
235+ -> IO ()
236+runBackendWith (BackendConfig runSnap staticAssets ghcjsWidgets) backend frontend = case checkEncoder $ _backend_routeEncoder backend of
237+ Left e -> fail $ "backend error:\n" <> T.unpack e
238+ Right validFullEncoder -> do
239+ publicConfigs <- getPublicConfigs
240+ _backend_run backend $ \serveRoute ->
241+ runSnap $
242+ getRouteWith validFullEncoder >>= \case
243+ Identity r -> case r of
244+ FullRoute_Backend backendRoute :/ a -> serveRoute $ backendRoute :/ a
245+ FullRoute_Frontend obeliskRoute :/ a ->
246+ serveDefaultObeliskApp routeToUrl (($ allJsUrl) <$> ghcjsWidgets) (serveStaticAssets staticAssets) frontend publicConfigs $
247+ obeliskRoute :/ a
248+ where
249+ routeToUrl (k :/ v) = renderObeliskRoute validFullEncoder $ FullRoute_Frontend (ObeliskRoute_App k) :/ v
250+ allJsUrl = renderAllJsPath validFullEncoder
251+
252+renderGhcjsFrontend
253+ :: (MonadSnap m, HasCookies m)
254+ => (route -> Text)
255+ -> GhcjsWidgets (FrontendWidgetT route ())
256+ -> route
257+ -> Map Text ByteString
258+ -> Frontend route
259+ -> m ByteString
260+renderGhcjsFrontend urlEnc ghcjsWidgets route configs f = do
261+ cookies <- askCookies
262+ renderFrontendHtml configs cookies urlEnc route f (_ghcjsWidgets_preload ghcjsWidgets) (_ghcjsWidgets_script ghcjsWidgets)
263+
264+-- | Preload all.js in a link tag.
265+-- This is the default preload method.
266+preloadGhcjs :: Text -> FrontendWidgetT r ()
267+preloadGhcjs allJsUrl = elAttr "link" ("rel" =: "preload" <> "as" =: "script" <> "href" =: allJsUrl) blank
268+
269+-- | Load the script from the given URL in a deferred script tag.
270+-- This is the default method.
271+deferredGhcjsScript :: Text -> FrontendWidgetT r ()
272+deferredGhcjsScript allJsUrl = elAttr "script" ("type" =: "text/javascript" <> "src" =: allJsUrl <> "defer" =: "defer") blank
273+
274+-- | An all.js script which is loaded after waiting for some time to pass. This
275+-- is useful to ensure any CSS animations on the page can play smoothly before
276+-- blocking the UI thread by running all.js.
277+delayedGhcjsScript
278+ :: Int -- ^ The number of milliseconds to delay loading by
279+ -> Text -- ^ URL to GHCJS app JavaScript
280+ -> FrontendWidgetT r ()
281+delayedGhcjsScript n allJsUrl = elAttr "script" ("type" =: "text/javascript") $ text $ T.unlines
282+ [ "setTimeout(function() {"
283+ , " var all_js_script = document.createElement('script');"
284+ , " all_js_script.type = 'text/javascript';"
285+ , " all_js_script.src = '" <> allJsUrl <> "';"
286+ , " document.body.appendChild(all_js_script);"
287+ , "}, " <> T.pack (show n) <> ");"
288+ ]
289+
290+instance HasCookies Snap where
291+ askCookies = map (\c -> (cookieName c, cookieValue c)) <$> getsRequest rqCookies
292+
293+-- | Get configs from the canonical "public" locations (i.e., locations that obelisk expects to make available
294+-- to frontend applications, and hence visible to end users).
295+getPublicConfigs :: IO (Map Text ByteString)
296+getPublicConfigs = Map.filterWithKey (\k _ -> isMemberOf k ["common", "frontend"]) <$> Lookup.getConfigs
297+ where
298+ isMemberOf k = any (`T.isPrefixOf` k)
lib/cliapp/obelisk-cliapp.cabalnew file+37
@@ -0,0 +1,37 @@
1+name: obelisk-cliapp
2+version: 0.1
3+license: BSD3
4+build-type: Simple
5+cabal-version: >=1.2
6+
7+library
8+ hs-source-dirs: src
9+ build-depends:
10+ aeson
11+ , ansi-terminal
12+ , base
13+ , bytestring
14+ , containers
15+ , exceptions
16+ , io-streams
17+ , lens
18+ , logging-effect
19+ , monad-loops
20+ , mtl
21+ , process
22+ , shell-escape
23+ , terminal-size
24+ , text
25+ , time
26+ , transformers
27+ , utf8-string
28+ exposed-modules:
29+ Obelisk.CliApp
30+ other-modules:
31+ Obelisk.CliApp.Logging
32+ Obelisk.CliApp.Process
33+ Obelisk.CliApp.Spinner
34+ Obelisk.CliApp.TerminalString
35+ Obelisk.CliApp.Theme
36+ Obelisk.CliApp.Types
37+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
lib/cliapp/src/Obelisk/CliApp.hsnew file+65
@@ -0,0 +1,65 @@
1+-- | Package for writing great CLI apps.
2+--
3+-- See Demo.hs for an example
4+--
5+-- This package should eventually be made its own library.
6+module Obelisk.CliApp
7+ (
8+ -- .Types
9+ CliLog
10+ , CliThrow
11+ , CliT(..)
12+ , runCli
13+ , CliConfig
14+ , HasCliConfig
15+ , getCliConfig
16+ , Output
17+
18+ -- .Spinner
19+ , withSpinner
20+ , withSpinnerNoTrail
21+ , withSpinner'
22+
23+ -- .Logging
24+ , AsUnstructuredError (..)
25+ , newCliConfig
26+ , getLogLevel
27+ , putLog
28+ , failWith
29+ , errorToWarning
30+ , withExitFailMessage
31+
32+ -- Control.Monad.Log
33+ , Severity (..)
34+
35+ -- .Process
36+ , AsProcessFailure (..)
37+ , ProcessFailure (..)
38+ , ProcessSpec (..)
39+ , callCommand
40+ , callProcess
41+ , callProcessAndLogOutput
42+ , createProcess
43+ , createProcess_
44+ , exitCodeToException
45+ , overCreateProcess
46+ , proc
47+ , readCreateProcessWithExitCode
48+ , readProcessAndLogOutput
49+ , readProcessAndLogStderr
50+ , readProcessJSONAndLogStderr
51+ , reconstructCommand
52+ , runProcess_
53+ , setCwd
54+ , setDelegateCtlc
55+ , setEnvOverride
56+ , shell
57+ , waitForProcess
58+ ) where
59+
60+import Control.Monad.Log (Severity (..))
61+
62+import Obelisk.CliApp.Logging
63+import Obelisk.CliApp.Process
64+import Obelisk.CliApp.Spinner
65+import Obelisk.CliApp.Types
lib/cliapp/src/Obelisk/CliApp/Logging.hsnew file+253
@@ -0,0 +1,253 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE LambdaCase #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE OverloadedStrings #-}
7+{-# LANGUAGE RankNTypes #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+-- | Provides a logging handler that facilitates safe ouputting to terminal using MVar based locking.
10+-- | Spinner.hs and Process.hs work on this guarantee.
11+module Obelisk.CliApp.Logging
12+ ( AsUnstructuredError (..)
13+ , newCliConfig
14+ , runCli
15+ , verboseLogLevel
16+ , isOverwrite
17+ , getSeverity
18+ , getLogLevel
19+ , setLogLevel
20+ , putLog
21+ , putLogRaw
22+ , failWith
23+ , errorToWarning
24+ , withExitFailMessage
25+ , writeLog
26+ , allowUserToMakeLoggingVerbose
27+ , getChars
28+ , fork
29+ ) where
30+
31+import Control.Concurrent (ThreadId, forkIO, killThread, threadDelay)
32+import Control.Concurrent.MVar (modifyMVar_, newMVar)
33+import Control.Lens (Prism', review)
34+import Control.Monad (unless, void, when)
35+import Control.Monad.Catch (MonadCatch, MonadMask, bracket, catch, throwM)
36+import Control.Monad.Except (throwError)
37+import Control.Monad.IO.Class (liftIO)
38+import Control.Monad.Log (Severity (..), WithSeverity (..), logMessage, runLoggingT)
39+import Control.Monad.Loops (iterateUntil)
40+import Control.Monad.Reader (MonadIO, ReaderT (..))
41+import Data.IORef (atomicModifyIORef', newIORef, readIORef, writeIORef)
42+import Data.Semigroup ((<>))
43+import Data.Text (Text)
44+import qualified Data.Text as T
45+import qualified Data.Text.IO as T
46+import GHC.IO.Encoding.Types
47+import System.Console.ANSI (Color (Red, Yellow), ColorIntensity (Vivid),
48+ ConsoleIntensity (FaintIntensity), ConsoleLayer (Foreground),
49+ SGR (SetColor, SetConsoleIntensity), clearLine)
50+import System.Exit (ExitCode (..))
51+import System.IO
52+
53+import qualified Obelisk.CliApp.TerminalString as TS
54+import Obelisk.CliApp.Theme
55+import Obelisk.CliApp.Types
56+
57+newCliConfig
58+ :: Severity
59+ -> Bool
60+ -> Bool
61+ -> (e -> (Text, Int))
62+ -> IO (CliConfig e)
63+newCliConfig sev noColor noSpinner errorLogExitCode = do
64+ level <- newIORef sev
65+ lock <- newMVar False
66+ tipDisplayed <- newIORef False
67+ stack <- newIORef ([], [])
68+ textEncoding <- hGetEncoding stdout
69+ let theme = if maybe False supportsUnicode textEncoding
70+ then unicodeTheme
71+ else noUnicodeTheme
72+ return $ CliConfig level noColor noSpinner lock tipDisplayed stack errorLogExitCode theme
73+
74+runCli :: MonadIO m => CliConfig e -> CliT e m a -> m a
75+runCli c =
76+ flip runLoggingT (handleLog c)
77+ . flip runReaderT (_cliConfig_errorLogExitCode c)
78+ . unDieT
79+ . flip runReaderT c
80+ . unCliT
81+
82+verboseLogLevel :: Severity
83+verboseLogLevel = Debug
84+
85+isOverwrite :: Output -> Bool
86+isOverwrite = \case
87+ Output_Overwrite _ -> True
88+ _ -> False
89+
90+getSeverity :: Output -> Maybe Severity
91+getSeverity = \case
92+ Output_Log (WithSeverity sev _) -> Just sev
93+ Output_LogRaw (WithSeverity sev _) -> Just sev
94+ _ -> Nothing
95+
96+getLogLevel :: (MonadIO m, HasCliConfig e m) => m Severity
97+getLogLevel = getLogLevel' =<< getCliConfig
98+
99+getLogLevel' :: MonadIO m => CliConfig e -> m Severity
100+getLogLevel' = liftIO . readIORef . _cliConfig_logLevel
101+
102+setLogLevel :: (MonadIO m, HasCliConfig e m) => Severity -> m ()
103+setLogLevel sev = do
104+ l <- _cliConfig_logLevel <$> getCliConfig
105+ liftIO $ writeIORef l sev
106+
107+handleLog :: MonadIO m => CliConfig e -> Output -> m ()
108+handleLog conf output = do
109+ level <- getLogLevel' conf
110+ liftIO $ modifyMVar_ (_cliConfig_lock conf) $ \wasOverwriting -> do
111+ let noColor = _cliConfig_noColor conf
112+ case getSeverity output of
113+ Nothing -> handleLog' noColor output
114+ Just sev -> if sev > level
115+ then return wasOverwriting -- Discard if sev is above configured log level
116+ else do
117+ -- If the last output was an overwrite (with cursor on same line), ...
118+ when wasOverwriting $
119+ void $ handleLog' noColor Output_ClearLine -- first clear it,
120+ handleLog' noColor output -- then, actually write the msg.
121+
122+handleLog' :: MonadIO m => Bool -> Output -> m Bool
123+handleLog' noColor output = do
124+ case output of
125+ Output_Log m -> liftIO $ do
126+ writeLog True noColor m
127+ Output_LogRaw m -> liftIO $ do
128+ writeLog False noColor m
129+ hFlush stdout -- Explicitly flush, as there is no newline
130+ Output_Write ts -> liftIO $ do
131+ T.putStrLn $ TS.render (not noColor) Nothing ts
132+ hFlush stdout
133+ Output_Overwrite ts -> liftIO $ do
134+ width <- TS.getTerminalWidth
135+ T.putStr $ "\r" <> TS.render (not noColor) width ts
136+ hFlush stdout
137+ Output_ClearLine -> liftIO $ do
138+ -- Go to the first column and clear the whole line
139+ putStr "\r"
140+ clearLine
141+ hFlush stdout
142+ return $ isOverwrite output
143+
144+-- | Like `putLog` but without the implicit newline added.
145+putLogRaw :: CliLog m => Severity -> Text -> m ()
146+putLogRaw sev = logMessage . Output_LogRaw . WithSeverity sev
147+
148+-- | Indicates unstructured errors form one variant (or conceptual projection)
149+-- of the error type.
150+--
151+-- Shouldn't really use this, but who has time to clean up that much!
152+class AsUnstructuredError e where
153+ asUnstructuredError :: Prism' e Text
154+
155+instance AsUnstructuredError Text where
156+ asUnstructuredError = id
157+
158+-- | Like `putLog Alert` but also abrupts the program.
159+failWith :: (CliThrow e m, AsUnstructuredError e) => Text -> m a
160+failWith = throwError . review asUnstructuredError
161+
162+errorToWarning
163+ :: (HasCliConfig e m, CliLog m)
164+ => e -> m ()
165+errorToWarning e = do
166+ c <- getCliConfig
167+ putLog Warning $ fst $ _cliConfig_errorLogExitCode c e
168+
169+-- | Intercept ExitFailure exceptions and log the given alert before exiting.
170+--
171+-- This is useful when you want to provide contextual information to a deeper failure.
172+withExitFailMessage :: (CliLog m, MonadCatch m) => Text -> m a -> m a
173+withExitFailMessage msg f = f `catch` \(e :: ExitCode) -> do
174+ case e of
175+ ExitFailure _ -> putLog Alert msg
176+ ExitSuccess -> pure ()
177+ throwM e
178+
179+-- | Write log to stdout, with colors (unless `noColor`)
180+writeLog :: (MonadIO m) => Bool -> Bool -> WithSeverity Text -> m ()
181+writeLog withNewLine noColor (WithSeverity severity s) = if T.null s then pure () else write
182+ where
183+ write
184+ | noColor && severity <= Warning = liftIO $ putFn $ T.pack (show severity) <> ": " <> s
185+ | not noColor && severity <= Error = TS.putStrWithSGR errorColors h withNewLine s
186+ | not noColor && severity <= Warning = TS.putStrWithSGR warningColors h withNewLine s
187+ | not noColor && severity >= Debug = TS.putStrWithSGR debugColors h withNewLine s
188+ | otherwise = liftIO $ putFn s
189+
190+ putFn = if withNewLine then T.hPutStrLn h else T.hPutStr h
191+ h = if severity <= Error then stderr else stdout
192+ errorColors = [SetColor Foreground Vivid Red]
193+ warningColors = [SetColor Foreground Vivid Yellow]
194+ debugColors = [SetConsoleIntensity FaintIntensity]
195+
196+-- | Allow the user to immediately switch to verbose logging upon pressing a particular key.
197+--
198+-- Call this function in a thread, and kill it to turn off keystroke monitoring.
199+allowUserToMakeLoggingVerbose
200+ :: (MonadIO m, MonadMask m, CliLog m, HasCliConfig e m)
201+ => String -- ^ The key to press in order to make logging verbose
202+ -> m ()
203+allowUserToMakeLoggingVerbose keyCode = bracket showTip (liftIO . killThread) $ \_ -> do
204+ unlessVerbose $ do
205+ liftIO $ hSetBuffering stdin NoBuffering
206+ _ <- iterateUntil (== keyCode) $ liftIO getChars
207+ putLog Warning "Ctrl+e pressed; making output verbose (-v)"
208+ setLogLevel verboseLogLevel
209+ where
210+ showTip = fork $ unlessVerbose $ do
211+ conf <- getCliConfig
212+ liftIO $ threadDelay $ 10*1000000 -- Only show tip for actions taking too long (10 seconds or more)
213+ tipDisplayed <- liftIO $ atomicModifyIORef' (_cliConfig_tipDisplayed conf) $ (,) True
214+ unless tipDisplayed $ unlessVerbose $ do -- Check again in case the user had pressed Ctrl+e recently
215+ putLog Notice "Tip: Press Ctrl+e to display full output"
216+ unlessVerbose f = do
217+ l <- getLogLevel
218+ unless (l == verboseLogLevel) f
219+
220+-- | Like `getChar` but also retrieves the subsequently pressed keys.
221+--
222+-- Allowing, for example, the ↑ key, which consists of the three characters
223+-- ['\ESC','[','A'] to be distinguished from an actual \ESC character input.
224+getChars :: IO String
225+getChars = reverse <$> f mempty
226+ where
227+ f xs = do
228+ x <- getChar
229+ hReady stdin >>= \case
230+ True -> f (x:xs)
231+ False -> return (x:xs)
232+
233+fork :: (HasCliConfig e m, MonadIO m) => CliT e IO () -> m ThreadId
234+fork f = do
235+ c <- getCliConfig
236+ liftIO $ forkIO $ runCli c f
237+
238+-- | Conservatively determines whether the encoding supports Unicode.
239+--
240+-- Currently this uses a whitelist of known-to-work encodings. In principle it
241+-- could test dynamically by opening a file with this encoding, but it doesn't
242+-- look like base exposes any way to determine this in a pure fashion.
243+supportsUnicode :: TextEncoding -> Bool
244+supportsUnicode enc = any ((textEncodingName enc ==) . textEncodingName)
245+ [ utf8
246+ , utf8_bom
247+ , utf16
248+ , utf16be
249+ , utf16le
250+ , utf32
251+ , utf32be
252+ , utf32le
253+ ]
lib/cliapp/src/Obelisk/CliApp/Process.hsnew file+272
@@ -0,0 +1,272 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE OverloadedStrings #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+{-# LANGUAGE TupleSections #-}
7+
8+-- | An extension of `System.Process` that integrates with logging (`Obelisk.CLI.Logging`)
9+-- and is thus spinner friendly.
10+module Obelisk.CliApp.Process
11+ ( AsProcessFailure (..)
12+ , ProcessFailure (..)
13+ , ProcessSpec (..)
14+ , callCommand
15+ , callProcess
16+ , callProcessAndLogOutput
17+ , createProcess
18+ , createProcess_
19+ , exitCodeToException
20+ , overCreateProcess
21+ , proc
22+ , readCreateProcessWithExitCode
23+ , readProcessAndLogOutput
24+ , readProcessAndLogStderr
25+ , readProcessJSONAndLogStderr
26+ , reconstructCommand
27+ , runProcess_
28+ , setCwd
29+ , setDelegateCtlc
30+ , setEnvOverride
31+ , shell
32+ , waitForProcess
33+ ) where
34+
35+import Control.Monad ((<=<), join, void)
36+import Control.Monad.Catch (MonadMask, bracketOnError)
37+import Control.Monad.Except (throwError)
38+import Control.Monad.Fail
39+import Control.Monad.IO.Class (MonadIO, liftIO)
40+import Control.Lens (Prism', review)
41+import qualified Data.ByteString as BS
42+import qualified Data.ByteString.Char8 as BSC
43+import qualified Data.ByteString.UTF8 as BSU
44+import Data.Function (fix)
45+import Data.Map (Map)
46+import qualified Data.Map as Map
47+import Data.Monoid ((<>))
48+import Data.Text (Text)
49+import qualified Data.Text as T
50+import qualified Data.Text.Encoding as T
51+import Data.Text.Encoding.Error (lenientDecode)
52+import System.Environment (getEnvironment)
53+import System.Exit (ExitCode (..))
54+import System.IO (Handle)
55+import System.IO.Streams (InputStream, handleToInputStream)
56+import qualified System.IO.Streams as Streams
57+import System.IO.Streams.Concurrent (concurrentMerge)
58+import System.Process (CreateProcess, ProcessHandle, StdStream (CreatePipe), std_err, std_out)
59+import qualified System.Process as Process
60+import Text.ShellEscape (bash, bytes)
61+import qualified Data.Aeson as Aeson
62+
63+import Control.Monad.Log (Severity (..))
64+import Obelisk.CliApp.Logging (putLog, putLogRaw)
65+import Obelisk.CliApp.Types (CliLog, CliThrow)
66+
67+data ProcessSpec = ProcessSpec
68+ { _processSpec_createProcess :: !CreateProcess
69+ , _processSpec_overrideEnv :: !(Maybe (Map String String -> Map String String))
70+ }
71+
72+proc :: FilePath -> [String] -> ProcessSpec
73+proc cmd args = ProcessSpec (Process.proc cmd args) Nothing
74+
75+shell :: String -> ProcessSpec
76+shell cmd = ProcessSpec (Process.shell cmd) Nothing
77+
78+setEnvOverride :: (Map String String -> Map String String) -> ProcessSpec -> ProcessSpec
79+setEnvOverride f p = p { _processSpec_overrideEnv = Just f }
80+
81+overCreateProcess :: (CreateProcess -> CreateProcess) -> ProcessSpec -> ProcessSpec
82+overCreateProcess f (ProcessSpec p x) = ProcessSpec (f p) x
83+
84+setDelegateCtlc :: Bool -> ProcessSpec -> ProcessSpec
85+setDelegateCtlc b = overCreateProcess (\p -> p { Process.delegate_ctlc = b })
86+
87+setCwd :: Maybe FilePath -> ProcessSpec -> ProcessSpec
88+setCwd fp = overCreateProcess (\p -> p { Process.cwd = fp })
89+
90+
91+-- TODO put back in `Obelisk.CliApp.Process` and use prisms for extensible exceptions
92+data ProcessFailure = ProcessFailure Process.CmdSpec Int -- exit code
93+ deriving Show
94+
95+-- | Indicates arbitrary process failures form one variant (or conceptual projection) of
96+-- the error type.
97+class AsProcessFailure e where
98+ asProcessFailure :: Prism' e ProcessFailure
99+
100+instance AsProcessFailure ProcessFailure where
101+ asProcessFailure = id
102+
103+readProcessAndLogStderr
104+ :: (MonadIO m, CliLog m, CliThrow e m, AsProcessFailure e, MonadMask m)
105+ => Severity -> ProcessSpec -> m Text
106+readProcessAndLogStderr sev process = do
107+ (out, _err) <- withProcess process $ \_out err -> do
108+ streamToLog =<< liftIO (streamHandle sev err)
109+ liftIO $ T.decodeUtf8With lenientDecode <$> BS.hGetContents out
110+
111+readProcessJSONAndLogStderr
112+ :: (Aeson.FromJSON a, MonadIO m, CliLog m, CliThrow e m, AsProcessFailure e, MonadMask m)
113+ => Severity -> ProcessSpec -> m a
114+readProcessJSONAndLogStderr sev process = do
115+ (out, _err) <- withProcess process $ \_out err -> do
116+ streamToLog =<< liftIO (streamHandle sev err)
117+ json <- liftIO $ BS.hGetContents out
118+ case Aeson.eitherDecodeStrict json of
119+ Right a -> pure a
120+ Left err -> do
121+ putLog Error $ "Could not decode process output as JSON: " <> T.pack err
122+ throwError $ review asProcessFailure $ ProcessFailure (Process.cmdspec $ _processSpec_createProcess process) 0
123+
124+readCreateProcessWithExitCode
125+ :: (MonadIO m, CliLog m)
126+ => ProcessSpec -> m (ExitCode, String, String)
127+readCreateProcessWithExitCode procSpec = do
128+ process <- mkCreateProcess procSpec
129+ putLog Debug $ "Creating process: " <> reconstructProcSpec procSpec
130+ liftIO $ Process.readCreateProcessWithExitCode process ""
131+
132+-- | Like `System.Process.readProcess` but logs the combined output (stdout and stderr)
133+-- with the corresponding severity.
134+--
135+-- Usually this function is called as `readProcessAndLogOutput (Debug, Error)`. However
136+-- some processes are known to spit out diagnostic or informative messages in stderr, in
137+-- which case it is advisable to call it with a non-Error severity for stderr, like
138+-- `readProcessAndLogOutput (Debug, Debug)`.
139+readProcessAndLogOutput
140+ :: (MonadIO m, CliLog m, CliThrow e m, AsProcessFailure e, MonadFail m)
141+ => (Severity, Severity) -> ProcessSpec -> m Text
142+readProcessAndLogOutput (sev_out, sev_err) process = do
143+ (_, Just out, Just err, p) <- createProcess $ overCreateProcess
144+ (\p -> p { std_out = CreatePipe , std_err = CreatePipe }) process
145+
146+ -- TODO interleave stdout and stderr in log correctly
147+ streamToLog =<< liftIO (streamHandle sev_err err)
148+ outText <- liftIO $ T.decodeUtf8With lenientDecode <$> BS.hGetContents out
149+ putLogRaw sev_out outText
150+
151+ outText <$ (exitCodeToException process =<< waitForProcess p)
152+
153+-- | Like 'System.Process.callProcess' but logs the combined output (stdout and stderr)
154+-- with the corresponding severity.
155+--
156+-- Usually this function is called as `callProcessAndLogOutput (Debug, Error)`. However
157+-- some processes are known to spit out diagnostic or informative messages in stderr, in
158+-- which case it is advisable to call it with a non-Error severity for stderr, like
159+-- `callProcessAndLogOutput (Debug, Debug)`.
160+callProcessAndLogOutput
161+ :: (MonadIO m, CliLog m, CliThrow e m, AsProcessFailure e, MonadMask m)
162+ => (Severity, Severity) -> ProcessSpec -> m ()
163+callProcessAndLogOutput (sev_out, sev_err) process =
164+ void $ withProcess process $ \out err -> do
165+ stream <- liftIO $ join $ combineStream
166+ <$> streamHandle sev_out out
167+ <*> streamHandle sev_err err
168+ streamToLog stream
169+ where
170+ combineStream s1 s2 = concurrentMerge [s1, s2]
171+
172+-- | Like 'System.Process.createProcess' but also logs (debug) the process being run
173+createProcess
174+ :: (MonadIO m, CliLog m)
175+ => ProcessSpec -> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
176+createProcess procSpec = do
177+ p <- mkCreateProcess procSpec
178+ putLog Debug $ "Creating process: " <> reconstructProcSpec procSpec
179+ liftIO $ Process.createProcess p
180+
181+-- | Like `System.Process.createProcess_` but also logs (debug) the process being run
182+createProcess_
183+ :: (MonadIO m, CliLog m)
184+ => String -> ProcessSpec -> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
185+createProcess_ name procSpec = do
186+ p <- mkCreateProcess procSpec
187+ putLog Debug $ "Creating process " <> T.pack name <> ": " <> reconstructProcSpec procSpec
188+ liftIO $ Process.createProcess_ name p
189+
190+mkCreateProcess :: MonadIO m => ProcessSpec -> m Process.CreateProcess
191+mkCreateProcess (ProcessSpec p override') = case override' of
192+ Nothing -> pure p
193+ Just override -> do
194+ procEnv <- Map.fromList <$> maybe (liftIO getEnvironment) pure (Process.env p)
195+ pure $ p { Process.env = Just $ Map.toAscList (override procEnv) }
196+
197+-- | Like `System.Process.callProcess` but also logs (debug) the process being run
198+callProcess
199+ :: (MonadIO m, CliLog m)
200+ => String -> [String] -> m ()
201+callProcess exe args = do
202+ putLog Debug $ "Calling process " <> T.pack exe <> " with args: " <> T.pack (show args)
203+ liftIO $ Process.callProcess exe args
204+
205+-- | Like `System.Process.callCommand` but also logs (debug) the command being run
206+callCommand
207+ :: (MonadIO m, CliLog m)
208+ => String -> m ()
209+callCommand cmd = do
210+ putLog Debug $ "Calling command " <> T.pack cmd
211+ liftIO $ Process.callCommand cmd
212+
213+withProcess
214+ :: (MonadIO m, CliLog m, CliThrow e m, AsProcessFailure e, MonadMask m)
215+ => ProcessSpec -> (Handle -> Handle -> m ()) -> m (Handle, Handle)
216+withProcess process f =
217+ bracketOnError
218+ (createProcess $ overCreateProcess
219+ (\x -> x { std_out = CreatePipe , std_err = CreatePipe }) process
220+ )
221+ (liftIO . Process.cleanupProcess)
222+ (\case
223+ (_, Just out, Just err, p) -> do
224+ f out err
225+ (out, err) <$ (exitCodeToException process =<< waitForProcess p)
226+ _ -> error "withProcess: createProcess did not provide handles for CreatePipe as expected"
227+ )
228+
229+-- | Runs a process to completion failing if it does not exit cleanly.
230+runProcess_
231+ :: (MonadIO m, CliLog m, CliThrow e m, MonadMask m, AsProcessFailure e)
232+ => ProcessSpec -> m ()
233+runProcess_ process =
234+ bracketOnError
235+ (createProcess process)
236+ (liftIO . Process.cleanupProcess)
237+ (\(_, _, _, ph) -> exitCodeToException process =<< waitForProcess ph)
238+
239+-- Create an input stream from the file handle, associating each item with the given severity.
240+streamHandle :: Severity -> Handle -> IO (InputStream (Severity, BSC.ByteString))
241+streamHandle sev = Streams.map (sev,) <=< handleToInputStream
242+
243+-- | Read from an input stream and log its contents
244+streamToLog
245+ :: (MonadIO m, CliLog m)
246+ => InputStream (Severity, BSC.ByteString) -> m ()
247+streamToLog stream = fix $ \loop -> do
248+ liftIO (Streams.read stream) >>= \case
249+ Nothing -> return ()
250+ Just (sev, line) -> putLogRaw sev (T.decodeUtf8With lenientDecode line) >> loop
251+
252+-- | Wrapper around `System.Process.waitForProcess`
253+waitForProcess :: MonadIO m => ProcessHandle -> m ExitCode
254+waitForProcess = liftIO . Process.waitForProcess
255+
256+-- | Converts an 'ExitCode' to an exception when it's non-zero.
257+exitCodeToException :: (CliThrow e m, AsProcessFailure e) => ProcessSpec -> ExitCode -> m ()
258+exitCodeToException spec = \case
259+ ExitSuccess -> pure ()
260+ ExitFailure code -> throwError $ review asProcessFailure $ ProcessFailure (Process.cmdspec $ _processSpec_createProcess spec) code
261+
262+-- | Pretty print a 'CmdSpec'
263+reconstructCommand :: Process.CmdSpec -> Text
264+reconstructCommand p = case p of
265+ Process.ShellCommand str -> T.pack str
266+ Process.RawCommand c as -> processToShellString c as
267+ where
268+ processToShellString cmd args = T.pack $ unwords $
269+ map (BSU.toString . bytes . bash . BSU.fromString) (cmd : args)
270+
271+reconstructProcSpec :: ProcessSpec -> Text
272+reconstructProcSpec = reconstructCommand . Process.cmdspec . _processSpec_createProcess
lib/cliapp/src/Obelisk/CliApp/Spinner.hsnew file+145
@@ -0,0 +1,145 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE OverloadedStrings #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+-- | Provides a simple CLI spinner that interoperates cleanly with the rest of the logging output.
7+module Obelisk.CliApp.Spinner
8+ ( withSpinner
9+ , withSpinnerNoTrail
10+ , withSpinner'
11+ ) where
12+
13+import Control.Concurrent (killThread, threadDelay)
14+import Control.Monad (forM_, (>=>))
15+import Control.Monad.Catch (MonadMask, mask, onException)
16+import Control.Monad.IO.Class
17+import Control.Monad.Log (Severity (..), logMessage)
18+import Data.IORef
19+import qualified Data.List as L
20+import Data.Maybe (isNothing)
21+import Data.Text (Text)
22+import System.Console.ANSI (Color (Blue, Cyan, Green, Red))
23+
24+import Obelisk.CliApp.Logging (allowUserToMakeLoggingVerbose, fork, putLog)
25+import Obelisk.CliApp.TerminalString (TerminalString (..), enquiryCode)
26+import Obelisk.CliApp.Theme
27+import Obelisk.CliApp.Types (CliLog, CliConfig (..), HasCliConfig, Output (..), getCliConfig)
28+
29+-- | Run an action with a CLI spinner.
30+withSpinner
31+ :: (MonadIO m, MonadMask m, CliLog m, HasCliConfig e m)
32+ => Text -> m a -> m a
33+withSpinner s = withSpinner' s $ Just $ const s
34+
35+-- | A spinner that leaves no trail after a successful run.
36+--
37+-- Use if you wish the spinner to be ephemerally visible to the user.
38+--
39+-- The 'no trail' property automatically carries over to sub-spinners (in that
40+-- they won't leave a trail either).
41+withSpinnerNoTrail
42+ :: (MonadIO m, MonadMask m, CliLog m, HasCliConfig e m)
43+ => Text -> m a -> m a
44+withSpinnerNoTrail s = withSpinner' s Nothing
45+
46+-- | Advanced version that controls the display and content of the trail message.
47+withSpinner'
48+ :: (MonadIO m, MonadMask m, CliLog m, HasCliConfig e m)
49+ => Text
50+ -> Maybe (a -> Text) -- ^ Leave an optional trail with the given message creator
51+ -> m a
52+ -> m a
53+withSpinner' msg mkTrail action = do
54+ cliConf <- getCliConfig
55+ let noSpinner = _cliConfig_noSpinner cliConf
56+ if noSpinner
57+ then putLog Notice msg >> action
58+ else bracket' run cleanup $ const action
59+ where
60+ run = do
61+ -- Add this log to the spinner stack, and start a spinner if it is top-level.
62+ modifyStack pushSpinner >>= \case
63+ True -> do -- Top-level spinner; fork a thread to manage output of anything on the stack
64+ ctrleThread <- fork $ allowUserToMakeLoggingVerbose enquiryCode
65+ cliConf <- getCliConfig
66+ let theme = _cliConfig_theme cliConf
67+ spinner = coloredSpinner $ _cliTheme_spinner theme
68+ spinnerThread <- fork $ runSpinner spinner $ \c -> do
69+ logs <- renderSpinnerStack theme c . snd <$> readStack
70+ logMessage $ Output_Overwrite logs
71+ pure [ctrleThread, spinnerThread]
72+ False -> -- Sub-spinner; nothing to do.
73+ pure []
74+ cleanup tids resultM = do
75+ liftIO $ mapM_ killThread tids
76+ logMessage Output_ClearLine
77+ cliConf <- getCliConfig
78+ let theme = _cliConfig_theme cliConf
79+ logsM <- modifyStack $ (popSpinner theme) $ case resultM of
80+ Nothing ->
81+ ( TerminalString_Colorized Red $ _cliTheme_failed $ _cliConfig_theme cliConf
82+ , Just msg -- Always display final message if there was an exception.
83+ )
84+ Just result ->
85+ ( TerminalString_Colorized Green $ _cliTheme_done $ _cliConfig_theme cliConf
86+ , mkTrail <*> pure result
87+ )
88+ -- Last message, finish off with newline.
89+ forM_ logsM $ logMessage . Output_Write
90+ pushSpinner (flag, old) =
91+ ( (isTemporary : flag, TerminalString_Normal msg : old)
92+ , null old -- Is empty?
93+ )
94+ where
95+ isTemporary = isNothing mkTrail
96+ popSpinner theme (mark, trailMsgM) (flag, old) =
97+ ( (newFlag, new)
98+ -- With final trail spinner message to render
99+ , renderSpinnerStack theme mark . (: new) . TerminalString_Normal <$> (
100+ if inTemporarySpinner then Nothing else trailMsgM
101+ )
102+ )
103+ where
104+ inTemporarySpinner = or newFlag -- One of our parent spinners is temporary
105+ newFlag = drop 1 flag
106+ new = L.delete (TerminalString_Normal msg) old
107+ readStack = liftIO . readIORef
108+ =<< fmap _cliConfig_spinnerStack getCliConfig
109+ modifyStack f = liftIO . flip atomicModifyIORef' f
110+ =<< fmap _cliConfig_spinnerStack getCliConfig
111+
112+-- | How nested spinner logs should be displayed
113+renderSpinnerStack
114+ :: CliTheme
115+ -> TerminalString -- ^ That which comes before the final element in stack
116+ -> [TerminalString] -- ^ Spinner elements in reverse order
117+ -> [TerminalString]
118+renderSpinnerStack theme mark = L.intersperse space . go . L.reverse
119+ where
120+ go [] = []
121+ go (x:[]) = mark : [x]
122+ go (x:xs) = arrow : x : go xs
123+ arrow = TerminalString_Colorized Blue $ _cliTheme_arrow theme
124+ space = TerminalString_Normal " "
125+
126+-- | A spinner is simply an infinite list of strings that supplant each other in a delayed loop, creating the
127+-- animation of a "spinner".
128+type Spinner = [TerminalString]
129+
130+coloredSpinner :: SpinnerTheme -> Spinner
131+coloredSpinner = cycle . fmap (TerminalString_Colorized Cyan)
132+
133+-- | Run a spinner with a monadic function that defines how to represent the individual spinner characters.
134+runSpinner :: MonadIO m => Spinner -> (TerminalString -> m ()) -> m ()
135+runSpinner spinner f = forM_ spinner $ f >=> const delay
136+ where
137+ delay = liftIO $ threadDelay 100000 -- A shorter delay ensures that we update promptly.
138+
139+-- | Like `bracket` but the `release` function can know whether an exception was raised
140+bracket' :: MonadMask m => m a -> (a -> Maybe c -> m b) -> (a -> m c) -> m c
141+bracket' acquire release use = mask $ \unmasked -> do
142+ resource <- acquire
143+ result <- unmasked (use resource) `onException` release resource Nothing
144+ _ <- release resource $ Just result
145+ return result
lib/cliapp/src/Obelisk/CliApp/TerminalString.hsnew file+84
@@ -0,0 +1,84 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE MultiParamTypeClasses #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+-- | Types and functions dealing with strings to be printed on terminal.
5+module Obelisk.CliApp.TerminalString
6+ ( TerminalString(..)
7+ , render
8+ , putStrWithSGR
9+ , getTerminalWidth
10+ , enquiryCode
11+ ) where
12+
13+import Control.Monad (when)
14+import Control.Monad.Catch (bracket_)
15+import Control.Monad.IO.Class (liftIO)
16+import Control.Monad.Reader (MonadIO)
17+import Data.Semigroup ((<>))
18+import Data.Text (Text)
19+import qualified Data.Text as T
20+import qualified Data.Text.IO as T
21+import System.Console.ANSI
22+import qualified System.Console.Terminal.Size as TerminalSize
23+import System.IO (Handle)
24+
25+-- | Printable text on terminals
26+--
27+-- Represents text with an optional color code.
28+data TerminalString
29+ = TerminalString_Normal Text
30+ | TerminalString_Colorized Color Text
31+ deriving (Eq, Show, Ord)
32+
33+printableLength :: [TerminalString] -> Int
34+printableLength = T.length . toText False
35+
36+-- Render a list of TerminalString as Text that can be directly putStr'ed.
37+render
38+ :: Bool -- ^ with color
39+ -> Maybe Int -- ^ optionally, trim to maximum width
40+ -> [TerminalString]
41+ -> Text
42+render withColor w ts = trim w $ toText withColor ts
43+ where
44+ trim = \case
45+ Nothing -> id
46+ Just n -> \s -> if printableLength ts > n
47+ then T.take (n-3) s <> "..." <> T.pack resetCode
48+ else s
49+
50+toText :: Bool -> [TerminalString] -> Text
51+toText withColor = mconcat . map (toText' withColor)
52+
53+-- | Convert to Text, controlling whether colorization should happen.
54+toText' :: Bool -> TerminalString -> Text
55+toText' withColor = \case
56+ TerminalString_Normal s -> s
57+ TerminalString_Colorized c s -> if withColor then colorizeText c s else s
58+
59+-- | Colorize the given text so that it is printed in color when using putStr.
60+colorizeText :: Color -> Text -> Text
61+colorizeText color s = mconcat
62+ [ T.pack $ setSGRCode [SetColor Foreground Vivid color]
63+ , s
64+ , T.pack resetCode
65+ ]
66+
67+-- | Safely print the string with the given ANSI control codes, resetting in the end.
68+putStrWithSGR :: MonadIO m => [SGR] -> Handle -> Bool -> Text -> m ()
69+putStrWithSGR sgr h withNewLine s = liftIO $ bracket_ (hSetSGR h sgr) reset $ T.hPutStr h s
70+ where
71+ reset = hSetSGR h [Reset] >> newline -- New line should come *after* reset (to reset cursor color).
72+ newline = when withNewLine $ T.hPutStrLn h ""
73+
74+-- | Code for https://en.wikipedia.org/wiki/Enquiry_character
75+enquiryCode :: String
76+enquiryCode = "\ENQ"
77+
78+-- | Code to reset ANSI colors
79+resetCode :: String
80+resetCode = setSGRCode [Reset]
81+
82+getTerminalWidth :: IO (Maybe Int)
83+getTerminalWidth = fmap TerminalSize.width <$> TerminalSize.size
84+
lib/cliapp/src/Obelisk/CliApp/Theme.hsnew file+29
@@ -0,0 +1,29 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Obelisk.CliApp.Theme where
3+
4+import Data.Text (Text)
5+
6+data CliTheme = CliTheme
7+ { _cliTheme_done :: Text
8+ , _cliTheme_failed :: Text
9+ , _cliTheme_arrow :: Text
10+ , _cliTheme_spinner :: SpinnerTheme
11+ }
12+
13+type SpinnerTheme = [Text]
14+
15+unicodeTheme :: CliTheme
16+unicodeTheme = CliTheme
17+ { _cliTheme_done = "✔"
18+ , _cliTheme_failed = "✖"
19+ , _cliTheme_arrow = "⇾"
20+ , _cliTheme_spinner = ["◐", "◓", "◑", "◒"]
21+ }
22+
23+noUnicodeTheme :: CliTheme
24+noUnicodeTheme = CliTheme
25+ { _cliTheme_done = "DONE"
26+ , _cliTheme_failed = "FAILED"
27+ , _cliTheme_arrow = "->"
28+ , _cliTheme_spinner = ["|", "/", "-", "\\"]
29+ }
lib/cliapp/src/Obelisk/CliApp/Types.hsnew file+132
@@ -0,0 +1,132 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE FunctionalDependencies #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE OverloadedStrings #-}
9+{-# LANGUAGE StandaloneDeriving #-}
10+{-# LANGUAGE UndecidableInstances #-}
11+module Obelisk.CliApp.Types where
12+
13+import Control.Concurrent.MVar (MVar)
14+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
15+import Control.Monad.Fail (MonadFail)
16+import Control.Monad.Log (LoggingT(..), MonadLog, Severity (..), WithSeverity (..), logMessage)
17+import Control.Monad.Reader (MonadIO, ReaderT (..), MonadReader (..), ask, mapReaderT)
18+import Control.Monad.Writer (WriterT)
19+import Control.Monad.State (StateT)
20+import Control.Monad.Except (ExceptT, MonadError (..))
21+import Control.Monad.IO.Class (liftIO)
22+import Control.Monad.Trans (MonadTrans, lift)
23+import Data.IORef (IORef)
24+import Data.Text (Text)
25+import System.Exit (ExitCode (..), exitWith)
26+
27+import Obelisk.CliApp.TerminalString (TerminalString)
28+import Obelisk.CliApp.Theme (CliTheme)
29+
30+--------------------------------------------------------------------------------
31+
32+data Output
33+ = Output_Log (WithSeverity Text) -- Regular logging message (with colors and newlines)
34+ | Output_LogRaw (WithSeverity Text) -- Like `Output_Log` but without the implicit newline added.
35+ | Output_Write [TerminalString] -- Render and write a TerminalString using putstrLn
36+ | Output_Overwrite [TerminalString] -- Overwrite the current line (i.e. \r followed by `putStr`)
37+ | Output_ClearLine -- Clear the line
38+ deriving (Eq, Show, Ord)
39+
40+type CliLog m = MonadLog Output m
41+
42+type CliThrow e m = MonadError e m
43+
44+-- | Log a message to the console.
45+--
46+-- Logs safely even if there are ongoing spinners.
47+putLog :: CliLog m => Severity -> Text -> m ()
48+putLog sev = logMessage . Output_Log . WithSeverity sev
49+
50+deriving instance MonadFail m => MonadFail (LoggingT Output m)
51+
52+newtype DieT e m a = DieT { unDieT :: ReaderT (e -> (Text, Int)) (LoggingT Output m) a }
53+ deriving
54+ ( Functor, Applicative, Monad, MonadIO, MonadFail
55+ , MonadThrow, MonadCatch, MonadMask
56+ , MonadLog Output
57+ )
58+
59+instance MonadTrans (DieT e) where
60+ lift = DieT . lift . lift
61+
62+-- | Error printer is private to DieT
63+instance MonadReader r m => MonadReader r (DieT e m) where
64+ ask = DieT $ lift $ ask
65+ local = (\f (DieT a) -> DieT $ f a) . mapReaderT . local
66+ reader = DieT . lift . lift . reader
67+
68+-- TODO generalize to bigger error types
69+instance MonadIO m => MonadError e (DieT e m) where
70+ throwError e = do
71+ handler <- DieT ask
72+ let (output, exitCode) = handler e
73+ putLog Alert output
74+ liftIO $ exitWith $ ExitFailure exitCode
75+
76+ -- Cannot catch
77+ catchError m _ = m
78+
79+--------------------------------------------------------------------------------
80+
81+data CliConfig e = CliConfig
82+ { -- | We are capable of changing the log level at runtime
83+ _cliConfig_logLevel :: IORef Severity
84+ , -- | Disallow coloured output
85+ _cliConfig_noColor :: Bool
86+ , -- | Disallow spinners
87+ _cliConfig_noSpinner :: Bool
88+ , -- | Whether the last message was an Overwrite output
89+ _cliConfig_lock :: MVar Bool
90+ , -- | Whether the user tip (to make verbose) was already displayed
91+ _cliConfig_tipDisplayed :: IORef Bool
92+ , -- | Stack of logs from nested spinners
93+ _cliConfig_spinnerStack :: IORef ([Bool], [TerminalString])
94+ , -- | Failure handler. How to log error and what exit status to use.
95+ _cliConfig_errorLogExitCode :: e -> (Text, Int)
96+ , -- | Theme strings for spinners
97+ _cliConfig_theme :: CliTheme
98+ }
99+
100+class Monad m => HasCliConfig e m | m -> e where
101+ getCliConfig :: m (CliConfig e)
102+
103+instance HasCliConfig e m => HasCliConfig e (ReaderT r m) where
104+ getCliConfig = lift getCliConfig
105+
106+instance (Monoid w, HasCliConfig e m) => HasCliConfig e (WriterT w m) where
107+ getCliConfig = lift getCliConfig
108+
109+instance HasCliConfig e m => HasCliConfig e (StateT s m) where
110+ getCliConfig = lift getCliConfig
111+
112+instance HasCliConfig e m => HasCliConfig e (ExceptT e m) where
113+ getCliConfig = lift getCliConfig
114+
115+--------------------------------------------------------------------------------
116+
117+newtype CliT e m a = CliT
118+ { unCliT :: ReaderT (CliConfig e) (DieT e m) a
119+ }
120+ deriving
121+ ( Functor, Applicative, Monad, MonadIO, MonadFail
122+ , MonadThrow, MonadCatch, MonadMask
123+ , MonadLog Output -- CliLog
124+ , MonadError e -- CliThrow
125+ , MonadReader (CliConfig e) -- HasCliConfig
126+ )
127+
128+instance MonadTrans (CliT e) where
129+ lift = CliT . lift . lift
130+
131+instance Monad m => HasCliConfig e (CliT e m)where
132+ getCliConfig = ask
lib/command/obelisk-command.cabal+27−17
@@ -1,5 +1,5 @@
1name: obelisk-command
1name: obelisk-command
2−version: 0.1
2+version: 0.9.0.1
3cabal-version: >= 1.8
3cabal-version: >= 1.8
4build-type: Simple
4build-type: Simple
5
5
@@ -7,53 +7,63 @@ library
7 hs-source-dirs: src
7 hs-source-dirs: src
8 build-depends:
8 build-depends:
9 aeson
9 aeson
10− , ansi-terminal
11− , Cabal
12 , aeson-pretty
10 , aeson-pretty
13− , attoparsec
11+ , ansi-terminal
14 , base
12 , base
15− , base16-bytestring
16− , binary
17 , bytestring
13 , bytestring
14+ , Cabal
18 , containers
15 , containers
19 , data-default
16 , data-default
20 , directory
17 , directory
18+ , either
19+ , errors
20+ , exceptions
21+ , extra
21 , filepath
22 , filepath
23+ , git
22 , github
24 , github
23− , hit
25+ , here
26+ , hnix
27+ , hpack
24 , io-streams
28 , io-streams
25− , exceptions
29+ , lens
26 , logging-effect
30 , logging-effect
31+ , megaparsec
32+ , modern-uri
33+ , monad-loops
34+ , monoidal-containers
27 , mtl
35 , mtl
28 , network
36 , network
29 , network-uri
37 , network-uri
38+ , obelisk-cliapp
30 , optparse-applicative
39 , optparse-applicative
31 , placeholders
40 , placeholders
32 , process
41 , process
42+ , shell-escape
33 , temporary
43 , temporary
44+ , terminal-size
34 , text
45 , text
35 , time
46 , time
36 , transformers
47 , transformers
37− , unix
48+ , unix-compat
49+ , unordered-containers
50+ , utf8-string
51+ , which
38 , yaml
52 , yaml
39 exposed-modules:
53 exposed-modules:
40 Obelisk.App
54 Obelisk.App
41− Obelisk.CLI
42− Obelisk.CLI.Logging
43− Obelisk.CLI.Process
44− Obelisk.CLI.Spinner
45 Obelisk.Command
55 Obelisk.Command
46 Obelisk.Command.Deploy
56 Obelisk.Command.Deploy
47 Obelisk.Command.Nix
57 Obelisk.Command.Nix
48 Obelisk.Command.Project
58 Obelisk.Command.Project
49− Obelisk.Command.Repl
50 Obelisk.Command.Run
59 Obelisk.Command.Run
51 Obelisk.Command.Thunk
60 Obelisk.Command.Thunk
52 Obelisk.Command.Utils
61 Obelisk.Command.Utils
53− -- -fobject-code is so that the StaticPointers extension can work in ghci
62+ Obelisk.Command.VmBuilder
63+ Obelisk.Command.Preprocessor
54− ghc-options: -Wall -fobject-code
64+ ghc-options: -Wall
55
65
56executable ob
66executable ob
57 main-is: src-bin/ob.hs
67 main-is: src-bin/ob.hs
58 build-depends: base, obelisk-command
68 build-depends: base, obelisk-command
59− ghc-options: -Wall -O2 -threaded
69+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O -threaded
lib/command/src/Obelisk/App.hs+94−12
@@ -1,31 +1,113 @@
1{-# LANGUAGE ConstraintKinds #-}
1{-# LANGUAGE ConstraintKinds #-}
2{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
3{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE LambdaCase #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE StandaloneDeriving #-}
9+{-# LANGUAGE TemplateHaskell #-}
10+{-# LANGUAGE TupleSections #-}
5module Obelisk.App where
11module Obelisk.App where
6
12
13+import Control.Lens
7import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
14import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
8−import Control.Monad.Log (LoggingT, MonadLog, runLoggingT)
15+import Control.Monad.Fail (MonadFail)
9−import Control.Monad.Reader (MonadIO, MonadReader, ReaderT, runReaderT)
16+import Control.Monad.Reader (MonadIO, ReaderT (..), ask, runReaderT)
17+import Control.Monad.Writer (WriterT)
18+import Control.Monad.State (StateT)
19+import Control.Monad.Except (ExceptT, MonadError)
20+import Control.Monad.Trans.Class (MonadTrans, lift)
21+import Data.Text (Text)
22+import System.Directory (XdgDirectory (XdgData), getXdgDirectory)
23+import Control.Monad.Log (MonadLog)
10
24
11−import Obelisk.CLI.Logging (LoggingConfig, Output, handleLog)
25+import Obelisk.CliApp
26+ ( CliConfig
27+ , CliLog
28+ , CliThrow
29+ , CliT (..)
30+ , ProcessFailure
31+ , AsProcessFailure (..)
32+ , AsUnstructuredError (..)
33+ , HasCliConfig
34+ , Output
35+ , runCli
36+ )
12
37
13−data Obelisk = Obelisk
38+data ObeliskError
14− { _obelisk_noSpinner :: Bool -- Used to disable the spinner.
39+ = ObeliskError_ProcessError
15− , _obelisk_logging :: LoggingConfig
40+ { obeliskError_err :: ProcessFailure
41+ , obeliskError_mAnn :: Maybe Text
42+ }
43+ | ObeliskError_Unstructured Text
44+
45+makePrisms ''ObeliskError
46+
47+instance AsUnstructuredError ObeliskError where
48+ asUnstructuredError = _ObeliskError_Unstructured
49+
50+-- Only project when the other field is null, otherwise we are not law abiding.
51+instance AsProcessFailure ObeliskError where
52+ asProcessFailure = _ObeliskError_ProcessError . prism (, Nothing) f
53+ where f = \case
54+ (pf, Nothing) -> Right pf
55+ pann@(_, Just _) -> Left pann
56+
57+newtype Obelisk = Obelisk
58+ { _obelisk_cliConfig :: CliConfig ObeliskError
16 }
59 }
17
60
18newtype ObeliskT m a = ObeliskT
61newtype ObeliskT m a = ObeliskT
19− { unObeliskT :: ReaderT Obelisk (LoggingT Output m) a
62+ { unObeliskT :: ReaderT Obelisk (CliT ObeliskError m) a
20 }
63 }
64+ deriving
21− deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask)
65+ ( Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask, MonadFail
66+ , MonadLog Output -- CliLog
67+ , MonadError ObeliskError -- CliThrow ObeliskError
68+ , HasCliConfig ObeliskError
69+ )
70+
71+instance MonadTrans ObeliskT where
72+ lift = ObeliskT . lift . lift
73+
74+class Monad m => HasObelisk m where
75+ getObelisk :: m Obelisk
76+
77+instance Monad m => HasObelisk (ObeliskT m) where
78+ getObelisk = ObeliskT ask
79+
80+instance HasObelisk m => HasObelisk (ReaderT r m) where
81+ getObelisk = lift getObelisk
82+
83+instance (Monoid w, HasObelisk m) => HasObelisk (WriterT w m) where
84+ getObelisk = lift getObelisk
85+
86+instance HasObelisk m => HasObelisk (StateT r m) where
87+ getObelisk = lift getObelisk
88+
89+instance HasObelisk m => HasObelisk (ExceptT e m) where
90+ getObelisk = lift getObelisk
22
91
23runObelisk :: MonadIO m => Obelisk -> ObeliskT m a -> m a
92runObelisk :: MonadIO m => Obelisk -> ObeliskT m a -> m a
24runObelisk c =
93runObelisk c =
25− flip runLoggingT loggingConfig
94+ runCli (_obelisk_cliConfig c)
26 . flip runReaderT c
95 . flip runReaderT c
27 . unObeliskT
96 . unObeliskT
28− where
29− loggingConfig = handleLog $ _obelisk_logging c
30
97
31−type MonadObelisk m = (MonadReader Obelisk m, MonadIO m, MonadMask m, MonadLog Output m)
98+type MonadInfallibleObelisk m =
99+ ( CliLog m
100+ , HasCliConfig ObeliskError m
101+ , HasObelisk m
102+ , MonadIO m
103+ , MonadMask m
104+ )
105+
106+type MonadObelisk m =
107+ ( MonadInfallibleObelisk m
108+ , CliThrow ObeliskError m
109+ , MonadFail m
110+ )
111+
112+getObeliskUserStateDir :: IO FilePath
113+getObeliskUserStateDir = getXdgDirectory XdgData "obelisk"
lib/command/src/Obelisk/CLI.hsdeleted−55
@@ -1,55 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−-- | Package for writing great CLI apps.
4−module Obelisk.CLI
5− ( withSpinner
6− , cliDemo
7− , module Obelisk.CLI.Logging
8− , module Obelisk.CLI.Process
9− ) where
10−
11−import Control.Concurrent (threadDelay)
12−import Control.Monad.IO.Class (liftIO)
13−import Control.Monad.Reader (ask)
14−import Data.Monoid ((<>))
15−import Data.Text (Text)
16−import qualified Data.Text as T
17−import System.Process (proc)
18−
19−import Obelisk.CLI.Logging
20−import Obelisk.CLI.Process
21−import Obelisk.CLI.Spinner
22−
23−import Obelisk.App (MonadObelisk, _obelisk_logging, _obelisk_noSpinner)
24−
25−-- NOTE: Everything under `Obelisk.CLI` is independent of the rest of Obelisk, with the exception of the
26−-- below functions, as they read the obelisk cli config using MonadReader.
27−
28−withSpinner :: MonadObelisk m => Text -> m a -> m a
29−withSpinner s action = do
30− conf <- ask
31− case _obelisk_noSpinner conf of
32− True -> putLog Notice s >> action
33− False -> withSpinner' (_obelisk_logging conf) s action
34−
35−cliDemo :: MonadObelisk m => m ()
36−cliDemo = do
37− putLog Notice "This demo will showcase the CLI library functionality"
38− withSpinner "Running some long-running task" $ do
39− delay
40− putLog Error "Some user error while spinning"
41− delay
42− putLog Notice "This is some info mesage"
43− putLog Warning "And now a warning as well"
44− delay
45− putLog Notice "Now we start a 2nd spinner, run a couple of process, the last of which fails:"
46− withSpinner "Looking around" $ do
47− delay
48− output <- readProcessAndLogStderr Notice $ proc "ls" ["-l", "/"]
49− putLog Notice $ "Output was: " <> T.pack output
50− delay
51− callProcessAndLogOutput (Notice, Error) $ proc "ls" ["-l", "/does-not-exist"]
52− delay
53− failWith "Something dangerous happened"
54− where
55− delay = liftIO $ threadDelay 1000000
lib/command/src/Obelisk/CLI/Logging.hsdeleted−115
@@ -1,115 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−{-# LANGUAGE MultiWayIf #-}
5−{-# LANGUAGE OverloadedStrings #-}
6−-- | Provides a logging handler that facilitates safe ouputting to terminal using MVar based locking.
7−-- | Spinner.hs and Process.hs work on this guarantee.
8−module Obelisk.CLI.Logging
9− ( Severity (Error, Warning, Notice, Debug)
10− , LoggingConfig (..)
11− , Output (..)
12− , failWith
13− , putLog
14− , putLogRaw
15− , handleLog
16− ) where
17−
18−import Control.Concurrent.MVar (MVar, modifyMVar_)
19−import Control.Monad (void, when)
20−import Control.Monad.Catch (MonadMask, bracket_)
21−import Control.Monad.IO.Class (liftIO)
22−import Control.Monad.Reader (MonadIO)
23−import Data.Text (Text)
24−import qualified Data.Text.IO as T
25−import System.Console.ANSI (Color (Red, White, Yellow), ColorIntensity (Vivid),
26− ConsoleIntensity (FaintIntensity), ConsoleLayer (Foreground),
27− SGR (Reset, SetColor, SetConsoleIntensity), clearLine, setSGR)
28−import System.Exit (ExitCode (ExitFailure), exitWith)
29−import System.IO (hFlush, stdout)
30−
31−import Control.Monad.Log (MonadLog, Severity (..), WithSeverity (..), logMessage)
32−
33−data LoggingConfig = LoggingConfig
34− { _loggingConfig_level :: Severity
35− , _loggingConfig_noColor :: Bool -- Disallow coloured output
36− , _loggingConfig_lock :: MVar Bool -- Whether the last message was an Overwrite output
37− }
38−
39−data Output
40− = Output_Log (WithSeverity Text) -- Regular logging message (with colors and newlines)
41− | Output_LogRaw (WithSeverity Text) -- Like `Output_Log` but without the implicit newline added.
42− | Output_Overwrite [String] -- Overwrites the current line (i.e. \r followed by `putStr`)
43− | Output_ClearLine -- Clears the line
44− deriving (Eq, Show, Ord)
45−
46−isOverwrite :: Output -> Bool
47−isOverwrite = \case
48− Output_Overwrite _ -> True
49− _ -> False
50−
51−getSeverity :: Output -> Maybe Severity
52−getSeverity = \case
53− Output_Log (WithSeverity sev _) -> Just sev
54− Output_LogRaw (WithSeverity sev _) -> Just sev
55− _ -> Nothing
56−
57−handleLog :: MonadIO m => LoggingConfig -> Output -> m ()
58−handleLog (LoggingConfig level noColor lock) output = do
59− liftIO $ modifyMVar_ lock $ \wasOverwriting -> do
60− case getSeverity output of
61− Nothing -> handleLog' noColor output
62− Just sev -> case sev > level of
63− True -> return wasOverwriting -- Discard if sev is above configured log level
64− False -> do
65− -- If the last output was an overwrite (with cursor on same line), ...
66− when wasOverwriting $
67− void $ handleLog' noColor Output_ClearLine -- first clear it,
68− handleLog' noColor output -- then, actually write the msg.
69−
70−handleLog' :: MonadIO m => Bool -> Output -> m Bool
71−handleLog' noColor output = do
72− case output of
73− Output_Log m -> liftIO $ do
74− writeLogWith T.putStrLn noColor m
75− Output_LogRaw m -> liftIO $ do
76− writeLogWith T.putStr noColor m
77− hFlush stdout -- Explicitly flush, as there is no newline
78− Output_Overwrite xs -> liftIO $ do
79− mapM_ putStr $ "\r" : xs
80− hFlush stdout
81− Output_ClearLine -> liftIO $ do
82− -- Go to the first column and clear the whole line
83− putStr "\r"
84− clearLine
85− hFlush stdout
86− return $ isOverwrite output
87−
88−-- | Safely log a message to the console. This is what we should use.
89−putLog :: MonadLog Output m => Severity -> Text -> m ()
90−putLog sev = logMessage . Output_Log . WithSeverity sev
91−
92−-- | Like `putLog` but without the implicit newline added.
93−putLogRaw :: MonadLog Output m => Severity -> Text -> m ()
94−putLogRaw sev = logMessage . Output_LogRaw . WithSeverity sev
95−
96−-- | Like `putLog Error` but also abrupts the program.
97−failWith :: (MonadIO m, MonadLog Output m) => Text -> m a
98−failWith s = do
99− putLog Alert s
100− liftIO $ exitWith $ ExitFailure 2
101−
102−-- | Write log to stdout, with colors (unless `noColor`)
103−writeLogWith :: (MonadIO m, MonadMask m) => (Text -> IO ()) -> Bool -> WithSeverity Text -> m ()
104−writeLogWith f noColor (WithSeverity severity s) = case sevColor severity of
105− Just setColor -> bracket_ setColor reset $ liftIO (T.putStr s)
106− Nothing -> liftIO $ f s
107− where
108− -- We must reset *before* outputting the newline (if any), otherwise the cursor won't be reset.
109− reset = liftIO $ setSGR [Reset] >> f ""
110− sevColor sev = if
111− | noColor -> Nothing
112− | sev <= Error -> Just $ liftIO $ setSGR [SetColor Foreground Vivid Red]
113− | sev <= Warning -> Just $ liftIO $ setSGR [SetColor Foreground Vivid Yellow]
114− | sev >= Debug -> Just $ liftIO $ setSGR [SetColor Foreground Vivid White, SetConsoleIntensity FaintIntensity]
115− | otherwise -> Nothing
lib/command/src/Obelisk/CLI/Process.hsdeleted−94
@@ -1,94 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE LambdaCase #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−{-# LANGUAGE MultiWayIf #-}
5−{-# LANGUAGE OverloadedStrings #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TupleSections #-}
8−
9−-- | An extension of `System.Process` that integrates with logging (`Obelisk.CLI.Logging`)
10−-- and is thus spinner friendly.
11−module Obelisk.CLI.Process
12− ( readProcessAndLogStderr
13− , callProcessAndLogOutput
14− ) where
15−
16−import Control.Applicative (liftA2)
17−import Control.Monad (void, (<=<))
18−import Control.Monad.Catch (MonadMask)
19−import Control.Monad.IO.Class (liftIO)
20−import Control.Monad.Log (MonadLog)
21−import Control.Monad.Reader (MonadIO)
22−import qualified Data.ByteString.Char8 as BSC
23−import Data.Function (fix)
24−import Data.Monoid ((<>))
25−import qualified Data.Text as T
26−import Data.Text.Encoding (decodeUtf8)
27−import qualified Data.Text.IO as T
28−import System.Exit (ExitCode (..))
29−import System.IO (Handle)
30−import System.IO.Streams (InputStream, handleToInputStream)
31−import qualified System.IO.Streams as Streams
32−import System.IO.Streams.Concurrent (concurrentMerge)
33−import System.Process (CreateProcess, StdStream (CreatePipe), cmdspec, createProcess, std_err, std_out,
34− waitForProcess)
35−
36−import Obelisk.CLI.Logging (Output, Severity (..), failWith, putLog, putLogRaw)
37−
38−-- | Like `System.Process.readProcess` but logs the stderr instead of letting the external process inherit it.
39−readProcessAndLogStderr
40− :: (MonadIO m, MonadMask m, MonadLog Output m)
41− => Severity -> CreateProcess -> m String
42−readProcessAndLogStderr sev process = do
43− (out, _err) <- withProcess process $ \_out err -> do
44− streamToLog =<< liftIO (streamHandle sev err)
45− -- TODO: Why are we using Text here?
46− liftIO $ T.unpack . T.strip <$> T.hGetContents out
47−
48−-- | Like `System.Process.callProcess` but logs the combined output--stdout and stderr with the corresponding
49−-- severity.
50−--
51−-- Usually this function is called as `callProcessAndLogOutput (Debug, Error)`. However some processes
52−-- are known to spit out diagnostic or informative messages in stderr, in which case it is advisable to call
53−-- it with a non-Error severity for stderr, like `callProcessAndLogOutput (Debug, Debug)`.
54−callProcessAndLogOutput
55− :: (MonadIO m, MonadMask m, MonadLog Output m)
56− => (Severity, Severity) -> CreateProcess -> m ()
57−callProcessAndLogOutput (sev_out, sev_err) process = do
58− void $ withProcess process $ \out err -> do
59− stream <- liftIO $ do
60− uncurry combineStream =<< liftA2 (,) (streamHandle sev_out out) (streamHandle sev_err err)
61− streamToLog stream
62− where
63− combineStream s1 s2 = concurrentMerge [s1, s2]
64−
65−withProcess
66− :: (MonadIO m, MonadMask m, MonadLog Output m)
67− => CreateProcess -> (Handle -> Handle -> m ()) -> m (Handle, Handle)
68−withProcess process f = do
69− let procTitle = T.pack $ show $ cmdspec process
70− putLog Debug $ "Starting process: " <> procTitle
71− (_, Just out, Just err, p) <- liftIO $ createProcess $ process
72− { std_out = CreatePipe
73− , std_err = CreatePipe
74− }
75− f out err -- Pass the handles to the passed function
76− liftIO (waitForProcess p) >>= \case
77− ExitSuccess -> return ()
78− ExitFailure code -> do
79− -- Log an error. We also fail immediately; however we should probably let the caller control that.
80− failWith $ procTitle <> " failed with exit code: " <> T.pack (show code)
81− return (out, err) -- Return the handles
82−
83−-- Create an input stream from the file handle, associating each item with the given severity.
84−streamHandle :: Severity -> Handle -> IO (InputStream (Severity, BSC.ByteString))
85−streamHandle sev = Streams.map (sev,) <=< handleToInputStream
86−
87−-- | Read from an input stream and log its contents
88−streamToLog
89− :: (MonadIO m, MonadMask m, MonadLog Output m)
90− => InputStream (Severity, BSC.ByteString) -> m ()
91−streamToLog stream = fix $ \loop -> do
92− liftIO (Streams.read stream) >>= \case
93− Nothing -> return ()
94− Just (sev, line) -> putLogRaw sev (decodeUtf8 line) >> loop
lib/command/src/Obelisk/CLI/Spinner.hsdeleted−77
@@ -1,77 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE MultiParamTypeClasses #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−-- | Provides a simple CLI spinner that interoperates cleanly with the rest of the logging output.
5−module Obelisk.CLI.Spinner (withSpinner') where
6−
7−import Control.Concurrent (forkIO, killThread, threadDelay)
8−import Control.Monad (forM_, (>=>))
9−import Control.Monad.Catch (MonadMask, mask, onException)
10−import Control.Monad.IO.Class (liftIO)
11−import Control.Monad.Log (MonadLog, logMessage, runLoggingT)
12−import Control.Monad.Reader (MonadIO)
13−import Data.Text (Text)
14−import qualified Data.Text as T
15−import System.Console.ANSI (Color (Cyan, Green, Red), ColorIntensity (Vivid), ConsoleLayer (Foreground),
16− SGR (Reset, SetColor), setSGRCode)
17−
18−import Obelisk.CLI.Logging (LoggingConfig, Output (..), handleLog)
19−
20−-- | Run an action with a CLI spinner.
21−withSpinner'
22− :: (MonadIO m, MonadMask m, MonadLog Output m)
23− => LoggingConfig -> Text -> m a -> m a
24−withSpinner' conf s = bracket' run cleanup . const
25− where
26− -- TODO: Can we obviate passing LoggingConfig just to use forkIO?
27− run = liftIO $ forkIO $ flip runLoggingT (handleLog conf) $ do
28− runSpinner (coloredSpinner defaultSpinnerTheme) $ \c -> do
29− logMessage $ Output_Overwrite [c, " ", T.unpack s]
30− cleanup failed tid = do
31− liftIO $ killThread tid
32− logMessage Output_ClearLine
33− let mark = if failed
34− then withColor Red "✖"
35− else withColor Green "✔"
36− logMessage $ Output_Overwrite [mark, " ", T.unpack s, "\n"]
37−
38−-- | A spinner is simply an infinite list of strings that supplant each other in a delayed loop, creating the
39−-- animation of a "spinner".
40−type Spinner = [String]
41−
42−defaultSpinner :: SpinnerTheme -> Spinner
43−defaultSpinner = cycle
44−
45−coloredSpinner :: SpinnerTheme -> Spinner
46−coloredSpinner = defaultSpinner . fmap (withColor Cyan)
47−
48−-- | Run a spinner with a monadic function that defines how to represent the individual spinner characters.
49−runSpinner :: MonadIO m => Spinner -> (String -> m ()) -> m ()
50−runSpinner spinner f = forM_ spinner $ f >=> const delay
51− where
52− delay = liftIO $ threadDelay 100000 -- A shorter delay ensures that we update promptly.
53−
54−type SpinnerTheme = [String]
55−
56−-- Find more spinners at https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json
57−spinnerCircleHalves :: SpinnerTheme
58−spinnerCircleHalves = ["◐", "◓", "◑", "◒"]
59−
60−defaultSpinnerTheme :: SpinnerTheme
61−defaultSpinnerTheme = spinnerCircleHalves
62−
63−-- | Like `bracket` but the `release` function can know whether an exception was raised
64−bracket' :: MonadMask m => m a -> (Bool -> a -> m b) -> (a -> m c) -> m c
65−bracket' acquire release use = mask $ \unmasked -> do
66− resource <- acquire
67− result <- unmasked (use resource) `onException` release True resource
68− _ <- release False resource
69− return result
70−
71−withColor :: Color -> String -> String
72−withColor color s = mconcat
73− [ setSGRCode [SetColor Foreground Vivid color]
74− , s
75− , setSGRCode [Reset]
76− ]
77−
lib/command/src/Obelisk/Command.hs+329−177
@@ -3,38 +3,36 @@
3{-# LANGUAGE MultiParamTypeClasses #-}
3{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE StaticPointers #-}
6+{-# LANGUAGE TupleSections #-}
7−{-# LANGUAGE TypeApplications #-}
8module Obelisk.Command where
7module Obelisk.Command where
9
8
10−import Control.Concurrent (newMVar)
11−import Control.Monad
12−import Control.Monad.IO.Class (liftIO)
9+import Control.Monad.IO.Class (MonadIO, liftIO)
13−import Control.Monad.Reader (ask)
14−import qualified Data.Binary as Binary
15import Data.Bool (bool)
10import Data.Bool (bool)
16−import qualified Data.ByteString.Base16 as Base16
11+import Data.Foldable (for_)
17−import qualified Data.ByteString.Lazy as LBS
12+import Data.List (isInfixOf, isPrefixOf)
18−import Data.List
13+import Data.List.NonEmpty (NonEmpty, nonEmpty)
19−import Data.Maybe (catMaybes)
14+import qualified Data.List.NonEmpty as NonEmpty
20−import Data.Monoid
15+import qualified Data.Map as Map
21import qualified Data.Text as T
16import qualified Data.Text as T
22−import Data.Text.Encoding
17+import Data.Traversable (for)
23−import GHC.StaticPtr
24import Options.Applicative
18import Options.Applicative
19+import Options.Applicative.Help.Pretty (text, (<$$>))
20+import System.Directory
25import System.Environment
21import System.Environment
26import System.FilePath
22import System.FilePath
23+import qualified System.Info
27import System.IO (hIsTerminalDevice, stdout)
24import System.IO (hIsTerminalDevice, stdout)
28−import System.Posix.Process (executeFile)
25+import System.Process (rawSystem)
29
26
30import Obelisk.App
27import Obelisk.App
31−import Obelisk.CLI (LoggingConfig (LoggingConfig, _loggingConfig_level), Severity (..), cliDemo, failWith,
28+import Obelisk.CliApp
32− putLog)
33import Obelisk.Command.Deploy
29import Obelisk.Command.Deploy
34import Obelisk.Command.Project
30import Obelisk.Command.Project
35−import Obelisk.Command.Repl
36import Obelisk.Command.Run
31import Obelisk.Command.Run
37import Obelisk.Command.Thunk
32import Obelisk.Command.Thunk
33+import qualified Obelisk.Command.VmBuilder as VmBuilder
34+import qualified Obelisk.Command.Preprocessor as Preprocessor
35+
38
36
39data Args = Args
37data Args = Args
40 { _args_noHandOffPassed :: Bool
38 { _args_noHandOffPassed :: Bool
@@ -46,8 +44,12 @@ data Args = Args
46 }
44 }
47 deriving Show
45 deriving Show
48
46
47+newtype ArgsConfig = ArgsConfig
48+ { _argsConfig_enableVmBuilderByDefault :: Bool
49+ }
50+
49−args :: Parser Args
51+args :: ArgsConfig -> Parser Args
50−args = Args <$> noHandoff <*> verbose <*> obCommand
52+args cfg = Args <$> noHandoff <*> verbose <*> obCommand cfg
51
53
52noHandoff :: Parser Bool
54noHandoff :: Parser Bool
53noHandoff = flag False True $ mconcat
55noHandoff = flag False True $ mconcat
@@ -59,11 +61,12 @@ noHandoff = flag False True $ mconcat
59verbose :: Parser Bool
61verbose :: Parser Bool
60verbose = flag False True $ mconcat
62verbose = flag False True $ mconcat
61 [ long "verbose"
63 [ long "verbose"
64+ , short 'v'
62 , help "Be more verbose"
65 , help "Be more verbose"
63 ]
66 ]
64
67
65−argsInfo :: ParserInfo Args
68+argsInfo :: ArgsConfig -> ParserInfo Args
66−argsInfo = info (args <**> helper) $ mconcat
69+argsInfo cfg = info (args cfg <**> helper) $ mconcat
67 [ fullDesc
70 [ fullDesc
68 , progDesc "Manage Obelisk projects"
71 , progDesc "Manage Obelisk projects"
69 ]
72 ]
@@ -71,174 +74,289 @@ argsInfo = info (args <**> helper) $ mconcat
71initSource :: Parser InitSource
74initSource :: Parser InitSource
72initSource = foldl1 (<|>)
75initSource = foldl1 (<|>)
73 [ pure InitSource_Default
76 [ pure InitSource_Default
74− , 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")
75− , InitSource_Symlink <$> strOption (long "symlink" <> 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")
76 ]
79 ]
77
80
81+initForce :: Parser Bool
82+initForce = switch (long "force" <> help "Allow ob init to overwrite files")
83+
78data ObCommand
84data ObCommand
79− = ObCommand_Init InitSource
85+ = ObCommand_Init InitSource Bool
80 | ObCommand_Deploy DeployCommand
86 | ObCommand_Deploy DeployCommand
81− | ObCommand_Run
87+ | ObCommand_Run [(FilePath, Interpret)]
88+ | ObCommand_Profile String [String]
82− | ObCommand_Thunk ThunkCommand
89+ | ObCommand_Thunk ThunkOption
83− | ObCommand_Repl FilePath
90+ | ObCommand_Repl [(FilePath, Interpret)]
84− | ObCommand_Watch FilePath
91+ | ObCommand_Watch [(FilePath, Interpret)]
92+ | ObCommand_Shell ShellOpts
93+ | ObCommand_Doc String [String] -- shell and list of packages
94+ | ObCommand_Hoogle String Int -- shell and port
85 | ObCommand_Internal ObInternal
95 | ObCommand_Internal ObInternal
86 deriving Show
96 deriving Show
87
97
88data ObInternal
98data ObInternal
89− = ObInternal_RunStaticIO StaticKey
99+ -- the preprocessor argument syntax is also handled outside
90− | ObInternal_CLIDemo
100+ -- optparse-applicative, but it shouldn't ever conflict with another syntax
101+ = ObInternal_ApplyPackages String String String [String]
102+ | ObInternal_ExportGhciConfig
103+ [(FilePath, Interpret)]
104+ Bool -- ^ Use relative paths
91 deriving Show
105 deriving Show
92
106
93−inNixShell' :: MonadObelisk m => StaticPtr (IO ()) -> m ()
107+obCommand :: ArgsConfig -> Parser ObCommand
94−inNixShell' p = withProjectRoot "." $ \root -> do
108+obCommand cfg = hsubparser
95− cmd <- liftIO $ unwords <$> mkCmd -- TODO: shell escape instead of unwords
109+ (mconcat
96− projectShell root False "ghc" cmd
110+ [ command "init" $ info (ObCommand_Init <$> initSource <*> initForce) $ progDesc "Initialize an Obelisk project"
111+ , command "deploy" $ info (ObCommand_Deploy <$> deployCommand cfg) $ progDesc "Prepare a deployment for an Obelisk project"
112+ , command "run" $ info (ObCommand_Run <$> interpretOpts) $ progDesc "Run current project in development mode"
113+ , command "profile" $ info (uncurry ObCommand_Profile <$> profileCommand) $ progDesc "Run current project with profiling enabled"
114+ , command "thunk" $ info (ObCommand_Thunk <$> thunkOption) $ progDesc "Manipulate thunk directories"
115+ , command "repl" $ info (ObCommand_Repl <$> interpretOpts) $ progDesc "Open an interactive interpreter"
116+ , command "watch" $ info (ObCommand_Watch <$> interpretOpts) $ progDesc "Watch current project for errors and warnings"
117+ , command "shell" $ info (ObCommand_Shell <$> shellOpts) $ progDesc "Enter a shell with project dependencies or run a command in such a shell. E.g. ob shell -- ghc-pkg list"
118+ , command "doc" $ info (ObCommand_Doc <$> shellFlags <*> packageNames) $
119+ progDesc "List paths to haddock documentation for specified packages"
120+ <> footerDoc (Just $
121+ text "Hint: To open the documentation you can pipe the output of this command like"
122+ <$$> text "ob doc reflex reflex-dom-core | xargs -n1 xdg-open")
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"
125+ ])
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+ ]
97 where
132 where
98− mkCmd = do
133+ useRelativePathsFlag = switch (long "use-relative-paths" <> help "Use relative paths")
99− obArgs <- getObArgs
134+
100− progName <- getExecutablePath
135+packageNames :: Parser [String]
101− return $ progName : catMaybes
136+packageNames = some (strArgument (metavar "PACKAGE-NAME..."))
102− [ Just "--no-handoff"
137+
103− , bool Nothing (Just "--verbose") $ _args_verbose obArgs
104− , Just "internal"
105− , Just "run-static-io"
106− , Just $ encodeStaticKey $ staticKey p
107− ]
108−
109−obCommand :: Parser ObCommand
110−obCommand = hsubparser
111− (mconcat
112− [ command "init" $ info (ObCommand_Init <$> initSource) $ progDesc "Initialize an Obelisk project"
113− , command "deploy" $ info (ObCommand_Deploy <$> deployCommand) $ progDesc "Prepare a deployment for an Obelisk project"
114− , command "run" $ info (pure ObCommand_Run) $ progDesc "Run current project in development mode"
115− , command "thunk" $ info (ObCommand_Thunk <$> thunkCommand) $ progDesc "Manipulate thunk directories"
116− , command "repl" $ info (ObCommand_Repl <$> strArgument (action "directory")) $ progDesc "Open an interactive interpreter"
117− , command "watch" $ info (ObCommand_Watch <$> strArgument (action "directory"))$ progDesc "Watch directory for changes and update interactive interpreter"
118− ])
119− <|> subparser
120− (mconcat
121− [ internal
122− , command "internal" (info (ObCommand_Internal <$> internalCommand) mempty)
123− ])
124−
125−deployCommand :: Parser DeployCommand
138+deployCommand :: ArgsConfig -> Parser DeployCommand
126−deployCommand = hsubparser $ mconcat
139+deployCommand cfg = hsubparser $ mconcat
127− [ command "init" $ info deployInitCommand $ progDesc "Initialize a deployment configuration directory"
140+ [ command "init" $ info (DeployCommand_Init <$> deployInitOpts) $ progDesc "Initialize a deployment configuration directory"
128− , command "push" $ info (pure DeployCommand_Push) mempty
141+ , command "push" $ info (DeployCommand_Push <$> remoteBuilderParser) mempty
142+ , command "test" $ info (DeployCommand_Test <$> platformP) $ progDesc "Test your obelisk project from a mobile platform."
129 , command "update" $ info (pure DeployCommand_Update) $ progDesc "Update the deployment's src thunk to latest"
143 , command "update" $ info (pure DeployCommand_Update) $ progDesc "Update the deployment's src thunk to latest"
130 ]
144 ]
131−
145+ where
132−deployInitCommand :: Parser DeployCommand
146+ platformP = hsubparser $ mconcat
133−deployInitCommand = fmap DeployCommand_Init $ DeployInitOpts
147+ [ command "android" $ info (pure (Android, [])) mempty
148+ , command "ios" $ info ((,) <$> pure IOS <*> fmap pure (strArgument (metavar "TEAMID" <> help "Your Team ID - found in the Apple developer portal"))) mempty
149+ ]
150+
151+ remoteBuilderParser :: Parser (Maybe RemoteBuilder)
152+ remoteBuilderParser =
153+ flag (if enabledByDefault then enabled else Nothing) enabled (mconcat
154+ [ long $ "enable-" <> flagBase
155+ , help $ "Enable " <> flagDesc <> (if enabledByDefault then " (default)" else "")
156+ ])
157+ <|> flag enabled Nothing (mconcat
158+ [ long $ "disable-" <> flagBase
159+ , help $ "Disable a " <> flagDesc <> (if not enabledByDefault then " (default)" else "")
160+ ])
161+ where
162+ enabledByDefault = _argsConfig_enableVmBuilderByDefault cfg
163+ enabled = Just RemoteBuilder_ObeliskVM
164+ flagBase = "vm-builder"
165+ flagDesc = "managed Linux virtual machine as a Nix remote builder (requires Docker)"
166+
167+
168+deployInitOpts :: Parser DeployInitOpts
169+deployInitOpts = DeployInitOpts
134− <$> strArgument (action "directory" <> metavar "DEPLOYDIR" <> help "Path to a directory that it will create")
170+ <$> strArgument (action "directory" <> metavar "DEPLOYDIR" <> help "Path to a directory where the deployment repository will be initialized")
135− <*> strOption (long "ssh-key" <> action "file" <> metavar "SSHKEY" <> help "Path to an ssh key that it will symlink to")
171+ <*> strOption (long "ssh-key" <> action "file" <> metavar "SSHKEY" <> help "Path to an SSH key that will be *copied* to the deployment repository")
136 <*> some (strOption (long "hostname" <> metavar "HOSTNAME" <> help "hostname of the deployment target"))
172 <*> some (strOption (long "hostname" <> metavar "HOSTNAME" <> help "hostname of the deployment target"))
137− <*> strOption (long "upstream" <> value "origin" <> metavar "REMOTE" <> help "git remote to use for the src thunk" <> showDefault)
173+ <*> strOption (long "route" <> metavar "PUBLICROUTE" <> help "Publicly accessible URL of your app")
174+ <*> strOption (long "admin-email" <> metavar "ADMINEMAIL" <> help "Email address where administrative alerts will be sent")
175+ <*> flag True False (long "disable-https" <> help "Disable automatic https configuration for the backend")
176+
177+type TeamID = String
178+data RemoteBuilder = RemoteBuilder_ObeliskVM
179+ deriving (Eq, Show)
138
180
139data DeployCommand
181data DeployCommand
140 = DeployCommand_Init DeployInitOpts
182 = DeployCommand_Init DeployInitOpts
141− | DeployCommand_Push
183+ | DeployCommand_Push (Maybe RemoteBuilder)
184+ | DeployCommand_Test (PlatformDeployment, [String])
142 | DeployCommand_Update
185 | DeployCommand_Update
143 deriving Show
186 deriving Show
144
187
145−data DeployInitOpts = DeployInitOpts
188+profileCommand :: Parser (String, [String])
146− { _deployInitOpts_ouputDir :: FilePath
189+profileCommand = (,)
147− , _deployInitOpts_sshKey :: FilePath
190+ <$> strOption
148− , _deployInitOpts_hostname :: [String]
191+ ( long "output"
149− , _deployInitOpts_remote :: String
192+ <> short 'o'
150− }
193+ <> help "Base output to use for profiling output. Suffixes are added to this based on the profiling type. Defaults to a timestamped path in the profile/ directory in the project's root."
194+ <> metavar "PATH"
195+ <> value "profile/%Y-%m-%dT%H:%M:%S"
196+ <> showDefault
197+ )
198+ <*> (words <$> strOption
199+ ( long "rts-flags"
200+ <> help "RTS Flags to pass to the executable."
201+ <> value "-p -hc"
202+ <> metavar "FLAGS"
203+ <> showDefault
204+ ))
205+
206+thunkConfig :: Parser ThunkConfig
207+thunkConfig = ThunkConfig
208+ <$>
209+ ( flag' (Just True) (long "private" <> help "Mark thunks as pointing to a private repository")
210+ <|> flag' (Just False) (long "public" <> help "Mark thunks as pointing to a public repository")
211+ <|> pure Nothing
212+ )
213+
214+thunkUpdateConfig :: Parser ThunkUpdateConfig
215+thunkUpdateConfig = ThunkUpdateConfig
216+ <$> optional (strOption (long "branch" <> metavar "BRANCH" <> help "Use the given branch when looking for the latest revision"))
217+ <*> thunkConfig
218+
219+thunkPackConfig :: Parser ThunkPackConfig
220+thunkPackConfig = ThunkPackConfig
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.")
222+ <*> thunkConfig
223+
224+data ThunkOption = ThunkOption
225+ { _thunkOption_thunks :: NonEmpty FilePath
226+ , _thunkOption_command :: ThunkCommand
151− deriving Show
227+ } deriving Show
152
228
153−internalCommand :: Parser ObInternal
229+data ThunkCommand
154−internalCommand = subparser $ mconcat
230+ = ThunkCommand_Update ThunkUpdateConfig
155− [ command "run-static-io" $ info (ObInternal_RunStaticIO <$> argument (eitherReader decodeStaticKey) (action "static-key")) mempty
231+ | ThunkCommand_Unpack
156− , command "clidemo" $ info (pure ObInternal_CLIDemo) mempty
232+ | ThunkCommand_Pack ThunkPackConfig
157− ]
233+ deriving Show
158
234
159−--TODO: Result should provide normalised path and also original user input for error reporting.
235+thunkOption :: Parser ThunkOption
160−thunkDirectoryParser :: Parser FilePath
236+thunkOption = hsubparser $ mconcat
161−thunkDirectoryParser = fmap (dropTrailingPathSeparator . normalise) . strArgument $ mconcat
237+ [ command "update" $ info (thunkOptionWith $ ThunkCommand_Update <$> thunkUpdateConfig) $ progDesc "Update packed thunk to latest revision available on the tracked branch"
162− [ action "directory"
238+ , command "unpack" $ info (thunkOptionWith $ pure ThunkCommand_Unpack) $ progDesc "Unpack thunk into git checkout of revision it points to"
163− , metavar "THUNKDIR"
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"
164− , help "Path to directory containing thunk data"
165 ]
240 ]
166−
241+ where
167−data ThunkPackOpts = ThunkPackOpts
242+ thunkOptionWith f = ThunkOption
168− { _thunkPackOpts_directory :: FilePath
243+ <$> ((NonEmpty.:|)
169− , _thunkPackOpts_upstream :: String
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
249+
250+data ShellOpts
251+ = ShellOpts
252+ { _shellOpts_shell :: String
253+ , _shellOpts_interpretPaths :: [(FilePath, Interpret)]
254+ , _shellOpts_command :: Maybe String
170− }
255+ }
171 deriving Show
256 deriving Show
172
257
173−data ThunkCommand
258+shellFlags :: Parser String
174− = ThunkCommand_Update [FilePath]
259+shellFlags =
175− | ThunkCommand_Unpack [FilePath]
260+ flag' "ghc" (long "ghc" <> help "Enter a shell environment having ghc (default)")
176− | ThunkCommand_Pack [ThunkPackOpts]
261+ <|> flag "ghc" "ghcjs" (long "ghcjs" <> help "Enter a shell having ghcjs rather than ghc")
177− deriving Show
262+ <|> strOption (short 'A' <> long "argument" <> metavar "NIXARG" <> help "Use the environment specified by the given nix argument of `shells'")
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"
178
283
179−thunkPackOpts :: Parser ThunkPackOpts
284+shellOpts :: Parser ShellOpts
180−thunkPackOpts = (ThunkPackOpts <$> thunkDirectoryParser <*>) . strOption $ mconcat
285+shellOpts = ShellOpts
181− [ long "upstream"
286+ <$> shellFlags
182− , value "origin"
287+ <*> interpretOpts
183− , metavar "REMOTE"
288+ -- This funny construction is used to support optparse-applicative's @--@ parsing.
184− , help "Git remote that packed thunk will point to"
289+ -- All arguments after @--@ are left unparsed and instead provided to the last positional parser
185− , showDefault
290+ -- which must therefore be 'many' in order to consume the rest of the input.
186− ]
291+ <*> ((\xs -> if null xs then Nothing else Just $ unwords xs) <$> many (strArgument (metavar "COMMAND")))
187
292
188−thunkCommand :: Parser ThunkCommand
293+portOpt :: Int -> Parser Int
189−thunkCommand = hsubparser $ mconcat
294+portOpt dfault = option auto (long "port" <> short 'p' <> help "Port number for server" <> showDefault <> value dfault <> metavar "INT")
190− [ command "update" $ info (ThunkCommand_Update <$> some thunkDirectoryParser) $ progDesc "Update thunk to latest revision available"
191− , command "unpack" $ info (ThunkCommand_Unpack <$> some thunkDirectoryParser) $ progDesc "Unpack thunk into git checkout of revision it points to"
192− , command "pack" $ info (ThunkCommand_Pack <$> some thunkPackOpts) $ progDesc "Pack git checkout into thunk that points at given upstream"
193− ]
194
295
195parserPrefs :: ParserPrefs
296parserPrefs :: ParserPrefs
196parserPrefs = defaultPrefs
297parserPrefs = defaultPrefs
197 { prefShowHelpOnEmpty = True
298 { prefShowHelpOnEmpty = True
198 }
299 }
199
300
200−-- | Are we on a terminal with active user interaction?
301+-- | Create an Obelisk config for the current process.
201−isInteractiveTerm :: IO Bool
202−isInteractiveTerm = do
203− isTerm <- hIsTerminalDevice stdout
204− -- Running in bash/fish/zsh completion
205− inShellCompletion <- liftIO $ isInfixOf "completion" . unwords <$> getArgs
206− return $ isTerm && not inShellCompletion
207−
208mkObeliskConfig :: IO Obelisk
302mkObeliskConfig :: IO Obelisk
209mkObeliskConfig = do
303mkObeliskConfig = do
210− logLevel <- getLogLevel <$> getObArgs
304+ cliArgs <- getArgs
305+ -- This function should not use argument parser (full argument parsing happens post handoff)
306+ -- TODO: See if we can use the argument parser with a subset of the parsers to get logging level out.
307+ let logLevel = toLogLevel $ any (`elem` ["-v", "--verbose"]) cliArgs
211 notInteractive <- not <$> isInteractiveTerm
308 notInteractive <- not <$> isInteractiveTerm
212− loggingConfig <- LoggingConfig logLevel notInteractive <$> newMVar False
309+ cliConf <- newCliConfig logLevel notInteractive notInteractive $ \case
310+ ObeliskError_ProcessError (ProcessFailure p code) ann ->
311+ ( "Process exited with code " <> T.pack (show code) <> "; " <> reconstructCommand p
312+ <> maybe "" ("\n" <>) ann
313+ , 2
314+ )
315+ ObeliskError_Unstructured msg -> (msg, 2)
316+
213− return $ Obelisk notInteractive loggingConfig
317+ return $ Obelisk cliConf
214 where
318 where
215− getLogLevel = bool Notice Debug . _args_verbose
319+ toLogLevel = bool Notice Debug
216−
320+ isInteractiveTerm = do
217−getObArgs :: IO Args
321+ isTerm <- hIsTerminalDevice stdout
218−getObArgs = getArgs >>= handleParseResult . execParserPure parserPrefs argsInfo
322+ -- Running in bash/fish/zsh completion
323+ inShellCompletion <- liftIO $ isInfixOf "completion" . unwords <$> getArgs
324+
325+ -- Respect the user’s TERM environment variable. Dumb terminals
326+ -- like Eshell cannot handle lots of control sequences that the
327+ -- spinner uses.
328+ termEnv <- lookupEnv "TERM"
329+ let isDumb = termEnv == Just "dumb"
330+
331+ return $ isTerm && not inShellCompletion && not isDumb
332+
333+-- | For use from development obelisk repls
334+--
335+-- Example:
336+-- > runCommand $ someFuncInMonadObelisk ...
337+runCommand :: ObeliskT IO a -> IO a
338+runCommand f = flip runObelisk f =<< mkObeliskConfig
219
339
220main :: IO ()
340main :: IO ()
221−main = mkObeliskConfig >>= (`runObelisk` ObeliskT main')
341+main = runCommand . main' =<< getArgsConfig
222
342
223−main' :: MonadObelisk m => m ()
343+main' :: MonadObelisk m => ArgsConfig -> m ()
224−main' = do
344+main' argsCfg = do
225− c <- ask
226 obPath <- liftIO getExecutablePath
345 obPath <- liftIO getExecutablePath
227− obArgs <- liftIO getObArgs
346+ myArgs <- liftIO getArgs
347+ logLevel <- getLogLevel
228 putLog Debug $ T.pack $ unwords
348 putLog Debug $ T.pack $ unwords
229 [ "Starting Obelisk <" <> obPath <> ">"
349 [ "Starting Obelisk <" <> obPath <> ">"
230− , "args=" <> show obArgs
350+ , "args=" <> show myArgs
231− , "noSpinner=" <> show (_obelisk_noSpinner c)
232− , "logging-level=" <> show (_loggingConfig_level $ _obelisk_logging c)
351+ , "logging-level=" <> show logLevel
233 ]
352 ]
234
353
235 --TODO: We'd like to actually use the parser to determine whether to hand off,
354 --TODO: We'd like to actually use the parser to determine whether to hand off,
236 --but in the case where this implementation of 'ob' doesn't support all
355 --but in the case where this implementation of 'ob' doesn't support all
237 --arguments being passed along, this could fail. For now, we don't bother
356 --arguments being passed along, this could fail. For now, we don't bother
238 --with optparse-applicative until we've done the handoff.
357 --with optparse-applicative until we've done the handoff.
239− myArgs <- liftIO getArgs
240 let go as = do
358 let go as = do
241− args' <- liftIO $ handleParseResult (execParserPure parserPrefs argsInfo as)
359+ args' <- liftIO $ handleParseResult (execParserPure parserPrefs (argsInfo argsCfg) as)
242 case _args_noHandOffPassed args' of
360 case _args_noHandOffPassed args' of
243 False -> return ()
361 False -> return ()
244 True -> putLog Warning "--no-handoff should only be passed once and as the first argument; ignoring"
362 True -> putLog Warning "--no-handoff should only be passed once and as the first argument; ignoring"
@@ -248,9 +366,13 @@ main' = do
248 Just impl -> do
366 Just impl -> do
249 -- Invoke the real implementation, using --no-handoff to prevent infinite recursion
367 -- Invoke the real implementation, using --no-handoff to prevent infinite recursion
250 putLog Debug $ "Handing off to " <> T.pack impl
368 putLog Debug $ "Handing off to " <> T.pack impl
251− liftIO $ executeFile impl False ("--no-handoff" : myArgs) Nothing
369+ _ <- liftIO $ rawSystem impl ("--no-handoff" : myArgs)
370+ return ()
252 case myArgs of
371 case myArgs of
253 "--no-handoff" : as -> go as -- If we've been told not to hand off, don't hand off
372 "--no-handoff" : as -> go as -- If we've been told not to hand off, don't hand off
373+ origPath:inPath:outPath:preprocessorName:packagePaths
374+ | preprocessorName == preprocessorIdentifier && any (\c -> c == '.' || c == pathSeparator) origPath ->
375+ ob $ ObCommand_Internal $ ObInternal_ApplyPackages origPath inPath outPath packagePaths
254 a:as -- Otherwise bash completion would always hand-off even if the user isn't trying to
376 a:as -- Otherwise bash completion would always hand-off even if the user isn't trying to
255 | "--bash-completion" `isPrefixOf` a
377 | "--bash-completion" `isPrefixOf` a
256 && "--no-handoff" `elem` as -> go (a:as)
378 && "--no-handoff" `elem` as -> go (a:as)
@@ -259,45 +381,75 @@ main' = do
259
381
260ob :: MonadObelisk m => ObCommand -> m ()
382ob :: MonadObelisk m => ObCommand -> m ()
261ob = \case
383ob = \case
262− ObCommand_Init source -> initProject source
384+ ObCommand_Init source force -> initProject source force
263 ObCommand_Deploy dc -> case dc of
385 ObCommand_Deploy dc -> case dc of
264− DeployCommand_Init deployOpts -> withProjectRoot "." $ \root -> do
386+ DeployCommand_Init deployOpts -> withProjectRoot "." $ \root -> deployInit deployOpts root
265− thunkPtr <- readThunk root >>= \case
387+ DeployCommand_Push remoteBuilder -> do
266− Left err -> failWith $ T.pack $ "thunk pack: " <> show err
388+ deployPath <- liftIO $ canonicalizePath "."
267− Right (ThunkData_Packed ptr) -> return ptr
389+ deployPush deployPath $ case remoteBuilder of
268− Right (ThunkData_Checkout (Just ptr)) -> return ptr
390+ Nothing -> pure []
269− Right (ThunkData_Checkout Nothing) ->
391+ Just RemoteBuilder_ObeliskVM -> (:[]) <$> VmBuilder.getNixBuildersArg
270− getThunkPtr root (_deployInitOpts_remote deployOpts)
271− let deployDir = _deployInitOpts_ouputDir deployOpts
272− sshKeyPath = _deployInitOpts_sshKey deployOpts
273− hostname = _deployInitOpts_hostname deployOpts
274− deployInit thunkPtr (root </> "config") deployDir sshKeyPath hostname
275− DeployCommand_Push -> deployPush "."
276 DeployCommand_Update -> deployUpdate "."
392 DeployCommand_Update -> deployUpdate "."
277− ObCommand_Run -> inNixShell' $ static run
393+ DeployCommand_Test (platform, extraArgs) -> deployMobile platform extraArgs
278− -- inNixShell ($(mkClosure 'ghcidAction) ())
394+ ObCommand_Run interpretPathsList -> withInterpretPaths interpretPathsList run
395+ ObCommand_Profile basePath rtsFlags -> profile basePath rtsFlags
279− ObCommand_Thunk tc -> case tc of
396+ ObCommand_Thunk to -> case _thunkOption_command to of
280− ThunkCommand_Update thunks -> mapM_ updateThunkToLatest thunks
397+ ThunkCommand_Update config -> for_ thunks (updateThunkToLatest config)
281− ThunkCommand_Unpack thunks -> mapM_ unpackThunk thunks
398+ ThunkCommand_Unpack -> for_ thunks unpackThunk
282− ThunkCommand_Pack thunks -> forM_ thunks $ \(ThunkPackOpts dir upstream) -> packThunk dir upstream
399+ ThunkCommand_Pack config -> for_ thunks (packThunk config)
283− ObCommand_Repl component -> runRepl component
400+ where
284− ObCommand_Watch component -> watch component
401+ thunks = _thunkOption_thunks to
402+ ObCommand_Repl interpretPathsList -> withInterpretPaths interpretPathsList runRepl
403+ ObCommand_Watch interpretPathsList -> withInterpretPaths interpretPathsList runWatch
404+ ObCommand_Shell (ShellOpts shellAttr interpretPathsList cmd) -> withInterpretPaths interpretPathsList $ \root interpretPaths ->
405+ nixShellForInterpretPaths False shellAttr root interpretPaths cmd -- N.B. We do NOT bash escape here; we want to run the command as-is
406+ ObCommand_Doc shellAttr pkgs -> withInterpretPaths [] $ \root interpretPaths ->
407+ nixShellForInterpretPaths True shellAttr root interpretPaths $ Just $ haddockCommand pkgs
408+ ObCommand_Hoogle shell' port -> withProjectRoot "." $ \root -> do
409+ nixShellWithHoogle root True shell' $ Just $ "hoogle server -p" <> show port <> " --local"
285 ObCommand_Internal icmd -> case icmd of
410 ObCommand_Internal icmd -> case icmd of
286− ObInternal_RunStaticIO k -> liftIO (unsafeLookupStaticPtr @(IO ()) k) >>= \case
411+ ObInternal_ApplyPackages origPath inPath outPath packagePaths -> do
287− Nothing -> failWith $ "ObInternal_RunStaticIO: no such StaticKey: " <> T.pack (show k)
412+ liftIO $ Preprocessor.applyPackages origPath inPath outPath packagePaths
288− Just p -> liftIO $ deRefStaticPtr p
413+ ObInternal_ExportGhciConfig interpretPathsList useRelativePaths ->
289− ObInternal_CLIDemo -> cliDemo
414+ liftIO . putStrLn . unlines =<< withInterpretPaths interpretPathsList (exportGhciConfig useRelativePaths)
415+
416+-- | A helper for the common case that the command you want to run needs the project root and a resolved
417+-- set of interpret paths.
418+withInterpretPaths :: MonadObelisk m => [(FilePath, Interpret)] -> (FilePath -> PathTree Interpret -> m a) -> m a
419+withInterpretPaths interpretPathsList f = withProjectRoot "." $ \root -> do
420+ interpretPaths' <- resolveInterpretPaths $ (root, Interpret_Interpret) : interpretPathsList
421+ case interpretPaths' of
422+ Nothing -> failWith "No paths provided for finding packages"
423+ Just interpretPaths -> f root interpretPaths
424+
425+haddockCommand :: [String] -> String
426+haddockCommand pkgs = unwords
427+ [ "for p in"
428+ , unwords [getHaddockPath p ++ "/index.html" | p <- pkgs]
429+ , "; do echo $p; done"
430+ ]
431+ where getHaddockPath p = "$(ghc-pkg field " ++ p ++ " haddock-html --simple-output)"
290
432
291--TODO: Clean up all the magic strings throughout this codebase
433--TODO: Clean up all the magic strings throughout this codebase
292
434
293−encodeStaticKey :: StaticKey -> String
435+getArgsConfig :: IO ArgsConfig
294−encodeStaticKey = T.unpack . decodeUtf8 . Base16.encode . LBS.toStrict . Binary.encode
436+getArgsConfig = pure $ ArgsConfig { _argsConfig_enableVmBuilderByDefault = System.Info.os == "darwin" }
295−
437+
296−-- TODO: Use failWith in place of fail to be consistent.
438+-- | Resolves an ordered list of paths for use with @--interpret@/@--no-interpret@ by coalescing
297−decodeStaticKey :: String -> Either String StaticKey
439+-- paths into a non-ambiguous set of paths. Ambiguity is resolved by choosing right-most paths
298−decodeStaticKey s = case Base16.decode $ encodeUtf8 $ T.pack s of
440+-- over any preceeding identical paths.
299− (b, "") -> case Binary.decodeOrFail $ LBS.fromStrict b of
441+--
300− Right ("", _, a) -> pure a
442+-- For example: @a/b=ON a/b/c=OFF@ and @a/b/c=OFF a/b=ON@ are the same.
301− Right _ -> fail "decodeStaticKey: Binary.decodeOrFail didn't consume all input"
443+-- @a/b=ON a/b=OFF@ is reduced to @a/b=OFF@. We prefer right-biased choice to increase
302− Left (_, _, e) -> fail $ "decodeStaticKey: Binary.decodeOrFail failed: " <> show e
444+-- scriptability.
303− _ -> fail $ "decodeStaticKey: could not decode hex string: " <> show s
445+--
446+-- N.B. All the paths in the result will be canonicalized. It's impossible to determine path
447+-- overlap otherwise.
448+resolveInterpretPaths :: MonadIO m => [(FilePath, a)] -> m (Maybe (PathTree a))
449+resolveInterpretPaths ps = do
450+ trees <- liftIO $ for ps $ \(p, a) -> pathToTree a <$> canonicalizePath p
451+ pure $ foldr1 mergeTrees <$> nonEmpty trees
452+ where
453+ -- | Merge two 'PathTree's preferring leaves on the right in as much as they overlap with paths on the left.
454+ mergeTrees :: PathTree a -> PathTree a -> PathTree a
455+ 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+357−90
@@ -1,119 +1,386 @@
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 #-}
7+{-# LANGUAGE ViewPatterns #-}
5module Obelisk.Command.Deploy where
8module Obelisk.Command.Deploy where
6
9
7−import Control.Applicative
10+import Control.Applicative (liftA2)
11+import Control.Lens
8import Control.Monad
12import Control.Monad
9−import Control.Monad.Catch (finally)
13+import Control.Monad.Catch (Exception (displayException), MonadThrow, bracket, throwM, try)
10−import Control.Monad.IO.Class (liftIO)
14+import Control.Monad.IO.Class (MonadIO, liftIO)
11−import Data.Attoparsec.ByteString.Char8 as A
15+import Data.Aeson (FromJSON, ToJSON, encode, eitherDecode)
16+import Data.Bits
12−import qualified Data.ByteString.Char8 as BC8
17+import qualified Data.ByteString.Lazy as BSL
13import Data.Default
18import Data.Default
14−import Data.Maybe
19+import qualified Data.Map as Map
20+import qualified Data.Set as Set
15−import Data.Monoid
21+import Data.String.Here.Interpolated (i)
16import qualified Data.Text as T
22import qualified Data.Text as T
17import qualified Data.Text.IO as T
23import qualified Data.Text.IO as T
24+import GHC.Generics
18import System.Directory
25import System.Directory
19−import System.Exit (ExitCode (..))
20import System.FilePath
26import System.FilePath
21−import System.Process
27+import System.IO
28+import System.PosixCompat.Files
29+import Text.URI (URI)
30+import qualified Text.URI as URI
31+import Text.URI.Lens
22
32
23import Obelisk.App (MonadObelisk)
33import Obelisk.App (MonadObelisk)
34+import Obelisk.CliApp (
24−import Obelisk.CLI (Severity (..), callProcessAndLogOutput, failWith)
35+ Severity (..), callProcessAndLogOutput, failWith, proc, putLog,
36+ setCwd, setDelegateCtlc, setEnvOverride, withSpinner)
25import Obelisk.Command.Nix
37import Obelisk.Command.Nix
38+import Obelisk.Command.Project
26import Obelisk.Command.Thunk
39import Obelisk.Command.Thunk
27import Obelisk.Command.Utils
40import Obelisk.Command.Utils
28
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+
29−deployInit :: MonadObelisk m => ThunkPtr -> FilePath -> FilePath -> FilePath -> [String] -> m ()
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
61+
62+deployInit'
63+ :: MonadObelisk m
64+ => ThunkPtr
65+ -> DeployInitOpts
66+ -> m ()
30−deployInit thunkPtr configDir deployDir sshKeyPath hostnames = do
67+deployInit' thunkPtr (DeployInitOpts deployDir sshKeyPath hostnames route adminEmail enableHttps) = do
31− hasConfigDir <- liftIO $ do
32− createDirectoryIfMissing True deployDir
68+ liftIO $ createDirectoryIfMissing True deployDir
33− doesDirectoryExist configDir
69+ localKey <- withSpinner ("Preparing " <> T.pack deployDir) $ do
34− when hasConfigDir $ do
35− callProcessAndLogOutput (Notice, Error) $
36− cp
37− [ "-r"
38− , "-T"
39− , configDir
40− , deployDir </> "config"
41− ]
42− keyExists <- liftIO $ doesFileExist sshKeyPath
70+ localKey <- liftIO (doesFileExist sshKeyPath) >>= \case
43− when keyExists $ do
71+ False -> failWith $ T.pack $ "ob deploy init: file does not exist: " <> sshKeyPath
44− let localKey = deployDir </> "ssh_key"
72+ True -> pure $ deployDir </> "ssh_key"
45 callProcessAndLogOutput (Notice, Error) $
73 callProcessAndLogOutput (Notice, Error) $
46− cp [sshKeyPath, localKey]
74+ proc cp [sshKeyPath, localKey]
47− liftIO $ setPermissions localKey $ setOwnerWritable True $ setOwnerReadable True emptyPermissions
75+ liftIO $ setFileMode localKey $ ownerReadMode .|. ownerWriteMode
48− liftIO $ do
76+ return localKey
77+ withSpinner "Validating configuration" $ do
78+ void $ getHostFromRoute enableHttps route -- make sure that hostname is present
79+ forM_ hostnames $ \hostname -> do
80+ putLog Notice $ "Verifying host keys (" <> T.pack hostname <> ")"
81+ -- Note: we can't use a spinner here as this function will prompt the user.
82+ verifyHostKey (deployDir </> "backend_known_hosts") localKey hostname
83+ --IMPORTANT: We cannot copy config directory from the development project to
84+ --the deployment directory. If we do, it's very likely someone will
85+ --accidentally create a production deployment that uses development
86+ --credentials to connect to some resources. This could result in, e.g.,
87+ --production data backed up to a dev environment.
88+ withSpinner "Creating project configuration directories" $ liftIO $ do
89+ mapM_ (createDirectoryIfMissing True)
90+ [ deployDir </> "config" </> "backend"
91+ , deployDir </> "config" </> "common"
92+ , deployDir </> "config" </> "frontend"
93+ ]
94+
49− createThunk (deployDir </> "src") thunkPtr
95+ let srcDir = deployDir </> "src"
96+ withSpinner ("Creating source thunk (" <> T.pack (makeRelative deployDir srcDir) <> ")") $ do
97+ createThunk srcDir $ Right thunkPtr
98+ setupObeliskImpl deployDir
99+
100+ withSpinner "Writing deployment configuration" $ do
50− writeFile (deployDir </> "backend_hosts") $ unlines hostnames
101+ writeDeployConfig deployDir "backend_hosts" $ unlines hostnames
102+ writeDeployConfig deployDir "enable_https" $ show enableHttps
103+ writeDeployConfig deployDir "admin_email" adminEmail
104+ writeDeployConfig deployDir ("config" </> "common" </> "route") route
105+ writeDeployConfig deployDir "module.nix" $
106+ "(import " <> toNixPath (makeRelative deployDir srcDir) <> " {}).obelisk.serverModules.mkBaseEc2"
107+
108+ withSpinner ("Initializing git repository (" <> T.pack deployDir <> ")") $
51 initGit deployDir
109 initGit deployDir
52
110
111+setupObeliskImpl :: MonadIO m => FilePath -> m ()
112+setupObeliskImpl deployDir = liftIO $ do
113+ let
114+ implDir = toImplDir deployDir
115+ goBackUp = foldr (</>) "" $ (".." <$) $ splitPath $ makeRelative deployDir implDir
116+ createDirectoryIfMissing True implDir
117+ writeFile (implDir </> "default.nix") $ "(import " <> toNixPath (goBackUp </> "src") <> " {}).obelisk"
118+
53−deployPush :: MonadObelisk m => FilePath -> m ()
119+deployPush :: MonadObelisk m => FilePath -> m [String] -> m ()
54−deployPush deployPath = do
120+deployPush deployPath getNixBuilders = do
55− host <- liftIO $ fmap (T.unpack . T.strip) $ T.readFile $ deployPath </> "backend_hosts"
121+ hosts <- Set.fromList . filter (/= mempty) . lines <$> readDeployConfig deployPath "backend_hosts"
122+ adminEmail <- readDeployConfig deployPath "admin_email"
123+ enableHttps <- read <$> readDeployConfig deployPath "enable_https"
124+ route <- readDeployConfig deployPath $ "config" </> "common" </> "route"
125+ routeHost <- getHostFromRoute enableHttps route
56 let srcPath = deployPath </> "src"
126 let srcPath = deployPath </> "src"
57− build = do
58− buildOutput <- nixBuild $ def
59− { _nixBuildConfig_target = Target
60− { _target_path = srcPath
61− , _target_attr = Just "server"
62− }
63− , _nixBuildConfig_outLink = OutLink_None
64− , _nixBuildConfig_args = pure $ Arg "hostName" host
65− }
66− return $ listToMaybe $ lines buildOutput
67− result <- readThunk srcPath >>= \case
127+ thunkPtr <- readThunk srcPath >>= \case
68− Right (ThunkData_Packed _) ->
128+ Right (ThunkData_Packed _ ptr) -> return ptr
69− build
70− Right (ThunkData_Checkout _) -> do
129+ Right ThunkData_Checkout -> do
71− liftIO (checkGitCleanStatus srcPath) >>= \case
130+ checkGitCleanStatus srcPath True >>= \case
72− True -> do
131+ True -> packThunk (ThunkPackConfig False (ThunkConfig Nothing)) srcPath
73− result <- build
74− packThunk srcPath "origin" -- get upstream
75− return result
76− False -> do
77− _ <- failWith $ T.pack $ "ob deploy push: ensure " <> srcPath <> " has no pending changes and latest is pushed upstream."
132+ False -> failWith $ T.pack $ "ob deploy push: ensure " <> srcPath <> " has no pending changes and latest is pushed upstream."
78− return Nothing
133+ Left err -> failWith $ "ob deploy push: couldn't read src thunk: " <> T.pack (show err)
79− _ -> return Nothing
134+ let version = show . _thunkRev_commit $ _thunkPtr_rev thunkPtr
80− liftIO $ forM_ result $ \res -> do
135+ builders <- getNixBuilders
81− let deployAndSwitch outputPath sshAgentEnv = do
136+ let moduleFile = deployPath </> "module.nix"
82− callProcess' (Just sshAgentEnv) "ssh-add" [deployPath </> "ssh_key"]
137+ moduleFileExists <- liftIO $ doesFileExist moduleFile
138+ buildOutputByHost <- ifor (Map.fromSet (const ()) hosts) $ \host () -> do
139+ --TODO: What does it mean if this returns more or less than 1 line of output?
140+ [result] <- fmap lines $ nixCmd $ NixCmd_Build $ def
141+ & nixCmdConfig_target .~ Target
142+ { _target_path = Just srcPath
143+ , _target_attr = Just "server.system"
144+ , _target_expr = Nothing
145+ }
146+ & nixBuildConfig_outLink .~ OutLink_None
147+ & nixCmdConfig_args .~ (
148+ [ strArg "hostName" host
149+ , strArg "adminEmail" adminEmail
150+ , strArg "routeHost" routeHost
151+ , strArg "version" version
152+ , boolArg "enableHttps" enableHttps
153+ ] <> [rawArg "module" ("import " <> toNixPath moduleFile) | moduleFileExists ])
154+ & nixCmdConfig_builders .~ builders
155+ pure result
156+ let knownHostsPath = deployPath </> "backend_known_hosts"
157+ sshOpts = sshArgs knownHostsPath (deployPath </> "ssh_key") False
158+ withSpinner "Uploading closures" $ ifor_ buildOutputByHost $ \host outputPath -> do
159+ callProcess'
160+ (Map.fromList [("NIX_SSHOPTS", unwords sshOpts)])
83− callProcess' (Just sshAgentEnv) "nix-copy-closure" ["-v", "--to", "root@" <> host, "--gzip", outputPath]
161+ "nix-copy-closure" ["-v", "--to", "--use-substitutes", "root@" <> host, "--gzip", outputPath]
84− callProcess' (Just sshAgentEnv) "ssh"
162+ withSpinner "Uploading config" $ ifor_ buildOutputByHost $ \host _ -> do
163+ callProcessAndLogOutput (Notice, Warning) $
164+ proc rsyncPath
165+ [ "-e " <> sshPath <> " " <> unwords sshOpts
166+ , "-qarvz"
167+ , deployPath </> "config"
168+ , "root@" <> host <> ":/var/lib/backend"
169+ ]
170+ --TODO: Create GC root so we're sure our closure won't go away during this time period
171+ withSpinner "Switching to new configuration" $ ifor_ buildOutputByHost $ \host outputPath -> do
172+ callProcessAndLogOutput (Notice, Warning) $
173+ proc sshPath $ sshOpts <>
85− [ "root@" <> host
174+ [ "root@" <> host
86− , unwords
175+ , unwords
176+ -- Note that we don't want to $(staticWhich "nix-env") here, because this is executing on a remote machine
87− [ "nix-env -p /nix/var/nix/profiles/system --set " <> outputPath
177+ [ "nix-env -p /nix/var/nix/profiles/system --set " <> outputPath
88− , "&&"
178+ , "&&"
89− , "/nix/var/nix/profiles/system/bin/switch-to-configuration switch"
179+ , "/nix/var/nix/profiles/system/bin/switch-to-configuration switch"
90− ]
91 ]
180 ]
92− sshAgentEnv <- sshAgent
181+ ]
93− deployAndSwitch res sshAgentEnv `finally` callProcess' (Just sshAgentEnv) "ssh-agent" ["-k"]
94− isClean <- checkGitCleanStatus deployPath
182+ isClean <- checkGitCleanStatus deployPath True
95− when (not isClean) $ do
183+ when (not isClean) $ do
184+ withSpinner "Committing changes to Git" $ do
185+ callProcessAndLogOutput (Debug, Error) $
96− callProcess "git" ["-C", deployPath, "add", "--update"]
186+ gitProc deployPath ["add", "."]
187+ callProcessAndLogOutput (Debug, Error) $
97− callProcess "git" ["-C", deployPath, "commit", "-m", "New deployment"]
188+ gitProc deployPath ["commit", "-m", "New deployment"]
189+ putLog Notice $ "Deployed => " <> T.pack route
98 where
190 where
99− callProcess' e cmd args = do
191+ callProcess' envMap cmd args = do
100− let p = (proc cmd args) { delegate_ctlc = True, env = e }
192+ let p = setEnvOverride (envMap <>) $ setDelegateCtlc True $ proc cmd args
101− exit_code <- withCreateProcess p $ \_ _ _ ph -> waitForProcess ph
193+ callProcessAndLogOutput (Notice, Notice) p
102− case exit_code of
103− ExitSuccess -> return ()
104− ExitFailure r -> fail $ "callProcess'" <> "(exit: " <> show r <> ")"
105
194
106deployUpdate :: MonadObelisk m => FilePath -> m ()
195deployUpdate :: MonadObelisk m => FilePath -> m ()
107−deployUpdate deployPath = updateThunkToLatest $ deployPath </> "src"
196+deployUpdate deployPath = updateThunkToLatest (ThunkUpdateConfig Nothing (ThunkConfig Nothing)) (deployPath </> "src")
108
197
109−sshAgent :: IO [(String, String)]
198+data PlatformDeployment = Android | IOS
110−sshAgent = do
199+ deriving (Show, Eq)
111− output <- BC8.pack <$> readProcess "ssh-agent" ["-c"] mempty
200+
112− return $ fromMaybe mempty $ A.maybeResult $ A.parse (A.many' p) output
201+renderPlatformDeployment :: PlatformDeployment -> String
202+renderPlatformDeployment = \case
203+ Android -> "android"
204+ IOS -> "ios"
205+
206+deployMobile :: forall m. MonadObelisk m => PlatformDeployment -> [String] -> m ()
207+deployMobile platform mobileArgs = withProjectRoot "." $ \root -> do
208+ let srcDir = root </> "src"
209+ configDir = root </> "config"
210+ exists <- liftIO $ doesDirectoryExist srcDir
211+ unless exists $ failWith "ob test should be run inside of a deploy directory"
212+ (nixBuildTarget, extraArgs) <- case platform of
213+ Android -> do
214+ let keystorePath = root </> "android_keystore.jks"
215+ keytoolConfPath = root </> "android_keytool_config.json"
216+ hasKeystore <- liftIO $ doesFileExist keystorePath
217+ when (not hasKeystore) $ do
218+ -- TODO log instructions for how to modify the keystore
219+ putLog Notice $ "Creating keystore: " <> T.pack keystorePath
220+ putLog Notice "Enter a keystore password: "
221+ keyStorePassword <- liftIO $ withEcho False getLine
222+ putLog Notice "Re-enter the keystore password: "
223+ keyStorePassword' <- liftIO $ withEcho False getLine
224+ unless (keyStorePassword' == keyStorePassword) $ failWith "passwords do not match"
225+ let keyToolConf = KeytoolConfig
226+ { _keytoolConfig_keystore = keystorePath
227+ , _keytoolConfig_alias = "obelisk"
228+ , _keytoolConfig_storepass = keyStorePassword
229+ , _keytoolConfig_keypass = keyStorePassword
230+ }
231+ createKeystore root keyToolConf
232+ liftIO $ BSL.writeFile keytoolConfPath $ encode keyToolConf
233+ checkKeytoolConfExist <- liftIO $ doesFileExist keytoolConfPath
234+ unless checkKeytoolConfExist $ failWith "Missing android KeytoolConfig"
235+ keytoolConfContents <- liftIO $ BSL.readFile keytoolConfPath
236+ keyArgs <- case eitherDecode keytoolConfContents :: Either String KeytoolConfig of
237+ Left err -> failWith $ T.pack err
238+ Right conf -> pure
239+ [ "--sign"
240+ , "--store-file", _keytoolConfig_keystore conf
241+ , "--store-password", _keytoolConfig_storepass conf
242+ , "--key-alias", _keytoolConfig_alias conf
243+ , "--key-password", _keytoolConfig_keypass conf
244+ ]
245+ let expr = mconcat
246+ [ "with (import ", toNixPath srcDir, " {});"
247+ , "android.frontend.override (drv: {"
248+ , "isRelease = true;"
249+ , "staticSrc = (passthru.__androidWithConfig ", configDir, ").frontend.staticSrc;"
250+ , "assets = (passthru.__androidWithConfig ", configDir, ").frontend.assets;"
251+ , "})"
252+ ]
253+ return (Target
254+ { _target_path = Nothing
255+ , _target_attr = Nothing
256+ , _target_expr = Just expr
257+ }, keyArgs)
258+ IOS -> do
259+ let expr = mconcat
260+ [ "with (import ", toNixPath srcDir, " {});"
261+ , "ios.frontend.override (_: { staticSrc = (passthru.__iosWithConfig ", toNixPath configDir, ").frontend.staticSrc; })"
262+ ]
263+ return (Target
264+ { _target_path = Nothing
265+ , _target_attr = Nothing
266+ , _target_expr = Just expr
267+ }, [])
268+ result <- nixCmd $ NixCmd_Build $ def
269+ & nixBuildConfig_outLink .~ OutLink_None
270+ & nixCmdConfig_target .~ nixBuildTarget
271+ let mobileArtifact = case platform of
272+ IOS -> "iOS App"
273+ Android -> "Android APK"
274+ putLog Notice $ T.pack $ unwords ["Your recently built", mobileArtifact, "can be found at the following path:", show result]
275+ callProcessAndLogOutput (Notice, Error) $ proc (result </> "bin" </> "deploy") (mobileArgs ++ extraArgs)
113 where
276 where
114− p = do
277+ withEcho showEcho f = bracket
115− key <- A.string "setenv" >> A.skipSpace >> A.takeWhile (not . isSpace)
278+ (do
116− val <- A.skipSpace >> A.takeWhile (/= ';')
279+ prevEcho <- hGetEcho stdin
117− _ <- A.string ";" >> A.endOfLine <|> void (A.string ";")
280+ hSetEcho stdin showEcho
118− return (BC8.unpack key, BC8.unpack val)
281+ pure prevEcho
282+ )
283+ (hSetEcho stdin)
284+ (const f)
285+
286+data KeytoolConfig = KeytoolConfig
287+ { _keytoolConfig_keystore :: FilePath
288+ , _keytoolConfig_alias :: String
289+ , _keytoolConfig_storepass :: String
290+ , _keytoolConfig_keypass :: String
291+ } deriving (Show, Generic)
292+
293+instance FromJSON KeytoolConfig
294+instance ToJSON KeytoolConfig
295+
296+createKeystore :: MonadObelisk m => FilePath -> KeytoolConfig -> m ()
297+createKeystore root config =
298+ callProcessAndLogOutput (Notice, Notice) $ setCwd (Just root) $ proc jreKeyToolPath
299+ [ "-genkeypair", "-noprompt"
300+ , "-keystore", _keytoolConfig_keystore config
301+ , "-keyalg", "RSA", "-keysize", "2048"
302+ , "-validity", "1000000"
303+ , "-storepass", _keytoolConfig_storepass config
304+ , "-alias", _keytoolConfig_alias config
305+ , "-keypass", _keytoolConfig_keypass config
306+ ]
307+
308+-- | Simplified deployment configuration mechanism. At one point we may revisit this.
309+writeDeployConfig :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
310+writeDeployConfig deployDir fname = liftIO . writeFile (deployDir </> fname)
311+
312+readDeployConfig :: MonadObelisk m => FilePath -> FilePath -> m String
313+readDeployConfig deployDir fname = liftIO $ do
314+ fmap (T.unpack . T.strip) $ T.readFile $ deployDir </> fname
315+
316+verifyHostKey :: MonadObelisk m => FilePath -> FilePath -> String -> m ()
317+verifyHostKey knownHostsPath keyPath hostName =
318+ callProcessAndLogOutput (Notice, Warning) $ proc sshPath $
319+ sshArgs knownHostsPath keyPath True <>
320+ [ "root@" <> hostName
321+ , "-o", "NumberOfPasswordPrompts=0"
322+ , "exit"
323+ ]
324+
325+sshArgs :: FilePath -> FilePath -> Bool -> [String]
326+sshArgs knownHostsPath keyPath askHostKeyCheck =
327+ [ "-o", "UserKnownHostsFile=" <> knownHostsPath
328+ , "-o", "StrictHostKeyChecking=" <> if askHostKeyCheck then "ask" else "yes"
329+ , "-i", keyPath
330+ ]
331+
332+-- common/route validation
333+-- TODO: move these to executable-config once the typed-config stuff is done.
334+
335+data InvalidRoute
336+ = InvalidRoute_NotHttps URI
337+ | InvalidRoute_MissingScheme URI
338+ | InvalidRoute_MissingHost URI
339+ | InvalidRoute_HasPort URI
340+ | InvalidRoute_HasPath URI
341+ deriving Show
342+
343+instance Exception InvalidRoute where
344+ displayException = \case
345+ InvalidRoute_MissingScheme uri -> route uri "must have an URI scheme"
346+ InvalidRoute_NotHttps uri -> route uri "must be HTTPS"
347+ InvalidRoute_MissingHost uri -> route uri "must contain a hostname"
348+ InvalidRoute_HasPort uri -> route uri "cannot specify port"
349+ InvalidRoute_HasPath uri -> route uri "cannot contain path"
350+ where
351+ route uri err = T.unpack $ "Route (" <> URI.render uri <> ") " <> err
352+
353+-- | Get the hostname from a https route
354+--
355+-- Fail if the route is invalid (i.e, no host present or scheme is not https)
356+getHostFromRoute
357+ :: MonadObelisk m
358+ => Bool -- ^ Ensure https?
359+ -> String
360+ -> m String
361+getHostFromRoute mustBeHttps route = do
362+ result :: Either InvalidRoute String <- try $ do
363+ validateCommonRouteAndGetHost mustBeHttps =<< URI.mkURI (T.strip $ T.pack route)
364+ either (failWith . T.pack . displayException) pure result
119
365
366+validateCommonRouteAndGetHost
367+ :: (MonadThrow m, MonadObelisk m)
368+ => Bool -- ^ Ensure https?
369+ -> URI
370+ -> m String
371+validateCommonRouteAndGetHost mustBeHttps uri = do
372+ case uri ^? uriScheme of
373+ Just (Just (URI.unRText -> s)) -> case (mustBeHttps, s) of
374+ (False, _) -> pure ()
375+ (True, "https") -> pure ()
376+ _ -> throwM $ InvalidRoute_NotHttps uri
377+ _ -> throwM $ InvalidRoute_MissingScheme uri
378+ case uri ^. uriPath of
379+ [] -> pure ()
380+ _path -> throwM $ InvalidRoute_HasPath uri
381+ case uri ^? uriAuthority . _Right . authPort of
382+ Just (Just _port) -> throwM $ InvalidRoute_HasPort uri
383+ _ -> pure ()
384+ case uri ^? uriAuthority . _Right . authHost of
385+ Nothing -> throwM $ InvalidRoute_MissingHost uri
386+ Just sslHost -> return $ T.unpack $ URI.unRText sslHost
lib/command/src/Obelisk/Command/Nix.hs+192−39
@@ -1,71 +1,224 @@
1+{-# LANGUAGE AllowAmbiguousTypes #-}
2+{-# LANGUAGE ConstraintKinds #-}
1{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE LambdaCase #-}
2{-# LANGUAGE MultiParamTypeClasses #-}
5{-# LANGUAGE MultiParamTypeClasses #-}
3{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
7+{-# LANGUAGE Rank2Types #-}
4{-# LANGUAGE ScopedTypeVariables #-}
8{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE TemplateHaskell #-}
10+{-# LANGUAGE TypeApplications #-}
5module Obelisk.Command.Nix
11module Obelisk.Command.Nix
6− ( nixBuild
12+ ( Arg (..)
7 , NixBuildConfig (..)
13 , NixBuildConfig (..)
8− , Target (..)
14+ , nixBuildConfig_common
15+ , nixBuildConfig_outLink
16+ , NixCmd (..)
17+ , nixCmdConfig_args
18+ , nixCmdConfig_builders
19+ , nixCmdConfig_target
20+ , NixCommonConfig (..)
21+ , NixInstantiateConfig (..)
22+ , nixInstantiateConfig_eval
23+ , NixShellConfig (..)
24+ , nixShellConfig_common
25+ , nixShellConfig_pure
26+ , nixShellConfig_run
9 , OutLink (..)
27 , OutLink (..)
10− , Arg (..)
28+ , Target (..)
29+ , target_attr
30+ , target_expr
31+ , target_path
32+
33+ , boolArg
34+ , nixCmd
35+ , nixCmdProc
36+ , nixCmdProc'
37+ , rawArg
38+ , runNixShellConfig
39+ , strArg
11 ) where
40 ) where
12
41
42+import Control.Monad (guard)
43+import Control.Lens
44+
45+import Data.Bool (bool)
13import Data.Default
46import Data.Default
47+import Data.List (intercalate)
48+import Data.Maybe
14import Data.Monoid ((<>))
49import Data.Monoid ((<>))
15import qualified Data.Text as T
50import qualified Data.Text as T
16−import System.Process (proc)
17
51
18import Obelisk.App (MonadObelisk)
52import Obelisk.App (MonadObelisk)
19−import Obelisk.CLI (Severity (..), readProcessAndLogStderr, withSpinner)
53+import Obelisk.CliApp
20−
21−-- | Where to put nix-build output
22−data OutLink
23− = OutLink_Default
24− | OutLink_None
25− | OutLink_IndirectRoot FilePath
26−
27−instance Default OutLink where
28− def = OutLink_Default
29
54
30-- | What to build
55-- | What to build
31data Target = Target
56data Target = Target
32− { _target_path :: FilePath
57+ { _target_path :: Maybe FilePath
33 , _target_attr :: Maybe String
58 , _target_attr :: Maybe String
59+ , _target_expr :: Maybe String
34 }
60 }
61+makeClassy ''Target
35
62
36instance Default Target where
63instance Default Target where
37 def = Target
64 def = Target
38− { _target_path = "."
65+ { _target_path = Just "."
39 , _target_attr = Nothing
66 , _target_attr = Nothing
67+ , _target_expr = Nothing
40 }
68 }
41
69
42−data Arg = Arg
70+data Arg
43− { _arg_key :: String
71+ = Arg_Str String String
44− , _arg_value :: String
72+ | Arg_Expr String String
73+ deriving (Eq, Show)
74+
75+strArg :: String -> String -> Arg
76+strArg = Arg_Str
77+
78+rawArg :: String -> String -> Arg
79+rawArg = Arg_Expr
80+
81+boolArg :: String -> Bool -> Arg
82+boolArg k = Arg_Expr k . bool "false" "true"
83+
84+cliFromArgs :: [Arg] -> [String]
85+cliFromArgs = concatMap $ \case
86+ Arg_Str k v -> ["--argstr", k, v]
87+ Arg_Expr k v -> ["--arg", k, v]
88+
89+data NixCommonConfig = NixCommonConfig
90+ { _nixCmdConfig_target :: Target
91+ , _nixCmdConfig_args :: [Arg]
92+ , _nixCmdConfig_builders :: [String]
45 }
93 }
94+makeClassy ''NixCommonConfig
95+
96+instance Default NixCommonConfig where
97+ def = NixCommonConfig def mempty mempty
98+
99+runNixCommonConfig :: NixCommonConfig -> [String]
100+runNixCommonConfig cfg = mconcat [maybeToList path, attrArg, exprArg, args, buildersArg]
101+ where
102+ path = _target_path $ _nixCmdConfig_target cfg
103+ attr = _target_attr $ _nixCmdConfig_target cfg
104+ expr = _target_expr $ _nixCmdConfig_target cfg
105+ attrArg = case attr of
106+ Nothing -> []
107+ Just a -> ["-A", a]
108+ exprArg = case expr of
109+ Nothing -> []
110+ Just a -> ["-E", a]
111+ args = cliFromArgs $ _nixCmdConfig_args cfg
112+ buildersArg = case _nixCmdConfig_builders cfg of
113+ [] -> []
114+ builders -> ["--builders", intercalate ";" builders]
115+
116+-- | Where to put nix-build output
117+data OutLink
118+ = OutLink_Default
119+ | OutLink_None
120+ | OutLink_IndirectRoot FilePath
121+
122+instance Default OutLink where
123+ def = OutLink_Default
46
124
47data NixBuildConfig = NixBuildConfig
125data NixBuildConfig = NixBuildConfig
48− { _nixBuildConfig_target :: Target
126+ { _nixBuildConfig_common :: NixCommonConfig
49 , _nixBuildConfig_outLink :: OutLink
127 , _nixBuildConfig_outLink :: OutLink
50− , _nixBuildConfig_args :: [Arg]
51 }
128 }
129+makeLenses ''NixBuildConfig
130+
131+instance HasNixCommonConfig NixBuildConfig where
132+ nixCommonConfig = nixBuildConfig_common
52
133
53instance Default NixBuildConfig where
134instance Default NixBuildConfig where
54− def = NixBuildConfig def def mempty
135+ def = NixBuildConfig def def
55−
136+
56−nixBuild :: MonadObelisk m => NixBuildConfig -> m FilePath
137+runNixBuildConfig :: NixBuildConfig -> [String]
57−nixBuild cfg = do
138+runNixBuildConfig cfg = mconcat
58− let args = mconcat
139+ [ runNixCommonConfig $ cfg ^. nixCommonConfig
59− [ [_target_path $ _nixBuildConfig_target cfg]
60− , case _target_attr $ _nixBuildConfig_target cfg of
61− Nothing -> []
62− Just attr -> ["-A", attr]
63− , mconcat [["--argstr", k, v] | Arg k v <- _nixBuildConfig_args cfg]
64− , case _nixBuildConfig_outLink cfg of
140+ , case _nixBuildConfig_outLink cfg of
65− OutLink_Default -> []
141+ OutLink_Default -> []
66− OutLink_None -> ["--no-out-link"]
142+ OutLink_None -> ["--no-out-link"]
67− OutLink_IndirectRoot outLink -> ["--out-link", outLink]
143+ OutLink_IndirectRoot l -> ["--out-link", l]
68− ]
144+ ]
69− let msg = T.pack $ "Running nix-build (" <> _target_path (_nixBuildConfig_target cfg) <> ")"
145+
70− withSpinner msg $ do
146+data NixInstantiateConfig = NixInstantiateConfig
147+ { _nixInstantiateConfig_common :: NixCommonConfig
148+ , _nixInstantiateConfig_eval :: Bool
149+ }
150+makeLenses ''NixInstantiateConfig
151+
152+instance HasNixCommonConfig NixInstantiateConfig where
153+ nixCommonConfig = nixInstantiateConfig_common
154+
155+instance Default NixInstantiateConfig where
156+ def = NixInstantiateConfig def False
157+
158+runNixInstantiateConfig :: NixInstantiateConfig -> [String]
159+runNixInstantiateConfig cfg = mconcat
160+ [ runNixCommonConfig $ cfg ^. nixCommonConfig
161+ , "--eval" <$ guard (_nixInstantiateConfig_eval cfg)
162+ ]
163+
164+data NixShellConfig = NixShellConfig
165+ { _nixShellConfig_common :: NixCommonConfig
166+ , _nixShellConfig_pure :: Bool
167+ , _nixShellConfig_run :: Maybe String
168+ }
169+
170+makeLenses ''NixShellConfig
171+
172+instance HasNixCommonConfig NixShellConfig where
173+ nixCommonConfig = nixShellConfig_common
174+
175+instance Default NixShellConfig where
176+ def = NixShellConfig def False Nothing
177+
178+data NixCmd
179+ = NixCmd_Build NixBuildConfig
180+ | NixCmd_Instantiate NixInstantiateConfig
181+
182+instance Default NixCmd where
183+ def = NixCmd_Build def
184+
185+runNixShellConfig :: NixShellConfig -> [String]
186+runNixShellConfig cfg = mconcat
187+ [ runNixCommonConfig $ cfg ^. nixCommonConfig
188+ , [ "--pure" | cfg ^. nixShellConfig_pure ]
189+ ] ++ mconcat [
190+ ["--run", run] | run <- maybeToList $ cfg ^. nixShellConfig_run
191+ ]
192+
193+nixCmdProc :: NixCmd -> ProcessSpec
194+nixCmdProc = fst . nixCmdProc'
195+
196+nixCmdProc' :: NixCmd -> (ProcessSpec, T.Text)
197+nixCmdProc' cmdCfg = (proc (T.unpack cmd) options, cmd)
198+ where
199+ (cmd, options) = case cmdCfg of
200+ NixCmd_Build cfg' ->
201+ ( "nix-build"
202+ , runNixBuildConfig cfg'
203+ )
204+ NixCmd_Instantiate cfg' ->
205+ ( "nix-instantiate"
206+ , runNixInstantiateConfig cfg'
207+ )
208+
209+nixCmd :: MonadObelisk m => NixCmd -> m FilePath
210+nixCmd cmdCfg = withSpinner' (T.unwords $ "Running" : cmd : desc) (Just $ const $ T.unwords $ "Built" : desc) $ do
71− readProcessAndLogStderr Debug (proc "nix-build" args)
211+ output <- readProcessAndLogStderr Debug cmdProc
212+ -- Remove final newline that Nix appends
213+ Just (outPath, '\n') <- pure $ T.unsnoc output
214+ pure $ T.unpack outPath
215+ where
216+ (cmdProc, cmd) = nixCmdProc' cmdCfg
217+ commonCfg = case cmdCfg of
218+ NixCmd_Build cfg' -> cfg' ^. nixCommonConfig
219+ NixCmd_Instantiate cfg' -> cfg' ^. nixCommonConfig
220+ path = commonCfg ^. nixCmdConfig_target . target_path
221+ desc = concat $ catMaybes
222+ [ (\x -> ["on", T.pack x]) <$> path
223+ , (\a -> ["[" <> T.pack a <> "]"]) <$> (commonCfg ^. nixCmdConfig_target . target_attr)
224+ ]
lib/command/src/Obelisk/Command/Preprocessor.hsnew file+100
@@ -0,0 +1,100 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+
4+module Obelisk.Command.Preprocessor where
5+
6+import qualified Data.ByteString.Lazy as BL
7+import qualified Data.ByteString.Lazy.Builder as BU
8+import Data.Foldable (for_)
9+import Data.List (intersperse, isPrefixOf, sortOn)
10+import Data.Maybe (fromMaybe)
11+import qualified Data.Text.Lazy.Builder as TL
12+import qualified Data.Text.Lazy.Encoding as TL
13+import Distribution.Compiler (CompilerFlavor (..))
14+import Language.Haskell.Extension (Extension (..), Language(..))
15+import System.Directory (canonicalizePath)
16+import System.IO (IOMode (..), hPutStrLn, stderr, withFile)
17+import System.FilePath (hasTrailingPathSeparator, joinPath, splitPath)
18+
19+import Obelisk.Command.Run (CabalPackageInfo (..), parseCabalPackage')
20+
21+-- | 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+-- 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+-- 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+-- We assume all the remaining arguments passed in are paths to cabal or hpack package specifications.
28+-- Thus we must select among the packagePaths for the file we are going to parse.
29+applyPackages :: FilePath -> FilePath -> FilePath -> [FilePath] -> IO ()
30+applyPackages origPath inPath outPath packagePaths' = do
31+ origPathCanonical <- canonicalizePath origPath
32+ packagePaths <- traverse canonicalizePath packagePaths'
33+
34+ let
35+ takeDirs = takeWhile hasTrailingPathSeparator
36+ packageDirs = sortOn (negate . length . takeDirs) $ map splitPath packagePaths
37+ origDir = splitPath origPathCanonical
38+ matches = [ joinPath d | d <- packageDirs, takeDirs d `isPrefixOf` origDir ]
39+
40+ -- The first element of matches is going to be the deepest path to a package spec that contains
41+ -- our file as a subdirectory.
42+ packageInfo' <- case matches of
43+ [] -> do
44+ hPutStrLn stderr $ "Error: Unable to find cabal information for " <> origPath <> "; Skipping preprocessor."
45+ pure Nothing
46+ packagePath:_ -> parseCabalPackage' packagePath >>= \case
47+ Left err -> do
48+ hPutStrLn stderr $ "Error: Unable to parse cabal package " <> packagePath <> "; Skipping preprocessor on " <> origPath <> ". Error: " <> show err
49+ pure Nothing
50+ Right (Just (_, packageInfo)) -> pure $ Just packageInfo
51+ Right Nothing -> pure Nothing
52+
53+ writeOutput packageInfo' inPath outPath
54+
55+writeOutput :: Maybe CabalPackageInfo -> FilePath -> FilePath -> IO ()
56+writeOutput packageInfo' origPath outPath = withFile outPath WriteMode $ \hOut -> do
57+ for_ packageInfo' $ \packageInfo -> hPutTextBuilder hOut (generateHeader origPath packageInfo)
58+ BL.readFile origPath >>= BL.hPut hOut
59+ where
60+ hPutTextBuilder h = BU.hPutBuilder h . TL.encodeUtf8Builder . TL.toLazyText
61+
62+generateHeader :: FilePath -> CabalPackageInfo -> TL.Builder
63+generateHeader origPath packageInfo =
64+ hsExtensions <> ghcOptions <> lineNumberPragma origPath
65+ where
66+ hsExtensions =
67+ if null extList
68+ then mempty
69+ else pragma $ TL.fromText "LANGUAGE " <> mconcat (intersperse (TL.fromText ", ") extList)
70+ extList = addDefaultLanguage $ concatMap showExt $ _cabalPackageInfo_defaultExtensions packageInfo
71+ addDefaultLanguage =
72+ case _cabalPackageInfo_defaultLanguage packageInfo of
73+ Nothing -> id
74+ Just x -> case x of
75+ UnknownLanguage ext -> (TL.fromString ext :)
76+ ext -> (TL.fromString (show ext) :)
77+ showExt = \case
78+ EnableExtension ext -> [TL.fromString (show ext)]
79+ DisableExtension ext -> ["No" <> TL.fromString (show ext)]
80+ UnknownExtension ext -> [TL.fromString ext]
81+
82+ ghcOptions =
83+ if null optList
84+ then mempty
85+ else pragma $
86+ TL.fromText "OPTIONS_GHC " <> mconcat (intersperse (TL.fromText " ") (map TL.fromString optList))
87+ ghcOptList
88+ = filter (not . isPrefixOf "-O")
89+ $ fromMaybe []
90+ $ lookup GHC (_cabalPackageInfo_compilerOptions packageInfo)
91+ optList = _cabalPackageInfo_cppOptions packageInfo <> ghcOptList
92+
93+lineNumberPragma :: FilePath -> TL.Builder
94+lineNumberPragma origPath = pragma $ TL.fromText "LINE 1 " <> quoted '"' (TL.fromString origPath)
95+
96+pragma :: TL.Builder -> TL.Builder
97+pragma x = TL.fromText "{-# " <> x <> TL.fromText " #-}\n"
98+
99+quoted :: Char -> TL.Builder -> TL.Builder
100+quoted char x = TL.singleton char <> x <> TL.singleton char
lib/command/src/Obelisk/Command/Project.hs+236−80
@@ -3,35 +3,56 @@
3{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE OverloadedStrings #-}
4module Obelisk.Command.Project
4module Obelisk.Command.Project
5 ( InitSource (..)
5 ( InitSource (..)
6− , initProject
7 , findProjectObeliskCommand
6 , findProjectObeliskCommand
8 , findProjectRoot
7 , findProjectRoot
8+ , findProjectAssets
9+ , initProject
10+ , nixShellRunConfig
11+ , nixShellRunProc
12+ , nixShellWithHoogle
13+ , nixShellWithoutPkgs
14+ , obeliskDirName
15+ , toImplDir
16+ , toObeliskDir
9 , withProjectRoot
17 , withProjectRoot
10− , inProjectShell
18+ , bashEscape
11− , inImpureProjectShell
12− , projectShell
13 ) where
19 ) where
14
20
21+import Control.Concurrent.MVar (MVar, newMVar, withMVarMasked)
22+import Control.Lens ((.~), (?~), (<&>))
15import Control.Monad
23import Control.Monad
16import Control.Monad.IO.Class (liftIO)
24import Control.Monad.IO.Class (liftIO)
17import Control.Monad.State
25import Control.Monad.State
26+import qualified Data.Aeson as Json
27+import qualified Data.ByteString.UTF8 as BSU
18import Data.Bits
28import Data.Bits
29+import qualified Data.ByteString.Lazy as BSL
30+import Data.Default (def)
19−import Data.Function (on)
31+import Data.Function ((&), on)
20−import Data.Monoid
32+import Data.Map (Map)
33+import Data.Text (Text)
21import qualified Data.Text as T
34import qualified Data.Text as T
35+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
36+import Data.Traversable (for)
22import System.Directory
37import System.Directory
38+import System.Environment (lookupEnv)
23import System.FilePath
39import System.FilePath
24−import System.Posix (FileStatus, UserID, deviceID, fileID, fileMode, fileOwner, getFileStatus, getRealUserID)
40+import System.IO.Temp
41+import System.IO.Unsafe (unsafePerformIO)
25−import System.Posix.Files
42+import System.PosixCompat.Files
26−import System.Process (CreateProcess, createProcess_, cwd, proc, waitForProcess)
43+import System.PosixCompat.Types
44+import System.PosixCompat.User
45+import Text.ShellEscape (bash, bytes)
27
46
28import GitHub.Data.GitData (Branch)
47import GitHub.Data.GitData (Branch)
29import GitHub.Data.Name (Name)
48import GitHub.Data.Name (Name)
30
49
31import Obelisk.App (MonadObelisk)
50import Obelisk.App (MonadObelisk)
32−import Obelisk.CLI (Severity (..), callProcessAndLogOutput, failWith, putLog, withSpinner)
51+import Obelisk.CliApp
52+import Obelisk.Command.Nix
33import Obelisk.Command.Thunk
53import Obelisk.Command.Thunk
34−import Obelisk.Command.Utils (cp)
54+import Obelisk.Command.Utils (nixBuildExePath, nixExePath, toNixPath, cp, nixShellPath)
55+
35--TODO: Make this module resilient to random exceptions
56--TODO: Make this module resilient to random exceptions
36
57
37--TODO: Don't hardcode this
58--TODO: Don't hardcode this
@@ -45,42 +66,67 @@ obeliskSourceWithBranch branch = ThunkSource_GitHub $ GitHubSource
45 { _gitHubSource_owner = "obsidiansystems"
66 { _gitHubSource_owner = "obsidiansystems"
46 , _gitHubSource_repo = "obelisk"
67 , _gitHubSource_repo = "obelisk"
47 , _gitHubSource_branch = Just branch
68 , _gitHubSource_branch = Just branch
48− , _gitHubSource_private = True
69+ , _gitHubSource_private = False
49 }
70 }
50
71
51data InitSource
72data InitSource
52− = InitSource_Default
73+ = InitSource_Default
53− | InitSource_Branch (Name Branch)
74+ | InitSource_Branch (Name Branch)
54− | InitSource_Symlink FilePath
75+ | InitSource_Symlink FilePath
55− deriving Show
76+ deriving Show
77+
78+obeliskDirName :: FilePath
79+obeliskDirName = ".obelisk"
56
80
57-- | Path to obelisk directory in given path
81-- | Path to obelisk directory in given path
58toObeliskDir :: FilePath -> FilePath
82toObeliskDir :: FilePath -> FilePath
59−toObeliskDir p = p </> ".obelisk"
83+toObeliskDir p = p </> obeliskDirName
60
84
61-- | Path to impl file in given path
85-- | Path to impl file in given path
62−implFile :: FilePath -> FilePath
86+toImplDir :: FilePath -> FilePath
63−implFile p = toObeliskDir p </> "impl"
87+toImplDir p = toObeliskDir p </> "impl"
64
88
65-- | Create a new project rooted in the current directory
89-- | Create a new project rooted in the current directory
66−initProject :: MonadObelisk m => InitSource -> m ()
90+initProject :: MonadObelisk m => InitSource -> Bool -> m ()
67−initProject source = do
91+initProject source force = withSystemTempDirectory "ob-init" $ \tmpDir -> do
68− let implDir = implFile "."
92+ let implDir = toImplDir tmpDir
93+ obDir = toObeliskDir tmpDir
94+ liftIO (listDirectory ".") >>= \case
95+ [] -> pure ()
96+ _ | force -> putLog Warning "Initializing in non-empty directory"
97+ | otherwise -> failWith "ob init requires an empty directory. Use the flag --force to init anyway, potentially overwriting files."
98+ skeleton <- withSpinner "Setting up obelisk" $ do
69− liftIO $ createDirectory $ toObeliskDir "."
99+ liftIO $ createDirectory obDir
100+ -- Clone the git source and repack it with the init source obelisk
101+ -- The purpose of this is to ensure we use the correct thunk spec.
102+ let cloneAndRepack src = do
103+ putLog Debug $ "Cloning obelisk into " <> T.pack implDir <> " and repacking using itself"
104+ commit <- getLatestRev src
105+ gitCloneForThunkUnpack (thunkSourceToGitSource src) (_thunkRev_commit commit) implDir
106+ callHandoffOb implDir ["thunk", "pack", implDir]
70− case source of
107+ case source of
71− InitSource_Default -> liftIO $ createThunkWithLatest implDir obeliskSource
108+ InitSource_Default -> cloneAndRepack obeliskSource
72− InitSource_Branch branch -> liftIO $ createThunkWithLatest implDir $ obeliskSourceWithBranch branch
109+ InitSource_Branch branch -> cloneAndRepack $ obeliskSourceWithBranch branch
73− InitSource_Symlink path -> do
110+ InitSource_Symlink path -> do
74− let symlinkPath = if isAbsolute path
111+ let symlinkPath = if isAbsolute path
75− then path
112+ then path
76− else ".." </> path
113+ else ".." </> path
77− liftIO $ createSymbolicLink symlinkPath implDir
114+ liftIO $ createSymbolicLink symlinkPath implDir
78− _ <- nixBuildAttrWithCache implDir "command"
115+ _ <- nixBuildAttrWithCache implDir "command"
79− --TODO: We should probably handoff to the impl here
80− skeleton <- nixBuildAttrWithCache implDir "skeleton" --TODO: I don't think there's actually any reason to cache this
116+ skel <- nixBuildAttrWithCache implDir "skeleton" --TODO: I don't think there's actually any reason to cache this
117+
118+ callProcessAndLogOutput (Notice, Error) $
119+ proc cp
120+ [ "-r"
121+ , "--preserve=links"
122+ , obDir
123+ , toObeliskDir "."
124+ ]
125+ pure skel
126+
81 withSpinner "Copying project skeleton" $ do
127 withSpinner "Copying project skeleton" $ do
82 callProcessAndLogOutput (Notice, Error) $
128 callProcessAndLogOutput (Notice, Error) $
83− cp --TODO: Make this package depend on nix-prefetch-url properly
129+ proc cp
84 [ "-r"
130 [ "-r"
85 , "--no-preserve=mode"
131 , "--no-preserve=mode"
86 , "-T"
132 , "-T"
@@ -91,44 +137,89 @@ initProject source = do
91 let configDir = "config"
137 let configDir = "config"
92 createDirectoryIfMissing False configDir
138 createDirectoryIfMissing False configDir
93 mapM_ (createDirectoryIfMissing False . (configDir </>)) ["backend", "common", "frontend"]
139 mapM_ (createDirectoryIfMissing False . (configDir </>)) ["backend", "common", "frontend"]
140+ putLog Notice $ T.intercalate "\n"
141+ [ "An obelisk project has been successfully initialized. Next steps:"
142+ , " 'ob run': Start a development server"
143+ , " 'ob watch': Watch for changes without starting a server"
144+ , " 'ob repl': Load your project into GHCi"
145+ ]
146+
147+callHandoffOb
148+ :: MonadObelisk m
149+ => FilePath -- ^ Directory of the obelisk we want to handoff to
150+ -> [String] -- ^ Arguments to pass to ob
151+ -> m ()
152+callHandoffOb dir args = do
153+ obeliskCommandPkg <- nixCmd $ NixCmd_Build $ def
154+ & nixBuildConfig_outLink .~ OutLink_None
155+ & nixCmdConfig_target .~ Target
156+ { _target_path = Just dir
157+ , _target_attr = Just "command"
158+ , _target_expr = Nothing
159+ }
160+ let impl = obeliskCommandPkg </> "bin" </> "ob"
161+ -- Invoke the real implementation, using --no-handoff to prevent infinite recursion
162+ putLog Debug $ "Running '" <> T.pack (unwords args) <> "' with " <> T.pack impl
163+ callProcessAndLogOutput (Debug, Warning) (proc impl ("--no-handoff" : args))
94
164
95--TODO: Allow the user to ignore our security concerns
165--TODO: Allow the user to ignore our security concerns
96-- | Find the Obelisk implementation for the project at the given path
166-- | Find the Obelisk implementation for the project at the given path
97findProjectObeliskCommand :: MonadObelisk m => FilePath -> m (Maybe FilePath)
167findProjectObeliskCommand :: MonadObelisk m => FilePath -> m (Maybe FilePath)
98findProjectObeliskCommand target = do
168findProjectObeliskCommand target = do
99 myUid <- liftIO getRealUserID
169 myUid <- liftIO getRealUserID
170+ processUmask <- liftIO getUmask
100 targetStat <- liftIO $ getFileStatus target
171 targetStat <- liftIO $ getFileStatus target
101− (result, insecurePaths) <- flip runStateT [] $ walkToProjectRoot target targetStat myUid >>= \case
172+ (result, insecurePaths) <- flip runStateT [] $ walkToProjectRoot target targetStat processUmask myUid >>= \case
102 Nothing -> pure Nothing
173 Nothing -> pure Nothing
103− Just projectRoot -> liftIO (doesFileExist $ implFile projectRoot) >>= \case
174+ Just projectRoot -> liftIO (doesDirectoryExist $ toImplDir projectRoot) >>= \case
104 False -> do
175 False -> do
105 putLog Warning $ "Found obelisk directory in " <> T.pack projectRoot <> " but the implementation (impl) file is missing"
176 putLog Warning $ "Found obelisk directory in " <> T.pack projectRoot <> " but the implementation (impl) file is missing"
106 pure Nothing
177 pure Nothing
107 True -> do
178 True -> do
108− walkToImplDir projectRoot myUid -- For security check
179+ walkToImplDir projectRoot myUid processUmask -- For security check
109 return $ Just projectRoot
180 return $ Just projectRoot
110 case (result, insecurePaths) of
181 case (result, insecurePaths) of
111 (Just projDir, []) -> do
182 (Just projDir, []) -> do
112− obeliskCommandPkg <- nixBuildAttrWithCache (implFile projDir) "command"
183+ obeliskCommandPkg <- nixBuildAttrWithCache (toImplDir projDir) "command"
113 return $ Just $ obeliskCommandPkg </> "bin" </> "ob"
184 return $ Just $ obeliskCommandPkg </> "bin" </> "ob"
114 (Nothing, _) -> return Nothing
185 (Nothing, _) -> return Nothing
115 (Just projDir, _) -> do
186 (Just projDir, _) -> do
116 putLog Error $ T.unlines
187 putLog Error $ T.unlines
117 [ "Error: Found a project at " <> T.pack (normalise projDir) <> ", but had to traverse one or more insecure directories to get there:"
188 [ "Error: Found a project at " <> T.pack (normalise projDir) <> ", but had to traverse one or more insecure directories to get there:"
118 , T.unlines $ fmap (T.pack . normalise) insecurePaths
189 , T.unlines $ fmap (T.pack . normalise) insecurePaths
119− , "Please ensure that all of these directories are owned by you and are not writable by anyone else."
190+ , "Please ensure that all of these directories are owned by you, not world-writable, and no more group-writable than permitted by your umask."
120 ]
191 ]
121 return Nothing
192 return Nothing
122
193
194+-- | Get the umask for the Obelisk process.
195+--
196+-- Because of
197+-- http://man7.org/linux/man-pages/man2/umask.2.html#NOTES we have to set the
198+-- umask to read it. We are using 'withMVarMasked' to guarantee that setting and
199+-- reading isn't interrupted by any exception or interleaved with another thread.
200+getUmask :: IO FileMode
201+getUmask = withMVarMasked globalUmaskLock $ \() -> do
202+ initialMask <- setFileCreationMask safeUmask
203+ void (setFileCreationMask initialMask)
204+ pure initialMask
205+ where
206+ safeUmask :: FileMode
207+ safeUmask = CMode 0o22
208+
209+{-# NOINLINE globalUmaskLock #-}
210+globalUmaskLock :: MVar ()
211+globalUmaskLock = unsafePerformIO (newMVar ())
212+
123-- | Get the FilePath to the containing project directory, if there is one
213-- | Get the FilePath to the containing project directory, if there is one
124findProjectRoot :: MonadObelisk m => FilePath -> m (Maybe FilePath)
214findProjectRoot :: MonadObelisk m => FilePath -> m (Maybe FilePath)
125findProjectRoot target = do
215findProjectRoot target = do
126 myUid <- liftIO getRealUserID
216 myUid <- liftIO getRealUserID
127 targetStat <- liftIO $ getFileStatus target
217 targetStat <- liftIO $ getFileStatus target
218+ umask <- liftIO getUmask
128− (result, _) <- liftIO $ runStateT (walkToProjectRoot target targetStat myUid) []
219+ (result, _) <- liftIO $ runStateT (walkToProjectRoot target targetStat umask myUid) []
129− return result
220+ return $ makeRelative "." <$> result
130
221
131−withProjectRoot :: MonadObelisk m => FilePath -> (FilePath -> m ()) -> m ()
222+withProjectRoot :: MonadObelisk m => FilePath -> (FilePath -> m a) -> m a
132withProjectRoot target f = findProjectRoot target >>= \case
223withProjectRoot target f = findProjectRoot target >>= \case
133 Nothing -> failWith "Must be used inside of an Obelisk project"
224 Nothing -> failWith "Must be used inside of an Obelisk project"
134 Just root -> f root
225 Just root -> f root
@@ -138,15 +229,15 @@ withProjectRoot target f = findProjectRoot target >>= \case
138-- traversed in the process. Return the project root directory, if found.
229-- traversed in the process. Return the project root directory, if found.
139walkToProjectRoot
230walkToProjectRoot
140 :: (MonadState [FilePath] m, MonadIO m)
231 :: (MonadState [FilePath] m, MonadIO m)
141− => FilePath -> FileStatus -> UserID -> m (Maybe FilePath)
232+ => FilePath -> FileStatus -> FileMode -> UserID -> m (Maybe FilePath)
142−walkToProjectRoot this thisStat myUid = liftIO (doesDirectoryExist this) >>= \case
233+walkToProjectRoot this thisStat desiredUmask myUid = liftIO (doesDirectoryExist this) >>= \case
143 -- It's not a directory, so it can't be a project
234 -- It's not a directory, so it can't be a project
144 False -> do
235 False -> do
145 let dir = takeDirectory this
236 let dir = takeDirectory this
146 dirStat <- liftIO $ getFileStatus dir
237 dirStat <- liftIO $ getFileStatus dir
147− walkToProjectRoot dir dirStat myUid
238+ walkToProjectRoot dir dirStat desiredUmask myUid
148 True -> do
239 True -> do
149− when (not $ isWritableOnlyBy thisStat myUid) $ modify (this:)
240+ when (not $ isWellOwnedAndWellPermissioned thisStat myUid desiredUmask) $ modify (this:)
150 liftIO (doesDirectoryExist $ toObeliskDir this) >>= \case
241 liftIO (doesDirectoryExist $ toObeliskDir this) >>= \case
151 True -> return $ Just this
242 True -> return $ Just this
152 False -> do
243 False -> do
@@ -156,44 +247,109 @@ walkToProjectRoot this thisStat myUid = liftIO (doesDirectoryExist this) >>= \ca
156 isSameFileAs = (==) `on` fileIdentity
247 isSameFileAs = (==) `on` fileIdentity
157 if thisStat `isSameFileAs` nextStat
248 if thisStat `isSameFileAs` nextStat
158 then return Nothing -- Found a cycle; probably hit root directory
249 then return Nothing -- Found a cycle; probably hit root directory
159− else walkToProjectRoot next nextStat myUid
250+ else walkToProjectRoot next nextStat desiredUmask myUid
160
251
161-- | Walk from the given project root directory to its Obelisk implementation
252-- | Walk from the given project root directory to its Obelisk implementation
162-- directory, accumulating potentially insecure directories that were traversed
253-- directory, accumulating potentially insecure directories that were traversed
163-- in the process.
254-- in the process.
164−walkToImplDir :: (MonadState [FilePath] m, MonadIO m) => FilePath -> UserID -> m ()
255+walkToImplDir :: (MonadState [FilePath] m, MonadIO m) => FilePath -> UserID -> FileMode -> m ()
165−walkToImplDir projectRoot myUid = do
256+walkToImplDir projectRoot myUid umask = do
166 let obDir = toObeliskDir projectRoot
257 let obDir = toObeliskDir projectRoot
167 obDirStat <- liftIO $ getFileStatus obDir
258 obDirStat <- liftIO $ getFileStatus obDir
168− when (not $ isWritableOnlyBy obDirStat myUid) $ modify (obDir:)
259+ when (not $ isWellOwnedAndWellPermissioned obDirStat myUid umask) $ modify (obDir:)
169 let implThunk = obDir </> "impl"
260 let implThunk = obDir </> "impl"
170 implThunkStat <- liftIO $ getFileStatus implThunk
261 implThunkStat <- liftIO $ getFileStatus implThunk
171− when (not $ isWritableOnlyBy implThunkStat myUid) $ modify (implThunk:)
262+ when (not $ isWellOwnedAndWellPermissioned implThunkStat myUid umask) $ modify (implThunk:)
172−
263+
173−--TODO: Is there a better way to ask if anyone else can write things?
174−--E.g. what about ACLs?
175−-- | Check to see if directory is only writable by a user whose User ID matches the second argument provided
264+-- | Check to see if directory is writable by a user whose User ID matches the
265+-- second argument provided, and if the fact that other people can write to that
266+-- directory is in accordance with the umask of the system, passed as the third
267+-- argument.
176−isWritableOnlyBy :: FileStatus -> UserID -> Bool
268+isWellOwnedAndWellPermissioned :: FileStatus -> UserID -> FileMode -> Bool
269+isWellOwnedAndWellPermissioned s uid umask = isOwnedBy s uid && filePermissionIsSafe s umask
270+
271+isOwnedBy :: FileStatus -> UserID -> Bool
177−isWritableOnlyBy s uid = fileOwner s == uid && fileMode s .&. 0o22 == 0
272+isOwnedBy s uid = fileOwner s == uid
178−
273+
179−-- | Run a command in the given shell for the current project
274+-- | Check to see if a directory respect the umask, but check explicitly that
180−inProjectShell :: MonadObelisk m => String -> String -> m ()
275+-- it's not world writable in any case.
181−inProjectShell shellName command = withProjectRoot "." $ \root ->
276+filePermissionIsSafe :: FileStatus -> FileMode -> Bool
182− projectShell root True shellName command
277+filePermissionIsSafe s umask = not fileWorldWritable && fileGroupWritable <= umaskGroupWritable
183−
278+ where
184−inImpureProjectShell :: MonadObelisk m => String -> String -> m ()
279+ fileWorldWritable = fileMode s .&. 0o002 == 0o002
185−inImpureProjectShell shellName command = withProjectRoot "." $ \root ->
280+ fileGroupWritable = fileMode s .&. 0o020 == 0o020
186− projectShell root False shellName command
281+ umaskGroupWritable = umask .&. 0o020 == 0
187−
282+
188−projectShell :: MonadObelisk m => FilePath -> Bool -> String -> String -> m ()
283+nixShellRunConfig :: MonadObelisk m => FilePath -> Bool -> Maybe String -> m NixShellConfig
189−projectShell root isPure shellName command = do
284+nixShellRunConfig root isPure command = do
190− (_, _, _, ph) <- liftIO $ createProcess_ "runNixShellAttr" $ setCwd (Just root) $ proc "nix-shell" $
285+ nixpkgsPath <- fmap T.strip $ readProcessAndLogStderr Debug $ setCwd (Just root) $
191− [ "--pure" | isPure ] <>
286+ proc nixExePath ["eval", "(import .obelisk/impl {}).nixpkgs.path"]
192− [ "-A"
287+ nixRemote <- liftIO $ lookupEnv "NIX_REMOTE"
193− , "shells." <> shellName
288+ pure $ def
194− , "--run", command
289+ & nixShellConfig_pure .~ isPure
195− ]
290+ & nixShellConfig_common . nixCmdConfig_target .~ (def & target_path .~ Nothing)
196− void $ liftIO $ waitForProcess ph
291+ & nixShellConfig_run .~ (command <&> \cs -> unwords $ concat
197−
292+ [ ["export", BSU.toString . bytes . bash $ "NIX_PATH=nixpkgs=" <> encodeUtf8 nixpkgsPath, ";"]
198−setCwd :: Maybe FilePath -> CreateProcess -> CreateProcess
293+ , maybe [] (\v -> ["export", BSU.toString . bytes . bash $ "NIX_REMOTE=" <> encodeUtf8 (T.pack v), ";"]) nixRemote
199−setCwd fp cfg = cfg { cwd = fp }
294+ , [cs]
295+ ])
296+
297+bashEscape :: String -> String
298+bashEscape = BSU.toString . bytes . bash . BSU.fromString
299+
300+nixShellRunProc :: NixShellConfig -> ProcessSpec
301+nixShellRunProc cfg = setDelegateCtlc True $ proc nixShellPath $ runNixShellConfig cfg
302+
303+nixShellWithoutPkgs
304+ :: MonadObelisk m
305+ => FilePath -- ^ Path to project root
306+ -> Bool -- ^ Should this be a pure shell?
307+ -> Bool -- ^ Should we chdir to the package root in the shell?
308+ -> Map Text FilePath -- ^ Package names mapped to their paths
309+ -> String -- ^ Shell attribute to use (e.g. @"ghc"@, @"ghcjs"@, etc.)
310+ -> Maybe String -- ^ If 'Just' run the given command; otherwise just open the interactive shell
311+ -> m ()
312+nixShellWithoutPkgs root isPure chdirToRoot packageNamesAndPaths shellAttr command = do
313+ packageNamesAndAbsPaths <- liftIO $ for packageNamesAndPaths makeAbsolute
314+ defShellConfig <- nixShellRunConfig root isPure command
315+ let setCwd_ = if chdirToRoot then setCwd (Just root) else id
316+ runProcess_ $ setCwd_ $ nixShellRunProc $ defShellConfig
317+ & nixShellConfig_common . nixCmdConfig_target . target_expr ?~
318+ "{root, pkgs, shell}: ((import root {}).passthru.__unstable__.self.extend (_: _: {\
319+ \shellPackages = builtins.fromJSON pkgs;\
320+ \})).project.shells.${shell}"
321+ & nixShellConfig_common . nixCmdConfig_args .~
322+ [ rawArg "root" $ toNixPath $ if chdirToRoot then "." else root
323+ , strArg "pkgs" (T.unpack $ decodeUtf8 $ BSL.toStrict $ Json.encode packageNamesAndAbsPaths)
324+ , strArg "shell" shellAttr
325+ ]
326+
327+nixShellWithHoogle :: MonadObelisk m => FilePath -> Bool -> String -> Maybe String -> m ()
328+nixShellWithHoogle root isPure shell' command = do
329+ defShellConfig <- nixShellRunConfig root isPure command
330+ runProcess_ $ setCwd (Just root) $ nixShellRunProc $ defShellConfig
331+ & nixShellConfig_common . nixCmdConfig_target . target_expr ?~
332+ "{shell}: ((import ./. {}).passthru.__unstable__.self.extend (_: super: {\
333+ \userSettings = super.userSettings // { withHoogle = true; };\
334+ \})).project.shells.${shell}"
335+ & nixShellConfig_common . nixCmdConfig_args .~ [ strArg "shell" shell' ]
336+
337+findProjectAssets :: MonadObelisk m => FilePath -> m Text
338+findProjectAssets root = do
339+ isDerivation <- readProcessAndLogStderr Debug $ setCwd (Just root) $
340+ proc nixExePath
341+ [ "eval"
342+ , "(let a = import ./. {}; in toString (a.reflex.nixpkgs.lib.isDerivation a.passthru.staticFilesImpure))"
343+ , "--raw"
344+ -- `--raw` is not available with old nix-instantiate. It drops quotation
345+ -- marks and trailing newline, so is very convenient for shelling out.
346+ ]
347+ -- Check whether the impure static files are a derivation (and so must be built)
348+ if isDerivation == "1"
349+ then fmap T.strip $ readProcessAndLogStderr Debug $ setCwd (Just root) $ -- Strip whitespace here because nix-build has no --raw option
350+ proc nixBuildExePath
351+ [ "--no-out-link"
352+ , "-E", "(import ./. {}).passthru.staticFilesImpure"
353+ ]
354+ else readProcessAndLogStderr Debug $ setCwd (Just root) $
355+ proc nixExePath ["eval", "-f", ".", "passthru.staticFilesImpure", "--raw"]
lib/command/src/Obelisk/Command/Repl.hsdeleted−20
@@ -1,20 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−module Obelisk.Command.Repl
4− ( runRepl
5− , watch
6− ) where
7−
8−import Data.Monoid ((<>))
9−
10−import Obelisk.App (MonadObelisk)
11−import Obelisk.Command.Project
12−
13−-- | Run an interactive repl within a given path
14−runRepl :: MonadObelisk m => FilePath -> m ()
15−runRepl dir = inProjectShell "ghc" $ "cd " <> dir <> "; cabal new-repl"
16−
17−-- | Watch the given directory for errors and warnings
18−watch :: MonadObelisk m => FilePath -> m ()
19−watch dir = inProjectShell "ghc" $ "cd " <> dir <> "; ghcid -W --command='cabal new-repl'"
20−
lib/command/src/Obelisk/Command/Run.hs+540−80
@@ -1,94 +1,554 @@
1+{-# LANGUAGE DeriveFoldable #-}
2+{-# LANGUAGE DeriveFunctor #-}
3+{-# LANGUAGE DeriveTraversable #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
1{-# LANGUAGE OverloadedStrings #-}
7{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE QuasiQuotes #-}
9+{-# LANGUAGE ScopedTypeVariables #-}
10+{-# LANGUAGE TupleSections #-}
11+{-# LANGUAGE ViewPatterns #-}
2module Obelisk.Command.Run where
12module Obelisk.Command.Run where
3
13
14+import Control.Arrow ((&&&))
4−import qualified Control.Exception as E
15+import Control.Exception (Exception, bracket)
5−import Control.Monad
16+import Control.Lens (ifor, (.~), (&))
17+import Control.Monad (filterM)
18+import Control.Monad.Except (runExceptT, throwError)
19+import Control.Monad.IO.Class (liftIO)
20+import Control.Monad.Reader (MonadIO)
21+import Data.Bifoldable (bifoldr1)
22+import Data.Bifunctor (bimap)
23+import Data.Coerce (coerce)
24+import Data.Default (def)
6−import Data.Either
25+import Data.Either (partitionEithers)
26+import Data.Foldable (fold, for_, toList)
27+import Data.Functor.Identity (runIdentity)
28+import Data.List (intercalate)
29+import Data.List.NonEmpty (NonEmpty)
7−import Data.List
30+import qualified Data.List.NonEmpty as NE
31+import Data.Map (Map)
32+import qualified Data.Map as Map
33+import qualified Data.Map.Monoidal as MMap
8−import Data.Maybe
34+import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
9−import Data.Monoid
35+import Data.Ord (comparing)
10−import Data.List.NonEmpty as NE
36+import Data.Set (Set)
11−import Distribution.Utils.Generic (withUTF8FileContents)
37+import qualified Data.Set as Set
38+import Data.String.Here.Interpolated (i)
39+import Data.Text (Text)
40+import qualified Data.Text as T
41+import Data.Time.Clock (getCurrentTime)
42+import Data.Time.Format (formatTime, defaultTimeLocale)
43+import Data.Traversable (for)
44+import Debug.Trace (trace)
45+import Distribution.Compiler (CompilerFlavor(..))
12−import Distribution.PackageDescription.Parse (parseGenericPackageDescription, ParseResult(..))
46+import Distribution.PackageDescription.Parsec (parseGenericPackageDescription)
13−import Distribution.Types.BuildInfo
47+import Distribution.Parsec.ParseResult (runParseResult)
48+import qualified Distribution.System as Dist
49+import Distribution.Types.BuildInfo (buildable, cppOptions, defaultExtensions, defaultLanguage, hsSourceDirs, options)
14−import Distribution.Types.CondTree
50+import Distribution.Types.CondTree (simplifyCondTree)
51+import Distribution.Types.GenericPackageDescription (ConfVar (Arch, Impl, OS), condLibrary)
15−import Distribution.Types.Library
52+import Distribution.Types.Library (libBuildInfo)
16−import Distribution.Types.GenericPackageDescription
53+import Distribution.Utils.Generic (toUTF8BS, readUTF8File)
54+import qualified Distribution.Parsec.Common as Dist
55+import qualified Hpack.Config as Hpack
56+import qualified Hpack.Render as Hpack
57+import qualified Hpack.Yaml as Hpack
58+import Language.Haskell.Extension (Extension, Language)
17−import Network.Socket
59+import qualified Network.Socket as Socket
18import System.Directory
60import System.Directory
61+import System.Environment (getExecutablePath)
19import System.FilePath
62import System.FilePath
63+import qualified System.Info
20import System.IO.Temp (withSystemTempDirectory)
64import System.IO.Temp (withSystemTempDirectory)
21−import System.Process (callCommand)
22
65
23−run :: IO ()
66+import Obelisk.App (MonadObelisk)
24−run = do
67+import Obelisk.CliApp (
68+ Severity (..),
69+ failWith,
70+ proc,
71+ putLog,
72+ readCreateProcessWithExitCode,
73+ readProcessAndLogStderr,
74+ runProcess_,
75+ setCwd,
76+ setDelegateCtlc,
77+ withSpinner,
78+ )
79+import Obelisk.Command.Nix
80+import Obelisk.Command.Project (nixShellWithoutPkgs, withProjectRoot, findProjectAssets, bashEscape)
81+import Obelisk.Command.Thunk (attrCacheFileName)
82+import Obelisk.Command.Utils (findExePath, ghcidExePath)
83+
84+data CabalPackageInfo = CabalPackageInfo
85+ { _cabalPackageInfo_packageFile :: FilePath
86+ , _cabalPackageInfo_packageName :: T.Text
87+ , _cabalPackageInfo_packageRoot :: FilePath
88+ , _cabalPackageInfo_buildable :: Bool
89+ , _cabalPackageInfo_sourceDirs :: NE.NonEmpty FilePath
90+ -- ^ List of hs src dirs of the library component
91+ , _cabalPackageInfo_defaultExtensions :: [Extension]
92+ -- ^ List of globally enable extensions of the library component
93+ , _cabalPackageInfo_defaultLanguage :: Maybe Language
94+ -- ^ List of globally set languages of the library component
95+ , _cabalPackageInfo_compilerOptions :: [(CompilerFlavor, [String])]
96+ -- ^ List of compiler-specific options (e.g., the "ghc-options" field of the cabal file)
97+ , _cabalPackageInfo_cppOptions :: [String]
98+ -- ^ List of CPP (C Preprocessor) options (e.g. the "cpp-options" field of the cabal file)
99+ }
100+
101+-- | 'Bool' with a better name for its purpose.
102+data Interpret = Interpret_Interpret | Interpret_NoInterpret deriving (Eq, Ord, Show)
103+
104+textInterpret :: Interpret -> Text
105+textInterpret = \case
106+ Interpret_Interpret -> "Interpret"
107+ Interpret_NoInterpret -> "NoInterpret"
108+
109+-- | Describe a set of 'FilePath's as a tree to facilitate merging them in a convenient way.
110+data PathTree a = PathTree_Node
111+ (Maybe a) -- An optional leaf at this point in the tree
112+ (Map FilePath (PathTree a)) -- Branches to deeper leaves
113+ deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
114+
115+-- | 2D ASCII drawing of a 'PathTree'. Adapted from Data.Tree.draw.
116+drawPathTree :: (a -> Text) -> PathTree a -> Text
117+drawPathTree showA (PathTree_Node _ ts0) = T.intercalate "\n" $ goForest (Map.toList ts0)
118+ where
119+ annotated ma = maybe id (\a b -> b <> " [" <> showA a <> "]") ma . T.pack
120+ goTree (fp, PathTree_Node ma forest) = annotated ma fp : goForest (Map.toList forest)
121+ goForest [] = []
122+ goForest [tree] = shift "└─ " " " (goTree tree)
123+ goForest (tree:forest) = shift "├─ " "│ " (goTree tree) <> goForest forest
124+ shift first other = zipWith (<>) (first : repeat other)
125+
126+-- | Used to signal to obelisk that it's being invoked as a preprocessor
127+preprocessorIdentifier :: String
128+preprocessorIdentifier = "__preprocessor-apply-packages"
129+
130+profile
131+ :: MonadObelisk m
132+ => String
133+ -> [String]
134+ -> m ()
135+profile profileBasePattern rtsFlags = withProjectRoot "." $ \root -> do
136+ putLog Debug "Using profiled build of project."
137+
138+ outPath <- withSpinner "Building profiled executable" $
139+ fmap (T.unpack . T.strip) $ readProcessAndLogStderr Debug $ setCwd (Just root) $ nixCmdProc $
140+ NixCmd_Build $ def
141+ & nixBuildConfig_outLink .~ OutLink_None
142+ & nixCmdConfig_target .~ Target
143+ { _target_path = Just "."
144+ , _target_attr = Just "__unstable__.profiledObRun"
145+ , _target_expr = Nothing
146+ }
147+ assets <- findProjectAssets root
148+ putLog Debug $ "Assets impurely loaded from: " <> assets
149+ time <- liftIO getCurrentTime
150+ let profileBaseName = formatTime defaultTimeLocale profileBasePattern time
151+ liftIO $ createDirectoryIfMissing True $ takeDirectory $ root </> profileBaseName
152+ putLog Debug $ "Storing profiled data under base name of " <> T.pack (root </> profileBaseName)
153+ freePort <- getFreePort
154+ runProcess_ $ setCwd (Just root) $ setDelegateCtlc True $ proc (outPath </> "bin" </> "ob-run") $
155+ [ show freePort
156+ , T.unpack assets
157+ , profileBaseName
158+ , "+RTS"
159+ , "-po" <> profileBaseName
160+ ] <> rtsFlags
161+ <> [ "-RTS" ]
162+
163+run :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
164+run root interpretPaths = do
165+ pkgs <- getParsedLocalPkgs root interpretPaths
166+ assets <- findProjectAssets root
167+ putLog Debug $ "Assets impurely loaded from: " <> assets
168+ ghciArgs <- getGhciSessionSettings pkgs root True
25 freePort <- getFreePort
169 freePort <- getFreePort
26− pkgs <- getLocalPkgs
170+ withGhciScriptArgs pkgs $ \dotGhciArgs -> do
27− (pkgDirErrs, hsSrcDirs) <- fmap partitionEithers $ forM pkgs $ \pkg -> do
171+ runGhcid root True (ghciArgs <> dotGhciArgs) pkgs $ Just $ unwords
28− let cabalFp = pkg </> pkg <.> "cabal"
172+ [ "Obelisk.Run.run"
29− xs <- parseHsSrcDir cabalFp
173+ , show freePort
30− return $ case xs of
174+ , "(Obelisk.Run.runServeAsset " ++ show assets ++ ")"
31− Nothing -> Left pkg
175+ , "Backend.backend"
32− Just hsSrcDirs -> Right $ toList $ fmap (pkg </>) hsSrcDirs
176+ , "Frontend.frontend"
33− when (null hsSrcDirs) $
177+ ]
34− fail $ "No valid pkgs found in " <> intercalate ", " pkgs
178+
35− when (not (null pkgDirErrs)) $
179+runRepl :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
36− putStrLn $ "Failed to find pkgs in " <> intercalate ", " pkgDirErrs
180+runRepl root interpretPaths = do
37− let dotGhci = unlines
181+ pkgs <- getParsedLocalPkgs root interpretPaths
38− [ ":set args --quiet --port " <> show freePort
182+ ghciArgs <- getGhciSessionSettings pkgs "." True
39− , ":set -i" <> intercalate ":" (mconcat hsSrcDirs)
183+ withGhciScriptArgs pkgs $ \dotGhciArgs ->
40− , ":set -XScopedTypeVariables"
184+ runGhciRepl root pkgs (ghciArgs <> dotGhciArgs)
41− , ":add Backend Frontend"
185+
42− , ":module + System.IO Control.Exception Control.Concurrent Obelisk.Widget.Run Frontend Backend"
186+runWatch :: MonadObelisk m => FilePath -> PathTree Interpret -> m ()
43− ]
187+runWatch root interpretPaths = do
44− testCmd = unlines
188+ pkgs <- getParsedLocalPkgs root interpretPaths
45− [ "let handleBackendErr (_ :: SomeException) = hPutStrLn stderr \"backend stopped; make a change to your code to reload\""
189+ ghciArgs <- getGhciSessionSettings pkgs root True
46− , "backendTid <- forkIO $ handle handleBackendErr backend"
190+ withGhciScriptArgs pkgs $ \dotGhciArgs ->
47− , "let conf = defRunConfig { _runConfig_redirectPort = " <> show freePort <> "}"
191+ runGhcid root True (ghciArgs <> dotGhciArgs) pkgs Nothing
48− , "runWidget conf frontend"
192+
49− , "killThread backendTid"
193+exportGhciConfig :: MonadObelisk m => Bool -> FilePath -> PathTree Interpret -> m [String]
194+exportGhciConfig useRelativePaths root interpretPaths = do
195+ pkgs <- getParsedLocalPkgs root interpretPaths
196+ getGhciSessionSettings pkgs "." useRelativePaths
197+
198+nixShellForInterpretPaths :: MonadObelisk m => Bool -> String -> FilePath -> PathTree Interpret -> Maybe String -> m ()
199+nixShellForInterpretPaths isPure shell root interpretPaths cmd = do
200+ pkgs <- getParsedLocalPkgs root interpretPaths
201+ nixShellWithoutPkgs root isPure False (packageInfoToNamePathMap pkgs) shell cmd
202+
203+-- | Like 'getLocalPkgs' but also parses them and fails if any of them can't be parsed.
204+getParsedLocalPkgs :: MonadObelisk m => FilePath -> PathTree Interpret -> m (NonEmpty CabalPackageInfo)
205+getParsedLocalPkgs root interpretPaths = parsePackagesOrFail =<< getLocalPkgs root interpretPaths
206+
207+-- | Relative paths to local packages of an obelisk project.
208+--
209+-- These are a combination of the obelisk predefined local packages,
210+-- and any packages that the user has set with the @packages@ argument
211+-- to the Nix @project@ function.
212+getLocalPkgs :: forall m. MonadObelisk m => FilePath -> PathTree Interpret -> m (Set FilePath)
213+getLocalPkgs root interpretPaths = do
214+ putLog Debug $ [i|Finding packages with root ${root} and interpret paths:|] <> "\n" <> drawPathTree textInterpret interpretPaths
215+ obeliskPackagePaths <- runFind ["-L", root, "-name", ".obelisk", "-type", "d"]
216+
217+ -- We do not want to find packages that are embedded inside other obelisk projects, unless that
218+ -- obelisk project is our own.
219+ obeliskPackageExclusions <- liftIO $ fmap Set.fromList $ traverse canonicalizePath $
220+ filter (/= root) $ map takeDirectory obeliskPackagePaths
221+ putLog Debug [i|Excluding obelisk packages: ${T.pack $ unwords $ Set.toList obeliskPackageExclusions}|]
222+ let rootsAndExclusions = calcIntepretFinds "" interpretPaths
223+
224+ fmap fold $ for (MMap.toAscList rootsAndExclusions) $ \(interpretPathRoot, exclusions) ->
225+ let allExclusions = obeliskPackageExclusions <> exclusions <> Set.singleton ("*" </> attrCacheFileName)
226+ in fmap (Set.fromList . map normalise) $ runFind $
227+ ["-L", interpretPathRoot, "(", "-name", "*.cabal", "-o", "-name", Hpack.packageConfig, ")", "-a", "-type", "f"]
228+ <> concat [["-not", "-path", p </> "*"] | p <- toList allExclusions]
229+ where
230+ runFind args = do
231+ (_exitCode, out, err) <- readCreateProcessWithExitCode $ proc findExePath args
232+ putLog Debug $ T.strip $ T.pack err
233+ pure $ map T.unpack $ T.lines $ T.strip $ T.pack out
234+
235+-- | Calculates a set of root 'FilePath's along with each one's corresponding set of exclusions.
236+-- This is used when constructing a set of @find@ commands to run to produce a set of packages
237+-- that matches the user's @--interpret@/@--no-interpret@ settings.
238+calcIntepretFinds :: FilePath -> PathTree Interpret -> MMap.MonoidalMap FilePath (Set FilePath)
239+calcIntepretFinds treeRoot0 tree0 = runIdentity $ go treeRoot0 tree0
240+ where
241+ go treeRoot tree = foldPathTreeFor (== Interpret_Interpret) treeRoot tree $ \parent children -> do
242+ exclusions <- foldPathTreeFor (== Interpret_NoInterpret) parent children $ \parent' children' ->
243+ pure $ Map.singleton parent' children'
244+ deeperFinds <- Map.traverseWithKey go exclusions
245+ pure $ MMap.singleton parent (Map.keysSet exclusions) <> fold (MMap.MonoidalMap deeperFinds)
246+
247+-- | Traverses a 'PathTree' and folds all leaves matching a given predicate.
248+foldPathTreeFor
249+ :: forall m a b. (Applicative m, Monoid b)
250+ => (a -> Bool)
251+ -> FilePath
252+ -> PathTree a
253+ -> (FilePath -> PathTree a -> m b)
254+ -> m b
255+foldPathTreeFor predicate parent children f = case children of
256+ PathTree_Node (Just x) children' | predicate x -> f parent (PathTree_Node Nothing children')
257+ PathTree_Node _ children' -> fmap fold $ flip Map.traverseWithKey children' $ \k children'' ->
258+ foldPathTreeFor predicate (parent </> k) children'' f
259+
260+data GuessPackageFileError = GuessPackageFileError_Ambiguous [FilePath] | GuessPackageFileError_NotFound
261+ deriving (Eq, Ord, Show)
262+instance Exception GuessPackageFileError
263+
264+newtype HPackFilePath = HPackFilePath { unHPackFilePath :: FilePath } deriving (Eq, Ord, Show)
265+newtype CabalFilePath = CabalFilePath { unCabalFilePath :: FilePath } deriving (Eq, Ord, Show)
266+
267+-- | Given a directory, try to guess what the appropriate @.cabal@ or @package.yaml@ file is for the package.
268+guessCabalPackageFile
269+ :: (MonadIO m)
270+ => FilePath -- ^ Directory or path to search for cabal package
271+ -> m (Either GuessPackageFileError (Either CabalFilePath HPackFilePath))
272+guessCabalPackageFile pkg = do
273+ liftIO (doesDirectoryExist pkg) >>= \case
274+ False -> case cabalOrHpackFile pkg of
275+ (Just hpack@(Right _)) -> pure $ Right hpack
276+ (Just cabal@(Left (CabalFilePath cabalFilePath))) -> do
277+ -- If the cabal file has a sibling hpack file, we use that instead
278+ -- since running hpack often generates a sibling cabal file
279+ let possibleHpackSibling = takeDirectory cabalFilePath </> Hpack.packageConfig
280+ hasHpackSibling <- liftIO $ doesFileExist possibleHpackSibling
281+ pure $ Right $ if hasHpackSibling then Right (HPackFilePath possibleHpackSibling) else cabal
282+ Nothing -> pure $ Left GuessPackageFileError_NotFound
283+ True -> do
284+ candidates <- liftIO $
285+ filterM (doesFileExist . either unCabalFilePath unHPackFilePath)
286+ =<< mapMaybe (cabalOrHpackFile . (pkg </>)) <$> listDirectory pkg
287+ pure $ case partitionEithers candidates of
288+ ([hpack], _) -> Right $ Left hpack
289+ ([], [cabal]) -> Right $ Right cabal
290+ ([], []) -> Left GuessPackageFileError_NotFound
291+ (hpacks, cabals) -> Left $ GuessPackageFileError_Ambiguous $ coerce hpacks <> coerce cabals
292+
293+cabalOrHpackFile :: FilePath -> Maybe (Either CabalFilePath HPackFilePath)
294+cabalOrHpackFile = \case
295+ x | takeExtension x == ".cabal" -> Just (Left $ CabalFilePath x)
296+ | takeFileName x == Hpack.packageConfig -> Just (Right $ HPackFilePath x)
297+ | otherwise -> Nothing
298+
299+-- | Parses the cabal package in a given directory.
300+-- This automatically figures out which .cabal file or package.yaml (hpack) file to use in the given directory.
301+parseCabalPackage
302+ :: MonadObelisk m
303+ => FilePath -- ^ Package directory
304+ -> m (Maybe CabalPackageInfo)
305+parseCabalPackage dir = parseCabalPackage' dir >>= \case
306+ Left err -> Nothing <$ putLog Error err
307+ Right (Just (warnings, pkgInfo)) -> do
308+ for_ warnings $ putLog Warning . T.pack . show
309+ pure $ Just pkgInfo
310+ Right Nothing -> pure Nothing
311+
312+-- | Like 'parseCabalPackage' but returns errors and warnings directly so as to avoid 'MonadObelisk'.
313+parseCabalPackage'
314+ :: (MonadIO m)
315+ => FilePath -- ^ Package directory
316+ -> m (Either T.Text (Maybe ([Dist.PWarning], CabalPackageInfo)))
317+parseCabalPackage' pkg = runExceptT $ do
318+ (cabalContents, packageFile, packageName) <- guessCabalPackageFile pkg >>= \case
319+ Left GuessPackageFileError_NotFound -> throwError $ "No .cabal or package.yaml file found in " <> T.pack pkg
320+ Left (GuessPackageFileError_Ambiguous _) -> throwError $ "Unable to determine which .cabal file to use in " <> T.pack pkg
321+ Right (Left (CabalFilePath file)) -> (, file, takeBaseName file) <$> liftIO (readUTF8File file)
322+ Right (Right (HPackFilePath file)) -> do
323+ let
324+ decodeOptions = Hpack.DecodeOptions (Hpack.ProgramName "ob") file Nothing Hpack.decodeYaml
325+ liftIO (Hpack.readPackageConfig decodeOptions) >>= \case
326+ Left err -> throwError $ T.pack $ "Failed to parse " <> file <> ": " <> err
327+ Right (Hpack.DecodeResult hpackPackage _ _ _) -> pure (Hpack.renderPackage [] hpackPackage, file, Hpack.packageName hpackPackage)
328+
329+ let
330+ (warnings, result) = runParseResult $ parseGenericPackageDescription $ toUTF8BS cabalContents
331+ osConfVar = case System.Info.os of
332+ "linux" -> Just Dist.Linux
333+ "darwin" -> Just Dist.OSX
334+ _ -> trace "Unrecgonized System.Info.os" Nothing
335+ archConfVar = Just Dist.X86_64 -- TODO: Actually infer this
336+ evalConfVar v = Right $ case v of
337+ OS osVar -> Just osVar == osConfVar
338+ Arch archVar -> Just archVar == archConfVar
339+ Impl GHC _ -> True -- TODO: Actually check version range
340+ _ -> False
341+ case condLibrary <$> result of
342+ Right (Just condLib) -> do
343+ let (_, lib) = simplifyCondTree evalConfVar condLib
344+ pure $ Just $ (warnings,) $ CabalPackageInfo
345+ { _cabalPackageInfo_packageName = T.pack packageName
346+ , _cabalPackageInfo_packageFile = packageFile
347+ , _cabalPackageInfo_packageRoot = takeDirectory packageFile
348+ , _cabalPackageInfo_buildable = buildable $ libBuildInfo lib
349+ , _cabalPackageInfo_sourceDirs =
350+ fromMaybe (pure ".") $ NE.nonEmpty $ hsSourceDirs $ libBuildInfo lib
351+ , _cabalPackageInfo_defaultExtensions =
352+ defaultExtensions $ libBuildInfo lib
353+ , _cabalPackageInfo_defaultLanguage =
354+ defaultLanguage $ libBuildInfo lib
355+ , _cabalPackageInfo_compilerOptions = options $ libBuildInfo lib
356+ , _cabalPackageInfo_cppOptions = cppOptions $ libBuildInfo lib
357+ }
358+ Right Nothing -> pure Nothing
359+ Left (_, errors) ->
360+ throwError $ T.pack $ "Failed to parse " <> packageFile <> ":\n" <> unlines (map show errors)
361+
362+parsePackagesOrFail :: (MonadObelisk m, Foldable f) => f FilePath -> m (NE.NonEmpty CabalPackageInfo)
363+parsePackagesOrFail dirs' = do
364+ packageInfos' <- fmap catMaybes $ for dirs $ \dir -> do
365+ flip fmap (parseCabalPackage dir) $ \case
366+ Just packageInfo
367+ | _cabalPackageInfo_buildable packageInfo -> Just packageInfo
368+ _ -> Nothing
369+
370+ -- Sort duplicate packages such that we prefer shorter paths, but fall back to alphabetical ordering.
371+ let packagesByName = Map.map (NE.sortBy $ comparing $ \p -> let n = _cabalPackageInfo_packageFile p in (length n, n))
372+ $ Map.fromListWith (<>) [(_cabalPackageInfo_packageName p, p NE.:| []) | p <- packageInfos']
373+ unambiguous <- ifor packagesByName $ \packageName ps -> case ps of
374+ p NE.:| [] -> pure p -- No ambiguity here
375+ p NE.:| _ -> do
376+ let chosenText = " [Chosen] "
377+ prefix p'
378+ | _cabalPackageInfo_packageFile p' == _cabalPackageInfo_packageFile p = chosenText
379+ | otherwise = T.map (const ' ') chosenText
380+ putLog Warning $ T.unlines $
381+ "Packages named '" <> packageName <> "' appear in " <> T.pack (show $ length ps) <> " different locations: "
382+ : map (\p' -> prefix p' <> T.pack (_cabalPackageInfo_packageFile p')) (toList ps)
383+ pure p
384+
385+ packageInfos <- case NE.nonEmpty $ toList unambiguous of
386+ Nothing -> failWith $ T.pack $
387+ "No valid, buildable packages found" <> (if null dirs then "" else " in " <> intercalate ", " dirs)
388+ Just xs -> pure xs
389+
390+ pure packageInfos
391+ where
392+ dirs = toList dirs'
393+
394+packageInfoToNamePathMap :: Foldable f => f CabalPackageInfo -> Map Text FilePath
395+packageInfoToNamePathMap = Map.fromList . map (_cabalPackageInfo_packageName &&& _cabalPackageInfo_packageRoot) . toList
396+
397+-- Like 'withGhciScript' but provides the precise ghci arguments to add to a ghci session
398+withGhciScriptArgs
399+ :: (MonadObelisk m, Foldable f)
400+ => f CabalPackageInfo -- ^ List of packages to load into ghci
401+ -> ([String] -> m ()) -- ^ Action to run with the extra ghci arguments
402+ -> m ()
403+withGhciScriptArgs packageInfos f = withGhciScript loadPreludeManually packageInfos $ \fp -> f ["-XNoImplicitPrelude", "-ghci-script", fp]
404+ where
405+ -- These lines must be first and allow the session to support a custom Prelude when @-XNoImplicitPrelude@
406+ -- is passed to the ghci session.
407+ loadPreludeManually =
408+ [ ":add Prelude" -- @:add@ is used because it's less noisy when there is no custom Prelude
409+ , ":set -XImplicitPrelude" -- Turn the default setting on
50− ]
410+ ]
411+
412+-- | Create ghci configuration to load the given packages
413+withGhciScript
414+ :: (MonadObelisk m, Foldable f)
415+ => [String] -- ^ Commands to prefix to file
416+ -> f CabalPackageInfo -- ^ List of packages to load into ghci
417+ -> (FilePath -> m ()) -- ^ Action to run with the path to generated temporary .ghci
418+ -> m ()
419+withGhciScript preCommands (toList -> packageInfos) f =
51 withSystemTempDirectory "ob-ghci" $ \fp -> do
420 withSystemTempDirectory "ob-ghci" $ \fp -> do
52 let dotGhciPath = fp </> ".ghci"
421 let dotGhciPath = fp </> ".ghci"
53− writeFile dotGhciPath dotGhci
422+ liftIO $ writeFile dotGhciPath dotGhci
54− runDev dotGhciPath $ Just testCmd
423+ f dotGhciPath
55−
424+ where
56−-- | Relative paths to local packages of an obelisk project
425+ packageNames = Set.fromList $ map _cabalPackageInfo_packageName packageInfos
57−-- TODO a way to query this
426+ modulesToLoad = mconcat
58−getLocalPkgs :: IO [FilePath]
427+ [ [ "Obelisk.Run" | "obelisk-run" `Set.member` packageNames ]
59−getLocalPkgs = return ["backend", "common", "frontend"]
428+ , [ "Backend" | "backend" `Set.member` packageNames ]
60−
429+ , [ "Frontend" | "frontend" `Set.member` packageNames ]
61−parseHsSrcDir :: FilePath -- ^ package cabal file path
430+ ]
62− -> IO (Maybe (NE.NonEmpty FilePath)) -- ^ List of hs src dirs of the library component
431+ dotGhci = unlines $
63−parseHsSrcDir cabalFp = do
432+ preCommands <>
64− exists <- doesFileExist cabalFp
433+ [ if null modulesToLoad then "" else ":load " <> unwords modulesToLoad
65− if exists
434+ , "import qualified Obelisk.Run"
66− then do
435+ , "import qualified Frontend"
67− withUTF8FileContents cabalFp $ \cabal -> do
436+ , "import qualified Backend"
68− case parseGenericPackageDescription cabal of
437+ ]
69− ParseOk warnings gpkg -> do
438+
70− mapM_ print warnings
439+-- | Builds a list of options to pass to ghci or set in .ghci file that configures
71− return $ do
440+-- the preprocessor and source includes.
72− (_, lib) <- simplifyCondTree (const $ pure True) <$> condLibrary gpkg
441+getGhciSessionSettings
73− pure $ fromMaybe (pure ".") $ NE.nonEmpty $ hsSourceDirs $ libBuildInfo lib
442+ :: (MonadObelisk m, Foldable f)
74− ParseFailed _ -> return Nothing
443+ => f CabalPackageInfo -- ^ List of packages to load into ghci
75− else return Nothing
444+ -> FilePath -- ^ All paths will be relative to this path
76−
445+ -> Bool -- ^ Use relative paths
77−-- | Dev
446+ -> m [String]
78−runDev :: FilePath -> Maybe String -> IO ()
447+getGhciSessionSettings (toList -> packageInfos) pathBase useRelativePaths = do
79−runDev dotGhci mcmd = callCommand $ unwords $ "ghcid" : ghcidOpts
448+ -- N.B. ghci settings do NOT support escaping in any way. To minimize the likelihood that
449+ -- paths-with-spaces ruin our day, we first canonicalize everything, and then relativize
450+ -- all paths to 'pathBase'.
451+ selfExe <- liftIO $ canonicalizePath =<< getExecutablePath
452+ canonicalPathBase <- liftIO $ canonicalizePath pathBase
453+
454+ (pkgFiles, pkgSrcPaths :: [NonEmpty FilePath]) <- fmap unzip $ liftIO $ for packageInfos $ \pkg -> do
455+ canonicalSrcDirs <- traverse canonicalizePath $ (_cabalPackageInfo_packageRoot pkg </>) <$> _cabalPackageInfo_sourceDirs pkg
456+ canonicalPkgFile <- canonicalizePath $ _cabalPackageInfo_packageFile pkg
457+ pure (canonicalPkgFile `relativeTo'` canonicalPathBase, (`relativeTo'` canonicalPathBase) <$> canonicalSrcDirs)
458+
459+ pure
460+ $ baseGhciOptions
461+ <> ["-F", "-pgmF", selfExe, "-optF", preprocessorIdentifier]
462+ <> concatMap (\p -> ["-optF", p]) pkgFiles
463+ <> [ "-i" <> intercalate ":" (concatMap toList pkgSrcPaths) ]
80 where
464 where
81− ghcidOpts =
465+ relativeTo' = if useRelativePaths then relativeTo else const
466+
467+baseGhciOptions :: [String]
468+baseGhciOptions =
469+ [ "-ignore-dot-ghci"
470+ , "-no-user-package-db"
471+ , "-package-env", "-"
472+ ]
473+
474+-- | Run ghci repl
475+runGhciRepl
476+ :: (MonadObelisk m, Foldable f)
477+ => FilePath -- ^ Path to project root
478+ -> f CabalPackageInfo -- ^ Packages to keep unbuilt
479+ -> [String] -- ^ GHCi arguments
480+ -> m ()
481+runGhciRepl root (toList -> packages) ghciArgs =
482+ -- NOTE: We do *not* want to use $(staticWhich "ghci") here because we need the
483+ -- ghc that is provided by the shell in the user's project.
484+ nixShellWithoutPkgs root True False (packageInfoToNamePathMap packages) "ghc" $
485+ Just $ unwords $ fmap bashEscape $ "ghci" : ghciArgs
486+
487+-- | Run ghcid
488+runGhcid
489+ :: (MonadObelisk m, Foldable f)
490+ => FilePath -- ^ Path to project root
491+ -> Bool -- ^ Should we chdir to root when running this process?
492+ -> [String] -- ^ GHCi arguments
493+ -> f CabalPackageInfo -- ^ Packages to keep unbuilt
494+ -> Maybe String -- ^ Optional command to run at every reload
495+ -> m ()
496+runGhcid root chdirToRoot ghciArgs (toList -> packages) mcmd =
497+ nixShellWithoutPkgs root True chdirToRoot (packageInfoToNamePathMap packages) "ghc" $
498+ Just $ unwords $ fmap bashEscape $ ghcidExePath : opts
499+ where
500+ opts = concat
82− [ "-W"
501+ [ ["-W"]
83− , "--command='ghci -ghci-script " <> dotGhci <> "' "
502+ , ["--outputfile=ghcid-output.txt"]
84− ] <> maybeToList (flip fmap mcmd $ \cmd -> " --test=$'" <> cmd <> "'")
503+ , map (\x -> "--reload=" <> x) reloadFiles
85−
504+ , map (\x -> "--restart=" <> x) restartFiles
505+ , maybe [] (\cmd -> ["--test=" <> cmd]) mcmd
506+ , ["--command=" <> unwords ("ghci" : ghciArgs)]
507+ ]
508+ adjustRoot x = if chdirToRoot then makeRelative root x else x
509+ reloadFiles = map adjustRoot [root </> "config"]
510+ restartFiles = map (adjustRoot . _cabalPackageInfo_packageFile) packages
511+
86−getFreePort :: IO PortNumber
512+getFreePort :: MonadIO m => m Socket.PortNumber
87−getFreePort = withSocketsDo $ do
513+getFreePort = liftIO $ Socket.withSocketsDo $ do
88− addr:_ <- getAddrInfo (Just defaultHints) (Just "127.0.0.1") (Just "0")
514+ addr:_ <- Socket.getAddrInfo (Just Socket.defaultHints) (Just "127.0.0.1") (Just "0")
89− E.bracket (open addr) close socketPort
515+ bracket (open addr) Socket.close Socket.socketPort
90 where
516 where
91 open addr = do
517 open addr = do
92− sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
518+ sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
93− bind sock (addrAddress addr)
519+ Socket.bind sock (Socket.addrAddress addr)
94 return sock
520 return sock
521+
522+
523+-- | Convert a 'FilePath' into a 'PathTree'.
524+pathToTree :: a -> FilePath -> PathTree a
525+pathToTree a p = go $ splitDirectories p
526+ where
527+ go [] = PathTree_Node (Just a) mempty
528+ go (x : xs) = PathTree_Node Nothing $ Map.singleton x $ go xs
529+
530+-- | Like 'zipWith' but pads with a padding value instead of stopping on the shortest list.
531+zipDefaultWith :: a -> b -> (a -> b -> c) -> [a] -> [b] -> [c]
532+zipDefaultWith _da _db _f [] [] = []
533+zipDefaultWith da db f (a:as) [] = f a db : zipDefaultWith da db f as []
534+zipDefaultWith da db f [] (b:bs) = f da b : zipDefaultWith da db f [] bs
535+zipDefaultWith da db f (a:as) (b:bs) = f a b : zipDefaultWith da db f as bs
536+
537+-- | Makes the first absolute path relative to the second absolute path.
538+--
539+-- Both input paths MUST be absolute.
540+--
541+-- Unlike 'makeRelative' this does not merely strip prefixes. It will introduce
542+-- enough @..@ paths to make the resulting path truly relative in virtually every
543+-- case. The only exception is on Windows when the two paths are on different
544+-- drives. In this case the resulting path may be absolute.
545+relativeTo :: FilePath -> FilePath -> FilePath
546+relativeTo dir base
547+ = bifoldr1 (</>)
548+ $ bimap (collapse . (".." <$) . catMaybes) (collapse . catMaybes)
549+ $ unzip
550+ $ dropWhile (\(a,b) -> a == b)
551+ $ zipDefaultWith Nothing Nothing (,)
552+ (map Just $ splitDirectories base)
553+ (map Just $ splitDirectories dir)
554+ where collapse = foldr (</>) ""
lib/command/src/Obelisk/Command/Thunk.hs+992−456
@@ -5,81 +5,70 @@
5{-# LANGUAGE MultiWayIf #-}
5{-# LANGUAGE MultiWayIf #-}
6{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
7{-# LANGUAGE PatternGuards #-}
7{-# LANGUAGE PatternGuards #-}
8−{-# LANGUAGE TemplateHaskell #-}
8+{-# LANGUAGE QuasiQuotes #-}
9−
9+{-# LANGUAGE ScopedTypeVariables #-}
10+{-# LANGUAGE TypeApplications #-}
10−module Obelisk.Command.Thunk
11+module Obelisk.Command.Thunk where
11− ( ThunkPtr (..)
12− , ThunkRev (..)
13− , ThunkSource (..)
14− , ThunkData (..)
15− , GitHubSource (..)
16− , getLatestRev
17− , updateThunkToLatest
18− , createThunk
19− , createThunkWithLatest
20− , nixBuildAttrWithCache
21− , nixBuildThunkAttrWithCache
22− , unpackThunk
23− , packThunk
24− , readThunk
25− , getThunkPtr
26− ) where
27
12
28import Control.Applicative
13import Control.Applicative
29−import Control.Exception (displayException, throwIO)
14+import Control.Exception (displayException, try)
15+import Control.Lens (ifor, ifor_, (.~))
30import Control.Monad
16import Control.Monad
31−import Control.Monad.Catch (handle)
17+import Control.Monad.Extra (findM)
18+import Control.Monad.Catch (MonadCatch, handle)
32import Control.Monad.Except
19import Control.Monad.Except
33−import Data.Aeson (decode, (.=))
20+import Data.Aeson ((.=))
34import qualified Data.Aeson as Aeson
21import qualified Data.Aeson as Aeson
35import Data.Aeson.Encode.Pretty
22import Data.Aeson.Encode.Pretty
23+import qualified Data.Aeson.Types as Aeson
24+import Data.Bifunctor (first)
36import qualified Data.ByteString.Lazy as LBS
25import qualified Data.ByteString.Lazy as LBS
26+import Data.Containers.ListUtils (nubOrd)
37import Data.Default
27import Data.Default
38−import Data.Foldable
28+import Data.Either.Combinators (fromRight', rightToMaybe)
29+import Data.Foldable (toList)
30+import Data.Function ((&))
31+import Data.Functor ((<&>))
39import Data.Git.Ref (Ref)
32import Data.Git.Ref (Ref)
40import qualified Data.Git.Ref as Ref
33import qualified Data.Git.Ref as Ref
41import qualified Data.List as L
34import qualified Data.List as L
42−import Data.List.NonEmpty (NonEmpty (..))
35+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
43import qualified Data.List.NonEmpty as NonEmpty
36import qualified Data.List.NonEmpty as NonEmpty
37+import Data.Map (Map)
44import qualified Data.Map as Map
38import qualified Data.Map as Map
45import Data.Maybe
39import Data.Maybe
46−import Data.Monoid
47import Data.Set (Set)
40import Data.Set (Set)
48import 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)
49import Data.Text (Text)
44import Data.Text (Text)
50import qualified Data.Text as T
45import qualified Data.Text as T
51import Data.Text.Encoding
46import Data.Text.Encoding
52import qualified Data.Text.IO as T
47import qualified Data.Text.IO as T
53import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
48import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
54−import Data.Yaml (parseMaybe, (.:))
49+import Data.Traversable (for)
55−import qualified Data.Yaml as Yaml
50+import Data.Yaml (parseMaybe)
56import GitHub
51import GitHub
57import GitHub.Data.Name
52import GitHub.Data.Name
58−import GitHub.Endpoints.Repos.Contents (archiveForR)
59−import Network.URI
60import Obelisk.Command.Nix
53import Obelisk.Command.Nix
61import System.Directory
54import System.Directory
62import System.Exit
55import System.Exit
63import System.FilePath
56import System.FilePath
64−import System.IO
65import System.IO.Error
57import System.IO.Error
66import System.IO.Temp
58import System.IO.Temp
67−import System.Posix (getSymbolicLinkStatus, modificationTime)
59+import System.PosixCompat.Files (getSymbolicLinkStatus, modificationTime)
68−import System.Process (StdStream (CreatePipe), callProcess, createProcess, proc, readProcess, std_err,
60+import qualified Text.URI as URI
69− std_out, waitForProcess)
70
61
71−import Development.Placeholders
72import Obelisk.App (MonadObelisk)
62import Obelisk.App (MonadObelisk)
73−import Obelisk.CLI (Severity (..), callProcessAndLogOutput, failWith, putLog, withSpinner)
63+import Obelisk.CliApp
74−import Obelisk.Command.Utils (checkGitCleanStatus, cp, procWithPackages)
64+import Obelisk.Command.Utils
75
65
76--TODO: Support symlinked thunk data
66--TODO: Support symlinked thunk data
77data ThunkData
67data ThunkData
78− = ThunkData_Packed ThunkPtr
68+ = ThunkData_Packed ThunkSpec ThunkPtr
79 -- ^ Packed thunk
69 -- ^ Packed thunk
80− | ThunkData_Checkout (Maybe ThunkPtr)
70+ | ThunkData_Checkout
81 -- ^ Checked out thunk that was unpacked from this pointer
71 -- ^ Checked out thunk that was unpacked from this pointer
82− deriving (Show, Eq, Ord)
83
72
84-- | 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
85data ThunkPtr = ThunkPtr
74data ThunkPtr = ThunkPtr
@@ -92,7 +81,7 @@ type NixSha256 = Text --TODO: Use a smart constructor and make this actually ver
92
81
93-- | A specific revision of data; it may be available from multiple sources
82-- | A specific revision of data; it may be available from multiple sources
94data ThunkRev = ThunkRev
83data ThunkRev = ThunkRev
95− { _thunkRev_commit :: Ref
84+ { _thunkRev_commit :: Ref Ref.SHA1
96 , _thunkRev_nixSha256 :: NixSha256
85 , _thunkRev_nixSha256 :: NixSha256
97 }
86 }
98 deriving (Show, Eq, Ord)
87 deriving (Show, Eq, Ord)
@@ -105,6 +94,11 @@ data ThunkSource
105 | ThunkSource_Git GitSource
94 | ThunkSource_Git GitSource
106 deriving (Show, Eq, Ord)
95 deriving (Show, Eq, Ord)
107
96
97+thunkSourceToGitSource :: ThunkSource -> GitSource
98+thunkSourceToGitSource = \case
99+ ThunkSource_GitHub s -> forgetGithub False s
100+ ThunkSource_Git s -> s
101+
108data GitHubSource = GitHubSource
102data GitHubSource = GitHubSource
109 { _gitHubSource_owner :: Name Owner
103 { _gitHubSource_owner :: Name Owner
110 , _gitHubSource_repo :: Name Repo
104 , _gitHubSource_repo :: Name Repo
@@ -113,158 +107,263 @@ data GitHubSource = GitHubSource
113 }
107 }
114 deriving (Show, Eq, Ord)
108 deriving (Show, Eq, Ord)
115
109
110+newtype GitUri = GitUri { unGitUri :: URI.URI } deriving (Eq, Ord, Show)
111+
112+gitUriToText :: GitUri -> Text
113+gitUriToText (GitUri uri)
114+ | (T.toLower . URI.unRText <$> URI.uriScheme uri) == Just "file"
115+ , Just (_, path) <- URI.uriPath uri
116+ = "/" <> T.intercalate "/" (map URI.unRText $ NonEmpty.toList path)
117+ | otherwise = URI.render uri
118+
116data GitSource = GitSource
119data GitSource = GitSource
117− { _gitSource_url :: URI
120+ { _gitSource_url :: GitUri
118− --TODO: Is it ok to use the types from the GitHub api bindings?
119 , _gitSource_branch :: Maybe (Name Branch)
121 , _gitSource_branch :: Maybe (Name Branch)
120 , _gitSource_fetchSubmodules :: Bool
122 , _gitSource_fetchSubmodules :: Bool
123+ , _gitSource_private :: Bool
121 }
124 }
122 deriving (Show, Eq, Ord)
125 deriving (Show, Eq, Ord)
123
126
127+newtype ThunkConfig = ThunkConfig
128+ { _thunkConfig_private :: Maybe Bool
129+ } deriving Show
130+
131+data ThunkUpdateConfig = ThunkUpdateConfig
132+ { _thunkUpdateConfig_branch :: Maybe String
133+ , _thunkUpdateConfig_config :: ThunkConfig
134+ } deriving Show
135+
136+data ThunkPackConfig = ThunkPackConfig
137+ { _thunkPackConfig_force :: Bool
138+ , _thunkPackConfig_config :: ThunkConfig
139+ } deriving Show
140+
141+-- | Convert a GitHub source to a regular Git source. Assumes no submodules.
142+forgetGithub :: Bool -> GitHubSource -> GitSource
143+forgetGithub useSsh s = GitSource
144+ { _gitSource_url = GitUri $ URI.URI
145+ { URI.uriScheme = Just $ fromRight' $ URI.mkScheme $ if useSsh then "ssh" else "https"
146+ , URI.uriAuthority = Right $ URI.Authority
147+ { URI.authUserInfo = URI.UserInfo (fromRight' $ URI.mkUsername "git") Nothing
148+ <$ guard useSsh
149+ , URI.authHost = fromRight' $ URI.mkHost "github.com"
150+ , URI.authPort = Nothing
151+ }
152+ , URI.uriPath = Just ( False
153+ , fromRight' . URI.mkPathPiece <$>
154+ untagName (_gitHubSource_owner s)
155+ :| [ untagName (_gitHubSource_repo s) <> ".git" ]
156+ )
157+ , URI.uriQuery = []
158+ , URI.uriFragment = Nothing
159+ }
160+ , _gitSource_branch = _gitHubSource_branch s
161+ , _gitSource_fetchSubmodules = False
162+ , _gitSource_private = _gitHubSource_private s
163+ }
164+
165+getThunkGitBranch :: ThunkPtr -> Maybe Text
166+getThunkGitBranch (ThunkPtr _ src) = fmap untagName $ case src of
167+ ThunkSource_GitHub s -> _gitHubSource_branch s
168+ ThunkSource_Git s -> _gitSource_branch s
169+
124−commitNameToRef :: Name Commit -> Ref
170+commitNameToRef :: Name Commit -> Ref Ref.SHA1
125commitNameToRef (N c) = Ref.fromHex $ encodeUtf8 c
171commitNameToRef (N c) = Ref.fromHex $ encodeUtf8 c
126
172
127-- TODO: Use spinner here.
173-- TODO: Use spinner here.
128−getNixSha256ForUriUnpacked :: URI -> IO NixSha256
174+getNixSha256ForUriUnpacked
175+ :: MonadObelisk m
176+ => GitUri
177+ -> m NixSha256
129−getNixSha256ForUriUnpacked uri = do
178+getNixSha256ForUriUnpacked uri =
130− --TODO: Make this package depend on nix-prefetch-url properly
179+ withExitFailMessage ("nix-prefetch-url: Failed to determine sha256 hash of URL " <> gitUriToText uri) $ do
131− let cmd = proc "nix-prefetch-url" ["--unpack" , "--type" , "sha256" , show uri]
180+ [hash] <- fmap T.lines $ readProcessAndLogOutput (Debug, Debug) $
132− (_, Just out, Just err, p) <- createProcess cmd
181+ proc nixPrefetchUrlPath ["--unpack", "--type", "sha256", T.unpack $ gitUriToText uri]
133− { std_out = CreatePipe
182+ pure hash
134− , std_err = CreatePipe
135− }
136− --TODO: Deal with errors here; usually they're HTTP errors
137− waitForProcess p >>= \case
138− ExitSuccess -> return ()
139− _ -> do
140− hPutStrLn stdout =<< hGetContents out
141− hPutStrLn stderr =<< hGetContents err
142− --TODO: actual error
143− fail "nix-prefetch-url"
144− T.strip <$> T.hGetContents out
145
183
146−-- | Get the latest revision available from the given source
184+nixPrefetchGit :: MonadObelisk m => GitUri -> Text -> Bool -> m NixSha256
147−getLatestRev :: ThunkSource -> IO ThunkRev
185+nixPrefetchGit uri rev fetchSubmodules =
148−getLatestRev = \case
186+ withExitFailMessage ("nix-prefetch-git: Failed to determine sha256 hash of Git repo " <> gitUriToText uri <> " at " <> rev) $ do
149− ThunkSource_GitHub s -> do
187+ out <- readProcessAndLogStderr Debug $
150− auth <- getHubAuth "github.com"
188+ proc nixPrefetchGitPath $ filter (/="")
151− commitsResult <- executeRequestMaybe auth $ commitsWithOptionsForR
189+ [ "--url", T.unpack $ gitUriToText uri
152− (_gitHubSource_owner s)
190+ , "--rev", T.unpack rev
153− (_gitHubSource_repo s)
191+ , if fetchSubmodules then "--fetch-submodules" else ""
154− (FetchAtLeast 1)
192+ , "--quiet"
155− $ case _gitHubSource_branch s of
193+ ]
156− Nothing -> []
194+
157− Just b -> [CommitQuerySha $ untagName b]
195+ case parseMaybe (Aeson..: "sha256") =<< Aeson.decodeStrict (encodeUtf8 out) of
158− commitInfos <- either throwIO return commitsResult
196+ Nothing -> failWith $ "nix-prefetch-git: unrecognized output " <> out
159− commitInfo : _ <- return $ toList commitInfos
197+ Just x -> pure x
160− let commit = commitSha commitInfo
161− Right archiveUri <- executeRequestMaybe auth $ archiveForR (_gitHubSource_owner s) (_gitHubSource_repo s) ArchiveFormatTarball $ Just $ untagName commit
162− nixSha256 <- getNixSha256ForUriUnpacked archiveUri
163− return $ ThunkRev
164− { _thunkRev_commit = commitNameToRef commit
165− , _thunkRev_nixSha256 = nixSha256
166− }
167− ThunkSource_Git _s -> do
168− $notImplemented
169
198
170--TODO: Pretty print these
199--TODO: Pretty print these
171data ReadThunkError
200data ReadThunkError
172− = ReadThunkError_WrongContents (Set String) (Set String)
201+ = ReadThunkError_UnrecognizedThunk
173− | ReadThunkError_UnrecognizedLoader Text
202+ | ReadThunkError_UnrecognizedPaths (NonEmpty FilePath)
174− | ReadThunkError_UnparseablePtr LBS.ByteString
203+ | ReadThunkError_MissingPaths (NonEmpty FilePath)
204+ | ReadThunkError_UnparseablePtr FilePath String
205+ | ReadThunkError_FileError IOError
206+ | ReadThunkError_FileDoesNotMatch FilePath Text
207+ | ReadThunkError_UnrecognizedState String
208+ | ReadThunkError_AmbiguousPackedState ThunkPtr ThunkPtr
175− deriving (Show)
209+ deriving (Show)
176−
210+
177−-- | Read a thunk and validate that it is only a thunk, either packed or unpacked.
211+unpackedDirName :: FilePath
178−-- If the thunk is packed and additional data is present, fail.
212+unpackedDirName = "."
213+
214+attrCacheFileName :: FilePath
215+attrCacheFileName = ".attr-cache"
216+
217+-- | Specification for how a file in a thunk version works.
218+data ThunkFileSpec
219+ = ThunkFileSpec_Ptr (LBS.ByteString -> Either String ThunkPtr) -- ^ This file specifies 'ThunkPtr' data
220+ | ThunkFileSpec_FileMatches Text -- ^ This file must match the given content exactly
221+ | ThunkFileSpec_CheckoutIndicator -- ^ Existence of this directory indicates that the thunk is unpacked
222+ | ThunkFileSpec_AttrCache -- ^ This directory is an attribute cache
223+
224+-- | Specification for how a set of files in a thunk version work.
225+data ThunkSpec = ThunkSpec
226+ { _thunkSpec_name :: !Text
227+ , _thunkSpec_files :: !(Map FilePath ThunkFileSpec)
228+ }
229+
230+thunkSpecTypes :: NonEmpty (NonEmpty ThunkSpec)
231+thunkSpecTypes = gitThunkSpecs :| [gitHubThunkSpecs]
232+
233+-- | Attempts to match a 'ThunkSpec' to a given directory.
234+matchThunkSpecToDir
235+ :: (MonadError ReadThunkError m, MonadIO m, MonadCatch m)
236+ => ThunkSpec -- ^ 'ThunkSpec' to match against the given files/directory
237+ -> FilePath -- ^ Path to directory
238+ -> Set FilePath -- ^ Set of file paths relative to the given directory
239+ -> m ThunkData
240+matchThunkSpecToDir thunkSpec dir dirFiles = do
241+ case nonEmpty (toList $ dirFiles `Set.difference` expectedPaths) of
242+ Just fs -> throwError $ ReadThunkError_UnrecognizedPaths $ (dir </>) <$> fs
243+ Nothing -> pure ()
244+ case nonEmpty (toList $ requiredPaths `Set.difference` dirFiles) of
245+ Just fs -> throwError $ ReadThunkError_MissingPaths $ (dir </>) <$> fs
246+ Nothing -> pure ()
247+ datas <- fmap toList $ flip Map.traverseMaybeWithKey (_thunkSpec_files thunkSpec) $ \expectedPath -> \case
248+ ThunkFileSpec_AttrCache -> Nothing <$ dirMayExist expectedPath
249+ ThunkFileSpec_CheckoutIndicator -> liftIO (doesDirectoryExist (dir </> expectedPath)) <&> \case
250+ False -> Nothing
251+ True -> Just ThunkData_Checkout
252+ ThunkFileSpec_FileMatches expectedContents -> handle (\(e :: IOError) -> throwError $ ReadThunkError_FileError e) $ do
253+ actualContents <- liftIO (T.readFile $ dir </> expectedPath)
254+ case T.strip expectedContents == T.strip actualContents of
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)
179−readThunk :: MonadObelisk m => FilePath -> m (Either ReadThunkError ThunkData)
298+ => NonEmpty (NonEmpty ThunkSpec) -> FilePath -> m (Either ReadThunkError ThunkData)
180−readThunk thunkDir = do
299+readThunkWith specTypes dir = do
181− files <- liftIO $ listDirectory thunkDir
300+ dirFiles <- Set.fromList <$> liftIO (listDirectory dir)
182− case ".git" `elem` files of
301+ let specs = concatMap toList $ toList $ NonEmpty.transpose specTypes -- Interleave spec types so we try each one in a "fair" ordering
183− True -> fmap ThunkData_Checkout <$> do
302+ flip fix specs $ \loop -> \case
184− let origThunkPath = thunkDir </> ".git" </> "obelisk" </> "orig-thunk"
303+ [] -> pure $ Left ReadThunkError_UnrecognizedThunk
185− liftIO $ doesDirectoryExist origThunkPath >>= \case
304+ spec:rest -> runExceptT (matchThunkSpecToDir spec dir dirFiles) >>= \case
186− True -> fmap Just <$> readPackedThunk origThunkPath
305+ Left e -> putLog Debug [i|Thunk specification ${_thunkSpec_name spec} did not match ${dir}: ${e}|] *> loop rest
187− False -> return $ return Nothing
306+ x@(Right _) -> x <$ putLog Debug [i|Thunk specification ${_thunkSpec_name spec} matched ${dir}|]
188− False -> liftIO $ fmap ThunkData_Packed <$> readPackedThunk thunkDir
189
307
190-- | 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.
191-- If additional data is present, fail.
309-- If additional data is present, fail.
192−readPackedThunk :: FilePath -> IO (Either ReadThunkError ThunkPtr)
310+readThunk :: (MonadObelisk m) => FilePath -> m (Either ReadThunkError ThunkData)
193−readPackedThunk thunkDir = runExceptT $ do
311+readThunk = readThunkWith thunkSpecTypes
194− let thunkLoader = thunkDir </> "default.nix"
195− githubJson = thunkDir </> "github.json"
196− attrCache = thunkDir </> ".attr-cache"
197− expectedContents = Set.fromList $
198− [ githubJson
199− , thunkLoader
200− ]
201− optionalContents = Set.fromList $
202− [ attrCache
203− ]
204
312
205− -- Ensure that there aren't any other files in the thunk
313+parseThunkPtr :: (Aeson.Object -> Aeson.Parser ThunkSource) -> Aeson.Object -> Aeson.Parser ThunkPtr
206− -- NB: System.Directory.listDirectory returns the contents without the directory path
314+parseThunkPtr parseSrc v = do
207− files <- liftIO $ Set.fromList . fmap (thunkDir </>) <$> listDirectory thunkDir
208− let unexpectedContents = files `Set.difference` (expectedContents `Set.union` optionalContents)
209− missingContents = expectedContents `Set.difference` files
210− unless (Set.null unexpectedContents && Set.null missingContents) $ do
211− throwError $ ReadThunkError_WrongContents unexpectedContents missingContents
212−
213− -- Ensure that we recognize the thunk loader
214− loader <- liftIO $ T.readFile thunkLoader
215− unless (loader `elem` gitHubStandaloneLoaders) $ do
216− throwError $ ReadThunkError_UnrecognizedLoader loader
217−
218− txt <- liftIO $ LBS.readFile githubJson
219− let parseThunk v = do
220− rev <- v Aeson..: "rev"
315+ rev <- v Aeson..: "rev"
221− sha256 <- v Aeson..: "sha256"
316+ sha256 <- v Aeson..: "sha256"
222− src <- parseGitHubSource v
317+ src <- parseSrc v
223− <|> parseGitSource v
224− return $ ThunkPtr
318+ pure $ ThunkPtr
225− { _thunkPtr_rev = ThunkRev
319+ { _thunkPtr_rev = ThunkRev
226− { _thunkRev_commit = Ref.fromHexString rev
320+ { _thunkRev_commit = Ref.fromHexString rev
227− , _thunkRev_nixSha256 = sha256
321+ , _thunkRev_nixSha256 = sha256
228− }
322+ }
229− , _thunkPtr_source = src
323+ , _thunkPtr_source = src
230− }
324+ }
325+
231− parseGitHubSource v = do
326+parseGitHubSource :: Aeson.Object -> Aeson.Parser GitHubSource
327+parseGitHubSource v = do
232− owner <- v Aeson..: "owner"
328+ owner <- v Aeson..: "owner"
233− repo <- v Aeson..: "repo"
329+ repo <- v Aeson..: "repo"
234− branch <- v Aeson..:! "branch"
330+ branch <- v Aeson..:! "branch"
235− mPrivate <- v Aeson..:! "private"
331+ private <- v Aeson..:? "private"
236− return $ ThunkSource_GitHub $ GitHubSource
332+ pure $ GitHubSource
237− { _gitHubSource_owner = owner
333+ { _gitHubSource_owner = owner
238− , _gitHubSource_repo = repo
334+ , _gitHubSource_repo = repo
239− , _gitHubSource_branch = branch
335+ , _gitHubSource_branch = branch
240− , _gitHubSource_private = fromMaybe False mPrivate
336+ , _gitHubSource_private = fromMaybe False private
241− }
337+ }
338+
242− parseGitSource v = do
339+parseGitSource :: Aeson.Object -> Aeson.Parser GitSource
340+parseGitSource v = do
243− Just url <- parseURI <$> v Aeson..: "url"
341+ Just url <- parseGitUri <$> v Aeson..: "url"
244− branch <- v Aeson..:! "branch"
342+ branch <- v Aeson..:! "branch"
245− fetchSubmodules <- v Aeson..: "fetchSubmodules"
343+ fetchSubmodules <- v Aeson..:! "fetchSubmodules"
344+ private <- v Aeson..:? "private"
246− return $ ThunkSource_Git $ GitSource
345+ pure $ GitSource
247− { _gitSource_url = url
346+ { _gitSource_url = url
248− , _gitSource_branch = branch
347+ , _gitSource_branch = branch
249− , _gitSource_fetchSubmodules = fetchSubmodules
348+ , _gitSource_fetchSubmodules = fromMaybe False fetchSubmodules
250− }
349+ , _gitSource_private = fromMaybe False private
251− case parseMaybe parseThunk =<< decode txt of
350+ }
252− Nothing -> throwError $ ReadThunkError_UnparseablePtr txt
253− Just ptr -> return ptr
254
351
255overwriteThunk :: MonadObelisk m => FilePath -> ThunkPtr -> m ()
352overwriteThunk :: MonadObelisk m => FilePath -> ThunkPtr -> m ()
256overwriteThunk target thunk = do
353overwriteThunk target thunk = do
257 -- 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)
258− Right _ <- readThunk target
355+ readThunk target >>= \case
356+ Left e -> failWith [i|Invalid thunk at ${target}: ${e}|]
357+ Right _ -> pure ()
259
358
260 --TODO: Is there a safer way to do this overwriting?
359 --TODO: Is there a safer way to do this overwriting?
261− liftIO $ removeDirectoryRecursive target
360+ liftIO $ removePathForcibly target
262− liftIO $ createThunk target thunk
361+ createThunk target $ Right thunk
263
362
264−thunkPtrLoader :: ThunkPtr -> Text
363+thunkPtrToSpec :: ThunkPtr -> ThunkSpec
265−thunkPtrLoader thunk = case _thunkPtr_source thunk of
364+thunkPtrToSpec thunk = case _thunkPtr_source thunk of
266− ThunkSource_GitHub _ -> NonEmpty.head gitHubStandaloneLoaders
365+ ThunkSource_GitHub _ -> NonEmpty.head gitHubThunkSpecs
267− ThunkSource_Git _ -> NonEmpty.head plainGitStandaloneLoaders
366+ ThunkSource_Git _ -> NonEmpty.head gitThunkSpecs
268
367
269-- It's important that formatting be very consistent here, because
368-- It's important that formatting be very consistent here, because
270-- otherwise when people update thunks, their patches will be messy
369-- otherwise when people update thunks, their patches will be messy
@@ -273,21 +372,18 @@ encodeThunkPtrData (ThunkPtr rev src) = case src of
273 ThunkSource_GitHub s -> encodePretty' githubCfg $ Aeson.object $ catMaybes
372 ThunkSource_GitHub s -> encodePretty' githubCfg $ Aeson.object $ catMaybes
274 [ Just $ "owner" .= _gitHubSource_owner s
373 [ Just $ "owner" .= _gitHubSource_owner s
275 , Just $ "repo" .= _gitHubSource_repo s
374 , Just $ "repo" .= _gitHubSource_repo s
276− , case _gitHubSource_branch s of
375+ , ("branch" .=) <$> _gitHubSource_branch s
277− Just b -> Just $ "branch" .= b
278− Nothing -> Nothing
279− , if _gitHubSource_private s
280− then Just $ "private" .= True
281− else Nothing
282 , Just $ "rev" .= Ref.toHexString (_thunkRev_commit rev)
376 , Just $ "rev" .= Ref.toHexString (_thunkRev_commit rev)
283 , Just $ "sha256" .= _thunkRev_nixSha256 rev
377 , Just $ "sha256" .= _thunkRev_nixSha256 rev
378+ , Just $ "private" .= _gitHubSource_private s
284 ]
379 ]
285 ThunkSource_Git s -> encodePretty' plainGitCfg $ Aeson.object $ catMaybes
380 ThunkSource_Git s -> encodePretty' plainGitCfg $ Aeson.object $ catMaybes
286− --TODO: Is this safe? read/show is jank for `URI`
287− [ Just $ "url" .= show (_gitSource_url s)
381+ [ Just $ "url" .= gitUriToText (_gitSource_url s)
288 , Just $ "rev" .= Ref.toHexString (_thunkRev_commit rev)
382 , Just $ "rev" .= Ref.toHexString (_thunkRev_commit rev)
383+ , ("branch" .=) <$> _gitSource_branch s
289 , Just $ "sha256" .= _thunkRev_nixSha256 rev
384 , Just $ "sha256" .= _thunkRev_nixSha256 rev
290 , Just $ "fetchSubmodules" .= _gitSource_fetchSubmodules s
385 , Just $ "fetchSubmodules" .= _gitSource_fetchSubmodules s
386+ , Just $ "private" .= _gitSource_private s
291 ]
387 ]
292 where
388 where
293 githubCfg = defConfig
389 githubCfg = defConfig
@@ -308,54 +404,84 @@ encodeThunkPtrData (ThunkPtr rev src) = case src of
308 [ "url"
404 [ "url"
309 , "rev"
405 , "rev"
310 , "sha256"
406 , "sha256"
407+ , "private"
311 , "fetchSubmodules"
408 , "fetchSubmodules"
312 ] <> compare
409 ] <> compare
313 , confTrailingNewline = True
410 , confTrailingNewline = True
314 }
411 }
315
412
316−createThunk :: FilePath -> ThunkPtr -> IO ()
413+createThunk :: MonadObelisk m => FilePath -> Either ThunkSpec ThunkPtr -> m ()
317−createThunk target thunk = do
414+createThunk target ptrInfo =
415+ ifor_ (_thunkSpec_files spec) $ \path -> \case
416+ ThunkFileSpec_FileMatches content -> withReadyPath path $ \p -> liftIO $ T.writeFile p content
417+ ThunkFileSpec_Ptr _ -> case ptrInfo of
418+ Left _ -> pure () -- We can't write the ptr without it
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
318− createDirectoryIfMissing True (target </> ".attr-cache")
426+ liftIO $ createDirectoryIfMissing True $ takeDirectory fullPath
319− T.writeFile (target </> "default.nix") (thunkPtrLoader thunk)
427+ f fullPath
320− LBS.writeFile (target </> "github.json") (encodeThunkPtrData thunk)
321
428
322−createThunkWithLatest :: FilePath -> ThunkSource -> IO ()
429+createThunkWithLatest :: MonadObelisk m => FilePath -> ThunkSource -> m ()
323createThunkWithLatest target s = do
430createThunkWithLatest target s = do
324 rev <- getLatestRev s
431 rev <- getLatestRev s
325− createThunk target $ ThunkPtr
432+ createThunk target $ Right $ ThunkPtr
326 { _thunkPtr_source = s
433 { _thunkPtr_source = s
327 , _thunkPtr_rev = rev
434 , _thunkPtr_rev = rev
328 }
435 }
329
436
330−updateThunkToLatest :: MonadObelisk m => FilePath -> m ()
437+updateThunkToLatest :: MonadObelisk m => ThunkUpdateConfig -> FilePath -> m ()
331−updateThunkToLatest target = do
438+updateThunkToLatest (ThunkUpdateConfig mBranch thunkConfig) target = spinner $ do
439+ checkThunkDirectory target
440+ -- check to see if thunk should be updated to a specific branch or just update it's current branch
441+ case mBranch of
442+ Nothing -> do
332− (overwrite, ptr) <- readThunk target >>= \case
443+ (overwrite, ptr) <- readThunk target >>= \case
333− Left err -> failWith $ T.pack $ "thunk update: " <> show err
444+ Left err -> failWith [i|Thunk update: ${err}|]
334− Right c -> case c of
445+ Right c -> case c of
335− ThunkData_Packed t -> return (target, t)
446+ ThunkData_Packed _ t -> return (target, t)
336− ThunkData_Checkout _ -> failWith "cannot update an unpacked thunk"
447+ ThunkData_Checkout -> failWith "cannot update an unpacked thunk"
337− let src = _thunkPtr_source ptr
448+ let src = _thunkPtr_source ptr
338− rev <- liftIO $ getLatestRev src
449+ rev <- getLatestRev src
339− overwriteThunk overwrite $ ThunkPtr
450+ overwriteThunk overwrite $ modifyThunkPtrByConfig thunkConfig $ ThunkPtr
340− { _thunkPtr_source = src
451+ { _thunkPtr_source = src
341− , _thunkPtr_rev = rev
452+ , _thunkPtr_rev = rev
342− }
453+ }
454+ Just branch -> readThunk target >>= \case
455+ Left err -> failWith [i|Thunk update: ${err}|]
456+ Right c -> case c of
457+ ThunkData_Packed _ t -> setThunk thunkConfig target (thunkSourceToGitSource $ _thunkPtr_source t) branch
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")
461+
462+setThunk :: MonadObelisk m => ThunkConfig -> FilePath -> GitSource -> String -> m ()
463+setThunk thunkConfig target gs branch = do
464+ newThunkPtr <- uriThunkPtr (_gitSource_url gs) (_thunkConfig_private thunkConfig) (Just $ T.pack branch) Nothing
465+ overwriteThunk target newThunkPtr
466+ updateThunkToLatest (ThunkUpdateConfig Nothing thunkConfig) target
343
467
344-- | All recognized github standalone loaders, ordered from newest to oldest.
468-- | All recognized github standalone loaders, ordered from newest to oldest.
345-- 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.
346−gitHubStandaloneLoaders :: NonEmpty Text
470+gitHubThunkSpecs :: NonEmpty ThunkSpec
347−gitHubStandaloneLoaders =
471+gitHubThunkSpecs =
348− gitHubStandaloneLoaderV2 :|
472+ gitHubThunkSpecV5 :|
349− [ gitHubStandaloneLoaderV1
473+ [ gitHubThunkSpecV4
474+ , gitHubThunkSpecV3
475+ , gitHubThunkSpecV2
476+ , gitHubThunkSpecV1
350 ]
477 ]
351
478
352−gitHubStandaloneLoaderV1 :: Text
479+gitHubThunkSpecV1 :: ThunkSpec
353−gitHubStandaloneLoaderV1 = T.unlines
480+gitHubThunkSpecV1 = legacyGitHubThunkSpec "github-v1"
354− [ "import ((import <nixpkgs> {}).fetchFromGitHub (builtins.fromJSON (builtins.readFile ./github.json)))"
481+ "import ((import <nixpkgs> {}).fetchFromGitHub (builtins.fromJSON (builtins.readFile ./github.json)))"
355− ]
356
482
357−gitHubStandaloneLoaderV2 :: Text
483+gitHubThunkSpecV2 :: ThunkSpec
358−gitHubStandaloneLoaderV2 = T.unlines
484+gitHubThunkSpecV2 = legacyGitHubThunkSpec "github-v2" $ T.unlines
359 [ "# 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.
360 , "import ((import <nixpkgs> {}).fetchFromGitHub ("
486 , "import ((import <nixpkgs> {}).fetchFromGitHub ("
361 , " let json = builtins.fromJSON (builtins.readFile ./github.json);"
487 , " let json = builtins.fromJSON (builtins.readFile ./github.json);"
@@ -365,32 +491,171 @@ gitHubStandaloneLoaderV2 = T.unlines
365 , "))"
491 , "))"
366 ]
492 ]
367
493
368−plainGitStandaloneLoaders :: NonEmpty Text
494+gitHubThunkSpecV3 :: ThunkSpec
369−plainGitStandaloneLoaders =
495+gitHubThunkSpecV3 = legacyGitHubThunkSpec "github-v3" $ T.unlines
370− plainGitStandaloneLoaderV1 :|
496+ [ "# DO NOT HAND-EDIT THIS FILE"
371− [
497+ , "let"
498+ , " fetch = { private ? false, ... }@args: if private && builtins.hasAttr \"fetchGit\" builtins"
499+ , " then fetchFromGitHubPrivate args"
500+ , " else (import <nixpkgs> {}).fetchFromGitHub (builtins.removeAttrs args [\"branch\"]);"
501+ , " fetchFromGitHubPrivate ="
502+ , " { owner, repo, rev, branch ? null, name ? null, sha256 ? null, private ? false"
503+ , " , fetchSubmodules ? false, githubBase ? \"github.com\", ..."
504+ , " }: assert !fetchSubmodules;"
505+ , " builtins.fetchGit ({"
506+ , " url = \"ssh://git@${githubBase}/${owner}/${repo}.git\";"
507+ , " inherit rev;"
508+ , " }"
509+ , " // (if branch == null then {} else { ref = branch; })"
510+ , " // (if name == null then {} else { inherit name; }));"
511+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
372 ]
512 ]
373
513
374−plainGitStandaloneLoaderV1 :: Text
514+gitHubThunkSpecV4 :: ThunkSpec
375−plainGitStandaloneLoaderV1 = T.unlines
515+gitHubThunkSpecV4 = legacyGitHubThunkSpec "github-v4" $ T.unlines
376− [ $notImplemented
516+ [ "# DO NOT HAND-EDIT THIS FILE"
517+ , "let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:"
518+ , " if !fetchSubmodules && !private then builtins.fetchTarball {"
519+ , " url = \"https://github.com/${owner}/${repo}/archive/${rev}.tar.gz\"; inherit sha256;"
520+ , " } else (import <nixpkgs> {}).fetchFromGitHub {"
521+ , " inherit owner repo rev sha256 fetchSubmodules private;"
522+ , " };"
523+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./github.json)))"
377 ]
524 ]
378
525
379−-- | Look for authentication info from the 'hub' command
526+legacyGitHubThunkSpec :: Text -> Text -> ThunkSpec
380−getHubAuth
527+legacyGitHubThunkSpec name loader = ThunkSpec name $ Map.fromList
381− :: Text -- ^ Domain name
528+ [ ("default.nix", ThunkFileSpec_FileMatches $ T.strip loader)
382− -> IO (Maybe Auth)
529+ , ("github.json" , ThunkFileSpec_Ptr parseGitHubJsonBytes)
383−getHubAuth domain = do
530+ , (attrCacheFileName, ThunkFileSpec_AttrCache)
384− hubConfig <- getXdgDirectory XdgConfig "hub"
531+ , (".git", ThunkFileSpec_CheckoutIndicator)
385− Yaml.decodeFile hubConfig >>= \case
532+ ]
386− Nothing -> return Nothing
533+
387− Just v -> return $ flip parseMaybe v $ \v' -> do
534+gitHubThunkSpecV5 :: ThunkSpec
388− Yaml.Array domainConfigs <- v' .: domain --TODO: Determine what multiple domainConfigs means
535+gitHubThunkSpecV5 = mkThunkSpec "github-v5" "github.json" parseGitHubJsonBytes [here|
389− [Yaml.Object domainConfig] <- return $ toList domainConfigs
536+# DO NOT HAND-EDIT THIS FILE
390− token <- domainConfig .: "oauth_token"
537+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
391− return $ OAuth $ encodeUtf8 token
538+ if !fetchSubmodules && !private then builtins.fetchTarball {
392−
539+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
393−--TODO: when checking something out, make a shallow clone
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
562+ [ "# DO NOT HAND-EDIT THIS FILE"
563+ , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
564+ , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
565+ , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
566+ ]
567+
568+gitThunkSpecV2 :: ThunkSpec
569+gitThunkSpecV2 = legacyGitThunkSpec "git-v2" $ T.unlines
570+ [ "# DO NOT HAND-EDIT THIS FILE"
571+ , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
572+ , " if builtins.hasAttr \"fetchGit\" builtins"
573+ , " then builtins.fetchGit ({ inherit url rev; } // (if branch == null then {} else { ref = branch; }))"
574+ , " else abort \"Plain Git repositories are only supported on nix 2.0 or higher.\";"
575+ , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
576+ ]
577+
578+-- This loader has a bug because @builtins.fetchGit@ is not given a @ref@
579+-- and will fail to find commits without this because it does shallow clones.
580+gitThunkSpecV3 :: ThunkSpec
581+gitThunkSpecV3 = legacyGitThunkSpec "git-v3" $ T.unlines
582+ [ "# DO NOT HAND-EDIT THIS FILE"
583+ , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
584+ , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
585+ , " if firstChar == \"/\" then /. + url"
586+ , " else if firstChar == \".\" then ./. + url"
587+ , " else url;"
588+ , " in if !fetchSubmodules && private then builtins.fetchGit {"
589+ , " url = realUrl; inherit rev;"
590+ , " } else (import <nixpkgs> {}).fetchgit {"
591+ , " url = realUrl; inherit rev sha256;"
592+ , " };"
593+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
594+ ]
595+
596+gitThunkSpecV4 :: ThunkSpec
597+gitThunkSpecV4 = legacyGitThunkSpec "git-v4" $ T.unlines
598+ [ "# DO NOT HAND-EDIT THIS FILE"
599+ , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
600+ , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
601+ , " if firstChar == \"/\" then /. + url"
602+ , " else if firstChar == \".\" then ./. + url"
603+ , " else url;"
604+ , " in if !fetchSubmodules && private then builtins.fetchGit {"
605+ , " url = realUrl; inherit rev;"
606+ , " ${if branch == null then null else \"ref\"} = branch;"
607+ , " } else (import <nixpkgs> {}).fetchgit {"
608+ , " url = realUrl; inherit rev sha256;"
609+ , " };"
610+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
611+ ]
612+
613+legacyGitThunkSpec :: Text -> Text -> ThunkSpec
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+|]
655+
656+
657+parseJsonObject :: (Aeson.Object -> Aeson.Parser a) -> LBS.ByteString -> Either String a
658+parseJsonObject p bytes = Aeson.parseEither p =<< Aeson.eitherDecode bytes
394
659
395-- | 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
396-- to the result of building an attribute of a thunk.
661-- to the result of building an attribute of a thunk.
@@ -398,42 +663,49 @@ getHubAuth domain = do
398-- and the result is symlinked into the cache.
663-- and the result is symlinked into the cache.
399nixBuildThunkAttrWithCache
664nixBuildThunkAttrWithCache
400 :: MonadObelisk m
665 :: MonadObelisk m
666+ => ThunkSpec
401− => FilePath
667+ -> FilePath
402 -- ^ Path to directory containing Thunk
668 -- ^ Path to directory containing Thunk
403 -> String
669 -> String
404 -- ^ Attribute to build
670 -- ^ Attribute to build
405− -> m FilePath
671+ -> m (Maybe FilePath)
406 -- ^ Symlink to cached or built nix output
672 -- ^ Symlink to cached or built nix output
407-- WARNING: If the thunk uses an impure reference such as '<nixpkgs>'
673-- WARNING: If the thunk uses an impure reference such as '<nixpkgs>'
408-- the caching mechanism will fail as it merely measures the modification
674-- the caching mechanism will fail as it merely measures the modification
409-- time of the cache link and the expression to build.
675-- time of the cache link and the expression to build.
410−nixBuildThunkAttrWithCache thunkDir attr = do
676+nixBuildThunkAttrWithCache thunkSpec thunkDir attr = do
411− --NB: Expects thunkDir to be normalised with no trailing path separator.
677+ latestChange <- liftIO $ do
412− --This should be guaranteed by the command argument parser.
678+ let
679+ getModificationTimeMaybe = fmap rightToMaybe . try @IOError . getModificationTime
680+ thunkFileNames = Map.keys $ _thunkSpec_files thunkSpec
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"
413− let cacheErrHandler e
689+ cacheErrHandler e
414− | isDoesNotExistError e = return Nothing -- expected from a cache miss
690+ | isDoesNotExistError e = pure Nothing -- expected from a cache miss
415− | otherwise = putLog Error (T.pack $ displayException e) >> return Nothing
691+ | otherwise = Nothing <$ putLog Error (T.pack $ displayException e)
416− cacheDir = thunkDir </> ".attr-cache"
417− cachePath = cacheDir </> attr <.> "out"
418− liftIO $ createDirectoryIfMissing False cacheDir
419− latestChange <- liftIO $ maximum <$> mapM (getModificationTime . (thunkDir </>)) ["default.nix", "github.json"]
420− cacheHit <- handle cacheErrHandler $ do
692+ cacheHit <- handle cacheErrHandler $ do
421− cacheTime <- liftIO $ posixSecondsToUTCTime . realToFrac . modificationTime <$> getSymbolicLinkStatus cachePath
693+ cacheTime <- liftIO $ posixSecondsToUTCTime . realToFrac . modificationTime <$> getSymbolicLinkStatus cachePath
422− return $ if latestChange <= cacheTime
694+ pure $ if latestChange <= cacheTime
423− then Just cachePath
695+ then Just cachePath
424− else Nothing
696+ else Nothing
425− case cacheHit of
697+ case cacheHit of
426− Just c -> return c
698+ Just c -> pure c
427− Nothing -> do
699+ Nothing -> do
428− putLog Warning $ T.pack $ mconcat [thunkDir, ": ", attr, " not cached, building ..."]
700+ putLog Warning $ T.pack $ mconcat [thunkDir, ": ", attr, " not cached, building ..."]
429− _ <- nixBuild $ def
701+ liftIO $ createDirectoryIfMissing True (takeDirectory cachePath)
430− { _nixBuildConfig_target = Target
702+ (cachePath <$) $ nixCmd $ NixCmd_Build $ def
703+ & nixBuildConfig_outLink .~ OutLink_IndirectRoot cachePath
704+ & nixCmdConfig_target .~ Target
431− { _target_path = thunkDir
705+ { _target_path = Just thunkDir
432− , _target_attr = Just attr
706+ , _target_attr = Just attr
433− }
707+ , _target_expr = Nothing
434− , _nixBuildConfig_outLink = OutLink_IndirectRoot cachePath
435− }
708+ }
436− return cachePath
437
709
438-- | Build a nix attribute, and cache the result if possible
710-- | Build a nix attribute, and cache the result if possible
439nixBuildAttrWithCache
711nixBuildAttrWithCache
@@ -444,212 +716,476 @@ nixBuildAttrWithCache
444 -- ^ Attribute to build
716 -- ^ Attribute to build
445 -> m FilePath
717 -> m FilePath
446 -- ^ Symlink to cached or built nix output
718 -- ^ Symlink to cached or built nix output
447−nixBuildAttrWithCache exprPath attr = do
719+nixBuildAttrWithCache exprPath attr = readThunk exprPath >>= \case
448− readThunk exprPath >>= \case
449− -- 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 _) ->
450− Right (ThunkData_Packed _) -> nixBuildThunkAttrWithCache exprPath attr
722+ maybe build pure =<< nixBuildThunkAttrWithCache spec exprPath attr
451− _ -> nixBuild $ def
723+ _ -> build
452− { _nixBuildConfig_target = Target
724+ where
725+ build = nixCmd $ NixCmd_Build $ def
726+ & nixBuildConfig_outLink .~ OutLink_None
727+ & nixCmdConfig_target .~ Target
453− { _target_path = exprPath
728+ { _target_path = Just exprPath
454 , _target_attr = Just attr
729 , _target_attr = Just attr
730+ , _target_expr = Nothing
455 }
731 }
456− , _nixBuildConfig_outLink = OutLink_None
457− }
458
732
459−unpackThunk
733+-- | Safely update thunk using a custom action
734+--
735+-- A temporary working space is used to do any update. When the custom
736+-- action successfully completes, the resulting (packed) thunk is copied
737+-- back to the original location.
460− :: MonadObelisk m
738+updateThunk :: MonadObelisk m => FilePath -> (FilePath -> m a) -> m a
461− => FilePath
739+updateThunk p f = withSystemTempDirectory "obelisk-thunkptr-" $ \tmpDir -> do
462− -> m ()
740+ p' <- copyThunkToTmp tmpDir p
741+ unpackThunk' True p'
742+ result <- f p'
743+ updateThunkFromTmp p'
744+ return result
745+ where
463−unpackThunk thunkDir = readThunk thunkDir >>= \case
746+ copyThunkToTmp tmpDir thunkDir = readThunk thunkDir >>= \case
464− Left err -> failWith $ "thunk unpack: " <> (T.pack $ show err)
747+ Left err -> failWith $ "withThunkUnpacked: " <> T.pack (show err)
465− --TODO: Overwrite option that rechecks out thunk; force option to do so even if working directory is dirty
466− Right (ThunkData_Checkout _) -> failWith "thunk unpack: thunk is already unpacked"
467− Right (ThunkData_Packed tptr) -> case _thunkPtr_source tptr of
748+ Right ThunkData_Packed{} -> do
468− ThunkSource_GitHub s | (thunkParent, thunkName) <- splitFileName thunkDir -> withTempDirectory thunkParent thunkName $ \tmpRepo -> do
749+ let tmpThunk = tmpDir </> "thunk"
469− mauth <- liftIO $ getHubAuth "github.com"
470− repoResult <- liftIO $ executeRequestMaybe mauth $ repositoryR (_gitHubSource_owner s) (_gitHubSource_repo s)
471− githubURI <- liftIO $ either throwIO (return . repoSshUrl) repoResult >>= \case
472− Nothing -> fail "Cannot determine clone URI for thunk source"
473− Just c -> return $ T.unpack $ getUrl c
474− withSpinner ("Retrieving thunk " <> T.pack thunkName <> " from GitHub") $ do
475− callProcessAndLogOutput (Notice, Notice) $
476− proc "hub" ["clone", "-n", githubURI, tmpRepo]
477− let obGitDir = tmpRepo </> ".git" </> "obelisk"
478− --If this directory already exists then something is weird and we should fail
479− liftIO $ createDirectory obGitDir
480− callProcessAndLogOutput (Notice, Error) $
481− cp ["-r", "-T", thunkDir </> ".", obGitDir </> "orig-thunk"]
482− withSpinner ("Preparing thunk in " <> T.pack thunkDir) $ do
483− -- Checkout
484− putLog Notice $ "Checking out " <> T.pack (show $ maybe "" untagName $ _gitHubSource_branch s)
485− callProcessAndLogOutput (Notice, Notice) $
486− proc "hub" $ concat
487− [ ["-C", tmpRepo]
488− , pure "checkout"
489− , maybe [] (\n -> ["-B", T.unpack (untagName n)]) (_gitHubSource_branch s)
490− , pure $ Ref.toHexString $ _thunkRev_commit $ _thunkPtr_rev tptr
491− ]
492− -- Set upstream branch
493− forM_ (_gitHubSource_branch s) $ \branch ->
494− callProcessAndLogOutput (Notice, Error) $
495− proc "hub" ["-C", tmpRepo, "branch", "-u", "origin/" <> T.unpack (untagName branch)]
496 callProcessAndLogOutput (Notice, Error) $
750 callProcessAndLogOutput (Notice, Error) $
497− proc "rm" ["-r", thunkDir]
751+ proc cp ["-r", "-T", thunkDir, tmpThunk]
752+ return tmpThunk
753+ Right _ -> failWith "Thunk is not packed"
754+ updateThunkFromTmp p' = do
755+ _ <- packThunk' True (ThunkPackConfig False (ThunkConfig Nothing)) p'
498− callProcessAndLogOutput (Notice, Error) $
756+ callProcessAndLogOutput (Notice, Error) $
499− procWithPackages ["coreutils"] "mv"
757+ proc cp ["-r", "-T", p', p]
500− [ "-T"
758+
501− , tmpRepo
759+finalMsg :: Bool -> (a -> Text) -> Maybe (a -> Text)
760+finalMsg noTrail s = if noTrail then Nothing else Just s
761+
762+-- | Check that we are not somewhere inside the thunk directory
763+checkThunkDirectory :: MonadObelisk m => FilePath -> m ()
502− , thunkDir
764+checkThunkDirectory thunkDir = do
503− ]
765+ currentDir <- liftIO getCurrentDirectory
504− ThunkSource_Git _s -> do
766+ thunkDir' <- liftIO $ canonicalizePath thunkDir
505− $notImplemented
767+ when (thunkDir' `L.isInfixOf` currentDir) $
506−
768+ failWith [i|Can't perform thunk operations from within the thunk directory: ${thunkDir}|]
507−--TODO: add force mode to pack even if changes are present
769+
508−--TODO: add a rollback mode to pack to the original thunk
770+ -- Don't let thunk commands work when directly given an unpacked repo
509−packThunk
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
778+
779+unpackThunk' :: MonadObelisk m => Bool -> FilePath -> m ()
780+unpackThunk' noTrail thunkDir = checkThunkDirectory thunkDir *> readThunk thunkDir >>= \case
781+ Left err -> failWith [i|Invalid thunk at ${thunkDir}: ${err}|]
782+ --TODO: Overwrite option that rechecks out thunk; force option to do so even if working directory is dirty
783+ Right ThunkData_Checkout -> failWith [i|Thunk at ${thunkDir} is already unpacked|]
784+ Right (ThunkData_Packed _ tptr) -> do
785+ let (thunkParent, thunkName) = splitFileName thunkDir
786+ withTempDirectory thunkParent thunkName $ \tmpThunk -> do
787+ let
788+ gitSrc = thunkSourceToGitSource $ _thunkPtr_source tptr
789+ newSpec = case _thunkPtr_source tptr of
790+ ThunkSource_GitHub _ -> NonEmpty.head gitHubThunkSpecs
791+ ThunkSource_Git _ -> NonEmpty.head gitThunkSpecs
792+ withSpinner' ("Fetching thunk " <> T.pack thunkName)
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
510 :: MonadObelisk m
806 :: MonadObelisk m
807+ => GitSource -- ^ Git source to use
808+ -> Ref hash -- ^ Commit hash to reset to
511− => FilePath
809+ -> FilePath -- ^ Directory to clone into
512− -> String
513 -> m ()
810 -> m ()
514−packThunk thunkDir upstream = readThunk thunkDir >>= \case
811+gitCloneForThunkUnpack gitSrc commit dir = do
515− Left err -> failWith $ T.pack $ "thunk pack: " <> show err
812+ let git = callProcessAndLogOutput (Notice, Notice) . gitProc dir
813+ git $ [ "clone" ]
814+ ++ ["--recursive" | _gitSource_fetchSubmodules gitSrc]
815+ ++ [ T.unpack $ gitUriToText $ _gitSource_url gitSrc ]
816+ ++ do branch <- maybeToList $ _gitSource_branch gitSrc
817+ [ "--branch", T.unpack $ untagName branch ]
818+ git ["reset", "--hard", Ref.toHexString commit]
819+ when (_gitSource_fetchSubmodules gitSrc) $
820+ git ["submodule", "update", "--recursive", "--init"]
821+
822+--TODO: add a rollback mode to pack to the original thunk
823+packThunk :: MonadObelisk m => ThunkPackConfig -> FilePath -> m ThunkPtr
824+packThunk = packThunk' False
825+
826+packThunk' :: MonadObelisk m => Bool -> ThunkPackConfig -> FilePath -> m ThunkPtr
827+packThunk' noTrail (ThunkPackConfig force thunkConfig) thunkDir = checkThunkDirectory thunkDir *> readThunk thunkDir >>= \case
516− Right (ThunkData_Packed _) -> failWith "pack: thunk is already packed"
828+ Right ThunkData_Packed{} -> failWith [i|Thunk at ${thunkDir} is is already packed|]
517− Right (ThunkData_Checkout _) -> do
829+ _ -> withSpinner'
518− thunkPtr <- getThunkPtr thunkDir upstream
830+ ("Packing thunk " <> T.pack thunkDir)
519− liftIO $ callProcess "rm"
831+ (finalMsg noTrail $ const $ "Packed thunk " <> T.pack thunkDir) $
520− [ "-rf"
832+ do
521− , thunkDir
833+ let checkClean = if force then CheckClean_NoCheck else CheckClean_FullCheck
834+ thunkPtr <- modifyThunkPtrByConfig thunkConfig <$> getThunkPtr checkClean thunkDir (_thunkConfig_private thunkConfig)
835+ liftIO $ removePathForcibly thunkDir
836+ createThunk thunkDir $ Right thunkPtr
837+ pure thunkPtr
838+
839+modifyThunkPtrByConfig :: ThunkConfig -> ThunkPtr -> ThunkPtr
840+modifyThunkPtrByConfig (ThunkConfig markPrivate') ptr = case markPrivate' of
841+ Nothing -> ptr
842+ Just markPrivate -> ptr { _thunkPtr_source = case _thunkPtr_source ptr of
843+ ThunkSource_Git s -> ThunkSource_Git $ s { _gitSource_private = markPrivate }
844+ ThunkSource_GitHub s -> ThunkSource_GitHub $ s { _gitHubSource_private = markPrivate }
845+ }
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+
855+getThunkPtr :: forall m. MonadObelisk m => CheckClean -> FilePath -> Maybe Bool -> m ThunkPtr
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)
868+ when checkClean $ ensureCleanGitRepo thunkDir checkIgnored
869+ "thunk pack: thunk checkout contains unsaved modifications"
870+
871+ -- Check whether there are any stashes
872+ when checkClean $ do
873+ stashOutput <- readGitProcess thunkDir ["stash", "list"]
874+ unless (T.null stashOutput) $
875+ failWith $ T.unlines $
876+ [ "thunk pack: thunk checkout has stashes"
877+ , "git stash list:"
878+ ] ++ T.lines stashOutput
879+
880+ -- Get current branch
881+ (mCurrentBranch, mCurrentCommit) <- do
882+ b <- listToMaybe . T.lines <$> readGitProcess thunkDir ["rev-parse", "--abbrev-ref", "HEAD"]
883+ c <- listToMaybe . T.lines <$> readGitProcess thunkDir ["rev-parse", "HEAD"]
884+ case b of
885+ (Just "HEAD") -> failWith $ T.unlines
886+ [ "thunk pack: You are in 'detached HEAD' state."
887+ , "If you want to pack at the current ref \
888+ \then please create a new branch with 'git checkout -b <new-branch-name>' and push this upstream."
889+ ]
890+ _ -> return (b, c)
891+
892+ -- Get information on all branches and their (optional) designated upstream
893+ -- correspondents
894+ headDump :: [Text] <- T.lines <$> readGitProcess thunkDir
895+ [ "for-each-ref"
896+ , "--format=%(refname:short) %(upstream:short) %(upstream:remotename)"
897+ , "refs/heads/"
898+ ]
899+
900+ (headInfo :: Map Text (Maybe (Text, Text)))
901+ <- fmap Map.fromList $ forM headDump $ \line -> do
902+ (branch : restOfLine) <- pure $ T.words line
903+ mUpstream <- case restOfLine of
904+ [] -> pure Nothing
905+ [u, r] -> pure $ Just (u, r)
906+ (_:_) -> failWith "git for-each-ref invalid output"
907+ pure (branch, mUpstream)
908+
909+ putLog Debug $ "branches: " <> T.pack (show headInfo)
910+
911+ let errorMap :: Map Text ()
912+ headUpstream :: Map Text (Text, Text)
913+ (errorMap, headUpstream) = flip Map.mapEither headInfo $ \case
914+ Nothing -> Left ()
915+ Just b -> Right b
916+
917+ putLog Debug $ "branches with upstream branch set: " <> T.pack (show headUpstream)
918+
919+ -- Check that every branch has a remote equivalent
920+ when checkClean $ do
921+ let untrackedBranches = Map.keys errorMap
922+ when (not $ L.null untrackedBranches) $ failWith $ T.unlines $
923+ [ "thunk pack: Certain branches in the thunk have no upstream branch \
924+ \set. This means we don't know to check whether all your work is \
925+ \saved. The offending branches are:"
926+ , ""
927+ , T.unwords untrackedBranches
928+ , ""
929+ , "To fix this, you probably want to do:"
930+ , ""
931+ ] ++
932+ ((\branch -> "git push -u origin " <> branch) <$> untrackedBranches) ++
933+ [ ""
934+ , "These will push the branches to the default remote under the same \
935+ \name, and (thanks to the `-u`) remember that choice so you don't \
936+ \get this error again."
522 ]
937 ]
523− withSpinner ("Packing thunk " <> T.pack thunkDir) $
938+
524− liftIO $ createThunk thunkDir thunkPtr
939+ -- loosely by https://stackoverflow.com/questions/7773939/show-git-ahead-and-behind-info-for-all-branches-including-remotes
525−
940+ stats <- ifor headUpstream $ \branch (upstream, _remote) -> do
526−getThunkPtr :: MonadObelisk m => FilePath -> String -> m ThunkPtr
941+ (stat :: [Text]) <- T.lines <$> readGitProcess thunkDir
527−getThunkPtr thunkDir upstream = do
942+ [ "rev-list", "--left-right"
528− liftIO (checkGitCleanStatus thunkDir) >>= \case
943+ , T.unpack branch <> "..." <> T.unpack upstream
529− False -> do
944+ ]
530− statusDebug <- liftIO $ fmap (T.strip . T.pack) $ readProcess "hub"
945+ let ahead = length $ [ () | Just ('<', _) <- T.uncons <$> stat ]
531− [ "-C", thunkDir, "status", "--ignored" ] ""
946+ behind = length $ [ () | Just ('>', _) <- T.uncons <$> stat ]
532− putLog Warning "cannot proceed with unsaved working copy (git status):"
947+ pure (upstream, (ahead, behind))
533− putLog Notice statusDebug
948+
534− failWith "thunk pack: thunk checkout contains unsaved modifications"
949+ -- Those branches which have commits ahead of, i.e. not on, the upstream
535− True -> return ()
950+ -- branch. Purely being behind is fine.
536−
951+ let nonGood = Map.filter ((/= 0) . fst . snd) stats
537− -- Check whether there are any stashes
952+
538− stashOutput <- liftIO $ fmap T.pack $ readProcess "hub" [ "-C", thunkDir, "stash", "list" ] ""
539− case T.null stashOutput of
540− False -> do
541− failWith $ T.unlines $
953+ when (not $ Map.null nonGood) $ failWith $ T.unlines $
542− [ "thunk pack: thunk checkout has stashes"
954+ [ "thunk pack: Certain branches in the thunk have commits not yet pushed upstream:"
543− , "git stash list:"
955+ , ""
544− ] ++ T.lines stashOutput
956+ ] ++
545− True -> return ()
957+ flip map (Map.toList nonGood) (\(branch, (upstream, (ahead, behind))) -> mconcat
546−
958+ [" ", branch, " ahead: ", T.pack (show ahead), " behind: ", T.pack (show behind), " remote branch ", upstream]) ++
547− --Check whether all local heads are pushed
959+ [ ""
548− repoHeads <- liftIO $ lines <$> readProcess "hub"
960+ , "Please push these upstream and try again. (Or just fetch, if they are somehow \
549− [ "-C", thunkDir
961+ \pushed but this repo's remote tracking branches don't know it.)"
550− , "for-each-ref", "--format=%(refname:short)", "refs/heads/"
962+ ]
551− ] ""
963+
552− remotes <- liftIO $ lines <$> readProcess "hub" [ "-C", thunkDir, "remote" ] ""
964+ when checkClean $ do
553− --Check that the upstream specified actually exists
554− case L.find (== upstream) remotes of
555− Nothing -> failWith $ T.pack $ "thunk pack: upstream " <> upstream <> " does not exist. Available upstreams are " <> L.intercalate ", " remotes
556− Just _ -> return ()
557− -- iterate over cartesian product
558− forM_ repoHeads $ \hd -> do
559− [localRev] <- liftIO $ lines <$> readProcess "hub" [ "-C", thunkDir, "rev-parse", hd ] ""
560− forM_ remotes $ \rm -> do
561− --TODO: The error you get if a branch isn't pushed anywhere could be made more user friendly
562− [remoteMergeRev] <- liftIO $ lines <$> readProcess "hub"
563− [ "-C", thunkDir
564− , "merge-base"
565− , localRev
566− , "remotes/" <> rm <> "/" <> hd
567− ] ""
568− case remoteMergeRev == localRev of
569− False -> failWith $ T.pack $ mconcat [ "thunk unpack: branch ", hd, " has not been pushed to ", rm ]
570− True -> return ()
571−
572− --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
573− [remoteUri'] <- liftIO $ lines <$> readProcess "hub"
966+ putLog Informational "All changes safe in git remotes. OK to pack thunk."
574− [ "-C", thunkDir
967+
575− , "config", "--get", "remote." <> upstream <> ".url"
968+ let remote = maybe "origin" snd $ flip Map.lookup headUpstream =<< mCurrentBranch
969+
970+ [remoteUri'] <- fmap T.lines $ readGitProcess thunkDir
971+ [ "config"
972+ , "--get"
973+ , "remote." <> T.unpack remote <> ".url"
576− ] ""
974+ ]
577−
975+
976+ remoteUri <- case parseGitUri remoteUri' of
578− let uriParseFailure = "Could not identify git remote: " <> remoteUri'
977+ Nothing -> failWith $ "Could not identify git remote: " <> remoteUri'
579− mRemoteUri = parseURIReference remoteUri'
978+ Just uri -> pure uri
580− <|> parseSshShorthand remoteUri'
979+ uriThunkPtr remoteUri mPrivate mCurrentBranch mCurrentCommit
581− case mRemoteUri of
980+
582− Nothing -> failWith $ T.pack uriParseFailure
981+-- | Get the latest revision available from the given source
583− Just remoteUri -> liftIO $ do
982+getLatestRev :: MonadObelisk m => ThunkSource -> m ThunkRev
584− refs <- fmap (refsToTuples . words) . lines <$> readProcess "hub"
983+getLatestRev os = do
585− [ "-C"
984+ let gitS = thunkSourceToGitSource os
586− , thunkDir
985+ (_, commit) <- gitGetCommitBranch (_gitSource_url gitS) (untagName <$> _gitSource_branch gitS)
587− , "show-ref"
986+ case os of
588− , "--head" ] ""
987+ ThunkSource_GitHub s -> githubThunkRev s commit
589− -- safe because exactly one hash is associated with HEAD
988+ ThunkSource_Git s -> gitThunkRev s commit
590− let Just currentHead = fst <$> L.find ((== "HEAD") . snd) refs
989+
591− remoteHeads = Map.fromList $ catMaybes $ fmap
990+-- | Convert a URI to a thunk
592− (\(x,y) -> (,) x <$> L.stripPrefix ("refs/remotes/" <> upstream <> "/") y)
991+--
593− refs
992+-- If the URL is a github URL, we try to just download an archive for
594− localHeads = Map.fromList $ catMaybes $ fmap
993+-- performance. If that doesn't work (e.g. authentication issue), we fall back
595− (\(x,y) -> (,) x <$> L.stripPrefix "refs/heads/" y)
994+-- on just doing things the normal way for git repos in general, and save it as
596− refs
995+-- a regular git thunk.
597− currentUpstreamBranch = Map.lookup currentHead remoteHeads
996+uriThunkPtr :: MonadObelisk m => GitUri -> Maybe Bool -> Maybe Text -> Maybe Text -> m ThunkPtr
598− <|> Map.lookup currentHead localHeads
997+uriThunkPtr uri mPrivate mbranch mcommit = do
599− if
998+ commit <- case mcommit of
600− | isGithubThunk remoteUri -> githubThunkPtr remoteUri currentHead currentUpstreamBranch
999+ Nothing -> gitGetCommitBranch uri mbranch >>= return . snd
601− | otherwise -> gitThunkPtr remoteUri currentHead currentUpstreamBranch
1000+ (Just c) -> return c
602− where
1001+ (src, rev) <- uriToThunkSource uri mPrivate mbranch >>= \case
603− refsToTuples [x, y] = (x, y)
1002+ ThunkSource_GitHub s -> do
604− refsToTuples x = error $ "thunk pack: cannot parse ref " <> show x
1003+ rev <- runExceptT $ githubThunkRev s commit
605− isGithubThunk u
1004+ case rev of
1005+ Right r -> pure (ThunkSource_GitHub s, r)
1006+ Left e -> do
1007+ putLog Warning "\
1008+\Failed to fetch archive from GitHub. This is probably a private repo. \
1009+\Falling back on normal fetchgit. Original failure:"
1010+ errorToWarning e
1011+ let s' = forgetGithub True s
1012+ (,) (ThunkSource_Git s') <$> gitThunkRev s' commit
1013+ ThunkSource_Git s -> (,) (ThunkSource_Git s) <$> gitThunkRev s commit
1014+ pure $ ThunkPtr
1015+ { _thunkPtr_rev = rev
1016+ , _thunkPtr_source = src
1017+ }
1018+
1019+-- | N.B. Cannot infer all fields.
1020+--
1021+-- If the thunk is a GitHub thunk and fails, we do *not* fall back like with
1022+-- `uriThunkPtr`. Unlike a plain URL, a thunk src explicitly states which method
1023+-- should be employed, and so we respect that.
1024+uriToThunkSource :: MonadObelisk m => GitUri -> Maybe Bool -> Maybe Text -> m ThunkSource
1025+uriToThunkSource (GitUri u) mPrivate
606− | Just uriAuth <- uriAuthority u
1026+ | Right uriAuth <- URI.uriAuthority u
607− = case uriScheme u of
1027+ , Just scheme <- URI.unRText <$> URI.uriScheme u
608− "ssh:" -> uriAuth == URIAuth "git@" "github.com" ""
1028+ , case scheme of
609− s -> s `L.elem` [ "git:", "https:", "http:" ] -- "http:" just redirects to "https:"
1029+ "ssh" -> uriAuth == URI.Authority
610− && uriRegName uriAuth == "github.com"
1030+ { URI.authUserInfo = Just $ URI.UserInfo (fromRight' $ URI.mkUsername "git") Nothing
611− | otherwise = False
1031+ , URI.authHost = fromRight' $ URI.mkHost "github.com"
612− githubThunkPtr u commit' branch' = do
1032+ , URI.authPort = Nothing
613− ["/", owner', repo'] <- return $ splitDirectories (uriPath u)
614− let owner = N (T.pack owner')
615− repo = N (T.pack (dropExtension repo'))
616− commit = N (T.pack commit')
617− branch = N . T.pack <$> branch'
618− mauth <- getHubAuth "github.com"
619− repoResult <- executeRequestMaybe mauth $ repositoryR owner repo
620− repoIsPrivate <- either throwIO (return . repoPrivate) repoResult
621− archiveResult <- executeRequestMaybe mauth $
622− archiveForR owner repo ArchiveFormatTarball (Just (untagName commit))
623− archiveUri <- either throwIO return archiveResult
624− hash <- getNixSha256ForUriUnpacked archiveUri
625− return $ ThunkPtr
626− { _thunkPtr_rev = ThunkRev
627− { _thunkRev_commit = commitNameToRef commit
628− , _thunkRev_nixSha256 = hash
629 }
1033 }
1034+ s -> s `L.elem` [ "git", "https", "http" ] -- "http:" just redirects to "https:"
1035+ && URI.unRText (URI.authHost uriAuth) == "github.com"
1036+ , Just (_, owner :| [repoish]) <- URI.uriPath u
1037+ = \mbranch -> do
1038+ isPrivate <- getIsPrivate
630− , _thunkPtr_source = ThunkSource_GitHub $ GitHubSource
1039+ pure $ ThunkSource_GitHub $ GitHubSource
631− { _gitHubSource_owner = owner
1040+ { _gitHubSource_owner = N $ URI.unRText owner
632− , _gitHubSource_repo = repo
1041+ , _gitHubSource_repo = N $ let
1042+ repoish' = URI.unRText repoish
1043+ in fromMaybe repoish' $ T.stripSuffix ".git" repoish'
633− , _gitHubSource_branch = branch
1044+ , _gitHubSource_branch = N <$> mbranch
634− , _gitHubSource_private = repoIsPrivate
1045+ , _gitHubSource_private = isPrivate
635 }
1046 }
1047+
1048+ | otherwise = \mbranch -> do
1049+ isPrivate <- getIsPrivate
1050+ pure $ ThunkSource_Git $ GitSource
1051+ { _gitSource_url = GitUri u
1052+ , _gitSource_branch = N <$> mbranch
1053+ , _gitSource_fetchSubmodules = False -- TODO: How do we determine if this should be true?
1054+ , _gitSource_private = isPrivate
1055+ }
1056+ where
1057+ getIsPrivate = maybe (guessGitRepoIsPrivate $ GitUri u) pure mPrivate
1058+
1059+guessGitRepoIsPrivate :: MonadObelisk m => GitUri -> m Bool
1060+guessGitRepoIsPrivate uri = flip fix urisToTry $ \loop -> \case
1061+ [] -> pure True
1062+ uriAttempt:xs -> do
1063+ result <- readCreateProcessWithExitCode $
1064+ isolateGitProc $
1065+ gitProcNoRepo
1066+ [ "ls-remote"
1067+ , "--quiet"
1068+ , "--exit-code"
1069+ , "--symref"
1070+ , T.unpack $ gitUriToText uriAttempt
1071+ ]
1072+ case result of
1073+ (ExitSuccess, _, _) -> pure False -- Must be a public repo
1074+ _ -> loop xs
1075+ where
1076+ urisToTry = nubOrd $
1077+ -- Include the original URI if it isn't using SSH because SSH will certainly fail.
1078+ [uri | fmap URI.unRText (URI.uriScheme (unGitUri uri)) /= Just "ssh"] <>
1079+ [changeScheme "https" uri, changeScheme "http" uri]
1080+ changeScheme scheme (GitUri u) = GitUri $ u
1081+ { URI.uriScheme = URI.mkScheme scheme
1082+ , URI.uriAuthority = (\x -> x { URI.authUserInfo = Nothing }) <$> URI.uriAuthority u
636 }
1083 }
637− gitThunkPtr u _commit' _branch' = do
1084+
638− case uriScheme u of
1085+-- Funny signature indicates no effects depend on the optional branch name.
639− "https:" -> return ()
1086+githubThunkRev
1087+ :: forall m
1088+ . MonadObelisk m
1089+ => GitHubSource
1090+ -> Text
1091+ -> m ThunkRev
1092+githubThunkRev s commit = do
1093+ owner <- forcePP $ _gitHubSource_owner s
1094+ repo <- forcePP $ _gitHubSource_repo s
1095+ revTarball <- URI.mkPathPiece $ commit <> ".tar.gz"
1096+ let archiveUri = GitUri $ URI.URI
1097+ { URI.uriScheme = Just $ fromRight' $ URI.mkScheme "https"
1098+ , URI.uriAuthority = Right $ URI.Authority
1099+ { URI.authUserInfo = Nothing
1100+ , URI.authHost = fromRight' $ URI.mkHost "github.com"
1101+ , URI.authPort = Nothing
1102+ }
1103+ , URI.uriPath = Just ( False
1104+ , owner :| [ repo, fromRight' $ URI.mkPathPiece "archive", revTarball ]
1105+ )
1106+ , URI.uriQuery = []
1107+ , URI.uriFragment = Nothing
1108+ }
1109+ hash <- getNixSha256ForUriUnpacked archiveUri
1110+ putLog Debug $ "Nix sha256 is " <> hash
640− "git:" -> return ()
1111+ return $ ThunkRev
1112+ { _thunkRev_commit = commitNameToRef $ N commit
1113+ , _thunkRev_nixSha256 = hash
1114+ }
1115+ where
1116+ forcePP :: Name entity -> m (URI.RText 'URI.PathPiece)
1117+ forcePP = URI.mkPathPiece . untagName
1118+
1119+gitThunkRev
1120+ :: MonadObelisk m
1121+ => GitSource
1122+ -> Text
1123+ -> m ThunkRev
1124+gitThunkRev s commit = do
1125+ let u = _gitSource_url s
1126+ protocols = ["file", "https", "ssh", "git"]
1127+ scheme = maybe "file" URI.unRText $ URI.uriScheme $ (\(GitUri x) -> x) u
1128+ unless (T.toLower scheme `elem` protocols) $
641− _ -> fail "thunk pack: obelisk currently only supports https and git protocols for non-GitHub remotes"
1129+ failWith $ "obelisk currently only supports "
642− $notImplemented
1130+ <> T.intercalate ", " protocols <> " protocols for plain Git remotes"
643− parseSshShorthand uri' = do
1131+ hash <- nixPrefetchGit u commit $ _gitSource_fetchSubmodules s
1132+ putLog Informational $ "Nix sha256 is " <> hash
1133+ pure $ ThunkRev
1134+ { _thunkRev_commit = commitNameToRef (N commit)
1135+ , _thunkRev_nixSha256 = hash
1136+ }
1137+
1138+-- | Given the URI to a git remote, and an optional branch name, return the name
1139+-- of the branch along with the hash of the commit at tip of that branch.
1140+--
1141+-- If the branch name is passed in, it is returned exactly as-is. If it is not
1142+-- passed it, the default branch of the repo is used instead.
1143+
1144+gitGetCommitBranch
1145+ :: MonadObelisk m => GitUri -> Maybe Text -> m (Text, CommitId)
1146+gitGetCommitBranch uri mbranch = withExitFailMessage ("Failure for git remote " <> uriMsg) $ do
1147+ (_, bothMaps) <- gitLsRemote
1148+ (T.unpack $ gitUriToText uri)
1149+ (GitRef_Branch <$> mbranch)
1150+ Nothing
1151+ branch <- case mbranch of
1152+ Nothing -> withExitFailMessage "Failed to find default branch" $ do
1153+ b <- rethrowE $ gitLookupDefaultBranch bothMaps
1154+ putLog Debug $ "Default branch for remote repo " <> uriMsg <> " is " <> b
1155+ pure b
1156+ Just b -> pure b
1157+ commit <- rethrowE $ gitLookupCommitForRef bothMaps (GitRef_Branch branch)
1158+ putLog Informational $ "Latest commit in branch " <> branch
1159+ <> " from remote repo " <> uriMsg
1160+ <> " is " <> commit
1161+ pure (branch, commit)
1162+ where
1163+ rethrowE = either failWith pure
1164+ uriMsg = gitUriToText uri
1165+
1166+parseGitUri :: Text -> Maybe GitUri
1167+parseGitUri x = GitUri <$> (parseFileURI x <|> parseAbsoluteURI x <|> parseSshShorthand x)
1168+
1169+parseFileURI :: Text -> Maybe URI.URI
1170+parseFileURI uri = if "/" `T.isPrefixOf` uri then parseAbsoluteURI ("file://" <> uri) else Nothing
1171+
1172+parseAbsoluteURI :: Text -> Maybe URI.URI
1173+parseAbsoluteURI uri = do
1174+ parsedUri <- URI.mkURI uri
1175+ guard $ URI.isPathAbsolute parsedUri
1176+ pure parsedUri
1177+
1178+parseSshShorthand :: Text -> Maybe URI.URI
1179+parseSshShorthand uri = do
644− -- This is what git does to check that the remote
1180+ -- This is what git does to check that the remote
645− -- is not a local file path when parsing shorthand.
1181+ -- is not a local file path when parsing shorthand.
646− -- Last referenced from here:
1182+ -- Last referenced from here:
647− -- https://github.com/git/git/blob/95ec6b1b3393eb6e26da40c565520a8db9796e9f/connect.c#L712
1183+ -- https://github.com/git/git/blob/95ec6b1b3393eb6e26da40c565520a8db9796e9f/connect.c#L712
648− let uri = T.pack uri'
1184+ let
649− (authAndHostname, colonAndPath) = T.break (== ':') uri
1185+ (authAndHostname, colonAndPath) = T.break (== ':') uri
650− properUri = "ssh://" <> authAndHostname <> "/" <> T.drop 1 colonAndPath
1186+ properUri = "ssh://" <> authAndHostname <> "/" <> T.drop 1 colonAndPath
651− -- Shorthand is valid iff a colon is present and it occurs before the first slash
1187+ -- Shorthand is valid iff a colon is present and it occurs before the first slash
652− -- This check is used to disambiguate a filepath containing a colon from shorthand
1188+ -- This check is used to disambiguate a filepath containing a colon from shorthand
653− guard $ isNothing (T.findIndex (=='/') authAndHostname)
1189+ guard $ isNothing (T.findIndex (=='/') authAndHostname)
654− && not (T.null colonAndPath)
1190+ && not (T.null colonAndPath)
655− parseURI $ T.unpack properUri
1191+ URI.mkURI properUri
lib/command/src/Obelisk/Command/Utils.hs+247−20
@@ -1,34 +1,261 @@
1{-# LANGUAGE FlexibleContexts #-}
1{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE MultiWayIf #-}
4+{-# LANGUAGE ScopedTypeVariables #-}
2{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE PatternGuards #-}
7+{-# LANGUAGE TemplateHaskell #-}
3module Obelisk.Command.Utils where
8module Obelisk.Command.Utils where
4
9
10+import Control.Applicative hiding (many)
11+import Control.Monad.Except
12+import Data.Bool (bool)
13+import Data.Bifunctor
14+import Data.Char
15+import Data.Either
16+import Data.List (isInfixOf)
17+import Data.Map (Map)
18+import qualified Data.Map as M
19+import Data.Maybe (maybeToList)
5import Data.Semigroup ((<>))
20import Data.Semigroup ((<>))
21+import Data.Text (Text)
6import qualified Data.Text as T
22import qualified Data.Text as T
7−import System.Process (CreateProcess, callProcess, proc, readProcess)
23+import Data.Void (Void)
24+import System.Exit (ExitCode)
25+import System.Which (staticWhich)
26+import qualified Text.Megaparsec.Char.Lexer as ML
27+import Text.Megaparsec as MP
28+import Text.Megaparsec.Char as MP
29+
30+import Obelisk.App (MonadObelisk)
31+import Obelisk.CliApp
32+
33+cp :: FilePath
34+cp = $(staticWhich "cp")
35+
36+mvPath :: FilePath
37+mvPath = $(staticWhich "mv")
38+
39+rmPath :: FilePath
40+rmPath = $(staticWhich "rm")
41+
42+ghcidExePath :: FilePath
43+ghcidExePath = $(staticWhich "ghcid")
44+
45+findExePath :: FilePath
46+findExePath = $(staticWhich "find")
47+
48+nixExePath :: FilePath
49+nixExePath = $(staticWhich "nix")
50+
51+nixBuildExePath :: FilePath
52+nixBuildExePath = $(staticWhich "nix-build")
53+
54+jreKeyToolPath :: FilePath
55+jreKeyToolPath = $(staticWhich "keytool")
56+
57+nixPrefetchGitPath :: FilePath
58+nixPrefetchGitPath = $(staticWhich "nix-prefetch-git")
59+
60+nixPrefetchUrlPath :: FilePath
61+nixPrefetchUrlPath = $(staticWhich "nix-prefetch-url")
62+
63+nixShellPath :: FilePath
64+nixShellPath = $(staticWhich "nix-shell")
65+
66+rsyncPath :: FilePath
67+rsyncPath = $(staticWhich "rsync")
68+
69+sshPath :: FilePath
70+sshPath = $(staticWhich "ssh")
71+
72+gitPath :: FilePath
73+gitPath = $(staticWhich "git")
74+
75+whichPath :: FilePath
76+whichPath = $(staticWhich "which")
77+
78+sshKeygenPath :: FilePath
79+sshKeygenPath = $(staticWhich "ssh-keygen")
80+
81+-- $(staticWhich "docker") was intentionally omitted, at least for now
82+-- One concern is that I don't know how particular docker is about having the
83+-- CLI exe match the version of the docker daemon, which is largely outside of
84+-- the control of obelisk-command.
85+-- TODO: Investigate the tradeoffs associated with this choice
86+dockerPath :: FilePath
87+dockerPath = "docker"
88+
89+-- | Nix syntax requires relative paths to be prefixed by @./@ or
90+-- @../@. This will make a 'FilePath' that can be embedded in a Nix
91+-- expression.
92+toNixPath :: FilePath -> FilePath
93+toNixPath root | "/" `isInfixOf` root = root
94+ | otherwise = "./" <> root
95+
8
96
9-- Check whether the working directory is clean
97-- Check whether the working directory is clean
10−checkGitCleanStatus :: FilePath -> IO Bool
98+checkGitCleanStatus :: MonadObelisk m => FilePath -> Bool -> m Bool
11−checkGitCleanStatus fp = do
99+checkGitCleanStatus repo withIgnored = do
12− statusOutput <- readProcess "hub"
100+ let
13− [ "-C", fp
101+ runGit = readProcessAndLogStderr Debug . gitProc repo
14− , "status", "--porcelain", "--ignored" ] ""
102+ gitStatus = runGit $ ["status", "--porcelain"] <> bool [] ["--ignored"] withIgnored
15− diffOutput <- readProcess "hub" [ "-C", fp , "diff" ] ""
103+ gitDiff = runGit ["diff"]
16− return $ null statusOutput && null diffOutput
104+ T.null <$> liftA2 (<>) gitStatus gitDiff
17−
105+
106+-- | Ensure that git repo is clean
107+ensureCleanGitRepo :: MonadObelisk m => FilePath -> Bool -> Text -> m ()
108+ensureCleanGitRepo path withIgnored s =
109+ withSpinnerNoTrail ("Ensuring clean git repo at " <> T.pack path) $ do
110+ checkGitCleanStatus path withIgnored >>= \case
111+ False -> do
112+ statusDebug <- readGitProcess path $ ["status"] <> bool [] ["--ignored"] withIgnored
113+ putLog Warning "Working copy is unsaved; git status:"
114+ putLog Notice statusDebug
115+ failWith s
116+ True -> pure ()
117+
18−initGit :: FilePath -> IO ()
118+initGit :: MonadObelisk m => FilePath -> m ()
19−initGit dir = do
119+initGit repo = do
20− let git args = callProcess "git" $ "-C" : dir : args
120+ let git = callProcessAndLogOutput (Debug, Debug) . gitProc repo
21 git ["init"]
121 git ["init"]
22 git ["add", "."]
122 git ["add", "."]
23 git ["commit", "-m", "Initial commit."]
123 git ["commit", "-m", "Initial commit."]
24
124
25−-- | Like `System.Process.proc` but with the specified Nix packages installed
125+gitProcNoRepo :: [String] -> ProcessSpec
26−procWithPackages :: [String] -> FilePath -> [String] -> CreateProcess
126+gitProcNoRepo args = setEnvOverride (M.singleton "GIT_TERMINAL_PROMPT" "0" <>) $ proc gitPath args
27−procWithPackages pkgs cmd args = proc "nix-shell" $
127+
28− "-p" : pkgs <> ["--run", unwords $ cmd : map quoteAndEscape args]
128+gitProc :: FilePath -> [String] -> ProcessSpec
129+gitProc repo = gitProcNoRepo . runGitInDir
130+ where
131+ runGitInDir args' = case filter (not . null) args' of
132+ args@("clone":_) -> args <> [repo]
133+ args -> ["-C", repo] <> args
134+
135+isolateGitProc :: ProcessSpec -> ProcessSpec
136+isolateGitProc = setEnvOverride (overrides <>)
29 where
137 where
138+ overrides = M.fromList
139+ [ ("HOME", "/dev/null")
140+ , ("GIT_CONFIG_NOSYSTEM", "1")
141+ , ("GIT_TERMINAL_PROMPT", "0") -- git 2.3+
142+ , ("GIT_ASKPASS", "echo") -- pre git 2.3 to just use empty password
143+ , ("GIT_SSH_COMMAND", "ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -o GSSAPIAuthentication=no")
144+ ]
145+
146+-- | Recursively copy a directory using `cp -a` -- TODO: Should use -rT instead of -a
147+copyDir :: FilePath -> FilePath -> ProcessSpec
148+copyDir src dest =
149+ setCwd (Just src) $ proc cp ["-a", ".", dest] -- TODO: This will break if dest is relative since we change cwd
150+
151+readGitProcess :: MonadObelisk m => FilePath -> [String] -> m Text
152+readGitProcess repo = readProcessAndLogOutput (Debug, Notice) . gitProc repo
153+
154+readGitProcessNoRepo :: MonadObelisk m => [String] -> m Text
155+readGitProcessNoRepo = readProcessAndLogOutput (Debug, Notice) . gitProcNoRepo
156+
157+processToShellString :: FilePath -> [String] -> String
158+processToShellString cmd args = unwords $ map quoteAndEscape (cmd : args)
30− quoteAndEscape x = T.unpack $ "'" <> T.replace "'" "'\''" (T.pack x) <> "'"
159+ where quoteAndEscape x = T.unpack $ "'" <> T.replace "'" "'\''" (T.pack x) <> "'"
160+
161+-- | A simpler wrapper for CliApp's most used process function with sensible defaults.
162+runProc :: MonadObelisk m => ProcessSpec -> m ()
163+runProc = callProcessAndLogOutput (Notice, Error)
164+
165+-- | Like runProc, but all output goes to Debug logging level
166+runProcSilently :: MonadObelisk m => ProcessSpec -> m ()
167+runProcSilently = callProcessAndLogOutput (Debug, Debug)
168+
169+-- | A simpler wrapper for CliApp's readProcessAndLogStderr with sensible defaults.
170+readProc :: MonadObelisk m => ProcessSpec -> m Text
171+readProc = readProcessAndLogOutput (Debug, Error)
172+
173+tshow :: Show a => a -> Text
174+tshow = T.pack . show
175+
176+gitLookupDefaultBranch :: GitLsRemoteMaps -> Either Text Text
177+gitLookupDefaultBranch (refs, _) = do
178+ ref <- case M.lookup GitRef_Head refs of
179+ Just ref -> pure ref
180+ Nothing -> throwError
181+ "No symref entry for HEAD. \
182+ \ Is your git version at least 1.8.5? \
183+ \ Otherwise `git ls-remote --symref` will not work."
184+ case ref of
185+ GitRef_Branch b -> pure b
186+ _ -> throwError $
187+ "Default ref " <> showGitRef ref <> " is not a branch!"
188+
189+gitLookupCommitForRef :: GitLsRemoteMaps -> GitRef -> Either Text CommitId
190+gitLookupCommitForRef (_, commits) ref = case M.lookup ref commits of
191+ Just a -> pure a
192+ Nothing -> throwError $ "Did not find commit for " <> showGitRef ref
193+
194+gitLsRemote
195+ :: MonadObelisk m
196+ => String
197+ -> Maybe GitRef
198+ -> Maybe String
199+ -> m (ExitCode, GitLsRemoteMaps)
200+gitLsRemote repository mRef mBranch = do
201+ (exitCode, out, _err) <- case mBranch of
202+ Nothing -> readCreateProcessWithExitCode $ gitProcNoRepo $
203+ ["ls-remote", "--exit-code", "--symref", repository]
204+ ++ maybeToList (T.unpack . showGitRef <$> mRef)
205+ Just branchName -> readCreateProcessWithExitCode $ gitProcNoRepo
206+ ["ls-remote", "--exit-code", repository, branchName]
207+ let t = T.pack out
208+ maps <- case MP.runParser parseLsRemote "" t of
209+ Left err -> failWith $ T.pack $ MP.errorBundlePretty err
210+ Right table -> pure $ bimap M.fromList M.fromList $ partitionEithers table
211+ putLog Debug $ "git ls-remote maps: " <> T.pack (show maps)
212+ pure (exitCode, maps)
213+
214+lexeme :: Parsec Void Text a -> Parsec Void Text a
215+lexeme = ML.lexeme $ void $ MP.takeWhileP (Just "within-line white space") $
216+ flip elem [' ', '\t']
217+
218+-- $ git ls-remote --symref git@github.com:obsidiansystems/obelisk.git HEAD
219+-- ref: refs/heads/master HEAD
220+-- d0a8d25dc93f0acd096bc4ff2f550da9e2d0c8f5 refs/heads/master
221+parseLsRemote :: Parsec Void Text [Either (GitRef, GitRef) (GitRef, CommitId)]
222+parseLsRemote =
223+ many ((fmap Left (try parseRef) <|> fmap Right parseCommit) <* try MP.eol) <* MP.eof
224+ where
225+ parseRef :: Parsec Void Text (GitRef, GitRef)
226+ parseRef = MP.label "ref and symbolic ref" $ do
227+ _ <- lexeme "ref:"
228+ ref <- lexeme $ MP.takeWhileP (Just "ref") $ not . isSpace
229+ symbolicRef <- lexeme $ MP.takeWhileP (Just "symbolic ref") $ not . isSpace
230+ return (toGitRef symbolicRef, toGitRef ref)
231+ parseCommit :: Parsec Void Text (GitRef, CommitId)
232+ parseCommit = MP.label "commit and ref" $ do
233+ commitId <- lexeme $ MP.takeWhileP (Just "commit id") $ not . isSpace
234+ ref <- lexeme $ MP.takeWhileP (Just "ref") $ not . isSpace
235+ return (toGitRef ref, commitId)
236+
237+data GitRef
238+ = GitRef_Head
239+ | GitRef_Branch Text
240+ | GitRef_Tag Text
241+ | GitRef_Other Text
242+ deriving (Show, Eq, Ord)
243+
244+showGitRef :: GitRef -> Text
245+showGitRef = \case
246+ GitRef_Head -> "HEAD"
247+ GitRef_Branch x -> "refs/heads/" <> x
248+ GitRef_Tag x -> "refs/tags/" <> x
249+ GitRef_Other x -> x
250+
251+toGitRef :: Text -> GitRef
252+toGitRef = \case
253+ "HEAD" -> GitRef_Head
254+ r -> if
255+ | Just s <- "refs/heads/" `T.stripPrefix` r -> GitRef_Branch s
256+ | Just s <- "refs/tags/" `T.stripPrefix` r -> GitRef_Tag s
257+ | otherwise -> GitRef_Other r
258+
259+type CommitId = Text
31
260
32−-- | Portable `cp` command
261+type GitLsRemoteMaps = (Map GitRef GitRef, Map GitRef CommitId)
33−cp :: [String] -> CreateProcess
34−cp = procWithPackages ["coreutils"] "cp"
lib/command/src/Obelisk/Command/VmBuilder.hsnew file+202
@@ -0,0 +1,202 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+{-# LANGUAGE QuasiQuotes #-}
4+{-# LANGUAGE ScopedTypeVariables #-}
5+module Obelisk.Command.VmBuilder where
6+
7+import Control.Applicative (liftA2)
8+import Control.Monad (when, unless)
9+import Control.Monad.Catch (handle)
10+import Control.Monad.IO.Class (liftIO)
11+import Data.Monoid ((<>))
12+import Data.String (IsString)
13+import Data.String.Here.Uninterpolated (hereLit)
14+import Data.Text (Text)
15+import qualified Data.Text as T
16+import qualified Data.Text.IO as T
17+import System.Directory (createDirectoryIfMissing)
18+import System.Exit (ExitCode(..))
19+import System.FilePath ((<.>), (</>))
20+import qualified System.Info
21+
22+import Obelisk.App (MonadObelisk, getObeliskUserStateDir)
23+import Obelisk.CliApp
24+import Obelisk.Command.Utils (rmPath, whichPath, sshKeygenPath, nixBuildExePath, dockerPath)
25+
26+-- | Generate the `--builders` argument string to enable the VM builder after ensuring it is available.
27+getNixBuildersArg :: MonadObelisk m => m String
28+getNixBuildersArg = do
29+ stateDir <- liftIO getDockerBuilderStateDir
30+ let sshIdFile = stateDir </> sshKeyFileName
31+ checkForNixDarwin sshIdFile
32+ exists <- containerExists stateDir
33+ if exists then startContainer else setupNixDocker stateDir
34+ pure $ nixBuildersArgString stateDir
35+
36+checkForNixDarwin :: MonadObelisk m => String -> m ()
37+checkForNixDarwin sshIdFile = do
38+ (exitCode, _, _) <- readCreateProcessWithExitCode $ proc whichPath ["darwin-rebuild"]
39+ unless (exitCode == ExitSuccess) $ failWith $ T.intercalate "\n"
40+ [ "Deployments from macOS require nix-darwin to be installed."
41+ , "Follow the installation instructions here: https://github.com/LnL7/nix-darwin"
42+ , "You'll also need to add the following to your 'configuration.nix' and run 'darwin-rebuild switch':"
43+ , ""
44+ , T.intercalate "\n" $ map (" " <>)
45+ [ "nix.distributedBuilds = true;"
46+ , "nix.buildMachines = [{"
47+ , " hostName = " <> T.pack (show (containerName :: String)) <> ";"
48+ , " sshUser = \"root\";"
49+ , " sshKey = " <> T.pack (show sshIdFile) <> ";"
50+ , " sshPort = " <> T.pack (show containerSshPort) <> ";"
51+ , " systems = [ \"x86_64-linux\" ];"
52+ , " maxJobs = 2;"
53+ , "}];"
54+ ]
55+ ]
56+
57+-- | String to pass to nix's `--builders` arguments to enable the VM builder.
58+nixBuildersArgString :: FilePath -> String
59+nixBuildersArgString stateDir = unwords [containerName, "x86_64-linux", stateDir </> sshKeyFileName, "1", "1", "kvm"]
60+
61+-- | Name of Docker container used for the VM builder.
62+containerName :: IsString str => str
63+containerName = "obelisk-docker-nix-builder"
64+
65+-- | Check to see if the Docker container exists. This will exit with a helpful message if Docker is not installed.
66+containerExists :: MonadObelisk m => FilePath -> m Bool
67+containerExists stateDir = handle (\(_ :: IOError) -> failWith needDockerMsg) $ do
68+ containerNames <- fmap (map T.strip . T.lines) $
69+ readProcessAndLogStderr Error $
70+ proc dockerPath ["container", "list", "--all", "--format", "{{.Names}}"]
71+ let exists = containerName `elem` containerNames
72+ when exists $ testLinuxBuild stateDir
73+ pure exists
74+ where
75+ needDockerMsg = T.intercalate "\n"
76+ [ "This feature requires that you have Docker installed and the `docker` command available on your PATH."
77+ , "Please go https://docs.docker.com/ to install Docker and try this command again."
78+ ]
79+
80+-- | SSH port on localhost that connects to the container.
81+containerSshPort :: Int
82+containerSshPort = 2222
83+
84+-- | Start the Docker container; assumes it already exists.
85+startContainer :: MonadObelisk m => m ()
86+startContainer = withSpinner "Starting VM builder" $
87+ callProcessAndLogOutput (Debug, Debug) $
88+ proc dockerPath ["start", containerName]
89+
90+-- | Creates the Docker container; assumes it does not exist.
91+setupNixDocker :: MonadObelisk m => FilePath -> m ()
92+setupNixDocker stateDir = withSpinner ("Creating Docker container named " <> containerName) $ do
93+ liftIO $ do
94+ createDirectoryIfMissing True stateDir
95+ T.writeFile (stateDir </> "Dockerfile") dockerfile
96+
97+ -- Create new SSH keys for this container
98+ callProcessAndLogOutput (Debug, Error) $
99+ proc rmPath ["-f", stateDir </> sshKeyFileName, stateDir </> sshKeyFileName <.> "pub"]
100+ callProcessAndLogOutput (Debug, Error) $
101+ proc sshKeygenPath ["-t", "ed25519", "-f", stateDir </> sshKeyFileName, "-P", ""]
102+
103+ -- Build the docker container (which uses the SSH keys in the 'ssh' folder)
104+ containerId <- fmap T.strip $ readProcessAndLogStderr Error $
105+ proc dockerPath ["build", stateDir, "--quiet"]
106+ callProcessAndLogOutput (Debug, Error) $ proc dockerPath
107+ [ "run"
108+ , "--restart", "always"
109+ , "--detach"
110+ , "--publish", show containerSshPort <> ":22"
111+ , "--name", T.unpack containerName, T.unpack containerId
112+ ]
113+ exists <- containerExists stateDir
114+ unless exists $
115+ failWith $ "Expected to see docker container named " <> containerName <> " but it does not exist."
116+
117+ testLinuxBuild stateDir
118+
119+-- | The instructions for setting up SSH access to the container for the Nix daemon.
120+setupInstructions :: FilePath -> Text
121+setupInstructions sshIdFile = T.unlines
122+ [ "Setting Up Docker Nix Builder"
123+ , "-----------------------------"
124+ , ""
125+ , "We've created a Docker container that can build for Linux. However, the Nix"
126+ , "daemon needs to connect to this container as root. Please run the following"
127+ , "commands in a root shell (`sudo su -`) to tell SSH how to access the"
128+ , "container. Then try your obelisk command again."
129+ , ""
130+ , "# sudo su -"
131+ , "touch ~/.ssh/config"
132+ , "cat >> ~/.ssh/config <<CONF"
133+ , ""
134+ , sshConfigHost sshIdFile
135+ , "CONF"
136+ , "ssh " <> containerName <> " nix --version # Answer 'yes' if prompted"
137+ ]
138+
139+-- | SSH configuration for `.ssh/config` to connect to the Docker container.
140+sshConfigHost :: FilePath -> Text
141+sshConfigHost sshIdFile = T.unlines
142+ [ "Host " <> containerName
143+ , " User root"
144+ , " HostName 127.0.0.1"
145+ , " Port " <> T.pack (show containerSshPort)
146+ , " IdentityFile " <> T.pack (show sshIdFile) -- TODO: Check to see how weird paths should be encoded here.
147+ ]
148+
149+-- | User directory where state (namely the SSH keys) is kept for the Docker container.
150+getDockerBuilderStateDir :: IO FilePath
151+getDockerBuilderStateDir = liftA2 (</>) getObeliskUserStateDir (pure "nix-docker-builder")
152+
153+-- | Run a test build to see if a Linux build can finish successfully.
154+testLinuxBuild :: MonadObelisk m => FilePath -> m ()
155+testLinuxBuild stateDir
156+ | System.Info.os == "linux" = failWith "Using the docker builder is not necessary on linux."
157+ | otherwise = do
158+ (exitCode, _stdout, stderr) <- readCreateProcessWithExitCode $ proc nixBuildExePath
159+ [ "--no-out-link"
160+ , "-E", "(import <nixpkgs> { system = \"x86_64-linux\"; }).writeText \"test\" builtins.currentTime"
161+ , "--builders", nixBuildersArgString stateDir
162+ ]
163+ unless (exitCode == ExitSuccess) $ do
164+ let sshIdFile = stateDir </> sshKeyFileName
165+ putLog Error $ T.pack stderr
166+ failWith $ setupInstructions sshIdFile
167+
168+-- Copied from https://github.com/LnL7/nix-docker/blob/8dcfb3aff1f87cdafeecb0d27964b27c3fb8b1d2/ssh/Dockerfile
169+-- Renamed "insecure_rsa" to 'sshKeyFileName'
170+dockerfile :: Text
171+dockerfile = [hereLit|
172+FROM lnl7/nix:2018-09-21
173+
174+RUN nix-env -f '<nixpkgs>' -iA \
175+ gnused \
176+ openssh \
177+ && nix-store --gc
178+
179+RUN mkdir -p /etc/ssh \
180+ && echo "sshd:x:498:65534::/var/empty:/run/current-system/sw/bin/nologin" >> /etc/passwd \
181+ && cp /root/.nix-profile/etc/ssh/sshd_config /etc/ssh \
182+ && sed -i '/^PermitRootLogin/d' /etc/ssh/sshd_config \
183+ && echo "PermitRootLogin yes" >> /etc/ssh/sshd_config \
184+ && ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N "" -t rsa \
185+ && ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N "" -t dsa \
186+ && echo "export SSL_CERT_FILE=$SSL_CERT_FILE" >> /etc/bashrc \
187+ && echo "export PATH=$PATH" >> /etc/bashrc \
188+ && echo "export NIX_PATH=$NIX_PATH" >> /etc/bashrc \
189+ && echo "source /etc/bashrc" >> /etc/profile
190+
191+|] <> T.unlines
192+ [ "ADD " <> T.pack sshKeyFileName <> " /root/.ssh/id_rsa"
193+ , "ADD " <> T.pack (sshKeyFileName <.> "pub") <> " /root/.ssh/authorized_keys"
194+ ] <> [hereLit|
195+
196+EXPOSE 22
197+CMD ["/nix/store/mydwfxzk8bka4iwjml033dir6gkmqwic-openssh-7.7p1/bin/sshd", "-D", "-e"]
198+
199+|]
200+
201+sshKeyFileName :: FilePath
202+sshKeyFileName = "id_ed25519_obelisk_vm"
lib/executable-config/README.md+2−7
@@ -7,10 +7,6 @@ Obelisk.ExecutableConfig serves two related purposes:
71. Injection: a cross-platform injection function, which can be used to put configuration files in a canonical location.
71. Injection: a cross-platform injection function, which can be used to put configuration files in a canonical location.
82. Retrieval: a cross-platform retrieval function that is aware of the canonical location on each platform and how to read files from that location.
82. Retrieval: a cross-platform retrieval function that is aware of the canonical location on each platform and how to read files from that location.
9
9
10−## File Location
11−
12−ExecutableConfig expects your configuration files to be placed in `./exe-config`.
13−
14## Supported Platforms
10## Supported Platforms
15
11
16| Function | iOS | Android | Warp |Web backend + GHCJS |
12| Function | iOS | Android | Warp |Web backend + GHCJS |
@@ -28,7 +24,7 @@ ExecutableConfig expects your configuration files to be placed in `./exe-config`
28
24
29There is currently no `inject` function for `jsaddle-warp`-based frontends.
25There is currently no `inject` function for `jsaddle-warp`-based frontends.
30
26
31−`get` is a Haskell function that simply reads the configuration files from `./exe-config`.
27+`get` is a Haskell function that simply reads the configuration files relative to the current directory.
32
28
33### Web backend + GHCJS
29### Web backend + GHCJS
34
30
@@ -36,9 +32,8 @@ There is currently no `inject` function for `jsaddle-warp`-based frontends.
36
32
37`inject` is a Haskell function that produces a snippet of HTML that must be appended to the `<head>` of the page that the backend serves (i.e., the entry point for the GHCJS application).
33`inject` is a Haskell function that produces a snippet of HTML that must be appended to the `<head>` of the page that the backend serves (i.e., the entry point for the GHCJS application).
38
34
39−`get` is a Haskell function that reads the configuration files from `./exe-config`.
35+`get` is a Haskell function that reads the configuration files relative to the current directory.
40
36
41#### GHCJS
37#### GHCJS
42
38
43`get` is a Haskell function that can be run by the GHCJS frontend to retrieve the injected configuration data from the served `<head>`. There is no `inject` that is run in GHCJS.
39`get` is a Haskell function that can be run by the GHCJS frontend to retrieve the injected configuration data from the served `<head>`. There is no `inject` that is run in GHCJS.
44−
lib/executable-config/default.nix+38−15
@@ -2,21 +2,44 @@
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
13+ mkdir -p $out
10− cp -a "${assets}" $out
14+ cp --no-preserve=mode -Lr "${assets}" $out/static
11− chmod +w "$out"
15+ chmod +w "$out"
16+ '' + lib.optionalString (!(builtins.isNull config)) ''
12− if ! mkdir $out/config; then
17+ if ! mkdir $out/config; then
13− 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
14− exit 1
19+ exit 1
15− fi
20+ fi
16− cp -a "${config}"/* "$out/config"
21+ cp -a "${config}"/* "$out/config"
17− '';
22+ # Needed for android deployments
18−in with nixpkgs.haskell.lib; {
23+ find "$out/config" -type f -printf '%P\0' > "$out/config.files"
19− haskellPackage = self: self.callPackage (filterGitSource ./lookup) {};
24+ '');
25+in
26+
27+{
28+ haskellOverlay = self: super:
29+ let
30+ pkgs = self.callPackage ({pkgs}: pkgs) {};
31+ in {
32+ obelisk-executable-config-lookup = pkgs.haskell.lib.overrideCabal
33+ (self.callCabal2nix "obelisk-executable-config-lookup" (obeliskCleanSource ./lookup) {})
34+ (drv: {
35+ # Hack until https://github.com/NixOS/cabal2nix/pull/432 lands
36+ libraryHaskellDepends = (drv.libraryHaskellDepends or [])
37+ ++ pkgs.stdenv.lib.optionals (with pkgs.stdenv.hostPlatform; isAndroid && is32bit) [
38+ self.android-activity
39+ ];
40+ });
41+ };
42+
20 platforms = {
43 platforms = {
21 android = {
44 android = {
22 # Inject the given config directory into an android assets folder
45 # Inject the given config directory into an android assets folder
@@ -27,7 +50,7 @@ in with nixpkgs.haskell.lib; {
27 inject = injectConfig;
50 inject = injectConfig;
28 };
51 };
29 web = {
52 web = {
30− inject = self: self.callCabal2nix "obelisk-executable-config-inject" (filterGitSource ./inject) {};
53+ inject = self: self.callCabal2nix "obelisk-executable-config-inject" (obeliskCleanSource ./inject) {};
31 };
54 };
32 };
55 };
33}
56}
lib/executable-config/inject/obelisk-executable-config-inject.cabal+6−5
@@ -7,11 +7,12 @@ library
7 hs-source-dirs: src
7 hs-source-dirs: src
8
8
9 build-depends:
9 build-depends:
10− base,
10+ base,
11 bytestring,
11 bytestring,
12− filepath,
12+ base64-bytestring,
13+ containers,
13− reflex-dom,
14+ reflex-dom-core,
14− text,
15+ text
15− transformers
16
16
17 exposed-modules: Obelisk.ExecutableConfig.Inject
17 exposed-modules: Obelisk.ExecutableConfig.Inject
18+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
lib/executable-config/inject/src/Obelisk/ExecutableConfig/Inject.hs+18−10
@@ -1,17 +1,25 @@
1{-# LANGUAGE OverloadedStrings #-}
1{-# LANGUAGE OverloadedStrings #-}
2module Obelisk.ExecutableConfig.Inject where
2module Obelisk.ExecutableConfig.Inject where
3
3
4+import Control.Monad (mapM_)
5+import Control.Monad.IO.Class (MonadIO)
4import Data.ByteString (ByteString)
6import Data.ByteString (ByteString)
5−import qualified Data.ByteString as BS
7+import qualified Data.ByteString.Base64 as B64
8+import Data.Map (Map)
9+import qualified Data.Map as Map
6import Data.Semigroup ((<>))
10import Data.Semigroup ((<>))
7−import qualified Data.Text as T
11+import Data.Text (Text)
8import qualified Data.Text.Encoding as T
12import qualified Data.Text.Encoding as T
9−import Reflex.Dom
13+import Reflex.Dom.Core hiding (value)
10−import System.FilePath ((</>))
11
14
12−inject :: FilePath -> IO ByteString
15+-- | Produces a @<script>@ tag with an @id@ attribute containing the key and
13−inject item = do
16+-- whose value is the provided configuration, encoded in base64.
14− f <- BS.readFile $ "exe-config" </> item
17+injectPure :: DomBuilder t m => Text -> ByteString -> m ()
15− fmap snd $ renderStatic $
18+injectPure key value =
16− elAttr "script" ("type" =: "text/plain" <> "id" =: ("config-" <> T.pack item)) $
19+ let attrs = ("type" =: "text/plain" <> "data-obelisk-executable-config-inject-key" =: key <> "data-hydration-skip" =: "")
17− text $ T.decodeUtf8 f
20+ in elAttr "script" attrs $ text (T.decodeUtf8 (B64.encode value))
21+
22+-- | Produces injectable @<script>@ tags containing the configuration keys
23+-- (filepaths) and values.
24+injectExecutableConfigs :: (MonadIO m, DomBuilder t m) => Map Text ByteString -> m ()
25+injectExecutableConfigs = mapM_ (uncurry injectPure) . Map.toList
lib/executable-config/lookup/default.nixdeleted−24
@@ -1,24 +0,0 @@
1−{ hostPlatform, ghc
2−, mkDerivation, base, bytestring, filepath, stdenv, text, transformers
3−, android-activity ? null, jsaddle-wkwebview ? null, ghcjs-dom ? null
4−}:
5−let isAndroid = hostPlatform.libc == "bionic";
6− isIOS = hostPlatform.isDarwin && hostPlatform.isAarch64;
7− isGhcjs = ghc.isGhcjs or false;
8−in mkDerivation {
9− pname = "obelisk-executable-config";
10− version = "0.1";
11− src = ./.;
12− libraryHaskellDepends = [
13− base bytestring filepath text transformers
14− ] ++ (if isAndroid then [
15− android-activity
16− ] else if isIOS then [
17− jsaddle-wkwebview
18− ] else if isGhcjs then [
19− ghcjs-dom
20− ] else [
21− ]);
22− license = stdenv.lib.licenses.bsd3;
23−}
24−
lib/executable-config/lookup/obelisk-executable-config-lookup.cabalnew file+48
@@ -0,0 +1,48 @@
1+name: obelisk-executable-config-lookup
2+version: 0.1.1
3+cabal-version: >= 1.2
4+build-type: Simple
5+
6+library
7+ exposed-modules: Obelisk.ExecutableConfig.Lookup, Obelisk.Configs
8+ if os(ios)
9+ hs-source-dirs: src-ios, src
10+ other-modules: Obelisk.Configs.Internal.Directory
11+ build-depends: jsaddle-wkwebview
12+ build-depends: directory
13+ else
14+ if os(linux-android)
15+ hs-source-dirs: src-android, src
16+ c-sources: cbits/ExecutableConfig.c
17+ other-modules: Obelisk.ExecutableConfig.Internal.AssetManager
18+ build-depends: android-activity
19+ ld-options: -landroid
20+ else
21+ if impl(ghcjs)
22+ hs-source-dirs: src-ghcjs, src
23+ build-depends: ghcjs-dom
24+ else
25+ hs-source-dirs: src-other, src
26+ other-modules: Obelisk.Configs.Internal.Directory
27+ build-depends: directory
28+
29+ build-depends:
30+ base,
31+ base64-bytestring,
32+ bytestring,
33+ containers,
34+ exceptions,
35+ filepath,
36+ jsaddle,
37+ mmorph,
38+ monad-control,
39+ mtl,
40+ primitive,
41+ ref-tf,
42+ reflex-dom-core,
43+ reflex,
44+ text,
45+ transformers-base,
46+ transformers
47+
48+ ghc-options: -Wall
lib/executable-config/lookup/obelisk-executable-config.cabaldeleted−30
@@ -1,30 +0,0 @@
1−name: obelisk-executable-config
2−version: 0.1.1
3−cabal-version: >= 1.2
4−build-type: Simple
5−
6−library
7− exposed-modules: Obelisk.ExecutableConfig
8− if os(ios)
9− hs-source-dirs: src-ios
10− build-depends: jsaddle-wkwebview
11− else
12− if os(linux-android)
13− hs-source-dirs: src-android
14− c-sources: cbits/ExecutableConfig.c
15− other-modules: Obelisk.ExecutableConfig.Internal.AssetManager
16− build-depends: android-activity
17− ld-options: -landroid
18− else
19− if impl(ghcjs)
20− hs-source-dirs: src-ghcjs
21− build-depends: ghcjs-dom
22− else
23− hs-source-dirs: src
24−
25− build-depends:
26− base,
27− bytestring,
28− filepath,
29− text,
30− transformers
lib/executable-config/lookup/src-android/Obelisk/ExecutableConfig.hsdeleted−27
@@ -1,27 +0,0 @@
1−module Obelisk.ExecutableConfig (get) where
2−
3−import Control.Exception (bracket)
4−import qualified Data.ByteString as BS
5−import Data.Text (Text)
6−import qualified Data.Text as T
7−import qualified Data.Text.Encoding as T
8−import Foreign.C.String (withCString)
9−import Foreign.Ptr (nullPtr)
10−import System.FilePath.Posix ((</>))
11−
12−import Obelisk.ExecutableConfig.Internal.AssetManager
13−
14−get :: Text -> IO (Maybe Text)
15−get name = bracket getAssets freeAssetManager $ \mgrObj -> do
16− mgr <- assetManagerFromJava mgrObj
17− let open = do
18− a <- withCString ("config" </> T.unpack name) $ \fn ->
19− assetManager_open mgr fn 3
20− return $ if unAAsset a == nullPtr
21− then Nothing
22− else Just a
23− close = mapM_ asset_close
24− bracket open close $ mapM $ \asset -> do
25− b <- asset_getBuffer asset
26− l <- asset_getLength asset
27− fmap T.decodeUtf8 $ BS.packCStringLen (b, fromIntegral l)
lib/executable-config/lookup/src-android/Obelisk/ExecutableConfig/Lookup.hsnew file+60
@@ -0,0 +1,60 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Obelisk.ExecutableConfig.Lookup where
4+
5+import Control.Exception (bracket)
6+import Control.Monad (forM)
7+import Data.ByteString (ByteString)
8+import qualified Data.ByteString as BS
9+import Data.Map (Map)
10+import qualified Data.Map as Map
11+import Data.Text (Text)
12+import qualified Data.Text.Encoding as T
13+import Foreign.C.String (withCString)
14+import Foreign.Ptr (nullPtr)
15+
16+import Obelisk.ExecutableConfig.Internal.AssetManager
17+
18+getFromMgr :: AAssetManager -> BS.ByteString -> IO (Maybe ByteString)
19+getFromMgr mgr name = do
20+ let open = do
21+ a <- BS.useAsCString name $ \fn ->
22+ assetManager_open mgr fn 3
23+ return $ if unAAsset a == nullPtr
24+ then Nothing
25+ else Just a
26+ close = mapM_ asset_close
27+ bracket open close $ mapM $ \asset -> do
28+ b <- asset_getBuffer asset
29+ l <- asset_getLength asset
30+ BS.packCStringLen (b, fromIntegral l)
31+
32+getConfigs :: IO (Map Text ByteString)
33+getConfigs = fmap (Map.mapKeys T.decodeUtf8) $ bracket getAssets freeAssetManager $ \mgrObj -> do
34+ mgr <- assetManagerFromJava mgrObj
35+ let openDir = do
36+ d <- withCString "config.files" $ \fn ->
37+ assetManager_open mgr fn 3
38+ return $ if unAAsset d == nullPtr
39+ then Nothing
40+ else Just d
41+ closeDir = mapM_ asset_close
42+ configPaths <- bracket openDir closeDir $ \case
43+ Just asset -> do
44+ b <- asset_getBuffer asset
45+ l <- asset_getLength asset
46+ lines0 <$> BS.packCStringLen (b, fromIntegral l)
47+ Nothing -> error "could not open configuration manifest 'config.files'"
48+ result <- fmap Map.fromList $ forM configPaths $ \fp ->
49+ getFromMgr mgr ("config/" <> fp) >>= \case
50+ Just v -> return (fp, v)
51+ Nothing -> error $ "Config present in config.files but not in assets: " <> show fp
52+ putStrLn $ "getConfigs: found " <> show result
53+ pure result
54+
55+lines0 :: BS.ByteString -> [BS.ByteString]
56+lines0 ps
57+ | BS.null ps = []
58+ | otherwise = case BS.elemIndex 0 ps of
59+ Nothing -> [ps]
60+ Just n -> BS.take n ps : lines0 (BS.drop (n+1) ps)
lib/executable-config/lookup/src-ghcjs/Obelisk/ExecutableConfig.hsdeleted−17
@@ -1,17 +0,0 @@
1−{-# LANGUAGE OverloadedStrings #-}
2−module Obelisk.ExecutableConfig where
3−
4−import Control.Monad.Trans.Maybe
5−import Data.Semigroup ((<>))
6−import Data.Text (Text)
7−import GHCJS.DOM
8−import GHCJS.DOM.Document
9−import GHCJS.DOM.Element
10−import GHCJS.DOM.NonElementParentNode
11−
12−get :: Text -> IO (Maybe Text)
13−get item = runMaybeT $ do
14− doc <- MaybeT currentDocument
15− e <- MaybeT $ getElementById doc $ "config-" <> item
16− getInnerHTML e
17−
lib/executable-config/lookup/src-ghcjs/Obelisk/ExecutableConfig/Lookup.hsnew file+51
@@ -0,0 +1,51 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Obelisk.ExecutableConfig.Lookup where
4+
5+import Data.ByteString (ByteString)
6+import qualified Data.ByteString.Base64 as B64
7+import Data.Map (Map)
8+import qualified Data.Map as Map
9+import Data.Maybe (catMaybes)
10+import Data.Text (Text)
11+import qualified Data.Text.Encoding as T
12+import Data.Traversable (for)
13+import GHCJS.DOM
14+import GHCJS.DOM.Document (getHead)
15+import GHCJS.DOM.DOMStringMap (get)
16+import GHCJS.DOM.Element (getInnerHTML)
17+import GHCJS.DOM.HTMLElement (HTMLElement(HTMLElement), getDataset)
18+import GHCJS.DOM.NodeList (IsNodeList, item, getLength)
19+import GHCJS.DOM.ParentNode (querySelectorAll)
20+import GHCJS.DOM.Types (MonadJSM, Node(Node), castTo)
21+
22+getConfigs :: IO (Map Text ByteString)
23+getConfigs = do
24+ Just doc <- currentDocument
25+ Just hd <- getHead doc
26+ nodes <- nodeListNodes =<< querySelectorAll hd ("[data-obelisk-executable-config-inject-key]" :: Text)
27+ fmap Map.fromList $ for nodes $ \node -> do
28+ e <- castTo HTMLElement node >>= \case
29+ Nothing -> error "Found node with data attribute obelisk-executable-config-inject-key that is not an HTMLElement."
30+ Just htmlE -> return htmlE
31+ dataset <- getDataset e
32+ (,)
33+ -- the key is camelCased: https://html.spec.whatwg.org/multipage/dom.html#dom-dataset
34+ <$> get dataset ("obeliskExecutableConfigInjectKey" :: Text)
35+ <*> (fmap decodeOrFail (getInnerHTML e))
36+ where
37+ decodeOrFail x = case B64.decode (T.encodeUtf8 x) of
38+ Left e -> error ("Obelisk.ExecutableConfig.Lookup.getConfigs: error when decoding base64: " ++ e)
39+ Right x' -> x'
40+
41+-- | Collect all nodes in the node list.
42+--
43+-- TODO: this and the version in obelisk-frontend should be
44+-- upstreamed to jsaddle.
45+nodeListNodes :: (IsNodeList l, MonadJSM m) => l -> m [Node]
46+nodeListNodes es = do
47+ len <- getLength es
48+ -- Warning! len is unsigned. If the NodeList is empty, we must avoid
49+ -- accidentally traversing over [0..maxBound::Word]
50+ nodes <- traverse (item es) $ if len == 0 then [] else [0..len-1]
51+ pure $ catMaybes nodes
lib/executable-config/lookup/src-ios/Obelisk/ExecutableConfig.hsdeleted−22
@@ -1,22 +0,0 @@
1−module Obelisk.ExecutableConfig (get) where
2−
3−import Control.Exception
4−import Control.Monad
5−import Control.Monad.Trans.Maybe
6−import Data.ByteString as BS
7−import Data.Text (Text)
8−import qualified Data.Text as T
9−import qualified Data.Text.IO as T
10−import qualified Data.Text.Encoding as T
11−import Language.Javascript.JSaddle.WKWebView
12−import System.FilePath.Posix ((</>))
13−import System.IO.Error
14−
15−get :: Text -> IO (Maybe Text)
16−get name = fmap join $ mainBundleResourcePath >>= \mp -> forM mp $ \p ->
17− catchDoesNotExist $ T.readFile $ T.unpack (T.decodeUtf8 p) </> "config" </> T.unpack name
18−
19−catchDoesNotExist :: IO a -> IO (Maybe a)
20−catchDoesNotExist f = catchJust doesNotExist (Just <$> f) $ const $ return Nothing
21− where
22− doesNotExist e = if isDoesNotExistError e then Just () else Nothing
lib/executable-config/lookup/src-ios/Obelisk/ExecutableConfig/Lookup.hsnew file+17
@@ -0,0 +1,17 @@
1+{-# LANGUAGE LambdaCase #-}
2+module Obelisk.ExecutableConfig.Lookup where
3+
4+import Data.ByteString (ByteString)
5+import Data.Map (Map)
6+import Data.Text (Text)
7+import qualified Data.Text as T
8+import qualified Data.Text.Encoding as T
9+import Language.Javascript.JSaddle.WKWebView
10+import System.FilePath.Posix
11+
12+import Obelisk.Configs.Internal.Directory
13+
14+getConfigs :: IO (Map Text ByteString)
15+getConfigs = mainBundleResourcePath >>= \case
16+ Nothing -> error "Could not get bundle resource path."
17+ Just p -> getConfigsFromDirectory $ T.unpack (T.decodeUtf8 p) </> "config"
lib/executable-config/lookup/src-other/Obelisk/ExecutableConfig/Lookup.hsnew file+11
@@ -0,0 +1,11 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Obelisk.ExecutableConfig.Lookup where
3+
4+import Data.Map (Map)
5+import Data.Text (Text)
6+import Data.ByteString (ByteString)
7+
8+import Obelisk.Configs.Internal.Directory (getConfigsFromDirectory)
9+
10+getConfigs :: IO (Map Text ByteString)
11+getConfigs = getConfigsFromDirectory "config"
lib/executable-config/lookup/src/Obelisk/Configs.hsnew file+148
@@ -0,0 +1,148 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE DefaultSignatures #-}
4+{-# LANGUAGE DeriveFunctor #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
9+{-# LANGUAGE OverloadedStrings #-}
10+{-# LANGUAGE RankNTypes #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+module Obelisk.Configs
14+ ( HasConfigs(..)
15+ , ConfigsT
16+ , runConfigsT
17+ , mapConfigsT
18+ , getTextConfig
19+ ) where
20+
21+import Control.Applicative (Alternative)
22+import Control.Monad (MonadPlus)
23+import Control.Monad.Base (MonadBase)
24+import Control.Monad.Catch (MonadThrow)
25+import Control.Monad.Fail (MonadFail)
26+import Control.Monad.Fix (MonadFix)
27+import Control.Monad.IO.Class (MonadIO)
28+import Control.Monad.Morph (MFunctor)
29+import Control.Monad.Primitive (PrimMonad, PrimState, primitive)
30+import Control.Monad.Ref (MonadRef)
31+import Control.Monad.Trans (MonadTrans, lift)
32+import Control.Monad.Trans.Control (MonadBaseControl)
33+import Control.Monad.Trans.Reader (ReaderT (..), ask, mapReaderT)
34+import Control.Monad.Trans.State (StateT)
35+import qualified Control.Monad.Trans.State.Strict as Strict
36+import Data.ByteString (ByteString)
37+import Data.Map (Map)
38+import qualified Data.Map as Map
39+import Data.Text (Text)
40+import qualified Data.Text.Encoding as T
41+import Reflex
42+import Reflex.Host.Class (MonadReflexCreateTrigger)
43+import Reflex.Dom.Core
44+ ( DomBuilder
45+ , DomRenderHook
46+ , HasDocument
47+ , HasJS
48+ , HasJSContext
49+ , Prerender (Client)
50+ , StaticDomBuilderT
51+ , prerender
52+ )
53+#ifndef ghcjs_HOST_OS
54+import Language.Javascript.JSaddle (MonadJSM)
55+#endif
56+
57+class Monad m => HasConfigs m where
58+ getConfigs :: m (Map Text ByteString)
59+ default getConfigs :: (HasConfigs m', m ~ t m', MonadTrans t) => m (Map Text ByteString)
60+ getConfigs = lift getConfigs
61+ getConfig :: Text -> m (Maybe ByteString)
62+ getConfig k = do
63+ configs <- getConfigs
64+ return $ Map.lookup k configs
65+
66+instance Monad m => HasConfigs (ConfigsT m) where
67+ getConfigs = ConfigsT ask
68+
69+getTextConfig :: HasConfigs m => Text -> m (Maybe Text)
70+getTextConfig k = fmap T.decodeUtf8 <$> getConfig k
71+
72+instance HasConfigs m => HasConfigs (BehaviorWriterT t w m)
73+instance HasConfigs m => HasConfigs (DynamicWriterT t w m)
74+instance HasConfigs m => HasConfigs (EventWriterT t w m)
75+instance HasConfigs m => HasConfigs (PostBuildT t m)
76+instance HasConfigs m => HasConfigs (QueryT t q m)
77+instance HasConfigs m => HasConfigs (ReaderT r m)
78+instance HasConfigs m => HasConfigs (RequesterT t request response m)
79+instance HasConfigs m => HasConfigs (StateT w m)
80+instance HasConfigs m => HasConfigs (Strict.StateT w m)
81+instance HasConfigs m => HasConfigs (StaticDomBuilderT t m)
82+instance HasConfigs m => HasConfigs (TriggerEventT t m)
83+
84+newtype ConfigsT m a = ConfigsT { unConfigsT :: ReaderT (Map Text ByteString) m a }
85+ deriving
86+ ( Functor
87+ , Applicative
88+ , Monad
89+ , MonadPlus
90+ , Alternative
91+ , MonadFail
92+ , MonadFix
93+ , MonadThrow
94+ , MonadIO
95+ , MonadBase m'
96+ , MonadBaseControl m'
97+ , MonadRef
98+ , MonadTrans
99+ , MFunctor
100+ , DomBuilder t
101+ , MonadHold t
102+ , MonadReflexCreateTrigger t
103+ , MonadSample t
104+ , NotReady t
105+ , PostBuild t
106+ , TriggerEvent t
107+ , HasDocument
108+ , DomRenderHook t
109+ , HasJSContext
110+ , HasJS js
111+#ifndef ghcjs_HOST_OS
112+ , MonadJSM
113+#endif
114+ )
115+
116+instance PerformEvent t m => PerformEvent t (ConfigsT m) where
117+ type Performable (ConfigsT m) = ConfigsT (Performable m)
118+ performEvent e = ConfigsT $ ReaderT $ \configs ->
119+ performEvent $ runConfigsT configs <$> e
120+ performEvent_ e = ConfigsT $ ReaderT $ \configs ->
121+ performEvent_ $ runConfigsT configs <$> e
122+
123+instance Adjustable t m => Adjustable t (ConfigsT m) where
124+ runWithReplace a e = ConfigsT $ runWithReplace (unConfigsT a) (unConfigsT <$> e)
125+ traverseDMapWithKeyWithAdjust f m e = ConfigsT $ traverseDMapWithKeyWithAdjust (\k v -> unConfigsT $ f k v) m e
126+ traverseIntMapWithKeyWithAdjust f m e = ConfigsT $ traverseIntMapWithKeyWithAdjust (\k v -> unConfigsT $ f k v) m e
127+ traverseDMapWithKeyWithAdjustWithMove f m e = ConfigsT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unConfigsT $ f k v) m e
128+
129+instance Prerender js t m => Prerender js t (ConfigsT m) where
130+ type Client (ConfigsT m) = ConfigsT (Client m)
131+ prerender server client = ConfigsT $ ReaderT $ \configs ->
132+ prerender (runConfigsT configs server) (runConfigsT configs client)
133+
134+instance PrimMonad m => PrimMonad (ConfigsT m) where
135+ type PrimState (ConfigsT m) = PrimState m
136+ primitive = lift . primitive
137+
138+runConfigsT
139+ :: Map Text ByteString
140+ -> ConfigsT m a
141+ -> m a
142+runConfigsT cs child = runReaderT (unConfigsT child) cs
143+
144+mapConfigsT
145+ :: (forall x. m x -> n x)
146+ -> ConfigsT m a
147+ -> ConfigsT n a
148+mapConfigsT f (ConfigsT x) = ConfigsT $ mapReaderT f x
lib/executable-config/lookup/src/Obelisk/Configs/Internal/Directory.hsnew file+24
@@ -0,0 +1,24 @@
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Obelisk.Configs.Internal.Directory where
4+
5+import Control.Monad
6+import Data.ByteString (ByteString)
7+import qualified Data.ByteString as BS
8+import Data.Map (Map)
9+import qualified Data.Map as Map
10+import Data.Text (Text)
11+import qualified Data.Text as T
12+import System.Directory
13+import System.FilePath.Posix
14+
15+getConfigsFromDirectory :: FilePath -> IO (Map Text ByteString)
16+getConfigsFromDirectory base = doesDirectoryExist base >>= \case
17+ True -> do
18+ ps <- listDirectory base
19+ fmap mconcat $ forM ps $ \p -> do
20+ subdirConfigs <- getConfigsFromDirectory $ base </> p
21+ pure $ Map.mapKeys (T.pack . (p </>) . T.unpack) subdirConfigs
22+ False -> doesFileExist base >>= \case
23+ True -> Map.singleton "" <$> BS.readFile base
24+ False -> pure mempty
lib/executable-config/lookup/src/Obelisk/ExecutableConfig.hsdeleted−13
@@ -1,13 +0,0 @@
1−module Obelisk.ExecutableConfig (get) where
2−
3−import Control.Exception
4−import Data.Text (Text)
5−import Data.Text as T
6−import Data.Text.IO as T
7−import System.FilePath.Posix ((</>))
8−import System.IO.Error
9−
10−get :: Text -> IO (Maybe Text)
11−get path = do
12− let doesNotExist = \e -> if isDoesNotExistError e then Just () else Nothing
13− catchJust doesNotExist (fmap Just $ T.readFile $ "exe-config" </> T.unpack path) (\_ -> pure Nothing)
lib/frontend/obelisk-frontend.cabalnew file+29
@@ -0,0 +1,29 @@
1+name: obelisk-frontend
2+version: 0.1
3+cabal-version: >= 1.2
4+build-type: Simple
5+
6+library
7+ hs-source-dirs: src
8+ build-depends: base,
9+ bytestring,
10+ containers,
11+ cookie,
12+ dependent-sum,
13+ ghcjs-dom,
14+ jsaddle,
15+ lens,
16+ mtl,
17+ obelisk-executable-config-inject,
18+ obelisk-executable-config-lookup,
19+ obelisk-route,
20+ primitive,
21+ ref-tf,
22+ reflex,
23+ reflex-dom-core,
24+ text,
25+ transformers
26+ exposed-modules:
27+ Obelisk.Frontend
28+ Obelisk.Frontend.Cookie
29+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
lib/frontend/src/Obelisk/Frontend.hsnew file+254
@@ -0,0 +1,254 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE PackageImports #-}
9+{-# LANGUAGE RankNTypes #-}
10+{-# LANGUAGE RecursiveDo #-}
11+{-# LANGUAGE ScopedTypeVariables #-}
12+{-# LANGUAGE TemplateHaskell #-}
13+{-# LANGUAGE TypeFamilies #-}
14+{-# LANGUAGE UndecidableInstances #-}
15+module Obelisk.Frontend
16+ ( ObeliskWidget
17+ , Frontend (..)
18+ , runFrontend
19+ , runFrontendWithConfigsAndCurrentRoute
20+ , renderFrontendHtml
21+ , removeHTMLConfigs
22+ , FrontendMode (..)
23+ , FrontendWidgetT
24+ , module Obelisk.Frontend.Cookie
25+ ) where
26+
27+import Prelude hiding ((.))
28+
29+import Control.Category
30+import Control.Lens
31+import Control.Monad.Fix
32+import Control.Monad.IO.Class
33+import Control.Monad.Primitive
34+import Control.Monad.Reader
35+import Control.Monad.Ref
36+import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
37+import Data.ByteString (ByteString)
38+import Data.Foldable (for_)
39+import Data.Functor.Sum
40+import Data.Map (Map)
41+import Data.Maybe (catMaybes)
42+import Data.Monoid ((<>))
43+import Data.Text (Text)
44+import qualified GHCJS.DOM as DOM
45+import qualified GHCJS.DOM.Types as DOM
46+import qualified GHCJS.DOM.History as DOM
47+import qualified GHCJS.DOM.Window as DOM
48+import Language.Javascript.JSaddle (MonadJSM, JSM, jsNull)
49+import GHCJS.DOM (currentDocument)
50+import "ghcjs-dom" GHCJS.DOM.Document (getHead)
51+import GHCJS.DOM.Node (Node, removeChild_)
52+import GHCJS.DOM.NodeList (IsNodeList, item, getLength)
53+import GHCJS.DOM.ParentNode (querySelectorAll)
54+import Obelisk.Frontend.Cookie
55+import Obelisk.Route.Frontend
56+import Reflex.Dom.Core
57+import Reflex.Host.Class
58+import Obelisk.Configs
59+import Obelisk.ExecutableConfig.Inject (injectExecutableConfigs)
60+import qualified Obelisk.ExecutableConfig.Lookup as Lookup
61+import Web.Cookie
62+
63+import Debug.Trace
64+
65+makePrisms ''Sum
66+
67+type ObeliskWidget js t route m =
68+ ( DomBuilder t m
69+ , MonadFix m
70+ , MonadHold t m
71+ , MonadSample t (Performable m)
72+ , MonadReflexCreateTrigger t m
73+ , PostBuild t m
74+ , PerformEvent t m
75+ , TriggerEvent t m
76+ , HasDocument m
77+ , MonadRef m
78+ , Ref m ~ Ref IO
79+ , MonadRef (Performable m)
80+ , Ref (Performable m) ~ Ref IO
81+ , MonadFix (Performable m)
82+ , PrimMonad m
83+ , Prerender js t m
84+ , PrebuildAgnostic t route m
85+ , PrebuildAgnostic t route (Client m)
86+ , HasConfigs m
87+ , HasCookies m
88+ , MonadIO (Performable m)
89+ )
90+
91+type PrebuildAgnostic t route m =
92+ ( SetRoute t route m
93+ , RouteToUrl route m
94+ , MonadFix m
95+ , HasConfigs m
96+ , HasConfigs (Performable m)
97+ )
98+
99+data Frontend route = Frontend
100+ { _frontend_head :: !(forall js t m. ObeliskWidget js t route m => RoutedT t route m ())
101+ , _frontend_body :: !(forall js t m. ObeliskWidget js t route m => RoutedT t route m ())
102+ }
103+
104+baseTag :: forall route js t m. ObeliskWidget js t route m => RoutedT t route m ()
105+baseTag = elAttr "base" ("href" =: "/") blank --TODO: Figure out the base URL from the routes
106+
107+removeHTMLConfigs :: JSM ()
108+removeHTMLConfigs = void $ runMaybeT $ do
109+ doc <- MaybeT currentDocument
110+ hd <- MaybeT $ getHead doc
111+ es <- nodeListNodes =<< querySelectorAll hd ("[data-obelisk-executable-config-inject-key]" :: Text)
112+ for_ es $ removeChild_ hd
113+
114+-- | Collect all nodes in the node list.
115+--
116+-- TODO: this and the version in exe-config/ghcjs/lookup should be
117+-- upstreamed to jsaddle.
118+nodeListNodes :: (IsNodeList l, MonadJSM m) => l -> m [Node]
119+nodeListNodes es = do
120+ len <- getLength es
121+ -- Warning! len is unsigned. If the NodeList is empty, we must avoid
122+ -- accidentally traversing over [0..maxBound::Word]
123+ nodes <- traverse (item es) $ if len == 0 then [] else [0..len-1]
124+ pure $ catMaybes nodes
125+
126+setInitialRoute :: Bool -> JSM ()
127+setInitialRoute useHash = do
128+ traceM "setInitialRoute"
129+ window <- DOM.currentWindowUnchecked
130+ initialLocation <- DOM.getLocation window
131+ initialUri <- getLocationUri initialLocation
132+ history <- DOM.getHistory window
133+ DOM.replaceState history jsNull ("" :: Text) $ Just $
134+ show $ setAdaptedUriPath useHash "/" initialUri
135+
136+data FrontendMode = FrontendMode
137+ { _frontendMode_hydrate :: Bool
138+ -- ^ There is already a rendering of the DOM in place; hydrate it rather
139+ -- than building new DOM
140+ , _frontendMode_adjustRoute :: Bool
141+ -- ^ The page can't use regular routes, so encode routes into the hash
142+ -- instead
143+ }
144+
145+-- | Run the frontend, setting the initial route to "/" on platforms where no
146+-- route exists ambiently in the context (e.g. anything but web).
147+-- Selects FrontendMode based on platform; this doesn't work for jsaddle-warp
148+runFrontend
149+ :: forall backendRoute route
150+ . Encoder Identity Identity (R (FullRoute backendRoute route)) PageName
151+ -> Frontend (R route)
152+ -> JSM ()
153+runFrontend validFullEncoder frontend = do
154+ let mode = FrontendMode
155+ { _frontendMode_hydrate =
156+#ifdef ghcjs_HOST_OS
157+ True
158+#else
159+ False
160+#endif
161+ , _frontendMode_adjustRoute =
162+#ifdef ghcjs_HOST_OS
163+ False
164+#else
165+ True
166+#endif
167+ }
168+ configs <- liftIO Lookup.getConfigs
169+ when (_frontendMode_hydrate mode) removeHTMLConfigs
170+ -- There's no fundamental reason that adjustRoute needs to control setting the
171+ -- initial route and *also* the useHash parameter; that's why these are
172+ -- separate here. However, currently, they are always the same.
173+ when (_frontendMode_adjustRoute mode) $ do
174+ setInitialRoute $ _frontendMode_adjustRoute mode
175+ runFrontendWithConfigsAndCurrentRoute mode configs validFullEncoder frontend
176+
177+runFrontendWithConfigsAndCurrentRoute
178+ :: forall backendRoute frontendRoute
179+ . FrontendMode
180+ -> Map Text ByteString
181+ -> Encoder Identity Identity (R (FullRoute backendRoute frontendRoute)) PageName
182+ -> Frontend (R frontendRoute)
183+ -> JSM ()
184+runFrontendWithConfigsAndCurrentRoute mode configs validFullEncoder frontend = do
185+ let ve = validFullEncoder . hoistParse errorLeft (reviewEncoder (rPrism $ _FullRoute_Frontend . _ObeliskRoute_App))
186+ errorLeft = \case
187+ Left _ -> error "runFrontend: Unexpected non-app ObeliskRoute reached the frontend. This shouldn't happen."
188+ Right x -> Identity x
189+ w :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s DomTimeline m)) ~ DOM.Document
190+ , Ref (Performable m) ~ Ref IO
191+ , Ref m ~ Ref IO
192+ , DomBuilder DomTimeline (HydrationDomBuilderT s DomTimeline m)
193+ , MonadHold DomTimeline m
194+ , MonadRef m
195+ , MonadRef (Performable m)
196+ , MonadReflexCreateTrigger DomTimeline m
197+ , PerformEvent DomTimeline m
198+ , PostBuild DomTimeline m
199+ , PrimMonad m
200+ , MonadSample DomTimeline (Performable m)
201+ , DOM.MonadJSM m
202+ , MonadFix (Client (HydrationDomBuilderT s DomTimeline m))
203+ , MonadFix (Performable m)
204+ , MonadFix m
205+ , Prerender js DomTimeline (HydrationDomBuilderT s DomTimeline m)
206+ , MonadIO (Performable m)
207+ )
208+ => (forall c. HydrationDomBuilderT s DomTimeline m c -> FloatingWidget () c)
209+ -> (forall c. HydrationDomBuilderT s DomTimeline m c -> FloatingWidget () c)
210+ -> FloatingWidget () ()
211+ w appendHead appendBody = do
212+ rec switchover <- runRouteViewT ve switchover (_frontendMode_adjustRoute mode) $ do
213+ (switchover'', fire) <- newTriggerEvent
214+ mapRoutedT (mapSetRouteT (mapRouteToUrlT (appendHead . runConfigsT configs))) $ do
215+ -- The order here is important - baseTag has to be before headWidget!
216+ baseTag
217+ _frontend_head frontend
218+ mapRoutedT (mapSetRouteT (mapRouteToUrlT (appendBody . runConfigsT configs))) $ do
219+ _frontend_body frontend
220+ switchover' <- case _frontendMode_hydrate mode of
221+ True -> lift $ lift $ lift $ lift $ HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_switchover
222+ False -> getPostBuild
223+ performEvent_ $ liftIO (fire ()) <$ switchover'
224+ pure switchover''
225+ pure ()
226+ if _frontendMode_hydrate mode
227+ then runHydrationWidgetWithHeadAndBody (pure ()) w
228+ else runImmediateWidgetWithHeadAndBody w
229+
230+type FrontendWidgetT r = RoutedT DomTimeline r (SetRouteT DomTimeline r (RouteToUrlT r (ConfigsT (CookiesT (HydratableT (PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost))))))))
231+
232+renderFrontendHtml
233+ :: MonadIO m
234+ => Map Text ByteString
235+ -> Cookies
236+ -> (r -> Text)
237+ -> r
238+ -> Frontend r
239+ -> FrontendWidgetT r ()
240+ -> FrontendWidgetT r ()
241+ -> m ByteString
242+renderFrontendHtml configs cookies urlEnc route frontend headExtra bodyExtra = do
243+ --TODO: We should probably have a "NullEventWriterT" or a frozen reflex timeline
244+ html <- fmap snd $ liftIO $ renderStatic $ runHydratableT $ fmap fst $ runCookiesT cookies $ runConfigsT configs $ flip runRouteToUrlT urlEnc $ runSetRouteT $ flip runRoutedT (pure route) $
245+ el "html" $ do
246+ el "head" $ do
247+ baseTag
248+ injectExecutableConfigs configs
249+ _frontend_head frontend
250+ headExtra
251+ el "body" $ do
252+ _frontend_body frontend
253+ bodyExtra
254+ return $ "<!DOCTYPE html>" <> html
lib/frontend/src/Obelisk/Frontend/Cookie.hsnew file+103
@@ -0,0 +1,103 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE DefaultSignatures #-}
4+{-# LANGUAGE DeriveFunctor #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
9+{-# LANGUAGE PackageImports #-}
10+{-# LANGUAGE RankNTypes #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+
14+module Obelisk.Frontend.Cookie where
15+
16+import Control.Monad.Fix
17+import Control.Monad.Primitive
18+import Control.Monad.Ref
19+import Control.Monad.IO.Class
20+import Control.Monad.Trans.Class
21+import Control.Monad.Trans.Reader
22+import Data.Text.Encoding (encodeUtf8)
23+import Reflex
24+import Reflex.Host.Class
25+import Reflex.Dom.Core
26+import "ghcjs-dom" GHCJS.DOM.Document (getCookie, Document)
27+import GHCJS.DOM.Types (MonadJSM)
28+import Web.Cookie
29+
30+import Obelisk.Configs
31+import Obelisk.Route.Frontend
32+
33+class Monad m => HasCookies m where
34+ askCookies :: m Cookies
35+ default askCookies :: (HasCookies m', m ~ t m', MonadTrans t) => m Cookies
36+ askCookies = lift askCookies
37+
38+instance HasCookies m => HasCookies (BehaviorWriterT t w m)
39+instance HasCookies m => HasCookies (DynamicWriterT t w m)
40+instance HasCookies m => HasCookies (EventWriterT t w m)
41+instance HasCookies m => HasCookies (PostBuildT t m)
42+instance HasCookies m => HasCookies (QueryT t q m)
43+instance HasCookies m => HasCookies (ReaderT r m)
44+instance HasCookies m => HasCookies (RequesterT t request response m)
45+instance HasCookies m => HasCookies (RouteToUrlT t m)
46+instance HasCookies m => HasCookies (SetRouteT t r m)
47+instance HasCookies m => HasCookies (StaticDomBuilderT t m)
48+instance HasCookies m => HasCookies (TriggerEventT t m)
49+instance HasCookies m => HasCookies (RoutedT t r m)
50+instance HasCookies m => HasCookies (ConfigsT m)
51+instance HasConfigs m => HasConfigs (CookiesT m)
52+
53+newtype CookiesT m a = CookiesT { unCookiesT :: ReaderT Cookies m a }
54+ deriving
55+ ( Functor
56+ , Applicative
57+ , DomBuilder t
58+ , Monad
59+ , MonadFix
60+ , MonadHold t
61+ , MonadIO
62+#ifndef ghcjs_HOST_OS
63+ , MonadJSM
64+#endif
65+ , MonadRef
66+ , MonadReflexCreateTrigger t
67+ , MonadSample t
68+ , MonadTrans
69+ , NotReady t
70+ , PerformEvent t
71+ , PostBuild t
72+ , Prerender js t
73+ , TriggerEvent t
74+ , HasDocument
75+ )
76+
77+instance Adjustable t m => Adjustable t (CookiesT m) where
78+ runWithReplace a e = CookiesT $ runWithReplace (unCookiesT a) (unCookiesT <$> e)
79+ traverseDMapWithKeyWithAdjust f m e = CookiesT $ traverseDMapWithKeyWithAdjust (\k v -> unCookiesT $ f k v) m e
80+ traverseIntMapWithKeyWithAdjust f m e = CookiesT $ traverseIntMapWithKeyWithAdjust (\k v -> unCookiesT $ f k v) m e
81+ traverseDMapWithKeyWithAdjustWithMove f m e = CookiesT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unCookiesT $ f k v) m e
82+
83+instance PrimMonad m => PrimMonad (CookiesT m) where
84+ type PrimState (CookiesT m) = PrimState m
85+ primitive = lift . primitive
86+
87+runCookiesT
88+ :: Cookies
89+ -> CookiesT m a
90+ -> m a
91+runCookiesT cs child = runReaderT (unCookiesT child) cs
92+
93+instance Monad m => HasCookies (CookiesT m) where
94+ askCookies = CookiesT ask
95+
96+mapCookiesT
97+ :: (forall x. m x -> n x)
98+ -> CookiesT m a
99+ -> CookiesT n a
100+mapCookiesT f (CookiesT x) = CookiesT $ mapReaderT f x
101+
102+instance (MonadJSM m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => HasCookies (HydrationDomBuilderT s t m) where
103+ askCookies = fmap (parseCookies . encodeUtf8) $ getCookie =<< askDocument
lib/https/github.jsondeleted−7
@@ -1,7 +0,0 @@
1−{
2− "owner": "obsidiansystems",
3− "repo": "obelisk-https",
4− "private": true,
5− "rev": "862214f9379a830f5e5b45a03f267896bd752971",
6− "sha256": "1m2ryi157c6hwgalibygb5swj0w4kha1g438vnp6z0bbw31bcvzg"
7−}
lib/route/README.mdnew file+6
@@ -0,0 +1,6 @@
1+# obelisk-route
2+
3+[![Haskell Programming Language](https://img.shields.io/badge/language-Haskell-blue.svg)](http://www.haskell.org)
4+[![BSD3 License](http://img.shields.io/badge/license-BSD3-brightgreen.svg)](https://github.com/obsidiansystems/obelisk/blob/master/LICENSE)
5+
6+Robust URL management for single-page apps.
lib/route/obelisk-route.cabalnew file+42
@@ -0,0 +1,42 @@
1+name: obelisk-route
2+version: 0.2
3+cabal-version: >= 1.2
4+build-type: Simple
5+
6+library
7+ hs-source-dirs: src
8+ build-depends: base,
9+ aeson,
10+ bytestring,
11+ categories,
12+ constraints,
13+ constraints-extras,
14+ containers,
15+ dependent-map,
16+ dependent-sum,
17+ dependent-sum-template,
18+ either,
19+ ghcjs-dom,
20+ http-types,
21+ jsaddle,
22+ lens,
23+ mmorph,
24+ monad-control,
25+ mtl,
26+ network-uri,
27+ obelisk-executable-config-lookup,
28+ primitive,
29+ ref-tf,
30+ reflex,
31+ reflex-dom-core,
32+ template-haskell,
33+ tabulation,
34+ text,
35+ th-extras,
36+ transformers,
37+ universe,
38+ universe-dependent-sum
39+ exposed-modules: Obelisk.Route
40+ Obelisk.Route.TH
41+ Obelisk.Route.Frontend
42+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
lib/route/src/Obelisk/Route.hsnew file+1228
@@ -0,0 +1,1228 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ApplicativeDo #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE EmptyCase #-}
5+{-# LANGUAGE EmptyDataDecls #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE GADTs #-}
9+{-# LANGUAGE LambdaCase #-}
10+{-# LANGUAGE MultiParamTypeClasses #-}
11+{-# LANGUAGE OverloadedStrings #-}
12+{-# LANGUAGE PatternSynonyms #-}
13+{-# LANGUAGE RankNTypes #-}
14+{-# LANGUAGE ScopedTypeVariables #-}
15+{-# LANGUAGE StandaloneDeriving #-}
16+{-# LANGUAGE TemplateHaskell #-}
17+{-# LANGUAGE TypeApplications #-}
18+{-# LANGUAGE TypeFamilies #-}
19+{-# LANGUAGE TypeOperators #-}
20+{-# LANGUAGE ViewPatterns #-}
21+module Obelisk.Route
22+ ( R
23+ , (:.)
24+ , (?/)
25+ , hoistR
26+ , pattern (:.)
27+ , pattern (:/)
28+ , PageName
29+ , PathQuery
30+ , Encoder
31+ , unsafeEncoder
32+ , checkEncoder
33+ , EncoderImpl (..)
34+ , EncoderFunc (..)
35+ , unsafeMkEncoder
36+ , encode
37+ , decode
38+ , tryDecode
39+ , hoistCheck
40+ , hoistParse
41+ , mapSome
42+ , SegmentResult (..)
43+ , pathComponentEncoder
44+ , enumEncoder
45+ , enum1Encoder
46+ , checkEnum1EncoderFunc
47+ , unitEncoder
48+ , pathOnlyEncoder
49+ , addPathSegmentEncoder
50+ , pathParamEncoder
51+ , pathLiteralEncoder
52+ , singletonListEncoder
53+ , packTextEncoder
54+ , unpackTextEncoder
55+ , prefixTextEncoder
56+ , unsafeTshowEncoder
57+ , someConstEncoder
58+ , singlePathSegmentEncoder
59+ , maybeEncoder
60+ , maybeToEitherEncoder
61+ , justEncoder
62+ , nothingEncoder
63+ , isoEncoder
64+ , viewEncoder
65+ , wrappedEncoder
66+ , unwrappedEncoder
67+ , listToNonEmptyEncoder
68+ , prefixNonemptyTextEncoder
69+ , joinPairTextEncoder
70+ , toListMapEncoder
71+ , shadowEncoder
72+ , prismEncoder
73+ , reviewEncoder
74+ , rPrism
75+ , _R
76+ , obeliskRouteEncoder
77+ , obeliskRouteSegment
78+ , pageNameEncoder
79+ , handleEncoder
80+ , FullRoute (..)
81+ , _FullRoute_Frontend
82+ , _FullRoute_Backend
83+ , mkFullRouteEncoder
84+ , ObeliskRoute (..)
85+ , _ObeliskRoute_App
86+ , _ObeliskRoute_Resource
87+ , ResourceRoute (..)
88+ , JSaddleWarpRoute (..)
89+ , jsaddleWarpRouteEncoder
90+ , IndexOnlyRoute (..)
91+ , indexOnlyRouteSegment
92+ , indexOnlyRouteEncoder
93+ , someSumEncoder
94+ , Void1
95+ , void1Encoder
96+ , pathSegmentsTextEncoder
97+ , queryParametersTextEncoder
98+ , renderObeliskRoute
99+ , renderBackendRoute
100+ , renderFrontendRoute
101+ , readShowEncoder
102+ , integralEncoder
103+ , pathSegmentEncoder
104+ , queryOnlyEncoder
105+ , Decoder(..)
106+ , dmapEncoder
107+ , fieldMapEncoder
108+ , pathFieldEncoder
109+ , jsonEncoder
110+ , byteStringsToPageName
111+ ) where
112+
113+import Prelude hiding ((.), id)
114+
115+import Control.Applicative
116+import Control.Category (Category (..))
117+import qualified Control.Categorical.Functor as Cat
118+import Control.Categorical.Bifunctor
119+import Control.Category.Associative
120+import Control.Category.Monoidal
121+import Control.Category.Braided
122+import Control.Lens
123+ ( Identity (..)
124+ , (^.)
125+ , (^?)
126+ , _Just
127+ , _Nothing
128+ , Cons(..)
129+ , from
130+ , imap
131+ , iso
132+ , Iso'
133+ , itraverse
134+ , makePrisms
135+ , Prism'
136+ , prism'
137+ , re
138+ , review
139+ , view
140+ , Wrapped (..)
141+ )
142+import Control.Monad.Except
143+import qualified Control.Monad.State.Strict as State
144+import Control.Monad.Trans (lift)
145+import Control.Monad.Writer (execWriter, tell)
146+import Data.Aeson (FromJSON, ToJSON)
147+import qualified Data.Aeson as Aeson
148+import qualified Data.ByteString as BS
149+import qualified Data.ByteString.Lazy as BSL
150+import Data.Dependent.Map (DMap)
151+import qualified Data.Dependent.Map as DMap
152+import Data.Dependent.Sum (DSum (..))
153+import Data.Either.Validation (Validation (..))
154+import Data.Foldable
155+import Data.Functor (($>))
156+import Data.Functor.Sum
157+import Data.GADT.Compare
158+import Data.GADT.Compare.TH
159+import Data.GADT.Show
160+import Data.List.NonEmpty (NonEmpty (..))
161+import Data.Map (Map)
162+import qualified Data.Map as Map
163+import Data.Maybe
164+import Data.Monoid ((<>))
165+import Data.Set (Set)
166+import qualified Data.Set as Set
167+import Data.Some (Some(Some))
168+import Data.Tabulation
169+import Data.Text (Text)
170+import qualified Data.Text as T
171+import qualified Data.Text.Encoding as T
172+import Data.Text.Lens (IsText, packed, unpacked)
173+import Data.Type.Equality
174+import Data.Universe
175+import Data.Universe.Some
176+import Network.HTTP.Types.URI
177+import qualified Numeric.Lens
178+import Obelisk.Route.TH
179+import Text.Read (readMaybe)
180+
181+-- Design goals:
182+-- No start-up time on the frontend (not yet met)
183+-- Able to ensure that there aren't overlapping routes prior to deployment
184+-- Easy to write common types of parsers
185+-- Completeness checking
186+
187+-- Laws:
188+-- We statically know that all valid Routes can be turned into valid URIs
189+-- - This means we need to know whether there are any overlaps, e.g. with the static file namespace
190+
191+--TODO:
192+-- Backend:
193+-- Redirect the user to a canonical route
194+-- Pre-render
195+-- Frontend:
196+-- Intercept links that can be kept within the app
197+-- Fragments
198+
199+--------------------------------------------------------------------------------
200+-- Subroutes/paths
201+--------------------------------------------------------------------------------
202+
203+type R f = DSum f Identity --TODO: Better name
204+
205+-- | Convenience builder for an 'R' using 'Identity' for the functor.
206+pattern (:/) :: f a -> a -> R f
207+pattern a :/ b = a :=> Identity b
208+{-# COMPLETE (:/) #-}
209+infixr 5 :/
210+
211+-- | Like '(:/)' but adds a 'Just' wrapper around the right-hand side.
212+(?/) :: f (Maybe a) -> a -> R f
213+r ?/ a = r :/ Just a
214+infixr 5 ?/
215+
216+mapSome :: (forall a. f a -> g a) -> Some f -> Some g
217+mapSome f (Some a) = Some $ f a
218+
219+hoistR :: (forall x. f x -> g x) -> R f -> R g
220+hoistR f (x :=> Identity y) = f x :/ y
221+
222+--------------------------------------------------------------------------------
223+-- Dealing with pairs (i.e. non-dependently-typed subroutes/paths)
224+--------------------------------------------------------------------------------
225+
226+infixr 5 :.
227+type (:.) = (,)
228+
229+#ifdef __GLASGOW_HASKELL__
230+#if __GLASGOW_HASKELL__ >= 810
231+{-# COMPLETE (:.) #-}
232+#else
233+{-# WARNING (:.)
234+ [ "Use of this pattern in GHC < 8.10 will result in spurious non-exhaustive warnings at every use site."
235+ , "We cannot provide a COMPLETE pragma to silence these due to a GHC bug: https://gitlab.haskell.org/ghc/ghc/issues/17729."
236+ , "The bug hides incompleteness warnings for all two tuples when the COMPLETE pattern is in scope."
237+ , "Instead, you should use (,) directly until you can switch to GHC >= 8.10, where the COMPLETE pragma is reinstated."
238+ ]
239+ #-}
240+#endif
241+#endif
242+pattern (:.) :: a -> b -> a :. b
243+pattern a :. b = (a, b)
244+
245+addPathSegmentEncoder
246+ :: ( Applicative check
247+ , MonadError Text parse
248+ )
249+ => Encoder check parse (Text, PageName) PageName
250+addPathSegmentEncoder = unsafeMkEncoder $ EncoderImpl
251+ { _encoderImpl_encode = \(ph, (pt, q)) -> (ph : pt, q)
252+ , _encoderImpl_decode = \(p, q) -> case p of
253+ [] -> throwError "Expected a path segment"
254+ ph : pt -> pure (ph, (pt, q))
255+ }
256+
257+pathParamEncoder
258+ :: forall check parse item rest.
259+ ( Applicative check
260+ , MonadError Text parse
261+ )
262+ => Encoder check parse item Text
263+ -> Encoder check parse rest PageName
264+ -> Encoder check parse (item :. rest) PageName
265+pathParamEncoder itemUnchecked restUnchecked = addPathSegmentEncoder . bimap itemUnchecked restUnchecked
266+
267+pathLiteralEncoder
268+ :: ( Applicative check
269+ , MonadError Text parse
270+ )
271+ => Text
272+ -> Encoder check parse a PageName
273+ -> Encoder check parse a PageName
274+pathLiteralEncoder t e = addPathSegmentEncoder . bimap (unitEncoder t) e . coidl
275+
276+--------------------------------------------------------------------------------
277+-- Encoder fundamentals
278+--------------------------------------------------------------------------------
279+
280+-- | This is the type of route encoder/decoders. It is parameterised over two monads: Firstly, the monad
281+-- used to check the validity of the encoder (i.e. that it is total), secondly the monad used for parsing
282+-- during the decode phase. The following two parameters are respectively the type of decoded data, and the
283+-- encoded type.
284+newtype Encoder check parse decoded encoded =
285+ Encoder { unEncoder :: check (EncoderImpl parse decoded encoded) }
286+
287+unsafeEncoder :: check (EncoderImpl parse decoded encoded) -> Encoder check parse decoded encoded
288+unsafeEncoder = Encoder
289+
290+-- | The internal type used to construct primitive 'Encoder' values.
291+-- Law:
292+-- forall p. _encoderImpl_decode ve . _encoderImpl_encode ve p == pure
293+-- Note that the reverse may not be the case: when parsing, a route may be canonicalized, and erroneous routes may be collapsed to a single 404 route. However, as a consequence of the law, encode . decode must be idempotent.
294+data EncoderImpl parse decoded encoded = EncoderImpl
295+ { _encoderImpl_decode :: !(encoded -> parse decoded) -- Can fail; can lose information; must always succeed on outputs of `_encoderImpl_encode` and result in the original value
296+ , _encoderImpl_encode :: !(decoded -> encoded) -- Must be injective
297+ }
298+
299+-- | Once an 'Encoder' has been checked, so that its check monad has become 'Identity', and its parser is total
300+-- so that its parse monad is also 'Identity', it may be used to actually decode by applying this function.
301+decode :: Encoder Identity Identity decoded encoded -> encoded -> decoded
302+decode e x = runIdentity (tryDecode e x)
303+
304+-- | Once an 'Encoder' has been checked, so that its check monad has become 'Identity', even if the same is not true of the
305+-- parse monad, we may still attempt to decode with it in its parse monad.
306+tryDecode :: Encoder Identity parse decoded encoded -> encoded -> parse decoded
307+tryDecode (Encoder (Identity impl)) = _encoderImpl_decode impl
308+
309+-- | Similar to 'decode', once an encoder has been checked so that its check monad is Identity, it
310+-- can be used to actually encode by using this. Note that while there's no constraint on the parse monad here,
311+-- one should usually be applying decode and encode to the same 'Encoder'
312+encode :: Encoder Identity parse decoded encoded -> decoded -> encoded
313+encode (Encoder (Identity impl)) = _encoderImpl_encode impl
314+
315+-- | This is a primitive used to build encoders which can't fail to check. It should not be used unless one is
316+-- reasonably certain that the law given for 'EncoderImpl' above holds.
317+unsafeMkEncoder :: (Applicative check) => EncoderImpl parse decoded encoded -> Encoder check parse decoded encoded
318+unsafeMkEncoder impl = Encoder (pure impl)
319+
320+-- | Transform the check monad of an 'Encoder' by applying a natural transformation.
321+hoistCheck :: (forall t. check t -> check' t) -> Encoder check parse a b -> Encoder check' parse a b
322+hoistCheck f (Encoder x) = Encoder (f x)
323+
324+-- | Transform the parse monad of an 'Encoder' by applying a natural transformation.
325+hoistParse :: (Functor check)
326+ => (forall t. parse t -> parse' t) -> Encoder check parse a b -> Encoder check parse' a b
327+hoistParse f (Encoder x) = Encoder (fmap (\(EncoderImpl dec enc) -> EncoderImpl (f . dec) enc) x)
328+
329+-- | Check an 'Encoder', transforming it into one whose check monad is anything we want (usually Identity).
330+checkEncoder :: (Applicative check', Functor check)
331+ => Encoder check parse decoded encoded
332+ -> check (Encoder check' parse decoded encoded)
333+checkEncoder = fmap unsafeMkEncoder . unEncoder
334+
335+instance (Applicative check, Monad parse) => Category (Encoder check parse) where
336+ id = Encoder $ pure id
337+ Encoder f . Encoder g = Encoder $ liftA2 (.) f g
338+
339+instance Monad parse => Category (EncoderImpl parse) where
340+ id = EncoderImpl
341+ { _encoderImpl_decode = pure
342+ , _encoderImpl_encode = id
343+ }
344+ f . g = EncoderImpl
345+ { _encoderImpl_decode = _encoderImpl_decode g <=< _encoderImpl_decode f
346+ , _encoderImpl_encode = _encoderImpl_encode f . _encoderImpl_encode g
347+ }
348+
349+instance Monad parse => PFunctor (,) (EncoderImpl parse) (EncoderImpl parse) where
350+ first f = bimap f id
351+instance Monad parse => QFunctor (,) (EncoderImpl parse) (EncoderImpl parse) where
352+ second g = bimap id g
353+instance Monad parse => Bifunctor (,) (EncoderImpl parse) (EncoderImpl parse) (EncoderImpl parse) where
354+ bimap f g = EncoderImpl
355+ { _encoderImpl_encode = bimap (_encoderImpl_encode f) (_encoderImpl_encode g)
356+ , _encoderImpl_decode = \(a, b) -> liftA2 (,) (_encoderImpl_decode f a) (_encoderImpl_decode g b)
357+ }
358+
359+instance (Monad parse, Applicative check) => Braided (Encoder check parse) (,) where
360+ braid = viewEncoder (iso swap swap)
361+
362+
363+instance (Applicative check, Monad parse) => PFunctor (,) (Encoder check parse) (Encoder check parse) where
364+ first f = bimap f id
365+instance (Applicative check, Monad parse) => QFunctor (,) (Encoder check parse) (Encoder check parse) where
366+ second g = bimap id g
367+instance (Applicative check, Monad parse) => Bifunctor (,) (Encoder check parse) (Encoder check parse) (Encoder check parse) where
368+ bimap f g = Encoder $ liftA2 bimap (unEncoder f) (unEncoder g)
369+
370+instance (Traversable f, Monad parse) => Cat.Functor f (EncoderImpl parse) (EncoderImpl parse) where
371+ fmap ve = EncoderImpl
372+ { _encoderImpl_encode = fmap $ _encoderImpl_encode ve
373+ , _encoderImpl_decode = traverse $ _encoderImpl_decode ve
374+ }
375+
376+instance Monad parse => PFunctor Either (EncoderImpl parse) (EncoderImpl parse) where
377+ first f = bimap f id
378+instance Monad parse => QFunctor Either (EncoderImpl parse) (EncoderImpl parse) where
379+ second g = bimap id g
380+instance Monad parse => Bifunctor Either (EncoderImpl parse) (EncoderImpl parse) (EncoderImpl parse) where
381+ bimap f g = EncoderImpl
382+ { _encoderImpl_encode = bimap (_encoderImpl_encode f) (_encoderImpl_encode g)
383+ , _encoderImpl_decode = \case
384+ Left a -> Left <$> _encoderImpl_decode f a
385+ Right b -> Right <$> _encoderImpl_decode g b
386+ }
387+
388+instance (Monad parse, Applicative check) => QFunctor Either (Encoder check parse) (Encoder check parse) where
389+ second g = bimap id g
390+instance (Monad parse, Applicative check) => PFunctor Either (Encoder check parse) (Encoder check parse) where
391+ first f = bimap f id
392+instance (Monad parse, Applicative check) => Bifunctor Either (Encoder check parse) (Encoder check parse) (Encoder check parse) where
393+ bimap f g = Encoder $ liftA2 bimap (unEncoder f) (unEncoder g)
394+
395+instance (Applicative check, Monad parse) => Associative (Encoder check parse) Either where
396+ associate = viewEncoder (iso (associate @(->) @Either) disassociate)
397+ disassociate = viewEncoder (iso disassociate associate)
398+
399+instance (Monad parse, Applicative check) => Braided (Encoder check parse) Either where
400+ braid = viewEncoder (iso swap swap)
401+
402+
403+
404+instance (Traversable f, Monad check, Monad parse) => Cat.Functor f (Encoder check parse) (Encoder check parse) where
405+ fmap e = Encoder $ do
406+ ve <- unEncoder e
407+ pure $ Cat.fmap ve
408+
409+instance Monad parse => Associative (EncoderImpl parse) (,) where
410+ associate = EncoderImpl
411+ { _encoderImpl_encode = associate
412+ , _encoderImpl_decode = pure . disassociate
413+ }
414+ disassociate = EncoderImpl
415+ { _encoderImpl_encode = disassociate
416+ , _encoderImpl_decode = pure . associate
417+ }
418+
419+instance Monad parse => Monoidal (EncoderImpl parse) (,) where
420+ type Id (EncoderImpl parse) (,) = ()
421+ idl = EncoderImpl
422+ { _encoderImpl_encode = idl
423+ , _encoderImpl_decode = pure . coidl
424+ }
425+ idr = EncoderImpl
426+ { _encoderImpl_encode = idr
427+ , _encoderImpl_decode = pure . coidr
428+ }
429+ coidl = EncoderImpl
430+ { _encoderImpl_encode = coidl
431+ , _encoderImpl_decode = pure . idl
432+ }
433+ coidr = EncoderImpl
434+ { _encoderImpl_encode = coidr
435+ , _encoderImpl_decode = pure . idr
436+ }
437+
438+instance (Applicative check, Monad parse) => Associative (Encoder check parse) (,) where
439+ associate = Encoder $ pure associate
440+ disassociate = Encoder $ pure disassociate
441+
442+instance (Applicative check, Monad parse) => Monoidal (Encoder check parse) (,) where
443+ type Id (Encoder check parse) (,) = ()
444+ idl = Encoder $ pure idl
445+ idr = Encoder $ pure idr
446+ coidl = Encoder $ pure coidl
447+ coidr = Encoder $ pure coidr
448+
449+--------------------------------------------------------------------------------
450+-- Specific instances of encoders
451+--------------------------------------------------------------------------------
452+
453+-- | Given a valid 'Iso' from lens, construct an 'Encoder'
454+viewEncoder :: (Applicative check, Applicative parse) => Iso' a b -> Encoder check parse a b
455+viewEncoder f = unsafeMkEncoder $ EncoderImpl
456+ { _encoderImpl_encode = view f
457+ , _encoderImpl_decode = pure . view (from f)
458+ }
459+
460+wrappedEncoder :: (Wrapped a, Applicative check, Applicative parse) => Encoder check parse (Unwrapped a) a
461+wrappedEncoder = viewEncoder $ from _Wrapped'
462+
463+unwrappedEncoder :: (Wrapped a, Applicative check, Applicative parse) => Encoder check parse a (Unwrapped a)
464+unwrappedEncoder = viewEncoder $ _Wrapped'
465+
466+maybeToEitherEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Maybe a) (Either () a)
467+maybeToEitherEncoder = unsafeMkEncoder $ EncoderImpl
468+ { _encoderImpl_encode = \case
469+ Nothing -> Left ()
470+ Just a -> Right a
471+ , _encoderImpl_decode = pure . \case
472+ Left _ -> Nothing
473+ Right a -> Just a
474+ }
475+
476+maybeEncoder
477+ :: ( MonadError Text check
478+ , Show a
479+ , Show b
480+ , check ~ parse
481+ )
482+ => Encoder check parse () b
483+ -> Encoder check parse a b
484+ -> Encoder check parse (Maybe a) b
485+maybeEncoder f g = shadowEncoder f g . maybeToEitherEncoder
486+
487+-- | Encode a value by simply applying 'Just'
488+justEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse a (Maybe a)
489+justEncoder = reviewEncoder _Just
490+
491+-- | Encode () to 'Nothing'.
492+nothingEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse () (Maybe a)
493+nothingEncoder = reviewEncoder _Nothing
494+
495+someConstEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Some (Const a)) a
496+someConstEncoder = unsafeMkEncoder $ EncoderImpl
497+ { _encoderImpl_encode = \(Some (Const a)) -> a
498+ , _encoderImpl_decode = pure . Some . Const
499+ }
500+
501+-- | WARNING: This is only safe if the Show and Read instances for 'a' are
502+-- inverses of each other
503+unsafeTshowEncoder :: (Show a, Read a, Applicative check, MonadError Text parse) => Encoder check parse a Text
504+unsafeTshowEncoder = unsafeMkEncoder $ EncoderImpl
505+ { _encoderImpl_encode = tshow
506+ , _encoderImpl_decode = \raw -> case readMaybe $ T.unpack raw of
507+ Nothing -> throwError $ "unsafeTshowEncoderImpl: couldn't decode " <> tshow raw
508+ Just parsed -> pure parsed
509+ }
510+
511+newtype EncoderFunc check parse p r = EncoderFunc { runEncoderImplFunc :: forall a. p a -> Encoder check parse a r }
512+
513+newtype Flip f a b = Flip { unFlip :: f b a }
514+
515+checkEnum1EncoderFunc
516+ :: forall check check' parse p r.
517+ ( Universe (Some p)
518+ , GCompare p
519+ , Monad check
520+ , Applicative check'
521+ )
522+ => (forall a. p a -> Encoder check parse a r)
523+ -> check (EncoderFunc check' parse p r)
524+checkEnum1EncoderFunc f = do
525+ (encoderImpls :: DMap p (Flip (EncoderImpl parse) r)) <- DMap.fromList <$>
526+ traverse (\(Some p) -> (p :=>) . Flip <$> unEncoder (f p)) universe
527+ pure $ EncoderFunc $ \p -> unsafeMkEncoder . unFlip $
528+ DMap.findWithDefault (error "checkEnum1EncoderFunc: EncoderImpl not found (should be impossible)") p encoderImpls
529+
530+-- | This type is used by pathComponentEncoder to allow the user to indicate how to treat various cases when encoding a dependent sum of type `(R p)`.
531+data SegmentResult check parse a =
532+ PathEnd (Encoder check parse a (Map Text (Maybe Text))) -- ^ Indicate that the path is finished, with an Encoder that translates the corresponding value into query parameters
533+ | PathSegment Text (Encoder check parse a PageName) -- ^ Indicate that the key should be represented by an additional path segment with the given 'Text', and give an Encoder for translating the corresponding value into the remainder of the route.
534+
535+-- | Encode a dependent sum of type `(R p)` into a PageName (i.e. the path and query part of a URL) by using the
536+-- supplied function to decide how to encode the constructors of p using the SegmentResult type. It is important
537+-- that the number of values of type `(Some p)` be relatively small in order for checking to complete quickly.
538+pathComponentEncoder
539+ :: forall check parse p.
540+ ( Universe (Some p)
541+ , GShow p
542+ , GCompare p
543+ , MonadError Text check
544+ , MonadError Text parse )
545+ => (forall a. p a -> SegmentResult check parse a)
546+ -> Encoder check parse (R p) PageName
547+pathComponentEncoder f = Encoder $ do
548+ let extractEncoder = \case
549+ PathEnd e -> first (unitEncoder []) . coidl . e
550+ PathSegment _ e -> e
551+ extractPathSegment = \case
552+ PathEnd _ -> Nothing
553+ PathSegment t _ -> Just t
554+ EncoderFunc f' <- checkEnum1EncoderFunc (extractEncoder . f)
555+ unEncoder (pathComponentEncoderImpl (enum1Encoder (extractPathSegment . f)) f')
556+
557+pathComponentEncoderImpl :: forall check parse p. (Monad check, Monad parse)
558+ => Encoder check parse (Some p) (Maybe Text)
559+ -> (forall a. p a -> Encoder Identity parse a PageName)
560+ -> Encoder check parse (R p) PageName
561+pathComponentEncoderImpl =
562+ chainEncoder (lensEncoder (\(_, b) a -> (a, b)) Prelude.fst consEncoder)
563+
564+--NOTE: Naming convention in this module is to always talk about things in the *encoding* direction, never in the *decoding* direction
565+
566+chainEncoder
567+ :: forall check parse p r b.
568+ ( Monad check
569+ , Monad parse
570+ )
571+ => Encoder check parse (b, r) r
572+ -> Encoder check parse (Some p) b
573+ -> (forall a. p a -> Encoder Identity parse a r)
574+ -> Encoder check parse (R p) r
575+chainEncoder cons this rest = Encoder $ do
576+ consValid <- unEncoder cons
577+ thisValid <- unEncoder this
578+ pure $ EncoderImpl
579+ { _encoderImpl_decode = \v -> do
580+ (here, following) <- _encoderImpl_decode consValid v
581+ _encoderImpl_decode thisValid here >>= \case
582+ Some r ->
583+ (r :/) <$> _encoderImpl_decode (runIdentity . unEncoder $ rest r) following
584+ , _encoderImpl_encode = \(r :/ s) ->
585+ _encoderImpl_encode consValid
586+ ( _encoderImpl_encode thisValid $ Some r
587+ , _encoderImpl_encode (runIdentity . unEncoder $ rest r) s)
588+ }
589+
590+--TODO: Do this in terms of a lens instead
591+lensEncoder :: (Applicative check, Monad parse)
592+ => (b -> [a] -> b) -> (b -> [a]) -> Encoder check parse (c, [a]) [a] -> Encoder check parse (c, b) b
593+lensEncoder set get g = Encoder $ do
594+ gImpl <- unEncoder g
595+ pure $ EncoderImpl
596+ { _encoderImpl_encode = \(ma, b) -> set b $ _encoderImpl_encode gImpl (ma, get b)
597+ , _encoderImpl_decode = \b -> do
598+ (ma, la) <- _encoderImpl_decode gImpl $ get b
599+ pure (ma, set b la)
600+ }
601+
602+consEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Maybe a, [a]) [a] --TODO: Really shouldn't *always* have the [a], even in the Nothing case
603+consEncoder = unsafeMkEncoder $ EncoderImpl
604+ { _encoderImpl_encode = \(h, t) -> maybeToList h <> t
605+ , _encoderImpl_decode = pure . \case
606+ [] -> (Nothing, [])
607+ h:t -> (Just h, t)
608+ }
609+
610+tshow :: Show a => a -> Text
611+tshow = T.pack . show
612+
613+shadowEncoder
614+ :: ( Universe a
615+ , MonadError Text check
616+ , Show a
617+ , Show b
618+ , Show c
619+ , check ~ parse --TODO: Get rid of this
620+ )
621+ => Encoder check parse a c -- ^ Overlaps; should have a small number of possible routes
622+ -> Encoder check parse b c -- ^ Gets overlapped
623+ -> Encoder check parse (Either a b) c
624+shadowEncoder f g = Encoder $ do
625+ vf <- unEncoder f
626+ vg <- unEncoder g
627+ let gCanParse c = catchError (Just <$> _encoderImpl_decode vg c) (\_ -> pure Nothing)
628+ overlaps <- fmap catMaybes $ forM universe $ \a -> do
629+ let c = _encoderImpl_encode vf a
630+ mb <- gCanParse c
631+ pure $ fmap (\b -> (a, b, c)) mb
632+ case overlaps of
633+ [] -> pure ()
634+ _ -> throwError $ "shadowEncoder: overlap detected: " <> T.unlines
635+ (flip fmap overlaps $ \(a, b, c) -> "first encoder encodes " <> tshow a <> " as " <> tshow c <> ", which second encoder decodes as " <> tshow b)
636+ pure $ EncoderImpl
637+ { _encoderImpl_encode = \case
638+ Left a -> _encoderImpl_encode vf a
639+ Right b -> _encoderImpl_encode vg b
640+ , _encoderImpl_decode = \c -> (Left <$> _encoderImpl_decode vf c) `catchError` \_ -> Right <$> _encoderImpl_decode vg c
641+ }
642+
643+enum1Encoder
644+ :: ( Universe (Some p)
645+ , GShow p
646+ , GCompare p
647+ , MonadError Text check
648+ , MonadError Text parse
649+ , Ord r
650+ , Show r
651+ )
652+ => (forall a. p a -> r) -> Encoder check parse (Some p) r
653+enum1Encoder f = enumEncoder $ \(Some p) -> f p
654+
655+-- | Encode an enumerable, bounded type. WARNING: Don't use this on types that
656+-- have a large number of values - it will use a lot of memory.
657+enumEncoder :: forall parse check p r. (Universe p, Show p, Ord p, Ord r, MonadError Text parse, MonadError Text check, Show r) => (p -> r) -> Encoder check parse p r
658+enumEncoder f = Encoder $ do
659+ let reversed = Map.fromListWith (<>) [ (f p, Set.singleton p) | p <- universe ]
660+ checkSingleton k vs = case Set.toList vs of
661+ [] -> error "enumEncoder: empty reverse mapping; should be impossible"
662+ [e] -> Success e
663+ _ -> Failure $ Map.singleton k vs
664+ showRedundant :: r -> Set p -> [Text]
665+ showRedundant k vs = (" " <> tshow k <> " can decode to any of:")
666+ : fmap ((" "<>) . tshow) (Set.toList vs)
667+ case itraverse checkSingleton reversed :: Validation (Map r (Set p)) (Map r p) of
668+ Failure ambiguousEntries -> throwError $ T.unlines $
669+ "enumEncoder: ambiguous encodings detected:" : concat (Map.elems $ imap showRedundant ambiguousEntries)
670+ Success m -> pure $ EncoderImpl
671+ { _encoderImpl_decode = \r -> case Map.lookup r m of
672+ Just a -> pure a
673+ Nothing -> throwError $ "enumEncoder: not recognized: " <> tshow r --TODO: Report this as a better type
674+ , _encoderImpl_encode = f
675+ }
676+
677+unitEncoder :: (Applicative check, MonadError Text parse, Show r, Eq r) => r -> Encoder check parse () r
678+unitEncoder expected = unsafeMkEncoder $ EncoderImpl
679+ { _encoderImpl_decode = \obtained ->
680+ if obtained == expected
681+ then pure ()
682+ else throwError $ "endEncoderImpl: expected " <> tshow expected <> ", got " <> tshow obtained
683+ , _encoderImpl_encode = \_ -> expected
684+ }
685+
686+singlePathSegmentEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse Text PageName
687+singlePathSegmentEncoder = pathOnlyEncoder . singletonListEncoder
688+
689+pathOnlyEncoderIgnoringQuery :: (Applicative check, MonadError Text parse) => Encoder check parse [Text] PageName
690+pathOnlyEncoderIgnoringQuery = unsafeMkEncoder $ EncoderImpl
691+ { _encoderImpl_decode = \(path, _query) -> pure path
692+ , _encoderImpl_encode = \path -> (path, mempty)
693+ }
694+
695+pathOnlyEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse [Text] PageName
696+pathOnlyEncoder = second (unitEncoder mempty) . coidr
697+
698+queryOnlyEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse (Map Text (Maybe Text)) PageName
699+queryOnlyEncoder = first (unitEncoder []) . coidl
700+
701+singletonListEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse a [a]
702+singletonListEncoder = unsafeMkEncoder $ EncoderImpl
703+ { _encoderImpl_decode = \case
704+ [a] -> pure a
705+ l -> throwError $ "singletonListEncoderImpl: expected one item, got " <> tshow (length l)
706+ , _encoderImpl_encode = (:[])
707+ }
708+
709+splitTextNonEmpty :: Text -> Text -> NonEmpty Text
710+splitTextNonEmpty separator v = case T.splitOn separator v of
711+ [] -> error "splitTextNonEmpty: Data.Text.splitOn should never return an empty list"
712+ h : t -> h :| t
713+
714+--TODO: To know this is reversible, we must know that the separator isn't included anywhere in the input text
715+pathSegmentsTextEncoder :: (Applicative check, Applicative parse) => Encoder check parse (NonEmpty Text) Text
716+pathSegmentsTextEncoder = unsafeMkEncoder $ EncoderImpl
717+ { _encoderImpl_encode = T.intercalate "/" . fmap (urlEncodeText False) . toList
718+ , _encoderImpl_decode = pure . fmap (urlDecodeText False) . splitTextNonEmpty "/"
719+ }
720+
721+queryParametersTextEncoder :: (Applicative check, Applicative parse) => Encoder check parse [(Text, Maybe Text)] Text
722+queryParametersTextEncoder = Encoder $ pure $ EncoderImpl
723+ { _encoderImpl_encode = \case
724+ [] -> ""
725+ params -> T.intercalate "&" (fmap encodeParameter params)
726+ , _encoderImpl_decode = pure . \case
727+ "" -> []
728+ encoded ->
729+ let h :| t = splitTextNonEmpty "&" encoded
730+ in fmap decodeParameter $ h : t
731+ }
732+ where
733+ encodeParameter (k, mv) = urlEncodeText True k <> case mv of
734+ Nothing -> ""
735+ Just v -> "=" <> urlEncodeText True v
736+ decodeParameter t =
737+ let (k, eqV) = T.breakOn "=" t
738+ mv = T.stripPrefix "=" eqV
739+ in (urlDecodeText True k, urlDecodeText True <$> mv)
740+
741+urlEncodeText :: Bool -> Text -> Text
742+urlEncodeText q = T.decodeUtf8 . urlEncode q . T.encodeUtf8
743+
744+urlDecodeText :: Bool -> Text -> Text
745+urlDecodeText q = T.decodeUtf8 . urlDecode q . T.encodeUtf8
746+
747+listToNonEmptyEncoder :: (Applicative check, Applicative parse, Monoid a, Eq a) => Encoder check parse [a] (NonEmpty a)
748+listToNonEmptyEncoder = Encoder $ pure $ EncoderImpl
749+ { _encoderImpl_encode = \case
750+ [] -> mempty :| []
751+ h : t -> h :| t
752+ , _encoderImpl_decode = \(h :| t) -> pure $
753+ if h == mempty
754+ then []
755+ else h : t
756+ }
757+
758+prefixTextEncoder :: (Applicative check, MonadError Text parse) => Text -> Encoder check parse Text Text
759+prefixTextEncoder p = Encoder $ pure $ EncoderImpl
760+ { _encoderImpl_encode = mappend p
761+ , _encoderImpl_decode = \v -> case T.stripPrefix p v of
762+ Nothing -> throwError $ "prefixTextEncoder: wrong prefix; expected " <> tshow p <> ", got " <> tshow (T.take (T.length p) v)
763+ Just stripped -> pure stripped
764+ }
765+
766+prefixNonemptyTextEncoder :: (Applicative check, MonadError Text parse) => Text -> Encoder check parse Text Text
767+prefixNonemptyTextEncoder p = Encoder $ pure $ EncoderImpl
768+ { _encoderImpl_encode = \case
769+ "" -> ""
770+ v -> p <> v
771+ , _encoderImpl_decode = \case
772+ "" -> pure ""
773+ v -> case T.stripPrefix p v of
774+ Nothing -> throwError $ "prefixTextEncoder: wrong prefix; expected " <> tshow p
775+ Just stripped -> pure stripped
776+ }
777+
778+packTextEncoder :: (Applicative check, Applicative parse, IsText text) => Encoder check parse String text
779+packTextEncoder = isoEncoder packed
780+
781+unpackTextEncoder :: (Applicative check, Applicative parse, IsText text) => Encoder check parse text String
782+unpackTextEncoder = isoEncoder unpacked
783+
784+toListMapEncoder :: (Applicative check, Applicative parse, Ord k) => Encoder check parse (Map k v) [(k, v)]
785+toListMapEncoder = Encoder $ pure $ EncoderImpl
786+ { _encoderImpl_encode = Map.toList
787+ , _encoderImpl_decode = pure . Map.fromList --TODO: Should we be stricter about repeated keys?
788+ }
789+
790+joinPairTextEncoder :: (MonadError Text check, MonadError Text parse) => Text -> Encoder check parse (Text, Text) Text
791+joinPairTextEncoder = Encoder . \case
792+ "" -> throwError "joinPairTextEncoder: empty separator"
793+ separator -> pure $ EncoderImpl
794+ { _encoderImpl_encode = \(k, v) -> k <> separator <> v
795+ , _encoderImpl_decode = \r ->
796+ let (kt, vt) = T.breakOn separator r
797+ in case vt of
798+ -- The separator was not found
799+ "" -> throwError $ "joinPairTextEncoder: separator not found; expected " <> tshow separator
800+ _ -> return (kt, T.drop (T.length separator) vt)
801+ }
802+
803+-- This slight generalization of 'rPrism' happens to be enough to write all our
804+-- prism combinators so far.
805+dSumPrism
806+ :: forall f f' g
807+ . (forall a. Prism' (f a) (f' a))
808+ -> Prism' (DSum f g) (DSum f' g)
809+dSumPrism p = prism'
810+ (\(f' :=> x) -> f' ^. re p :=> x)
811+ (\(f :=> x) -> (:=> x) <$> (f ^? p))
812+
813+-- already in obelisk
814+rPrism
815+ :: forall f f'
816+ . (forall a. Prism' (f a) (f' a))
817+ -> Prism' (R f) (R f')
818+rPrism = dSumPrism
819+
820+dSumPrism'
821+ :: forall f g a
822+ . (forall b. Prism' (f b) (a :~: b))
823+ -> Prism' (DSum f g) (g a)
824+dSumPrism' p = dSumPrism p . iso (\(Refl :=> b) -> b) (Refl :=>)
825+
826+dSumGEqPrism
827+ :: GEq f
828+ => f a
829+ -> Prism' (DSum f g) (g a)
830+dSumGEqPrism variant = dSumPrism' $ prism' (\Refl -> variant) (geq variant)
831+
832+-- | Given a 'tag :: f a', make a prism for 'R f'. This generalizes the usual
833+-- prisms for a sum type (the ones that 'mkPrisms' would make), just as 'R'
834+-- generalized a usual sum type.
835+--
836+-- [This is given the '_R' name of the "cannonical" prism not because it is the
837+-- most general, but because it seems the most useful for routes, and 'R' itself
838+-- trades generality for route-specificity.]
839+_R
840+ :: GEq f
841+ => f a
842+ -> Prism' (R f) a
843+_R variant = dSumGEqPrism variant . iso runIdentity Identity
844+
845+-- | An encoder that only works on the items available via the prism. An error will be thrown in the parse monad
846+-- if the prism doesn't match.
847+--
848+-- Note that a 'Prism' from @a@ to @b@ will produce an 'Encoder' from @b@ to @a@
849+-- (i.e. 'reviewEncoder' is a contravariant functor from the category of prisms to the category of encoders),
850+-- just like 'review' produces a function @b -> a@. This is because 'Prism's extract values, in a way that might
851+-- fail, in their forward direction and inject values, in a way that cannot fail, in their reverse direction;
852+-- whereas 'Encoder's encode, which cannot fail, in their forward direction, and decode, which can fail, in their
853+-- reverse direction. In short @reviewEncoder (f . g) = reviewEncoder g . reviewEncoder f@.
854+reviewEncoder :: (Applicative check, MonadError Text parse) => Prism' b a -> Encoder check parse a b
855+reviewEncoder p = unsafeMkEncoder $ EncoderImpl
856+ { _encoderImpl_encode = review p
857+ , _encoderImpl_decode = \r -> case r ^? p of
858+ Just a -> pure a
859+ Nothing -> throwError "reviewEncoder: value is not present in the prism"
860+ }
861+
862+-- | A URL path and query string, in which trailing slashes don't matter in the path
863+-- and duplicate query parameters are not allowed. A final goal of encoders using this library
864+-- will frequently be to produce this.
865+type PageName = ([Text], Map Text (Maybe Text))
866+
867+-- | A path (separated by slashes), and a query string.
868+type PathQuery = (String, String)
869+
870+-- | Encode a PageName into a path and query string.
871+pageNameEncoder :: (Applicative check, MonadError Text parse) => Encoder check parse PageName PathQuery
872+pageNameEncoder = bimap
873+ (unpackTextEncoder . prefixTextEncoder "/" . pathSegmentsTextEncoder . listToNonEmptyEncoder)
874+ (unpackTextEncoder . prefixNonemptyTextEncoder "?" . queryParametersTextEncoder . toListMapEncoder)
875+
876+-- | Handle an error in parsing, for example, in order to redirect to a 404 page.
877+handleEncoder
878+ :: (Functor check)
879+ => (e -> a)
880+ -> Encoder check (Either e) a b
881+ -> Encoder check Identity a b
882+handleEncoder recover e = Encoder $ do
883+ i <- unEncoder e
884+ return $ i
885+ { _encoderImpl_decode = \a -> pure $ case _encoderImpl_decode i a of
886+ Right r -> r
887+ Left err -> recover err
888+ }
889+
890+--------------------------------------------------------------------------------
891+-- Actual obelisk route info
892+--------------------------------------------------------------------------------
893+
894+-- | The typical full route type comprising all of an Obelisk application's routes.
895+-- Parameterised by the top level GADTs that define backend and frontend routes, respectively.
896+data FullRoute :: (* -> *) -> (* -> *) -> * -> * where
897+ FullRoute_Backend :: br a -> FullRoute br fr a
898+ FullRoute_Frontend :: ObeliskRoute fr a -> FullRoute br fr a
899+
900+instance (GShow br, GShow fr) => GShow (FullRoute br fr) where
901+ gshowsPrec p = \case
902+ FullRoute_Backend x -> showParen (p > 10) (showString "FullRoute_Backend " . gshowsPrec 11 x)
903+ FullRoute_Frontend x -> showParen (p > 10) (showString "FullRoute_Frontend " . gshowsPrec 11 x)
904+
905+instance (GEq br, GEq fr) => GEq (FullRoute br fr) where
906+ geq (FullRoute_Backend x) (FullRoute_Backend y) = geq x y
907+ geq (FullRoute_Frontend x) (FullRoute_Frontend y) = geq x y
908+ geq _ _ = Nothing
909+
910+instance (GCompare br, GCompare fr) => GCompare (FullRoute br fr) where
911+ gcompare (FullRoute_Backend _) (FullRoute_Frontend _) = GLT
912+ gcompare (FullRoute_Frontend _) (FullRoute_Backend _) = GGT
913+ gcompare (FullRoute_Backend x) (FullRoute_Backend y) = gcompare x y
914+ gcompare (FullRoute_Frontend x) (FullRoute_Frontend y) = gcompare x y
915+
916+instance (UniverseSome br, UniverseSome fr) => UniverseSome (FullRoute br fr) where
917+ universeSome = [Some (FullRoute_Backend x) | Some x <- universeSome]
918+ ++ [Some (FullRoute_Frontend x) | Some x <- universeSome]
919+
920+-- | Build the typical top level application route encoder from a route for handling 404's,
921+-- and segment encoders for backend and frontend routes.
922+mkFullRouteEncoder
923+ :: (GCompare br, GCompare fr, GShow br, GShow fr, UniverseSome br, UniverseSome fr)
924+ => R (FullRoute br fr) -- ^ 404 handler
925+ -> (forall a. br a -> SegmentResult (Either Text) (Either Text) a) -- ^ How to encode a single backend route segment
926+ -> (forall a. fr a -> SegmentResult (Either Text) (Either Text) a) -- ^ How to encode a single frontend route segment
927+ -> Encoder (Either Text) Identity (R (FullRoute br fr)) PageName
928+mkFullRouteEncoder missing backendSegment frontendSegment = handleEncoder (const missing) $
929+ pathComponentEncoder $ \case
930+ FullRoute_Backend backendRoute -> backendSegment backendRoute
931+ FullRoute_Frontend obeliskRoute -> obeliskRouteSegment obeliskRoute frontendSegment
932+
933+-- | A type which can represent Obelisk-specific resource routes, in addition to application specific routes which serve your
934+-- frontend.
935+data ObeliskRoute :: (* -> *) -> * -> * where
936+ -- We need to have the `f a` as an argument here, because otherwise we have no way to specifically check for overlap between us and the given encoder
937+ ObeliskRoute_App :: f a -> ObeliskRoute f a
938+ ObeliskRoute_Resource :: ResourceRoute a -> ObeliskRoute f a
939+
940+instance UniverseSome f => UniverseSome (ObeliskRoute f) where
941+ universeSome = concat
942+ [ (\(Some x) -> Some (ObeliskRoute_App x)) <$> universe
943+ , (\(Some x) -> Some (ObeliskRoute_Resource x)) <$> universe
944+ ]
945+
946+instance GEq f => GEq (ObeliskRoute f) where
947+ geq (ObeliskRoute_App x) (ObeliskRoute_App y) = geq x y
948+ geq (ObeliskRoute_Resource x) (ObeliskRoute_Resource y) = geq x y
949+ geq _ _ = Nothing
950+
951+instance GCompare f => GCompare (ObeliskRoute f) where
952+ gcompare (ObeliskRoute_App x) (ObeliskRoute_App y) = gcompare x y
953+ gcompare (ObeliskRoute_Resource x) (ObeliskRoute_Resource y) = gcompare x y
954+ gcompare (ObeliskRoute_App _) (ObeliskRoute_Resource _) = GLT
955+ gcompare (ObeliskRoute_Resource _) (ObeliskRoute_App _) = GGT
956+
957+-- | A type representing the various resource routes served by Obelisk. These can in principle map to any physical routes you want,
958+-- but sane defaults are provided by 'resourceRouteSegment'
959+data ResourceRoute :: * -> * where
960+ ResourceRoute_Static :: ResourceRoute [Text] -- This [Text] represents the *path in our static files directory*, not necessarily the URL path that the asset gets served at (although that will often be "/static/this/text/thing")
961+ ResourceRoute_Ghcjs :: ResourceRoute [Text]
962+ ResourceRoute_JSaddleWarp :: ResourceRoute (R JSaddleWarpRoute)
963+ ResourceRoute_Version :: ResourceRoute ()
964+
965+-- | If there are no additional backend routes in your app (i.e. ObeliskRoute gives you all the routes you need),
966+-- this constructs a suitable 'Encoder' to use for encoding routes to 'PageName's. If you do have additional backend routes,
967+-- you'll want to use 'pathComponentEncoder' yourself, applied to a function that will likely use obeliskRouteSegment in order to
968+-- handle the ObeliskRoute case (i.e. Obelisk resource routes and app frontend routes).
969+obeliskRouteEncoder :: forall check parse appRoute.
970+ ( Universe (Some (ObeliskRoute appRoute))
971+ , GCompare (ObeliskRoute appRoute)
972+ , GShow appRoute
973+ , MonadError Text check
974+ , check ~ parse --TODO: Get rid of this
975+ )
976+ => (forall a. appRoute a -> SegmentResult check parse a)
977+ -> Encoder check parse (R (ObeliskRoute appRoute)) PageName
978+obeliskRouteEncoder appRouteSegment = pathComponentEncoder $ \r ->
979+ obeliskRouteSegment r appRouteSegment
980+
981+-- | From a function which explains how app-specific frontend routes translate into segments, produce a function which does the
982+-- same for ObeliskRoute. This uses the given function for the 'ObeliskRoute_App' case, and 'resourceRouteSegment' for the
983+-- 'ObeliskRoute_Resource' case.
984+obeliskRouteSegment :: forall check parse appRoute a.
985+ (MonadError Text check, MonadError Text parse)
986+ => ObeliskRoute appRoute a
987+ -> (forall b. appRoute b -> SegmentResult check parse b)
988+ -> SegmentResult check parse a
989+obeliskRouteSegment r appRouteSegment = case r of
990+ ObeliskRoute_App appRoute -> appRouteSegment appRoute
991+ ObeliskRoute_Resource resourceRoute -> resourceRouteSegment resourceRoute
992+
993+-- | A function which gives a sane default for how to encode Obelisk resource routes. It's given in this form, because it will
994+-- be combined with other such segment encoders before 'pathComponentEncoder' turns it into a proper 'Encoder'.
995+resourceRouteSegment :: (MonadError Text check, MonadError Text parse) => ResourceRoute a -> SegmentResult check parse a
996+resourceRouteSegment = \case
997+ ResourceRoute_Static -> PathSegment "static" pathOnlyEncoderIgnoringQuery
998+ ResourceRoute_Ghcjs -> PathSegment "ghcjs" pathOnlyEncoder
999+ ResourceRoute_JSaddleWarp -> PathSegment "jsaddle" jsaddleWarpRouteEncoder
1000+ ResourceRoute_Version -> PathSegment "version" $ unitEncoder mempty
1001+
1002+data JSaddleWarpRoute :: * -> * where
1003+ JSaddleWarpRoute_JavaScript :: JSaddleWarpRoute ()
1004+ JSaddleWarpRoute_WebSocket :: JSaddleWarpRoute ()
1005+ JSaddleWarpRoute_Sync :: JSaddleWarpRoute [Text]
1006+
1007+jsaddleWarpRouteEncoder :: (MonadError Text check, MonadError Text parse) => Encoder check parse (R JSaddleWarpRoute) PageName
1008+jsaddleWarpRouteEncoder = pathComponentEncoder $ \case
1009+ JSaddleWarpRoute_JavaScript -> PathSegment "jsaddle.js" $ unitEncoder mempty
1010+ JSaddleWarpRoute_WebSocket -> PathEnd $ unitEncoder mempty
1011+ JSaddleWarpRoute_Sync -> PathSegment "sync" pathOnlyEncoder
1012+
1013+instance GShow appRoute => GShow (ObeliskRoute appRoute) where
1014+ gshowsPrec prec = \case
1015+ ObeliskRoute_App appRoute -> showParen (prec > 10) $
1016+ showString "ObeliskRoute_App " . gshowsPrec 11 appRoute
1017+ ObeliskRoute_Resource appRoute -> showParen (prec > 10) $
1018+ showString "ObeliskRoute_Resource " . gshowsPrec 11 appRoute
1019+
1020+data IndexOnlyRoute :: * -> * where
1021+ IndexOnlyRoute :: IndexOnlyRoute ()
1022+
1023+indexOnlyRouteSegment :: (Applicative check, MonadError Text parse) => IndexOnlyRoute a -> SegmentResult check parse a
1024+indexOnlyRouteSegment = \case
1025+ IndexOnlyRoute -> PathEnd $ unitEncoder mempty
1026+
1027+indexOnlyRouteEncoder :: (MonadError Text check, MonadError Text parse) => Encoder check parse (R IndexOnlyRoute) PageName
1028+indexOnlyRouteEncoder = pathComponentEncoder indexOnlyRouteSegment
1029+
1030+someSumEncoder :: (Applicative check, Applicative parse) => Encoder check parse (Some (Sum a b)) (Either (Some a) (Some b))
1031+someSumEncoder = Encoder $ pure $ EncoderImpl
1032+ { _encoderImpl_encode = \(Some t) -> case t of
1033+ InL l -> Left $ Some l
1034+ InR r -> Right $ Some r
1035+ , _encoderImpl_decode = pure . \case
1036+ Left (Some l) -> Some (InL l)
1037+ Right (Some r) -> Some (InR r)
1038+ }
1039+
1040+data Void1 :: * -> * where {}
1041+
1042+instance UniverseSome Void1 where
1043+ universeSome = []
1044+
1045+void1Encoder :: (Applicative check, MonadError Text parse) => Encoder check parse (Some Void1) a
1046+void1Encoder = Encoder $ pure $ EncoderImpl
1047+ { _encoderImpl_encode = \case
1048+ Some f -> case f of {}
1049+ , _encoderImpl_decode = \_ -> throwError "void1Encoder: can't decode anything"
1050+ }
1051+
1052+instance GShow Void1 where
1053+ gshowsPrec _ = \case {}
1054+
1055+-- | Given a backend route and a checked route encoder, render the route (path
1056+-- and query string). See 'checkEncoder' for how to produce a checked encoder.
1057+renderBackendRoute
1058+ :: forall br a.
1059+ Encoder Identity Identity (R (FullRoute br a)) PageName
1060+ -> R br
1061+ -> Text
1062+renderBackendRoute enc = renderObeliskRoute enc . hoistR FullRoute_Backend
1063+
1064+-- | Renders a frontend route with the supplied checked encoder
1065+renderFrontendRoute
1066+ :: forall a fr.
1067+ Encoder Identity Identity (R (FullRoute a fr)) PageName
1068+ -> R fr
1069+ -> Text
1070+renderFrontendRoute enc = renderObeliskRoute enc . hoistR (FullRoute_Frontend . ObeliskRoute_App)
1071+
1072+-- | Renders a route of the form typically found in an Obelisk project
1073+renderObeliskRoute
1074+ :: forall a b.
1075+ Encoder Identity Identity (R (FullRoute a b)) PageName
1076+ -> R (FullRoute a b)
1077+ -> Text
1078+renderObeliskRoute e r =
1079+ let enc :: Encoder Identity (Either Text) (R (FullRoute a b)) PathQuery
1080+ enc = (pageNameEncoder . hoistParse (pure . runIdentity) e)
1081+ in (T.pack . uncurry (<>)) $ encode enc r
1082+
1083+readShowEncoder :: (MonadError Text parse, Read a, Show a, Applicative check) => Encoder check parse a PageName
1084+readShowEncoder = singlePathSegmentEncoder . unsafeTshowEncoder
1085+
1086+integralEncoder :: (MonadError Text parse, Applicative check, Integral a) => Encoder check parse a Integer
1087+integralEncoder = reviewEncoder Numeric.Lens.integral
1088+
1089+pathSegmentEncoder :: (MonadError Text parse, Applicative check, Cons as as a a) =>
1090+ Encoder check parse (a, (as, b)) (as, b)
1091+pathSegmentEncoder = first (reviewEncoder _Cons) . disassociate
1092+
1093+newtype Decoder check parse b a = Decoder { toEncoder :: Encoder check parse a b }
1094+
1095+dmapEncoder :: forall check parse k k' v.
1096+ ( Monad check
1097+ , MonadError Text parse
1098+ , Universe (Some k')
1099+ , Ord k
1100+ , GCompare k'
1101+ , GShow k'
1102+ )
1103+ => Encoder check parse (Some k') k
1104+ -> (forall v'. k' v' -> Encoder check parse v' v)
1105+ -> Encoder check parse (DMap k' Identity) (Map k v)
1106+dmapEncoder keyEncoder' valueEncoderFor = unsafeEncoder $ do
1107+ keyEncoder :: Encoder Identity parse (Some k') k <- checkEncoder keyEncoder'
1108+ valueDecoders :: DMap k' (Decoder Identity parse v) <- fmap DMap.fromList . forM universe $ \(Some (k' :: k' t)) -> do
1109+ ve :: Encoder Identity parse t v <- checkEncoder (valueEncoderFor k')
1110+ return $ (k' :: k' t) :=> (Decoder ve :: Decoder Identity parse v t)
1111+ let keyError k = "dmapEncoder: key `" <> k <> "' was missing from the Universe instance for its type."
1112+ return $ EncoderImpl
1113+ { _encoderImpl_encode = \dm -> Map.fromList $ do
1114+ ((k' :: k' t) :=> Identity v') <- DMap.toList dm
1115+ return ( encode keyEncoder (Some k')
1116+ , encode (toEncoder (DMap.findWithDefault (error . keyError $ gshow k') k' valueDecoders)) v'
1117+ )
1118+ , _encoderImpl_decode = \m -> fmap DMap.fromList . forM (Map.toList m) $ \(k,v) -> do
1119+ tryDecode keyEncoder k >>= \case
1120+ Some (k' :: k' t) -> case DMap.lookup k' valueDecoders of
1121+ Nothing -> throwError . T.pack . keyError $ gshow k'
1122+ Just (Decoder e) -> do
1123+ v' <- tryDecode e v
1124+ return (k' :=> Identity v')
1125+ }
1126+
1127+fieldMapEncoder :: forall check parse r.
1128+ ( Applicative check
1129+ , MonadError Text parse
1130+ , HasFields r
1131+ , Universe (Some (Field r))
1132+ , GShow (Field r)
1133+ , GCompare (Field r)
1134+ )
1135+ => Encoder check parse r (DMap (Field r) Identity)
1136+fieldMapEncoder = unsafeEncoder $ do
1137+ pure $ EncoderImpl
1138+ { _encoderImpl_encode = \r -> DMap.fromList [ f :=> Identity (indexField r f) | Some f <- universe ]
1139+ , _encoderImpl_decode = \dm -> tabulateFieldsA $ \f -> do
1140+ case DMap.lookup f dm of
1141+ Nothing -> throwError $ "fieldMapEncoder: Couldn't find key for `" <> T.pack (gshow f) <> "' in DMap."
1142+ Just (Identity v) -> return v
1143+ }
1144+
1145+-- this is in base 4.12 (GHC 8.6);
1146+newtype Ap f a = Ap {getAp :: f a}
1147+
1148+instance (Applicative f, Semigroup a) => Semigroup (Ap f a) where
1149+ Ap x <> Ap y = Ap (liftA2 (<>) x y)
1150+
1151+instance (Applicative f, Monoid a) => Monoid (Ap f a) where
1152+ mappend = (<>)
1153+ mempty = Ap (pure mempty)
1154+
1155+pathFieldEncoder :: forall a p check parse . (HasFields a, Monad check, MonadError Text parse, GCompare (Field a)) => (forall x. Field a x -> Encoder check parse x p) -> Encoder check parse (a, [p]) [p]
1156+pathFieldEncoder fieldEncoder = unsafeEncoder $ do
1157+ fieldEncoderPureMap :: DMap.DMap (Field a) (Decoder Identity parse p) <- getAp $ getConst $ tabulateFieldsA @a $ \f -> Const (Ap $ fmap (DMap.singleton f . Decoder) $ (checkEncoder @Identity) $ fieldEncoder f)
1158+ let fieldEncoderPure :: forall x. Field a x -> Encoder Identity parse x p
1159+ fieldEncoderPure f = toEncoder (DMap.findWithDefault (error "bad") f fieldEncoderPureMap)
1160+ pure $ EncoderImpl
1161+ { _encoderImpl_encode = \(x, rest) -> execWriter $ do
1162+ _ <- traverseWithField (\f x_i -> tell (pure $ encode (fieldEncoderPure f) x_i) $> x_i) x
1163+ tell rest
1164+ , _encoderImpl_decode = State.runStateT $ tabulateFieldsA $ \f -> State.get >>= \case
1165+ [] -> throwError $ T.pack "not enough path components"
1166+ p:ps -> do
1167+ State.put ps
1168+ lift $ tryDecode (fieldEncoderPure f) p
1169+ }
1170+
1171+-- | Use ToJSON/FromJSON to encode to Text. The correctness of this encoder is dependent on the encoding being injective and round-tripping correctly.
1172+jsonEncoder :: forall check parse r.
1173+ ( ToJSON r
1174+ , FromJSON r
1175+ , Applicative check
1176+ , MonadError Text parse
1177+ )
1178+ => Encoder check parse r Text
1179+jsonEncoder = unsafeEncoder $ do
1180+ pure $ EncoderImpl
1181+ { _encoderImpl_encode = \r -> T.decodeUtf8 . BSL.toStrict $ Aeson.encode r
1182+ , _encoderImpl_decode = \t -> case Aeson.eitherDecodeStrict $ T.encodeUtf8 t of
1183+ Left err -> throwError ("jsonEncoder: " <> T.pack err)
1184+ Right x -> return x
1185+ }
1186+
1187+-- Useful for app server integration.
1188+-- p must not start with slashes
1189+byteStringsToPageName :: BS.ByteString -> BS.ByteString -> PageName
1190+byteStringsToPageName p q =
1191+ let pageNameEncoder' :: Encoder Identity Identity PageName (String, String)
1192+ pageNameEncoder' = bimap
1193+ (unpackTextEncoder . pathSegmentsTextEncoder . listToNonEmptyEncoder)
1194+ (unpackTextEncoder . queryParametersTextEncoder . toListMapEncoder)
1195+ in decode pageNameEncoder' (T.unpack (T.decodeUtf8 p), T.unpack (T.decodeUtf8 q))
1196+
1197+--TODO: decodeURIComponent as appropriate
1198+
1199+
1200+{-# DEPRECATED isoEncoder "Instead of 'isoEncoder f', use 'viewEncoder f'" #-}
1201+-- | Given a valid 'Iso' from lens, construct an 'Encoder'
1202+isoEncoder :: (Applicative check, Applicative parse) => Iso' a b -> Encoder check parse a b
1203+isoEncoder = viewEncoder
1204+
1205+{-# DEPRECATED prismEncoder "Instead of 'prismEncoder f', use 'reviewEncoder f'" #-}
1206+-- | An encoder that only works on the items available via the prism. An error will be thrown in the parse monad
1207+-- if the prism doesn't match.
1208+--
1209+-- Note that a 'Prism' from @a@ to @b@ will produce an 'Encoder' from @b@ to @a@
1210+-- (i.e. 'prismEncoder' is a contravariant functor from the category of prisms to the category of encoders),
1211+-- just like 'review' produces a function @b -> a@. This is because 'Prism's extract values, in a way that might
1212+-- fail, in their forward direction and inject values, in a way that cannot fail, in their reverse direction;
1213+-- whereas 'Encoder's encode, which cannot fail, in their forward direction, and decode, which can fail, in their
1214+-- reverse direction. In short @prismEncoder (f . g) = prismEncoder g . prismEncoder f@.
1215+prismEncoder :: (Applicative check, MonadError Text parse) => Prism' b a -> Encoder check parse a b
1216+prismEncoder = reviewEncoder
1217+
1218+
1219+concat <$> mapM deriveRouteComponent
1220+ [ ''ResourceRoute
1221+ , ''JSaddleWarpRoute
1222+ , ''IndexOnlyRoute
1223+ ]
1224+
1225+makePrisms ''ObeliskRoute
1226+makePrisms ''FullRoute
1227+deriveGEq ''Void1
1228+deriveGCompare ''Void1
lib/route/src/Obelisk/Route/Frontend.hsnew file+662
@@ -0,0 +1,662 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ApplicativeDo #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE DefaultSignatures #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE LambdaCase #-}
12+{-# LANGUAGE OverloadedStrings #-}
13+{-# LANGUAGE PatternSynonyms #-}
14+{-# LANGUAGE RankNTypes #-}
15+{-# LANGUAGE RecursiveDo #-}
16+{-# LANGUAGE ScopedTypeVariables #-}
17+{-# LANGUAGE StandaloneDeriving #-}
18+{-# LANGUAGE TypeFamilies #-}
19+{-# LANGUAGE TypeOperators #-}
20+{-# LANGUAGE UndecidableInstances #-}
21+{-# LANGUAGE ViewPatterns #-}
22+
23+module Obelisk.Route.Frontend
24+ ( module Obelisk.Route
25+ , pattern (:~)
26+ , Routed
27+ , RoutedT
28+ , runRoutedT
29+ , askRoute
30+ , withRoutedT
31+ , mapRoutedT
32+ , subRoute
33+ , subRoute_
34+ , subPairRoute
35+ , subPairRoute_
36+ , maybeRoute
37+ , maybeRoute_
38+ , maybeRouted
39+ , eitherRoute
40+ , eitherRoute_
41+ , eitherRouted
42+ , runRouteViewT
43+ , SetRouteT(..)
44+ , SetRoute(..)
45+ , runSetRouteT
46+ , mapSetRouteT
47+ , RouteToUrl(..)
48+ , RouteToUrlT(..)
49+ , runRouteToUrlT
50+ , mapRouteToUrlT
51+ , routeLink
52+ , routeLinkDynAttr
53+ , dynRouteLink
54+ , adaptedUriPath
55+ , setAdaptedUriPath
56+ ) where
57+
58+import Prelude hiding ((.), id)
59+
60+import Control.Category (Category (..), (.))
61+import Control.Category.Cartesian ((&&&))
62+import Control.Lens hiding (Bifunctor, bimap, universe, element)
63+import Control.Monad ((<=<))
64+import Control.Monad.Fix
65+import Control.Monad.Morph
66+import Control.Monad.Primitive
67+import Control.Monad.Reader
68+import Control.Monad.Ref
69+import Control.Monad.Trans.Control
70+import Data.Coerce
71+import Data.Dependent.Sum (DSum (..))
72+import Data.Functor.Compose
73+import Data.Functor.Misc
74+import Data.GADT.Compare
75+import qualified Data.List as L
76+import Data.Map (Map)
77+import Data.Maybe (fromMaybe)
78+import Data.Monoid
79+import Data.Proxy
80+import Data.Text (Text)
81+import qualified Data.Text as T
82+import Data.Type.Coercion
83+import qualified GHCJS.DOM as DOM
84+import qualified GHCJS.DOM.Types as DOM
85+import qualified GHCJS.DOM.Window as Window
86+import Language.Javascript.JSaddle (MonadJSM, jsNull, liftJSM) --TODO: Get rid of this - other platforms can also be routed
87+import Network.URI
88+import Reflex.Class
89+import Reflex.Dom.Builder.Class
90+import Reflex.Dom.Core
91+import Reflex.Host.Class
92+import Unsafe.Coerce
93+
94+import Obelisk.Configs
95+import Obelisk.Route
96+
97+infixr 5 :~
98+pattern (:~) :: Reflex t => f a -> Dynamic t a -> DSum f (Compose (Dynamic t) Identity)
99+pattern a :~ b <- a :=> (coerceDynamic . getCompose -> b)
100+
101+class Routed t r m | m -> t r where
102+ askRoute :: m (Dynamic t r)
103+ default askRoute :: (Monad m', MonadTrans f, Routed t r m', m ~ f m') => m (Dynamic t r)
104+ askRoute = lift askRoute
105+
106+instance Monad m => Routed t r (RoutedT t r m) where
107+ askRoute = RoutedT ask
108+
109+instance (Monad m, Routed t r m) => Routed t r (ReaderT r' m)
110+
111+newtype RoutedT t r m a = RoutedT { unRoutedT :: ReaderT (Dynamic t r) m a }
112+ deriving
113+ ( Functor
114+ , Applicative
115+ , Monad
116+ , MonadFix
117+ , MonadTrans
118+ , MFunctor
119+ , NotReady t
120+ , MonadHold t
121+ , MonadSample t
122+ , PostBuild t
123+ , TriggerEvent t
124+ , MonadIO
125+ , MonadReflexCreateTrigger t
126+ , HasDocument
127+ , DomRenderHook t
128+ )
129+
130+instance MonadReader r' m => MonadReader r' (RoutedT t r m) where
131+ ask = lift ask
132+ local = mapRoutedT . local
133+
134+instance HasJSContext m => HasJSContext (RoutedT t r m) where
135+ type JSContextPhantom (RoutedT t r m) = JSContextPhantom m
136+ askJSContext = lift askJSContext
137+
138+instance (Prerender js t m, Monad m) => Prerender js t (RoutedT t r m) where
139+ type Client (RoutedT t r m) = RoutedT t r (Client m)
140+ prerender server client = RoutedT $ do
141+ r <- ask
142+ lift $ prerender (runRoutedT server r) (runRoutedT client r)
143+
144+instance Requester t m => Requester t (RoutedT t r m) where
145+ type Request (RoutedT t r m) = Request m
146+ type Response (RoutedT t r m) = Response m
147+ requesting = RoutedT . requesting
148+ requesting_ = RoutedT . requesting_
149+
150+#ifndef ghcjs_HOST_OS
151+deriving instance MonadJSM m => MonadJSM (RoutedT t r m)
152+#endif
153+
154+instance PerformEvent t m => PerformEvent t (RoutedT t r m) where
155+ type Performable (RoutedT t r m) = Performable m
156+ performEvent = lift . performEvent
157+ performEvent_ = lift . performEvent_
158+
159+instance MonadRef m => MonadRef (RoutedT t r m) where
160+ type Ref (RoutedT t r m) = Ref m
161+ newRef = lift . newRef
162+ readRef = lift . readRef
163+ writeRef r = lift . writeRef r
164+
165+instance HasJS x m => HasJS x (RoutedT t r m) where
166+ type JSX (RoutedT t r m) = JSX m
167+ liftJS = lift . liftJS
168+
169+deriving instance EventWriter t w m => EventWriter t w (RoutedT t r m)
170+
171+instance MonadTransControl (RoutedT t r) where
172+ type StT (RoutedT t r) a = StT (ReaderT (Dynamic t r)) a
173+ liftWith = defaultLiftWith RoutedT unRoutedT
174+ restoreT = defaultRestoreT RoutedT
175+
176+instance PrimMonad m => PrimMonad (RoutedT t r m ) where
177+ type PrimState (RoutedT t r m) = PrimState m
178+ primitive = lift . primitive
179+
180+instance DomBuilder t m => DomBuilder t (RoutedT t r m) where
181+ type DomBuilderSpace (RoutedT t r m) = DomBuilderSpace m
182+
183+instance Adjustable t m => Adjustable t (RoutedT t r m) where
184+ runWithReplace a0 a' = RoutedT $ runWithReplace (coerce a0) $ coerceEvent a'
185+ traverseIntMapWithKeyWithAdjust f a0 a' = RoutedT $ traverseIntMapWithKeyWithAdjust (coerce f) (coerce a0) $ coerce a'
186+ traverseDMapWithKeyWithAdjust f a0 a' = RoutedT $ traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
187+ traverseDMapWithKeyWithAdjustWithMove f a0 a' = RoutedT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
188+
189+instance (Monad m, MonadQuery t vs m) => MonadQuery t vs (RoutedT t r m) where
190+ tellQueryIncremental = lift . tellQueryIncremental
191+ askQueryResult = lift askQueryResult
192+ queryIncremental = lift . queryIncremental
193+
194+instance HasConfigs m => HasConfigs (RoutedT t r m)
195+
196+instance (Monad m, RouteToUrl r m) => RouteToUrl r (QueryT t q m)
197+
198+instance (Monad m, SetRoute t r m) => SetRoute t r (QueryT t q m)
199+
200+instance (Monad m, RouteToUrl r m) => RouteToUrl r (EventWriterT t w m)
201+
202+instance (Monad m, SetRoute t r m) => SetRoute t r (EventWriterT t w m)
203+
204+instance (Monad m, RouteToUrl r m) => RouteToUrl r (DynamicWriterT t w m)
205+
206+instance (Monad m, SetRoute t r m) => SetRoute t r (DynamicWriterT t w m)
207+
208+runRoutedT :: RoutedT t r m a -> Dynamic t r -> m a
209+runRoutedT = runReaderT . unRoutedT
210+
211+mapRoutedT :: (m a -> n b) -> RoutedT t r m a -> RoutedT t r n b
212+mapRoutedT f = RoutedT . mapReaderT f . unRoutedT
213+
214+withRoutedT :: (Dynamic t r -> Dynamic t r') -> RoutedT t r' m a -> RoutedT t r m a
215+withRoutedT f = RoutedT . withReaderT f . unRoutedT
216+
217+subRoute_ :: (MonadFix m, MonadHold t m, GEq r, Adjustable t m) => (forall a. r a -> RoutedT t a m ()) -> RoutedT t (R r) m ()
218+subRoute_ f = factorRouted $ strictDynWidget_ $ \(c :=> r') -> do
219+ runRoutedT (f c) r'
220+
221+-- | Like 'subRoute_', but with a pair rather than an R
222+subPairRoute_ :: (MonadFix m, MonadHold t m, Eq a, Adjustable t m) => (a -> RoutedT t b m ()) -> RoutedT t (a, b) m ()
223+subPairRoute_ f = withRoutedT (fmap (\(a, b) -> Const2 a :/ b)) $ subRoute_ (\(Const2 a) -> f a)
224+
225+subRoute :: (MonadFix m, MonadHold t m, GEq r, Adjustable t m) => (forall a. r a -> RoutedT t a m b) -> RoutedT t (R r) m (Dynamic t b)
226+subRoute f = factorRouted $ strictDynWidget $ \(c :=> r') -> do
227+ runRoutedT (f c) r'
228+
229+-- | Like 'subRoute_', but with a pair rather than an R
230+subPairRoute :: (MonadFix m, MonadHold t m, Eq a, Adjustable t m) => (a -> RoutedT t b m c) -> RoutedT t (a, b) m (Dynamic t c)
231+subPairRoute f = withRoutedT (fmap (\(a, b) -> Const2 a :/ b)) $ subRoute (\(Const2 a) -> f a)
232+
233+maybeRoute_ :: (MonadFix m, MonadHold t m, Adjustable t m) => m () -> RoutedT t r m () -> RoutedT t (Maybe r) m ()
234+maybeRoute_ n j = maybeRouted $ strictDynWidget_ $ \case
235+ Nothing -> n
236+ Just r -> runRoutedT j r
237+
238+maybeRoute :: (MonadFix m, MonadHold t m, Adjustable t m) => m a -> RoutedT t r m a -> RoutedT t (Maybe r) m (Dynamic t a)
239+maybeRoute n j = maybeRouted $ strictDynWidget $ \case
240+ Nothing -> n
241+ Just r -> runRoutedT j r
242+
243+{-
244+maybeRoute :: (MonadFix m, MonadHold t m, GEq r, Adjustable t m) => m a -> RoutedT t r m a -> RoutedT t (Maybe r) m a
245+maybeRoute f = factorRouted $ strictDynWidget $ \(c :=> r') -> do
246+ runRoutedT (f c) r'
247+-}
248+
249+eitherRoute_
250+ :: (MonadFix m, MonadHold t m, Adjustable t m)
251+ => RoutedT t l m ()
252+ -> RoutedT t r m ()
253+ -> RoutedT t (Either l r) m ()
254+eitherRoute_ l r = eitherRouted $ strictDynWidget_ $ either (runRoutedT l) (runRoutedT r)
255+
256+eitherRoute
257+ :: (MonadFix m, MonadHold t m, Adjustable t m)
258+ => RoutedT t l m a
259+ -> RoutedT t r m a
260+ -> RoutedT t (Either l r) m (Dynamic t a)
261+eitherRoute l r = eitherRouted $ strictDynWidget $ either (runRoutedT l) (runRoutedT r)
262+
263+dsumValueCoercion :: Coercion f g -> Coercion (DSum k f) (DSum k g)
264+dsumValueCoercion Coercion = Coercion
265+
266+dynamicIdentityCoercion :: Coercion (Compose (Dynamic t) Identity) (Dynamic t)
267+dynamicIdentityCoercion = unsafeCoerce (Coercion :: Coercion (Identity ()) ()) --TODO: Is it possible to prove this?
268+
269+factorRouted :: (Reflex t, MonadFix m, MonadHold t m, GEq f) => RoutedT t (DSum f (Dynamic t)) m a -> RoutedT t (DSum f Identity) m a
270+factorRouted r = RoutedT $ ReaderT $ \d -> do
271+ d' <- factorDyn d
272+ runRoutedT r $ coerceWith (dynamicCoercion $ dsumValueCoercion dynamicIdentityCoercion) d'
273+
274+maybeRouted :: (Reflex t, MonadFix m, MonadHold t m) => RoutedT t (Maybe (Dynamic t a)) m b -> RoutedT t (Maybe a) m b
275+maybeRouted r = RoutedT $ ReaderT $ \d -> do
276+ d' <- maybeDyn d
277+ runRoutedT r d'
278+
279+eitherRouted :: (Reflex t, MonadFix m, MonadHold t m) => RoutedT t (Either (Dynamic t a) (Dynamic t b)) m c -> RoutedT t (Either a b) m c
280+eitherRouted r = RoutedT $ ReaderT $ runRoutedT r <=< eitherDyn
281+
282+-- | WARNING: The input 'Dynamic' must be fully constructed when this is run
283+strictDynWidget :: (MonadSample t m, MonadHold t m, Adjustable t m) => (a -> m b) -> RoutedT t a m (Dynamic t b)
284+strictDynWidget f = RoutedT $ ReaderT $ \r -> do
285+ r0 <- sample $ current r
286+ (result0, result') <- runWithReplace (f r0) $ f <$> updated r
287+ holdDyn result0 result'
288+
289+strictDynWidget_ :: (MonadSample t m, MonadHold t m, Adjustable t m) => (a -> m ()) -> RoutedT t a m ()
290+strictDynWidget_ f = RoutedT $ ReaderT $ \r -> do
291+ r0 <- sample $ current r
292+ (_, _) <- runWithReplace (f r0) $ f <$> updated r
293+ pure ()
294+
295+newtype SetRouteT t r m a = SetRouteT { unSetRouteT :: EventWriterT t (Endo r) m a }
296+ deriving (Functor, Applicative, Monad, MonadFix, MonadTrans, MonadIO, NotReady t, MonadHold t, MonadSample t, PostBuild t, TriggerEvent t, MonadReflexCreateTrigger t, HasDocument, DomRenderHook t)
297+
298+instance (MonadFix m, MonadHold t m, DomBuilder t m) => DomBuilder t (SetRouteT t r m) where
299+ type DomBuilderSpace (SetRouteT t r m) = DomBuilderSpace m
300+ element t cfg child = SetRouteT $ element t cfg $ unSetRouteT child
301+ inputElement = lift . inputElement
302+ textAreaElement = lift . textAreaElement
303+ selectElement cfg child = SetRouteT $ selectElement cfg $ unSetRouteT child
304+
305+instance HasJSContext m => HasJSContext (SetRouteT t r m) where
306+ type JSContextPhantom (SetRouteT t r m) = JSContextPhantom m
307+ askJSContext = lift askJSContext
308+
309+mapSetRouteT :: (forall x. m x -> n x) -> SetRouteT t r m a -> SetRouteT t r n a
310+mapSetRouteT f (SetRouteT x) = SetRouteT (mapEventWriterT f x)
311+
312+runSetRouteT :: (Reflex t, Monad m) => SetRouteT t r m a -> m (a, Event t (Endo r))
313+runSetRouteT = runEventWriterT . unSetRouteT
314+
315+class Reflex t => SetRoute t r m | m -> t r where
316+ setRoute :: Event t r -> m ()
317+ modifyRoute :: Event t (r -> r) -> m ()
318+ default modifyRoute :: (Monad m', MonadTrans f, SetRoute t r m', m ~ f m') => Event t (r -> r) -> m ()
319+ modifyRoute = lift . modifyRoute
320+
321+ setRoute = modifyRoute . fmap const
322+
323+instance (Reflex t, Monad m) => SetRoute t r (SetRouteT t r m) where
324+ modifyRoute = SetRouteT . tellEvent . fmap Endo
325+
326+instance (Monad m, SetRoute t r m) => SetRoute t r (RoutedT t r' m)
327+
328+instance (Monad m, SetRoute t r m) => SetRoute t r (ReaderT r' m)
329+
330+instance (PerformEvent t m, Prerender js t m, Monad m, Reflex t) => Prerender js t (SetRouteT t r m) where
331+ type Client (SetRouteT t r m) = SetRouteT t r (Client m)
332+ prerender server client = do
333+ d <- lift $ prerender (runSetRouteT server) (runSetRouteT client)
334+ let (a, r) = splitDynPure d
335+ -- Must be prompt here
336+ SetRouteT . tellEvent $ switchPromptlyDyn r
337+ pure a
338+
339+instance Requester t m => Requester t (SetRouteT t r m) where
340+ type Request (SetRouteT t r m) = Request m
341+ type Response (SetRouteT t r m) = Response m
342+ requesting = SetRouteT . requesting
343+ requesting_ = SetRouteT . requesting_
344+
345+instance (Monad m, SetRoute t r m) => SetRoute t r (RequesterT t req rsp m)
346+
347+#ifndef ghcjs_HOST_OS
348+deriving instance MonadJSM m => MonadJSM (SetRouteT t r m)
349+#endif
350+
351+instance PerformEvent t m => PerformEvent t (SetRouteT t r m) where
352+ type Performable (SetRouteT t r m) = Performable m
353+ performEvent = lift . performEvent
354+ performEvent_ = lift . performEvent_
355+
356+instance MonadRef m => MonadRef (SetRouteT t r m) where
357+ type Ref (SetRouteT t r m) = Ref m
358+ newRef = lift . newRef
359+ readRef = lift . readRef
360+ writeRef r = lift . writeRef r
361+
362+instance HasJS x m => HasJS x (SetRouteT t r m) where
363+ type JSX (SetRouteT t r m) = JSX m
364+ liftJS = lift . liftJS
365+
366+instance PrimMonad m => PrimMonad (SetRouteT t r m ) where
367+ type PrimState (SetRouteT t r m) = PrimState m
368+ primitive = lift . primitive
369+
370+instance HasConfigs m => HasConfigs (SetRouteT t r m)
371+
372+instance (MonadHold t m, Adjustable t m) => Adjustable t (SetRouteT t r m) where
373+ runWithReplace a0 a' = SetRouteT $ runWithReplace (coerce a0) $ coerceEvent a'
374+ traverseIntMapWithKeyWithAdjust f a0 a' = SetRouteT $ traverseIntMapWithKeyWithAdjust (coerce f) (coerce a0) $ coerce a'
375+ traverseDMapWithKeyWithAdjust f a0 a' = SetRouteT $ traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
376+ traverseDMapWithKeyWithAdjustWithMove f a0 a' = SetRouteT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
377+
378+instance (Monad m, MonadQuery t vs m) => MonadQuery t vs (SetRouteT t r m) where
379+ tellQueryIncremental = lift . tellQueryIncremental
380+ askQueryResult = lift askQueryResult
381+ queryIncremental = lift . queryIncremental
382+
383+class RouteToUrl r m | m -> r where
384+ askRouteToUrl :: m (r -> Text)
385+ default askRouteToUrl :: (Monad m', MonadTrans f, RouteToUrl r m', m ~ f m') => m (r -> Text)
386+ askRouteToUrl = lift askRouteToUrl
387+
388+newtype RouteToUrlT r m a = RouteToUrlT { unRouteToUrlT :: ReaderT (r -> Text) m a }
389+ deriving (Functor, Applicative, Monad, MonadFix, MonadTrans, NotReady t, MonadHold t, MonadSample t, PostBuild t, TriggerEvent t, MonadIO, MonadReflexCreateTrigger t, HasDocument, DomRenderHook t)
390+
391+runRouteToUrlT
392+ :: RouteToUrlT r m a
393+ -> (r -> Text)
394+ -> m a
395+runRouteToUrlT a = runReaderT (unRouteToUrlT a)
396+
397+mapRouteToUrlT :: (forall x. m x -> n x) -> RouteToUrlT r m a -> RouteToUrlT r n a
398+mapRouteToUrlT f (RouteToUrlT m) = RouteToUrlT $ mapReaderT f m
399+
400+instance Monad m => RouteToUrl r (RouteToUrlT r m) where
401+ askRouteToUrl = RouteToUrlT ask
402+
403+instance (Monad m, RouteToUrl r m) => RouteToUrl r (SetRouteT t r' m) where
404+
405+instance (Monad m, RouteToUrl r m) => RouteToUrl r (RoutedT t r' m) where
406+
407+instance (Monad m, RouteToUrl r m) => RouteToUrl r (ReaderT r' m) where
408+
409+instance (Monad m, RouteToUrl r m) => RouteToUrl r (RequesterT t req rsp m)
410+
411+instance HasJSContext m => HasJSContext (RouteToUrlT r m) where
412+ type JSContextPhantom (RouteToUrlT r m) = JSContextPhantom m
413+ askJSContext = lift askJSContext
414+
415+instance (Prerender js t m, Monad m) => Prerender js t (RouteToUrlT r m) where
416+ type Client (RouteToUrlT r m) = RouteToUrlT r (Client m)
417+ prerender server client = do
418+ r <- RouteToUrlT ask
419+ lift $ prerender (runRouteToUrlT server r) (runRouteToUrlT client r)
420+
421+instance Requester t m => Requester t (RouteToUrlT r m) where
422+ type Request (RouteToUrlT r m) = Request m
423+ type Response (RouteToUrlT r m) = Response m
424+ requesting = RouteToUrlT . requesting
425+ requesting_ = RouteToUrlT . requesting_
426+
427+#ifndef ghcjs_HOST_OS
428+deriving instance MonadJSM m => MonadJSM (RouteToUrlT r m)
429+#endif
430+
431+instance PerformEvent t m => PerformEvent t (RouteToUrlT r m) where
432+ type Performable (RouteToUrlT r m) = Performable m
433+ performEvent = lift . performEvent
434+ performEvent_ = lift . performEvent_
435+
436+instance MonadRef m => MonadRef (RouteToUrlT r m) where
437+ type Ref (RouteToUrlT r m) = Ref m
438+ newRef = lift . newRef
439+ readRef = lift . readRef
440+ writeRef r = lift . writeRef r
441+
442+instance HasJS x m => HasJS x (RouteToUrlT r m) where
443+ type JSX (RouteToUrlT r m) = JSX m
444+ liftJS = lift . liftJS
445+
446+instance MonadTransControl (RouteToUrlT r) where
447+ type StT (RouteToUrlT r) a = StT (ReaderT (r -> Text)) a
448+ liftWith = defaultLiftWith RouteToUrlT unRouteToUrlT
449+ restoreT = defaultRestoreT RouteToUrlT
450+
451+instance PrimMonad m => PrimMonad (RouteToUrlT r m ) where
452+ type PrimState (RouteToUrlT r m) = PrimState m
453+ primitive = lift . primitive
454+
455+instance DomBuilder t m => DomBuilder t (RouteToUrlT r m) where
456+ type DomBuilderSpace (RouteToUrlT r m) = DomBuilderSpace m
457+
458+instance Adjustable t m => Adjustable t (RouteToUrlT r m) where
459+ runWithReplace a0 a' = RouteToUrlT $ runWithReplace (coerce a0) $ coerceEvent a'
460+ traverseIntMapWithKeyWithAdjust f a0 a' = RouteToUrlT $ traverseIntMapWithKeyWithAdjust (coerce f) (coerce a0) $ coerce a'
461+ traverseDMapWithKeyWithAdjust f a0 a' = RouteToUrlT $ traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
462+ traverseDMapWithKeyWithAdjustWithMove f a0 a' = RouteToUrlT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) (coerce a0) $ coerce a'
463+
464+instance (Monad m, MonadQuery t vs m) => MonadQuery t vs (RouteToUrlT r m) where
465+ tellQueryIncremental = lift . tellQueryIncremental
466+ askQueryResult = lift askQueryResult
467+ queryIncremental = lift . queryIncremental
468+
469+instance HasConfigs m => HasConfigs (RouteToUrlT t m)
470+
471+runRouteViewT
472+ :: forall t m r a.
473+ ( TriggerEvent t m
474+ , PerformEvent t m
475+ , MonadHold t m
476+ , MonadJSM m
477+ , MonadJSM (Performable m)
478+ , MonadFix m
479+ )
480+ => Encoder Identity Identity r PageName
481+ --TODO: Get rid of the switchover and useHash arguments
482+ -- useHash can probably be baked into the encoder
483+ -> Event t () -- ^ Switchover event, nothing is done until this event fires. Used to prevent incorrect DOM expectations at hydration switchover time
484+ -> Bool
485+ -> RoutedT t r (SetRouteT t r (RouteToUrlT r m)) a
486+ -> m a
487+runRouteViewT routeEncoder switchover useHash a = do
488+ rec historyState <- manageHistory' switchover $ HistoryCommand_PushState <$> setState
489+ let theEncoder = pageNameEncoder . hoistParse (pure . runIdentity) routeEncoder
490+ -- NB: The can only fail if the uriPath doesn't begin with a '/' or if the uriQuery
491+ -- is nonempty, but begins with a character that isn't '?'. Since we don't expect
492+ -- this ever to happen, we'll just handle it by failing completely with 'error'.
493+ route :: Dynamic t r
494+ route = fmap (errorLeft . tryDecode theEncoder . (adaptedUriPath useHash &&& uriQuery) . _historyItem_uri) historyState
495+ where
496+ errorLeft (Left e) = error (T.unpack e)
497+ errorLeft (Right x) = x
498+ (result, changeState) <- runRouteToUrlT (runSetRouteT $ runRoutedT a route) $ (\(p, q) -> T.pack $ p <> q) . encode theEncoder
499+ let f (currentHistoryState, oldRoute) change =
500+ let newRoute = appEndo change oldRoute
501+ (newPath, newQuery) = encode theEncoder newRoute
502+ in HistoryStateUpdate
503+ { _historyStateUpdate_state = DOM.SerializedScriptValue jsNull
504+ -- We always provide "" as the title. On Firefox, Chrome, and
505+ -- Edge, this parameter does nothing. On Safari, "" has the
506+ -- same behavior as other browsers (as far as I can tell), but
507+ -- anything else sets the title for the back button list item
508+ -- the *next* time pushState is called, unless the page title
509+ -- is changed in the interim. Since the Safari functionality
510+ -- is near-pointless and also confusing, I'm not going to even
511+ -- bother exposing it; if there ends up being a real use case,
512+ -- we can change this function later to accommodate.
513+ -- See: https://github.com/whatwg/html/issues/2174
514+ , _historyStateUpdate_title = ""
515+ , _historyStateUpdate_uri = Just $ setAdaptedUriPath useHash newPath $ (_historyItem_uri currentHistoryState)
516+ { uriQuery = newQuery
517+ }
518+ }
519+ setState = attachWith f ((,) <$> current historyState <*> current route) changeState
520+ return result
521+
522+-- | A link widget that, when clicked, sets the route to the provided route. In non-javascript
523+-- contexts, this widget falls back to using @href@s to control navigation
524+routeLink
525+ :: forall t m a route js.
526+ ( DomBuilder t m
527+ , RouteToUrl route m
528+ , SetRoute t route m
529+ , Prerender js t m
530+ )
531+ => route -- ^ Target route
532+ -> m a -- ^ Child widget
533+ -> m a
534+routeLink r w = do
535+ (e, a) <- routeLinkImpl r w
536+ scrollToTop e
537+ return a
538+
539+-- | Raw implementation of 'routeLink'. Does not scroll to the top of the page on clicks.
540+routeLinkImpl
541+ :: forall t m a route.
542+ ( DomBuilder t m
543+ , RouteToUrl route m
544+ , SetRoute t route m
545+ )
546+ => route -- ^ Target route
547+ -> m a -- ^ Child widget
548+ -> m (Event t (), a)
549+routeLinkImpl r w = do
550+ enc <- askRouteToUrl
551+ let cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
552+ & elementConfig_eventSpec %~ addEventSpecFlags (Proxy :: Proxy (DomBuilderSpace m)) Click (\_ -> preventDefault)
553+ & elementConfig_initialAttributes .~ "href" =: enc r
554+ (e, a) <- element "a" cfg w
555+ setRoute $ r <$ domEvent Click e
556+ return (domEvent Click e, a)
557+
558+scrollToTop :: forall m t js. (Prerender js t m, Monad m) => Event t () -> m ()
559+scrollToTop e = prerender_ blank $ performEvent_ $ ffor e $ \_ -> liftJSM $ DOM.currentWindow >>= \case
560+ Nothing -> pure ()
561+ Just win -> Window.scrollTo win 0 0
562+
563+-- | Like 'routeLinkDynAttr' but without custom attributes.
564+dynRouteLink
565+ :: forall t m a route js.
566+ ( DomBuilder t m
567+ , PostBuild t m
568+ , RouteToUrl route m
569+ , SetRoute t route m
570+ , Prerender js t m
571+ )
572+ => Dynamic t route -- ^ Target route
573+ -> m a -- ^ Child widget
574+ -> m a
575+dynRouteLink r w = do
576+ (e, a) <- dynRouteLinkImpl r w
577+ scrollToTop e
578+ return a
579+
580+-- | Raw implementation of 'dynRouteLink'. Does not scroll to the top of the page on clicks.
581+dynRouteLinkImpl
582+ :: forall t m a route.
583+ ( DomBuilder t m
584+ , PostBuild t m
585+ , RouteToUrl route m
586+ , SetRoute t route m
587+ )
588+ => Dynamic t route -- ^ Target route
589+ -> m a -- ^ Child widget
590+ -> m (Event t (), a)
591+dynRouteLinkImpl dr w = do
592+ enc <- askRouteToUrl
593+ er <- dynamicAttributesToModifyAttributes $ ("href" =:) . enc <$> dr
594+ let cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
595+ & elementConfig_eventSpec %~ addEventSpecFlags (Proxy :: Proxy (DomBuilderSpace m)) Click (\_ -> preventDefault)
596+ & elementConfig_modifyAttributes .~ er
597+ (e, a) <- element "a" cfg w
598+ let clk = domEvent Click e
599+ setRoute $ tag (current dr) clk
600+ return (clk, a)
601+
602+-- | An @a@-tag link widget that, when clicked, sets the route to current value of the
603+-- provided dynamic route. In non-JavaScript contexts the value of the dynamic post
604+-- build is used so the link still works like 'routeLink'.
605+routeLinkDynAttr
606+ :: forall t m a route js.
607+ ( DomBuilder t m
608+ , PostBuild t m
609+ , RouteToUrl (R route) m
610+ , SetRoute t (R route) m
611+ , Prerender js t m
612+ )
613+ => Dynamic t (Map AttributeName Text) -- ^ Attributes for @a@ element. Note that if @href@ is present it will be ignored
614+ -> Dynamic t (R route) -- ^ Target route
615+ -> m a -- ^ Child widget of the @a@ element
616+ -> m a
617+routeLinkDynAttr dAttr dr w = do
618+ (e, a) <- routeLinkDynAttrImpl dAttr dr w
619+ scrollToTop e
620+ return a
621+
622+-- | Raw implementation of 'routeLinkDynAttr'. Does not scroll to the top of the page on clicks.
623+routeLinkDynAttrImpl
624+ :: forall t m a route.
625+ ( DomBuilder t m
626+ , PostBuild t m
627+ , RouteToUrl (R route) m
628+ , SetRoute t (R route) m
629+ )
630+ => Dynamic t (Map AttributeName Text) -- ^ Attributes for @a@ element. Note that if @href@ is present it will be ignored
631+ -> Dynamic t (R route) -- ^ Target route
632+ -> m a -- ^ Child widget of the @a@ element
633+ -> m (Event t (), a)
634+routeLinkDynAttrImpl dAttr dr w = do
635+ enc <- askRouteToUrl
636+ er <- dynamicAttributesToModifyAttributes $ zipDynWith (<>) (("href" =:) . enc <$> dr) dAttr
637+ let cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
638+ & elementConfig_eventSpec %~ addEventSpecFlags (Proxy :: Proxy (DomBuilderSpace m)) Click (\_ -> preventDefault)
639+ & elementConfig_modifyAttributes .~ er
640+ (e, a) <- element "a" cfg w
641+ let clk = domEvent Click e
642+ setRoute $ tag (current dr) clk
643+ return (clk, a)
644+
645+-- On ios due to sandboxing when loading the page from a file adapt the
646+-- path to be based on the hash.
647+
648+adaptedUriPath :: Bool -> URI -> String
649+adaptedUriPath = \case
650+ True -> hashToPath . uriFragment
651+ False -> uriPath
652+
653+setAdaptedUriPath :: Bool -> String -> URI -> URI
654+setAdaptedUriPath useHash s u = case useHash of
655+ True -> u { uriFragment = pathToHash s }
656+ False -> u { uriPath = s }
657+
658+pathToHash :: String -> String
659+pathToHash = ('#' :) . fromMaybe "" . L.stripPrefix "/"
660+
661+hashToPath :: String -> String
662+hashToPath = ('/' :) . fromMaybe "" . L.stripPrefix "#"
lib/route/src/Obelisk/Route/TH.hsnew file+17
@@ -0,0 +1,17 @@
1+module Obelisk.Route.TH (deriveRouteComponent) where
2+
3+import Data.Constraint.Extras.TH
4+import Data.GADT.Show.TH
5+import Data.GADT.Compare.TH
6+import Data.Universe.Some.TH
7+import Language.Haskell.TH
8+
9+-- | Derive all the typeclasses needed for a RouteComponent type. The argument should be the name of a type of kind @k -> *@
10+deriveRouteComponent :: Name -> Q [Dec]
11+deriveRouteComponent x = concat <$> traverse ($ x)
12+ [ deriveGShow
13+ , deriveGEq
14+ , deriveGCompare
15+ , deriveUniverseSome
16+ , deriveArgDict
17+ ]
lib/run-frontend/obelisk-run-frontend.cabaldeleted−28
@@ -1,28 +0,0 @@
1−name: obelisk-run-frontend
2−version: 0.1
3−license: BSD3
4−build-type: Simple
5−cabal-version: >=1.2
6−
7−library
8− hs-source-dirs: src
9− build-depends:
10− attoparsec
11− , base
12− , bytestring
13− , http-client
14− , http-reverse-proxy
15− , jsaddle
16− , jsaddle-warp
17− , network
18− , network-uri
19− , process
20− , reflex-dom
21− , streaming-commons
22− , text
23− , wai
24− , warp
25− , websockets
26− exposed-modules:
27− Obelisk.Widget.Run
28− ghc-options: -Wall
lib/run-frontend/src/Obelisk/Widget/Run.hsdeleted−95
@@ -1,95 +0,0 @@
1−{-# LANGUAGE LambdaCase #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−module Obelisk.Widget.Run where
5−
6−import Control.Concurrent
7−import Control.Exception
8−import qualified Data.Attoparsec.ByteString.Char8 as A
9−import Data.ByteString (ByteString)
10−import qualified Data.ByteString.Char8 as BSC
11−import Data.List (uncons)
12−import Data.Semigroup ((<>))
13−import Data.Streaming.Network (bindPortTCP)
14−import Language.Javascript.JSaddle.WebSockets
15−import Language.Javascript.JSaddle.Run (syncPoint)
16−import Network.HTTP.Client (defaultManagerSettings, newManager, Manager)
17−import qualified Network.HTTP.ReverseProxy as RP
18−import Network.Socket
19−import Network.URI
20−import Network.Wai (Application)
21−import Network.Wai.Handler.Warp
22−import Network.WebSockets.Connection (defaultConnectionOptions)
23−import Network.Wai.Handler.Warp.Internal (settingsPort, settingsHost)
24−import System.Process
25−import Reflex.Dom.Core
26−
27−runWidget :: RunConfig -> Widget () () -> IO ()
28−runWidget conf w = do
29− let redirectHost = _runConfig_redirectHost conf
30− redirectPort = _runConfig_redirectPort conf
31− beforeMainLoop = do
32− putStrLn $ "Frontend running on " <> showUrl "127.0.0.1" (_runConfig_port conf)
33− settings = setBeforeMainLoop beforeMainLoop (setPort (_runConfig_port conf) (setTimeout 3600 defaultSettings))
34− logErr p = putStrLn $ unwords [ "Port", show p, "is in use."]
35− bracket
36− (bindPortTCPRetry settings (logErr (_runConfig_port conf)) (_runConfig_retryTimeout conf))
37− close
38− (\skt -> do
39− man <- newManager defaultManagerSettings
40− app <- jsaddleWithAppOr defaultConnectionOptions (mainWidget' w >> syncPoint) (fallbackProxy redirectHost redirectPort man)
41− runSettingsSocket settings skt app)
42−
43−-- | like 'bindPortTCP' but reconnects on exception
44−bindPortTCPRetry :: Settings
45− -> IO () -- ^ Action to run the first time an exception is caught
46− -> Int
47− -> IO Socket
48−bindPortTCPRetry settings m n = catch (bindPortTCP (settingsPort settings) (settingsHost settings)) $ \(_ :: IOError) -> do
49− m
50− threadDelay $ 1000000 * n
51− bindPortTCPRetry settings (return ()) n
52−
53−-- TODO
54−logPortBindErr :: Int -> IO ()
55−logPortBindErr p = getProcessIdForPort p >>= \case
56− Nothing -> return ()
57− Just _ -> return ()
58−
59−getProcessIdForPort :: Int -> IO (Maybe Int)
60−getProcessIdForPort port = do
61− xs <- lines <$> readProcess "ss" ["-lptn", "sport = " <> show port] mempty
62− case uncons xs of
63− Just (_, x:_) -> return $ A.maybeResult $ A.parse parseSsPid $ BSC.pack x
64− _ -> return Nothing
65−
66−parseSsPid :: A.Parser Int
67−parseSsPid = do
68− _ <- A.count 5 $ A.takeWhile (not . A.isSpace) *> A.skipSpace
69− _ <- A.skipWhile (/= ':') >> A.string ":((" >> A.skipWhile (/= ',')
70− A.string ",pid=" *> A.decimal
71−
72−showUrl :: String -> Int -> String
73−showUrl host port = show nullURI
74− { uriScheme = "http:"
75− , uriAuthority = Just $ URIAuth "" host $ ":" ++ show port
76− }
77−
78−fallbackProxy :: ByteString -> Int -> Manager -> Application
79−fallbackProxy host port = RP.waiProxyTo handleRequest RP.defaultOnExc
80− where handleRequest _req = return $ RP.WPRProxyDest $ RP.ProxyDest host port
81−
82−data RunConfig = RunConfig
83− { _runConfig_port :: Int
84− , _runConfig_redirectHost :: ByteString
85− , _runConfig_redirectPort :: Int
86− , _runConfig_retryTimeout :: Int -- seconds
87− }
88−
89−defRunConfig :: RunConfig
90−defRunConfig = RunConfig
91− { _runConfig_port = 8000
92− , _runConfig_redirectHost = "127.0.0.1"
93− , _runConfig_redirectPort = 3001
94− , _runConfig_retryTimeout = 1
95− }
lib/run/obelisk-run.cabalnew file+53
@@ -0,0 +1,53 @@
1+name: obelisk-run
2+version: 0.1
3+license: BSD3
4+build-type: Simple
5+cabal-version: >=1.2
6+
7+library
8+ hs-source-dirs: src
9+ build-depends:
10+ attoparsec
11+ , base
12+ , bytestring
13+ , containers
14+ , cookie
15+ , dependent-sum
16+ , dependent-sum-template
17+ , ghcjs-dom
18+ , HsOpenSSL
19+ , http-client
20+ , http-reverse-proxy
21+ , http-types
22+ , jsaddle
23+ , jsaddle-warp
24+ , lens
25+ , modern-uri
26+ , mtl
27+ , network
28+ , obelisk-asset-serve-snap
29+ , obelisk-backend
30+ , obelisk-executable-config-lookup
31+ , obelisk-frontend
32+ , obelisk-route
33+ , process
34+ , ref-tf
35+ , reflex
36+ , reflex-dom-core
37+ , snap-core
38+ , streaming-commons
39+ , text
40+ , time
41+ , universe
42+ , utf8-string
43+ , wai
44+ , wai-websockets
45+ , warp
46+ , warp-tls
47+ , websockets
48+ exposed-modules:
49+ Obelisk.Run
50+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
51+ if os(linux)
52+ cpp-options: -DIPROUTE_SUPPORTED
53+ build-depends: which
lib/run/src/Obelisk/Run.hsnew file+268
@@ -0,0 +1,268 @@
1+{-# LANGUAGE CPP #-}
2+#if defined(IPROUTE_SUPPORTED)
3+{-# LANGUAGE TemplateHaskell #-}
4+#endif
5+
6+{-# LANGUAGE ConstraintKinds #-}
7+{-# LANGUAGE FlexibleContexts #-}
8+{-# LANGUAGE FlexibleInstances #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE LambdaCase #-}
11+{-# LANGUAGE MultiParamTypeClasses #-}
12+{-# LANGUAGE OverloadedStrings #-}
13+{-# LANGUAGE Rank2Types #-}
14+{-# LANGUAGE ScopedTypeVariables #-}
15+{-# LANGUAGE TypeFamilies #-}
16+{-# LANGUAGE UndecidableInstances #-}
17+{-# OPTIONS_GHC -fno-warn-orphans #-} -- Due to instance HasJS x (EventWriterT t w m)
18+module Obelisk.Run where
19+
20+import Prelude hiding ((.), id)
21+
22+import Control.Category
23+import Control.Concurrent
24+import Control.Exception
25+import Control.Lens ((%~), (^?), _Just, _Right)
26+import qualified Data.Attoparsec.ByteString.Char8 as A
27+import Data.ByteString (ByteString)
28+import qualified Data.ByteString as BS
29+import qualified Data.ByteString.Char8 as BSC
30+import qualified Data.ByteString.Lazy.Char8 as BSLC
31+import qualified Data.ByteString.UTF8 as BSUTF8
32+import Data.Functor.Identity
33+import Data.List (uncons)
34+import Data.Map (Map)
35+import qualified Data.Map as Map
36+import Data.Maybe
37+import Data.Semigroup ((<>))
38+import Data.Streaming.Network (bindPortTCP)
39+import Data.String (fromString)
40+import Data.Text (Text)
41+import qualified Data.Text as T
42+import qualified Data.Text.Encoding as T
43+import Data.Time.Clock (getCurrentTime, addUTCTime)
44+import Language.Javascript.JSaddle.Run (syncPoint)
45+import Language.Javascript.JSaddle.WebSockets
46+import Network.HTTP.Client (Manager, defaultManagerSettings, newManager)
47+import qualified Network.HTTP.ReverseProxy as RP
48+import qualified Network.HTTP.Types as H
49+import Network.Socket
50+import Network.Wai (Application)
51+import qualified Network.Wai as W
52+import Network.Wai.Handler.Warp
53+import Network.Wai.Handler.WarpTLS
54+import Network.Wai.Handler.Warp.Internal (settingsHost, settingsPort)
55+import Network.WebSockets (ConnectionOptions)
56+import Network.WebSockets.Connection (defaultConnectionOptions)
57+import qualified Obelisk.Asset.Serve.Snap as Snap
58+import Obelisk.Backend
59+import Obelisk.Frontend
60+import Obelisk.Route.Frontend
61+import qualified OpenSSL.PEM as PEM
62+import qualified OpenSSL.RSA as RSA
63+import qualified OpenSSL.X509 as X509
64+import qualified OpenSSL.X509.Request as X509Request
65+import Reflex.Dom.Core
66+import Snap.Core (Snap)
67+import System.Environment
68+import System.IO
69+import System.Process
70+import Text.URI (URI)
71+import qualified Text.URI as URI
72+import Text.URI.Lens
73+import Web.Cookie
74+
75+#if defined(IPROUTE_SUPPORTED)
76+import qualified System.Which
77+#endif
78+
79+run
80+ :: Int -- ^ Port to run the backend
81+ -> ([Text] -> Snap ()) -- ^ Static asset handler
82+ -> Backend backendRoute frontendRoute -- ^ Backend
83+ -> Frontend (R frontendRoute) -- ^ Frontend
84+ -> IO ()
85+run port serveStaticAsset backend frontend = do
86+ prettifyOutput
87+ let handleBackendErr (e :: IOException) = hPutStrLn stderr $ "backend stopped; make a change to your code to reload - error " <> show e
88+ --TODO: Use Obelisk.Backend.runBackend; this will require separating the checking and running phases
89+ case checkEncoder $ _backend_routeEncoder backend of
90+ Left e -> hPutStrLn stderr $ "backend error:\n" <> T.unpack e
91+ Right validFullEncoder -> do
92+ publicConfigs <- getPublicConfigs
93+ backendTid <- forkIO $ handle handleBackendErr $ withArgs ["--quiet", "--port", show port] $
94+ _backend_run backend $ \serveRoute ->
95+ runSnapWithCommandLineArgs $
96+ getRouteWith validFullEncoder >>= \case
97+ Identity r -> case r of
98+ FullRoute_Backend backendRoute :/ a -> serveRoute $ backendRoute :/ a
99+ FullRoute_Frontend obeliskRoute :/ a ->
100+ serveDefaultObeliskApp appRouteToUrl (($ allJsUrl) <$> defaultGhcjsWidgets) serveStaticAsset frontend publicConfigs $ obeliskRoute :/ a
101+ where
102+ appRouteToUrl (k :/ v) = renderObeliskRoute validFullEncoder (FullRoute_Frontend (ObeliskRoute_App k) :/ v)
103+ allJsUrl = renderAllJsPath validFullEncoder
104+
105+ let conf = defRunConfig { _runConfig_redirectPort = port }
106+ runWidget conf publicConfigs frontend validFullEncoder `finally` killThread backendTid
107+
108+-- Convenience wrapper to handle path segments for 'Snap.serveAsset'
109+runServeAsset :: FilePath -> [Text] -> Snap ()
110+runServeAsset rootPath = Snap.serveAsset "" rootPath . T.unpack . T.intercalate "/"
111+
112+getConfigRoute :: Map Text ByteString -> Either Text URI
113+getConfigRoute configs = case Map.lookup "common/route" configs of
114+ Just r ->
115+ let stripped = T.strip (T.decodeUtf8 r)
116+ in case URI.mkURI stripped of
117+ Just route -> Right route
118+ Nothing -> Left $ "Couldn't parse route as URI; value read was: " <> T.pack (show stripped)
119+ Nothing -> Left $ "Couldn't find config file common/route; it should contain the site's canonical root URI" <> T.pack (show $ Map.keys configs)
120+
121+runWidget
122+ :: RunConfig
123+ -> Map Text ByteString
124+ -> Frontend (R frontendRoute)
125+ -> Encoder Identity Identity (R (FullRoute backendRoute frontendRoute)) PageName
126+ -> IO ()
127+runWidget conf configs frontend validFullEncoder = do
128+ uri <- either (fail . T.unpack) pure $ getConfigRoute configs
129+ let port = fromIntegral $ fromMaybe 80 $ uri ^? uriAuthority . _Right . authPort . _Just
130+ redirectHost = _runConfig_redirectHost conf
131+ redirectPort = _runConfig_redirectPort conf
132+ beforeMainLoop = do
133+ putStrLn $ "Frontend running on " <> T.unpack (URI.render uri)
134+ settings = setBeforeMainLoop beforeMainLoop (setPort port (setTimeout 3600 defaultSettings))
135+ -- Providing TLS here will also incidentally provide it to proxied requests to the backend.
136+ prepareRunner = case uri ^? uriScheme . _Just . unRText of
137+ Just "https" -> do
138+ -- Generate a private key and self-signed certificate for TLS
139+ privateKey <- RSA.generateRSAKey' 2048 3
140+
141+ certRequest <- X509Request.newX509Req
142+ _ <- X509Request.setPublicKey certRequest privateKey
143+ _ <- X509Request.signX509Req certRequest privateKey Nothing
144+
145+ cert <- X509.newX509 >>= X509Request.makeX509FromReq certRequest
146+ _ <- X509.setPublicKey cert privateKey
147+ timenow <- getCurrentTime
148+ _ <- X509.setNotBefore cert $ addUTCTime (-1) timenow
149+ _ <- X509.setNotAfter cert $ addUTCTime (365 * 24 * 60 * 60) timenow
150+ _ <- X509.signX509 cert privateKey Nothing
151+
152+ certByteString <- BSUTF8.fromString <$> PEM.writeX509 cert
153+ privateKeyByteString <- BSUTF8.fromString <$> PEM.writePKCS8PrivateKey privateKey Nothing
154+
155+ return $ runTLSSocket (tlsSettingsMemory certByteString privateKeyByteString)
156+ _ -> return runSettingsSocket
157+ runner <- prepareRunner
158+ bracket
159+ (bindPortTCPRetry settings (logPortBindErr port) (_runConfig_retryTimeout conf))
160+ close
161+ (\skt -> do
162+ man <- newManager defaultManagerSettings
163+ app <- obeliskApp configs defaultConnectionOptions frontend validFullEncoder uri $ fallbackProxy redirectHost redirectPort man
164+ runner settings skt app)
165+
166+obeliskApp
167+ :: forall frontendRoute backendRoute
168+ . Map Text ByteString
169+ -> ConnectionOptions
170+ -> Frontend (R frontendRoute)
171+ -> Encoder Identity Identity (R (FullRoute backendRoute frontendRoute)) PageName
172+ -> URI
173+ -> Application
174+ -> IO Application
175+obeliskApp configs opts frontend validFullEncoder uri backend = do
176+ let mode = FrontendMode
177+ { _frontendMode_hydrate = True
178+ , _frontendMode_adjustRoute = False
179+ }
180+ entryPoint = do
181+ runFrontendWithConfigsAndCurrentRoute mode configs validFullEncoder frontend
182+ syncPoint
183+ jsaddlePath <- URI.mkPathPiece "jsaddle"
184+ let jsaddleUri = BSLC.fromStrict $ URI.renderBs $ uri & uriPath %~ (<>[jsaddlePath])
185+ Right (jsaddleWarpRouteValidEncoder :: Encoder Identity (Either Text) (R JSaddleWarpRoute) PageName) <- return $ checkEncoder jsaddleWarpRouteEncoder
186+ jsaddle <- jsaddleWithAppOr opts entryPoint $ \_ sendResponse -> sendResponse $ W.responseLBS H.status500 [("Content-Type", "text/plain")] "obeliskApp: jsaddle got a bad URL"
187+ return $ \req sendResponse -> case tryDecode validFullEncoder $ byteStringsToPageName (BS.dropWhile (== (fromIntegral $ fromEnum '/')) $ W.rawPathInfo req) (BS.drop 1 $ W.rawQueryString req) of
188+ Identity r -> case r of
189+ FullRoute_Frontend (ObeliskRoute_Resource ResourceRoute_JSaddleWarp) :/ jsaddleRoute -> case jsaddleRoute of
190+ JSaddleWarpRoute_JavaScript :/ () -> sendResponse $ W.responseLBS H.status200 [("Content-Type", "application/javascript")] $ jsaddleJs' (Just jsaddleUri) False
191+ _ -> flip jsaddle sendResponse $ req
192+ { W.pathInfo = fst $ encode jsaddleWarpRouteValidEncoder jsaddleRoute
193+ }
194+ FullRoute_Frontend (ObeliskRoute_App appRouteComponent) :/ appRouteRest -> do
195+ let cookies = maybe [] parseCookies $ lookup (fromString "Cookie") (W.requestHeaders req)
196+ routeToUrl (k :/ v) = renderObeliskRoute validFullEncoder $ FullRoute_Frontend (ObeliskRoute_App k) :/ v
197+ html <- renderJsaddleFrontend configs cookies routeToUrl (appRouteComponent :/ appRouteRest) frontend
198+ sendResponse $ W.responseLBS H.status200 [("Content-Type", staticRenderContentType)] $ BSLC.fromStrict html
199+ _ -> backend req sendResponse
200+
201+renderJsaddleFrontend
202+ :: Map Text ByteString
203+ -> Cookies
204+ -> (route -> Text)
205+ -> route
206+ -> Frontend route
207+ -> IO ByteString
208+renderJsaddleFrontend configs cookies urlEnc r f =
209+ let jsaddleScript = elAttr "script" ("src" =: "/jsaddle/jsaddle.js") blank
210+ jsaddlePreload = elAttr "link" ("rel" =: "preload" <> "as" =: "script" <> "href" =: "/jsaddle/jsaddle.js") blank
211+ in renderFrontendHtml configs cookies urlEnc r f jsaddlePreload jsaddleScript
212+
213+-- | like 'bindPortTCP' but reconnects on exception
214+bindPortTCPRetry :: Settings
215+ -> (IOError -> IO ()) -- ^ Action to run the first time an exception is caught
216+ -> Int
217+ -> IO Socket
218+bindPortTCPRetry settings m n = catch (bindPortTCP (settingsPort settings) (settingsHost settings)) $ \(e :: IOError) -> do
219+ m e
220+ threadDelay $ 1000000 * n
221+ bindPortTCPRetry settings (\_ -> pure ()) n
222+
223+logPortBindErr :: Int -> IOError -> IO ()
224+logPortBindErr p e = getProcessIdForPort p >>= \case
225+ Nothing -> putStrLn $ "runWidget: " <> show e
226+ Just pid -> putStrLn $ unwords [ "Port", show p, "is being used by process ID", show pid <> ".", "Please kill that process or change the port in config/common/route."]
227+
228+ssPath :: Maybe String
229+ssPath =
230+#if defined(IPROUTE_SUPPORTED)
231+ Just $(System.Which.staticWhich "ss")
232+#else
233+ Nothing
234+#endif
235+
236+getProcessIdForPort :: Int -> IO (Maybe Int)
237+getProcessIdForPort port = case ssPath of
238+ Just ss -> do
239+ xs <- lines <$> readProcess ss ["-lptn", "sport = " <> show port] mempty
240+ case uncons xs of
241+ Just (_, x:_) -> return $ A.maybeResult $ A.parse parseSsPid $ BSC.pack x
242+ _ -> return Nothing
243+ _ -> return Nothing
244+
245+parseSsPid :: A.Parser Int
246+parseSsPid = do
247+ _ <- A.count 5 $ A.takeWhile (not . A.isSpace) *> A.skipSpace
248+ _ <- A.skipWhile (/= ':') >> A.string ":((" >> A.skipWhile (/= ',')
249+ A.string ",pid=" *> A.decimal
250+
251+fallbackProxy :: ByteString -> Int -> Manager -> Application
252+fallbackProxy host port = RP.waiProxyTo handleRequest RP.defaultOnExc
253+ where handleRequest _req = return $ RP.WPRProxyDest $ RP.ProxyDest host port
254+
255+data RunConfig = RunConfig
256+ { _runConfig_port :: Int
257+ , _runConfig_redirectHost :: ByteString
258+ , _runConfig_redirectPort :: Int
259+ , _runConfig_retryTimeout :: Int -- seconds
260+ }
261+
262+defRunConfig :: RunConfig
263+defRunConfig = RunConfig
264+ { _runConfig_port = 8000
265+ , _runConfig_redirectHost = "127.0.0.1"
266+ , _runConfig_redirectPort = 3001
267+ , _runConfig_retryTimeout = 1
268+ }
lib/selftest/obelisk-selftest.cabal+17−3
@@ -1,20 +1,34 @@
1name: obelisk-selftest
1name: obelisk-selftest
2version: 0.1
2version: 0.1
3−synopsys: Impure and nix-level tests for obelisk
3+synopsis: Impure and nix-level tests for obelisk
4license: BSD3
4license: BSD3
5build-type: Simple
5build-type: Simple
6cabal-version: >=1.8
6cabal-version: >=1.8
7
7
8library
8library
9− hs-source-dir: src
9+ hs-source-dirs: src
10 build-depends:
10 build-depends:
11 base
11 base
12+ , bytestring
13+ , aeson
14+ , containers
15+ , directory
16+ , filepath
12 , hspec
17 , hspec
18+ , http-client
19+ , http-types
20+ , HUnit
21+ , network
22+ , obelisk-executable-config-lookup
23+ , obelisk-run
24+ , which
25+ , process
13− , shelly
26+ , shelly >= 1.9.0
14 , temporary
27 , temporary
15 , text
28 , text
16 exposed-modules:
29 exposed-modules:
17 Obelisk.SelfTest
30 Obelisk.SelfTest
31+ ghc-options: -Wall
18
32
19executable obelisk-selftest
33executable obelisk-selftest
20 main-is: src-bin/obelisk-selftest.hs
34 main-is: src-bin/obelisk-selftest.hs
lib/selftest/src/Obelisk/SelfTest.hs+613−12
@@ -1,25 +1,626 @@
1+{-# LANGUAGE DoAndIfThenElse #-}
2+{-# LANGUAGE EmptyCase #-}
3+{-# LANGUAGE LambdaCase #-}
1{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE OverloadedStrings #-}
5+{-# LANGUAGE PatternGuards #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE TemplateHaskell #-}
8+{-# LANGUAGE TypeApplications #-}
9+{-# LANGUAGE ViewPatterns #-}
2module Obelisk.SelfTest where
10module Obelisk.SelfTest where
3
11
12+import Control.Concurrent (threadDelay)
13+import Control.Exception (bracket, throw, try)
4import Control.Monad
14import Control.Monad
15+import Control.Monad.IO.Class
16+import qualified Data.Aeson as Aeson
17+import qualified Data.Aeson.Types as Aeson
18+import Data.Bool (bool)
19+import qualified Data.ByteString.Lazy as LBS
20+import Data.Foldable (for_)
21+import Data.Function (fix)
22+import Data.List (isInfixOf)
23+import qualified Data.Map as Map
24+import Data.Semigroup ((<>))
25+import qualified Data.Set as Set
5import Data.String
26import Data.String
27+import Data.Text (Text)
6import qualified Data.Text as T
28import qualified Data.Text as T
29+import qualified Data.Text.Encoding as T
30+import qualified Data.Text.IO as T
31+import qualified Network.HTTP.Client as HTTP
32+import qualified Network.HTTP.Types as HTTP
33+import qualified Network.Socket as Socket
7import Shelly
34import Shelly
35+import System.Directory (getCurrentDirectory, withCurrentDirectory, getDirectoryContents)
8import System.Environment
36import System.Environment
37+import System.Exit (ExitCode (..))
38+import System.FilePath (addTrailingPathSeparator)
39+import qualified System.Info
40+import System.IO (Handle, hClose, hIsEOF, hGetContents)
9import System.IO.Temp
41import System.IO.Temp
42+import System.Process (readProcessWithExitCode)
43+import System.Which (staticWhich)
10import Test.Hspec
44import Test.Hspec
45+import Test.HUnit.Base
46+
47+import Obelisk.ExecutableConfig.Lookup (getConfigs)
48+import Obelisk.Run (getConfigRoute)
49+
50+data ObRunState
51+ = ObRunState_Init
52+ | ObRunState_Startup
53+ | ObRunState_BackendStarted
54+ deriving (Eq, Show)
55+
56+cpPath :: FilePath
57+cpPath = $(staticWhich "cp")
58+
59+cabalPath :: FilePath
60+cabalPath = $(staticWhich "cabal")
61+
62+gitPath :: FilePath
63+gitPath = $(staticWhich "git")
64+
65+chownPath :: FilePath
66+chownPath = $(staticWhich "chown")
67+
68+chmodPath :: FilePath
69+chmodPath = $(staticWhich "chmod")
70+
71+whoamiPath :: FilePath
72+whoamiPath = $(staticWhich "whoami")
73+
74+nixInstantiatePath :: FilePath
75+nixInstantiatePath = $(staticWhich "nix-instantiate")
76+
77+nixBuildPath :: FilePath
78+nixBuildPath = $(staticWhich "nix-build")
79+
80+nixPrefetchGitPath :: FilePath
81+nixPrefetchGitPath = $(staticWhich "nix-prefetch-git")
82+
83+lnPath :: FilePath
84+lnPath = $(staticWhich "ln")
85+
86+rmPath :: FilePath
87+rmPath = $(staticWhich "rm")
88+
89+rsyncPath :: FilePath
90+rsyncPath = $(staticWhich "rsync")
91+
92+gitUserConfig :: [Text]
93+gitUserConfig = ["-c", "user.name=Obelisk Selftest", "-c", "user.email=noreply@example.com"]
94+
95+commit :: Text -> Sh ()
96+commit msg = void $ run gitPath $ gitUserConfig <> [ "commit"
97+ , "--no-gpg-sign"
98+ , "--allow-empty"
99+ , "-m"
100+ , msg
101+ ]
102+
103+tshow :: Show a => a -> Text
104+tshow = T.pack . show
105+
106+-- | Like `shelly` but used when running `ob` commands
107+shellyOb :: MonadIO m => (Sh a -> Sh a) -> Sh a -> m a
108+shellyOb f obTest = shelly $ f obTest
109+
110+-- Set "ob" in a single place so it can be replaced with a
111+-- link to obelisk in the nix store in the future,
112+-- and avoid PATH hacking before calling this script.
113+ob :: FilePath
114+ob = "ob"
115+
116+augmentWithVerbosity :: (String -> [Text] -> a) -> String -> Bool -> [Text] -> a
117+augmentWithVerbosity runner executable isVerbose args = runner executable $ (if isVerbose then ("-v" :) else id) args
118+
119+isolatedGitShell :: Bool -> FilePath -> (([Text] -> Sh Text) -> Sh a) -> IO a
120+isolatedGitShell isVerbose dir f = shelly $ bool silently verbosely isVerbose $ do
121+ setenv "HOME" "/dev/null"
122+ setenv "GIT_CONFIG_NOSYSTEM" "1"
123+ _ <- git ["init"]
124+ _ <- git ["config", "user.name", "SelfTest"]
125+ _ <- git ["config", "user.email", "self@test"]
126+ f git
127+ where
128+ git args = run gitPath $ ["-C", toTextIgnore dir] <> args
129+
130+-- | Copies a git repo to a new location and "resets" the git history to include
131+-- exactly one commit with all files added. It then restricts writing and reading
132+-- for group and user to make the repo ideal for being a valid git remote for thunks.
133+--
134+-- Using this allows dirty repos to be used as git remotes during the test since 'git clone'ing
135+-- a dirty repo will not include the uncommitted changes.
136+copyForGitRemote :: Bool -> FilePath -> FilePath -> IO ()
137+copyForGitRemote isVerbose origDir copyDir = isolatedGitShell isVerbose copyDir $ \git -> do
138+ run_ rsyncPath
139+ [ "-r", "--no-perms", "--no-owner", "--no-group", "--exclude", ".git"
140+ , toTextIgnore (addTrailingPathSeparator origDir), toTextIgnore copyDir
141+ ]
142+ _ <- git ["add", "--all"]
143+ _ <- git ["commit", "-m", "Copy repo"]
144+ run_ chmodPath ["-R", "u-w,g-rw,o-rw", toTextIgnore copyDir] -- Freeze this state
11
145
12main :: IO ()
146main :: IO ()
13main = do
147main = do
14− obeliskImpl <- getEnv "OBELISK_IMPL"
148+ -- Note: you can pass hspec arguments as well, eg: `-m <pattern>`
15− withSystemTempDirectory "blank-project" $ \blankProject ->
149+ isVerbose <- elem "-v" <$> getArgs
16− hspec $ do
150+ unless isVerbose $
17− describe "blank initialized project" $ do
151+ putStrLn "Tests may take longer to run if there are unbuilt derivations: use -v for verbose output"
18− let inProj :: Sh a -> IO ()
152+
19− inProj = void . shelly . silently . chdir (fromString blankProject)
153+ obeliskImplDirtyReadOnly <- getCurrentDirectory
20− it "can be created" $ inProj $ do
154+ httpManager <- HTTP.newManager HTTP.defaultManagerSettings
21− run "ob" ["init", "--symlink", T.pack obeliskImpl]
155+
22− it "can build ghc.backend" $ inProj $ do
156+ withSystemTempDirectory "obelisk-repo-git-remote" $ \copyDir -> do
23− run "nix-build" ["--no-out-link", "-A", "ghc.backend"]
157+ copyForGitRemote isVerbose obeliskImplDirtyReadOnly copyDir
24− it "can build ghcjs.frontend" $ inProj $ do
158+ main' isVerbose httpManager copyDir
25− run "nix-build" ["--no-out-link", "-A", "ghcjs.frontend"]
159+
160+main' :: Bool -> HTTP.Manager -> FilePath -> IO ()
161+main' isVerbose httpManager obeliskRepoReadOnly = withInitCache $ \initCache -> hspec $ parallel $ do
162+ let
163+ inTmpObInit' dirname f = inTmp' dirname $ \dir -> do
164+ run_ cpPath ["-rT", fromString initCache, toTextIgnore dir]
165+ f dir
166+ inTmpObInit = inTmpObInit' defaultTmpDirName
167+
168+ -- To be used in tests that change the obelisk impl directory
169+ inTmpObInitWithImplCopy f = inTmpObInit $ \dir ->
170+ withObeliskImplClean $ \(fromString -> implClean) -> do
171+ run_ rmPath [thunk]
172+ run_ lnPath ["-s", implClean, thunk]
173+ f dir
174+
175+ describe "ob init" $ parallel $ do
176+ it "works with default impl" $ inTmp $ \_ -> runOb ["init"]
177+ it "works with master branch impl" $ inTmp $ \_ -> runOb ["init", "--branch", "master"]
178+ it "works with symlink" $ inTmp $ \_ -> runOb ["init", "--symlink", toTextIgnore obeliskRepoReadOnly]
179+ it "doesn't silently overwrite existing files" $ inTmp $ \_ -> do
180+ let p force = errExit False $ do
181+ run_ ob $ "--no-handoff" : "-v" : "init" : ["--force"|force]
182+ (== 0) <$> lastExitCode
183+
184+ True <- p False
185+ False <- p False
186+ True <- p True
187+ pure ()
188+
189+ it "doesn't create anything when given an invalid impl" $ inTmp $ \tmp -> do
190+ void $ errExit False $ runOb ["init", "--symlink", "/dev/null"]
191+ ls tmp >>= liftIO . assertEqual "" []
192+
193+ it "produces a valid route config" $ inTmpObInit $ \tmp -> liftIO $
194+ withCurrentDirectory (T.unpack $ toTextIgnore tmp) $ do
195+ configs <- getConfigs
196+ return (either (const Nothing) Just $ getConfigRoute configs) `shouldNotReturn` Nothing
197+
198+ it "can unpack and repack .obelisk/impl after init with master branch impl" $ inTmp $ \_ -> do
199+ runOb_ ["init", "--branch", "master"]
200+ runOb_ ["thunk", "unpack", ".obelisk/impl"]
201+ runOb_ ["thunk", "pack", ".obelisk/impl"]
202+
203+ -- These tests fail with "Could not find module 'Obelisk.Generated.Static'"
204+ -- when not run by 'nix-build --attr selftest'
205+ describe "ob run" $ {- NOT parallel $ -} do
206+ it "works in root directory" $ inTmpObInit $ \_ -> testObRunInDir' Nothing httpManager
207+ it "works in sub directory" $ inTmpObInit $ \_ -> testObRunInDir' (Just "frontend") httpManager
208+
209+ describe "ob repl" $ do
210+ it "accepts stdin commands" $ inTmpObInit $ \_ -> do
211+ setStdin "print 3\n:q"
212+ output <- runOb ["repl"]
213+ liftIO $ assertBool "" $
214+ [ "*Obelisk.Run Obelisk.Run Frontend Backend> 3"
215+ , "*Obelisk.Run Obelisk.Run Frontend Backend> Leaving GHCi."
216+ ] `isInfixOf` T.lines (T.strip output)
217+ it "works with custom Prelude" $ inTmpObInit $ \_ -> do
218+ writefile "common/src/Prelude.hs"
219+ "{-# LANGUAGE PackageImports #-} module Prelude (module X) where import \"base\" Prelude as X"
220+ setStdin ":q"
221+ output <- runOb ["repl"]
222+ liftIO $ assertBool "" $
223+ "*Obelisk.Run Obelisk.Run Frontend Backend> Leaving GHCi." `T.isInfixOf` output
224+
225+ describe "obelisk project" $ parallel $ do
226+ it "can build obelisk command" $ inTmpObInit $ \_ -> nixBuild ["-A", "command" , toTextIgnore obeliskRepoReadOnly]
227+ it "can build obelisk skeleton" $ inTmpObInit $ \_ -> nixBuild ["-A", "skeleton", toTextIgnore obeliskRepoReadOnly]
228+ it "can build obelisk shell" $ inTmpObInit $ \_ -> nixBuild ["-A", "shell", toTextIgnore obeliskRepoReadOnly]
229+ it "can build everything" $ inTmpObInit $ \_ -> nixBuild [toTextIgnore obeliskRepoReadOnly]
230+
231+ describe "blank initialized project" $ parallel $ do
232+
233+ it "can build ghc.backend" $ inTmpObInit $ \_ -> nixBuild ["-A", "ghc.backend"]
234+ it "can build ghcjs.frontend" $ inTmpObInit $ \_ -> nixBuild ["-A", "ghcjs.frontend"]
235+
236+ if System.Info.os == "darwin"
237+ then it "can build ios" $ inTmpObInit $ \_ -> nixBuild ["-A", "ios.frontend"]
238+ else it "can build android after accepting license" $ inTmpObInit $ \dir -> do
239+ let defaultNixPath = dir </> ("default.nix" :: FilePath)
240+ writefile defaultNixPath
241+ =<< T.replace
242+ "# config.android_sdk.accept_license = false;"
243+ "config.android_sdk.accept_license = true;"
244+ <$> readfile defaultNixPath
245+ nixBuild ["-A", "android.frontend"]
246+
247+ forM_ ["ghc", "ghcjs"] $ \compiler -> do
248+ let
249+ shellName = "shells." <> compiler
250+ inShell cmd' = run_ "nix-shell" ["default.nix", "-A", fromString shellName, "--run", cmd']
251+ it ("can enter " <> shellName) $ inTmpObInit $ \_ -> inShell "exit"
252+ -- NOTE: We override the temporary directory name because cabal has a bug preventing new-build from working
253+ -- in a path that has unicode characters.
254+ it ("can build in " <> shellName) $ inTmpObInit' "test" $ \_ -> inShell $
255+ T.pack cabalPath <> " --version; " <> T.pack cabalPath <> " new-build --" <> T.pack compiler <> " all"
256+
257+ it "has idempotent thunk update" $ inTmpObInitWithImplCopy $ \_ -> do
258+ _ <- pack
259+ u <- update
260+ uu <- update
261+ assertRevEQ u uu
262+
263+ it "can run 'ob doc'" $ inTmpObInit $ \_ -> runOb_ ["doc", "reflex"]
264+
265+ describe "ob thunk pack/unpack" $ parallel $ do
266+ it "has thunk pack and unpack inverses" $ inTmpObInitWithImplCopy $ \_ -> do
267+
268+ _ <- pack
269+ e <- commitAll
270+ eu <- unpack
271+ eup <- pack
272+ eupu <- unpack
273+ _ <- pack
274+
275+ assertRevEQ e eup
276+ assertRevEQ eu eupu
277+ assertRevNE e eu
278+
279+ it "unpacks the correct branch" $ withTmp $ \dir -> do
280+ let branch = "master"
281+ run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch]
282+ runOb_ ["thunk", "pack", toTextIgnore dir]
283+ runOb_ ["thunk", "unpack", toTextIgnore dir]
284+ branch' <- run gitPath ["-C", toTextIgnore $ dir </> unpackedDirName, "rev-parse", "--abbrev-ref", "HEAD"]
285+ liftIO $ assertEqual "" branch (T.strip branch')
286+
287+ it "can pack and unpack plain git repos" $
288+ shelly_ $ withSystemTempDirectory "git-repo" $ \dir -> do
289+ let repo = toTextIgnore $ dir </> ("repo" :: FilePath)
290+ run_ gitPath ["clone", "https://github.com/haskell/process.git", repo]
291+ origHash <- chdir (fromText repo) revParseHead
292+
293+ runOb_ ["thunk", "pack", repo]
294+ packedFiles <- Set.fromList <$> ls (fromText repo)
295+ liftIO $ assertEqual "" packedFiles $ Set.fromList $ (repo </>) <$>
296+ ["default.nix", "thunk.nix", "github.json" :: FilePath]
297+
298+ runOb_ ["thunk", "unpack", repo]
299+ chdir (fromText repo </> unpackedDirName) $ do
300+ unpackHash <- revParseHead
301+ assertRevEQ origHash unpackHash
302+
303+ testThunkPack' $ fromText repo
304+
305+ it "aborts thunk pack when there are uncommitted files" $ inTmpObInitWithImplCopy $ \dir -> do
306+ testThunkPack' (dir </> thunk)
307+
308+ it "works on legacy git thunks" $ testLegacyGitThunks isVerbose
309+
310+ describe "ob thunk update --branch" $ parallel $ do
311+ it "can change a thunk to the latest version of a desired branch" $ withTmp $ \dir -> do
312+ let branch1 = "master"
313+ branch2 = "develop"
314+ run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", branch1]
315+ runOb_ ["thunk" , "pack", toTextIgnore dir]
316+ runOb_ ["thunk", "update", toTextIgnore dir, "--branch", branch2]
317+
318+ it "doesn't create anything when given an invalid branch" $ withTmp $ \dir -> do
319+ let checkDir dir' = liftIO $ getDirectoryContents $ T.unpack $ toTextIgnore dir'
320+ run_ gitPath ["clone", "https://github.com/reflex-frp/reflex.git", toTextIgnore dir, "--branch", "master"]
321+ runOb_ ["thunk" , "pack", toTextIgnore dir]
322+ startingContents <- checkDir dir
323+ void $ errExit False $ runOb ["thunk", "update", toTextIgnore dir, "--branch", "dumble-palooza"]
324+ checkDir dir >>= liftIO . assertEqual "" startingContents
325+
326+ describe "ob shell" $ parallel $ do
327+ it "works with --" $ inTmpObInit $ \_ -> do
328+ output <- runOb ["shell", "--", "ghc-pkg", "list"]
329+ liftIO $ assertBool "Unexpected output from ob shell" $ ("Cabal-" `T.isInfixOf` output) && ("ghc-" `T.isInfixOf` output)
330+
331+ describe "ob hoogle" $ {- NOT parallel -} do
332+ it "starts a hoogle server on the given port" $ inTmpObInit $ \_ -> do
333+ [p0] <- liftIO $ getFreePorts 1
334+ maskExitSuccess $ runHandle "ob" ["hoogle", "--port", T.pack (show p0)] $ \stdout -> flip fix Nothing $ \loop -> \case
335+ Nothing -> do -- Still waiting for initial signal that the server has started
336+ ln <- liftIO $ T.hGetLine stdout
337+ let search = "Server starting on port " <> T.pack (show p0)
338+ case search `T.isInfixOf` ln of
339+ False -> loop Nothing -- keep waiting
340+ True -> loop $ Just 10
341+ Just (n :: Int) -> do -- Server has started and we have n attempts left
342+ let req uri = liftIO $ try @HTTP.HttpException $ HTTP.parseRequest uri >>= flip HTTP.httpLbs httpManager
343+ req ("http://127.0.0.1:" <> show p0) >>= \case
344+ Right r | HTTP.responseStatus r == HTTP.ok200 -> exit 0
345+ e -> if n <= 0
346+ then errorExit $ "Request to hoogle server failed: " <> T.pack (show e)
347+ else liftIO (threadDelay (1*10^(6 :: Int))) *> loop (Just $ n - 1)
348+ where
349+ verbosity = bool silently verbosely isVerbose
350+ nixBuild args = run nixBuildPath ("--no-out-link" : args)
351+
352+ runOb_ = augmentWithVerbosity run_ ob isVerbose
353+ runOb = augmentWithVerbosity run ob isVerbose
354+ testObRunInDir' = augmentWithVerbosity testObRunInDir ob isVerbose ["run"]
355+ testThunkPack' = augmentWithVerbosity testThunkPack ob isVerbose []
356+
357+ withObeliskImplClean f =
358+ withSystemTempDirectory "obelisk-impl-clean" $ \obeliskImpl -> do
359+ void . shellyOb verbosity $ do
360+ dirtyFiles <- T.strip <$> run gitPath ["-C", toTextIgnore obeliskRepoReadOnly, "diff", "--stat"]
361+ () <- when (dirtyFiles /= "") $ error "SelfTest does not work correctly with dirty obelisk repos as remote"
362+ run_ gitPath ["clone", "file://" <> toTextIgnore obeliskRepoReadOnly, toTextIgnore obeliskImpl]
363+ f obeliskImpl
364+
365+ withInitCache f =
366+ withSystemTempDirectory "init Cache λ" $ \initCache -> do
367+ -- Setup the ob init cache
368+ void . shellyOb verbosity $ chdir initCache $ do
369+ runOb_ ["init", "--symlink", toTextIgnore obeliskRepoReadOnly]
370+ run_ gitPath ["init"]
371+
372+ f initCache
373+
374+ shelly_ = void . shellyOb verbosity
375+
376+ defaultTmpDirName = "test λ"
377+
378+ inTmp' :: FilePath -> (FilePath -> Sh a) -> IO ()
379+ inTmp' dirname f = withTmp' dirname (chdir <*> f)
380+ inTmp = inTmp' defaultTmpDirName
381+
382+ withTmp' dirname f = shelly_ . withSystemTempDirectory dirname $ f . fromString
383+ withTmp = withTmp' defaultTmpDirName
384+
385+ assertRevEQ a b = liftIO . assertEqual "" "" =<< diff a b
386+ assertRevNE a b = liftIO . assertBool "" . (/= "") =<< diff a b
387+
388+ revParseHead = T.strip <$> run gitPath ["rev-parse", "HEAD"]
389+
390+ commitAll = do
391+ run_ gitPath ["add", "."]
392+ commit "checkpoint"
393+ revParseHead
394+
395+ thunk = ".obelisk/impl"
396+ update = runOb ["thunk", "update", thunk] *> commitAll
397+ pack = runOb ["thunk", "pack", thunk] *> commitAll
398+ unpack = runOb ["thunk", "unpack", thunk] *> commitAll
399+
400+ diff a b = run gitPath ["diff", a, b]
401+
402+
403+maskExitSuccess :: Sh () -> Sh ()
404+maskExitSuccess = handle_sh (\case ExitSuccess -> pure (); e -> throw e)
405+
406+-- | Run `ob run` in the given directory (maximum of one level deep)
407+testObRunInDir :: String -> [Text] -> Maybe FilePath -> HTTP.Manager -> Sh ()
408+testObRunInDir executable extraArgs mdir httpManager = maskExitSuccess $ do
409+ [p0, p1] <- liftIO $ getFreePorts 2
410+ let uri p = "http://localhost:" <> T.pack (show p) <> "/" -- trailing slash required for comparison
411+ writefile "config/common/route" $ uri p0
412+ maybe id chdir mdir $ runHandles executable extraArgs [] $ \_stdin stdout stderr -> do
413+ firstUri <- handleObRunStdout httpManager stdout stderr
414+ let newUri = uri p1
415+ when (firstUri == newUri) $ errorExit $
416+ "Startup URI (" <> firstUri <> ") is the same as test URI (" <> newUri <> ")"
417+ maybe id (\_ -> chdir "..") mdir $ alterRouteTo newUri stdout
418+ runningUri <- handleObRunStdout httpManager stdout stderr
419+ if runningUri /= newUri
420+ then errorExit $ "Reloading failed: expected " <> newUri <> " but got " <> runningUri
421+ else exit 0
422+
423+testThunkPack :: String -> [Text] -> FilePath -> Sh ()
424+testThunkPack executable args path' = withTempFile repoDir "test-file" $ \file handle -> do
425+ let
426+ pack' = readProcessWithExitCode executable (["thunk", "pack", path'] ++ map T.unpack args) ""
427+ ensureThunkPackFails q = liftIO $ pack' >>= \case
428+ (code, out, err)
429+ | code == ExitSuccess -> fail $ "ob thunk pack succeeded when it should have failed with error '" <> show q <> "'"
430+ | q `T.isInfixOf` T.pack (out <> err) -> pure ()
431+ | otherwise -> fail $ "ob thunk pack failed for an unexpected reason, expecting '" <> show q <> "', received: " <> show out <> "\nstderr: " <> err
432+ git = chdir repoDir . run_ gitPath
433+ -- Untracked files
434+ ensureThunkPackFails "Untracked files"
435+ git ["add", T.pack file]
436+ -- Uncommitted files (staged)
437+ ensureThunkPackFails "unsaved"
438+ chdir repoDir $ commit "test commit"
439+ -- Non-pushed commits in any branch
440+ ensureThunkPackFails "not yet pushed"
441+ -- Uncommitted files (unstaged)
442+ liftIO $ T.hPutStrLn handle "test file" >> hClose handle
443+ ensureThunkPackFails "modified"
444+ -- Existing stashes
445+ git $ gitUserConfig <> [ "stash" ]
446+ ensureThunkPackFails "has stashes"
447+ where
448+ repoDir = path' </> unpackedDirName
449+
450+-- | Blocks until a non-empty line is available
451+hGetLineSkipBlanks :: MonadIO m => Handle -> m Text
452+hGetLineSkipBlanks h = liftIO $ fix $ \loop -> T.hGetLine h >>= \case
453+ "" -> loop
454+ t -> pure t
455+
456+-- | Alters the route file and waits for `ob run` to reload
457+alterRouteTo :: Text -> Handle -> Sh ()
458+alterRouteTo uri stdout = do
459+ writefile "config/common/route" uri
460+ hGetLineSkipBlanks stdout >>= \t -> when (t /= "Reloading...") $ errorExit $
461+ "Reloading failed: " <> T.pack (show t)
462+ hGetLineSkipBlanks stdout >>= \t -> when (t /= " config/common/route") $ errorExit $
463+ "Reloading failed: " <> T.pack (show t)
464+ hGetLineSkipBlanks stdout >>= \t -> when (t /= "Interrupted.") $ errorExit $
465+ "Reloading failed: " <> T.pack (show t)
466+
467+-- | Handle stdout of `ob run`: check that the frontend and backend servers are started correctly
468+handleObRunStdout :: HTTP.Manager -> Handle -> Handle -> Sh Text
469+handleObRunStdout httpManager stdout stderr = flip fix (ObRunState_Init, []) $ \loop (state, msgs) -> do
470+ isEOF <- liftIO $ hIsEOF stdout
471+ if isEOF
472+ then handleObRunError msgs
473+ else liftIO (T.hGetLine stdout) >>= \t -> case state of
474+ ObRunState_Init
475+ | "Running test..." `T.isPrefixOf` t -> loop (ObRunState_BackendStarted, msgs)
476+ ObRunState_Startup
477+ | t == "backend stopped; make a change to your code to reload" -> loop (ObRunState_Startup, msgs)
478+ -- | Just port <- "Backend running on port " `T.stripPrefix` t -> loop $ ObRunState_BackendStarted port
479+ | not (T.null t) -> errorExit $ "Startup: " <> t -- If theres any other output here, startup failed
480+ ObRunState_BackendStarted
481+ | Just uri <- "Frontend running on " `T.stripPrefix` t -> do
482+ obRunCheck httpManager stdout uri
483+ pure uri
484+ | not (T.null t) -> errorExit $ "Started: " <> t -- If theres any other output here, startup failed
485+ _ | "Failed" `T.isPrefixOf` t -> handleObRunError (t : msgs)
486+ | otherwise -> loop (state, t : msgs)
487+ where
488+ handleObRunError msgs = do
489+ stderrContent <- liftIO $ hGetContents stderr
490+ errorExit $ "ob run failed: " <> T.unlines (reverse msgs) <> " stderr: " <> T.pack stderrContent
491+
492+-- | Make requests to frontend/backend servers to check they are working properly
493+obRunCheck :: HTTP.Manager -> Handle -> Text -> Sh ()
494+obRunCheck httpManager _stdout frontendUri = do
495+ let req uri = liftIO $ HTTP.parseRequest (T.unpack uri) >>= flip HTTP.httpLbs httpManager
496+ req frontendUri >>= \r -> when (HTTP.responseStatus r /= HTTP.ok200) $ errorExit $
497+ "Request to frontend server failed: " <> T.pack (show r)
498+
499+getFreePorts :: Int -> IO [Socket.PortNumber]
500+getFreePorts 0 = pure []
501+getFreePorts n = Socket.withSocketsDo $ do
502+ addr:_ <- Socket.getAddrInfo (Just Socket.defaultHints) (Just "127.0.0.1") (Just "0")
503+ bracket (open addr) Socket.close $ \s -> (:) <$> Socket.socketPort s <*> getFreePorts (n - 1)
504+ where
505+ open addr = do
506+ sock <- Socket.socket (Socket.addrFamily addr) (Socket.addrSocketType addr) (Socket.addrProtocol addr)
507+ Socket.bind sock (Socket.addrAddress addr)
508+ pure sock
509+
510+testLegacyGitThunks :: Bool -> IO ()
511+testLegacyGitThunks isVerbose = withSystemTempDirectory "test-git-repo" $ \gitDir -> do
512+ isolatedGitShell isVerbose gitDir $ \git -> do
513+ writefile (gitDir </> ("default.nix" :: FilePath)) "{}: \"hello\""
514+ _ <- git ["add", "--all"]
515+ _ <- git ["commit", "-m", "Initial commit"]
516+ rev <- T.strip <$> git ["rev-parse", "HEAD"]
517+ sha256 :: Text
518+ <- either error pure
519+ =<< (Aeson.parseEither (Aeson..: "sha256") <=< Aeson.eitherDecodeStrict . T.encodeUtf8)
520+ <$> run nixPrefetchGitPath [toTextIgnore gitDir]
521+
522+ for_ (legacyGitThunks (GitThunkParams gitDir rev sha256)) $ \mkFiles ->
523+ withSystemTempDirectory "test-thunks" $ \thunkDir -> do
524+ liftIO $ mkFiles thunkDir
525+ run_ "ob" ["thunk", "unpack", toTextIgnore thunkDir]
526+ run_ "ob" ["thunk", "pack", toTextIgnore thunkDir]
527+
528+data GitThunkParams = GitThunkParams
529+ { _gitThunkParams_repo :: !FilePath
530+ , _gitThunkParams_rev :: !Text
531+ , _gitThunkParams_sha256 :: !Text
532+ } deriving Show
533+
534+legacyGitThunks :: GitThunkParams -> [FilePath -> IO ()]
535+legacyGitThunks (GitThunkParams repo' rev sha256) =
536+ [ mkLegacyIO
537+ (T.unlines
538+ [ "# DO NOT HAND-EDIT THIS FILE"
539+ , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
540+ , " assert !fetchSubmodules; (import <nixpkgs> {}).fetchgit { inherit url rev sha256; };"
541+ , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
542+ ]
543+ )
544+ (Map.fromList
545+ [ ("url", repo)
546+ , ("rev", rev)
547+ , ("branch", "master")
548+ , ("sha256", sha256)
549+ ]
550+ )
551+ , mkLegacyIO
552+ (T.unlines
553+ [ "# DO NOT HAND-EDIT THIS FILE"
554+ , "let fetchGit = {url, rev, ref ? null, branch ? null, sha256 ? null, fetchSubmodules ? null}:"
555+ , " if builtins.hasAttr \"fetchGit\" builtins"
556+ , " then builtins.fetchGit ({ inherit url rev; } // (if branch == null then {} else { ref = branch; }))"
557+ , " else abort \"Plain Git repositories are only supported on nix 2.0 or higher.\";"
558+ , "in import (fetchGit (builtins.fromJSON (builtins.readFile ./git.json)))"
559+ ]
560+ )
561+ (Map.fromList
562+ [ ("url", repo)
563+ , ("rev", rev)
564+ , ("branch", "master")
565+ , ("sha256", sha256)
566+ ]
567+ )
568+ , mkLegacyIO
569+ (T.unlines
570+ [ "# DO NOT HAND-EDIT THIS FILE"
571+ , "let fetch = {url, rev, ref ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
572+ , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
573+ , " if firstChar == \"/\" then /. + url"
574+ , " else if firstChar == \".\" then ./. + url"
575+ , " else url;"
576+ , " in if !fetchSubmodules && private then builtins.fetchGit {"
577+ , " url = realUrl; inherit rev;"
578+ , " } else (import <nixpkgs> {}).fetchgit {"
579+ , " url = realUrl; inherit rev sha256;"
580+ , " };"
581+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
582+ ]
583+ )
584+ (Map.fromList
585+ [ ("url", Aeson.String repo)
586+ , ("rev", Aeson.String rev)
587+ , ("branch", Aeson.String "master")
588+ , ("sha256", Aeson.String sha256)
589+ , ("private", Aeson.Bool False)
590+ ]
591+ )
592+ , mkLegacyIO
593+ (T.unlines
594+ [ "# DO NOT HAND-EDIT THIS FILE"
595+ , "let fetch = {url, rev, branch ? null, sha256 ? null, fetchSubmodules ? false, private ? false, ...}:"
596+ , " let realUrl = let firstChar = builtins.substring 0 1 url; in"
597+ , " if firstChar == \"/\" then /. + url"
598+ , " else if firstChar == \".\" then ./. + url"
599+ , " else url;"
600+ , " in if !fetchSubmodules && private then builtins.fetchGit {"
601+ , " url = realUrl; inherit rev;"
602+ , " ${if branch == null then null else \"ref\"} = branch;"
603+ , " } else (import <nixpkgs> {}).fetchgit {"
604+ , " url = realUrl; inherit rev sha256;"
605+ , " };"
606+ , "in import (fetch (builtins.fromJSON (builtins.readFile ./git.json)))"
607+ ]
608+ )
609+ (Map.fromList
610+ [ ("url", Aeson.String repo)
611+ , ("rev", Aeson.String rev)
612+ , ("branch", Aeson.String "master")
613+ , ("sha256", Aeson.String sha256)
614+ , ("private", Aeson.Bool False)
615+ ]
616+ )
617+ ]
618+ where
619+ repo = T.pack repo'
620+ mkLegacyIO :: Aeson.ToJSON v => Text -> Map.Map Text v -> FilePath -> IO ()
621+ mkLegacyIO defaultNix gitJson dir = do
622+ T.writeFile (dir </> ("default.nix" :: FilePath)) defaultNix
623+ LBS.writeFile (dir </> ("git.json" :: FilePath)) (Aeson.encode gitJson)
624+
625+unpackedDirName :: FilePath
626+unpackedDirName = "."
lib/snap-extras/obelisk-snap-extras.cabal+2−3
@@ -1,6 +1,6 @@
1name: obelisk-snap-extras
1name: obelisk-snap-extras
2version: 0.1
2version: 0.1
3−synopsys: Extra functionality for Snap that should be considered for upstreaming
3+synopsis: Extra functionality for Snap that should be considered for upstreaming
4license: BSD3
4license: BSD3
5build-type: Simple
5build-type: Simple
6cabal-version: >=1.2
6cabal-version: >=1.2
@@ -12,10 +12,9 @@ library
12 , base
12 , base
13 , bytestring
13 , bytestring
14 , snap-core
14 , snap-core
15− , unix
16 , directory
15 , directory
17 , filepath
16 , filepath
18 , text
17 , text
19 exposed-modules:
18 exposed-modules:
20 Obelisk.Snap.Extras
19 Obelisk.Snap.Extras
21− ghc-options: -Wall
20+ ghc-options: -Wall -Werror -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O
lib/snap-extras/src/Obelisk/Snap/Extras.hs+2−2
@@ -2,13 +2,13 @@
2module Obelisk.Snap.Extras
2module Obelisk.Snap.Extras
3 ( cachePermanently
3 ( cachePermanently
4 , doNotCache
4 , doNotCache
5+ , ensureSecure
5 , serveFileIfExists
6 , serveFileIfExists
6 , serveFileIfExistsAs
7 , serveFileIfExistsAs
7 ) where
8 ) where
8
9
9import Control.Monad.IO.Class
10import Control.Monad.IO.Class
10import Data.ByteString (ByteString)
11import Data.ByteString (ByteString)
11−import Data.Monoid
12import Data.String
12import Data.String
13import Snap.Core
13import Snap.Core
14import Snap.Util.FileServe
14import Snap.Util.FileServe
@@ -17,7 +17,7 @@ import System.Directory
17-- | Set response header for "permanent" caching
17-- | Set response header for "permanent" caching
18cachePermanently :: MonadSnap m => m ()
18cachePermanently :: MonadSnap m => m ()
19cachePermanently = do
19cachePermanently = do
20− modifyResponse $ setHeader "Cache-Control" "public, max-age=315360000"
20+ modifyResponse $ setHeader "Cache-Control" "public, max-age=315360000, immutable"
21 modifyResponse $ setHeader "Expires" "Tue, 01 Feb 2050 00:00:00 GMT" --TODO: This should be set to "approximately one year from the time the response is sent"
21 modifyResponse $ setHeader "Expires" "Tue, 01 Feb 2050 00:00:00 GMT" --TODO: This should be set to "approximately one year from the time the response is sent"
22
22
23-- | Set response header to not cache
23-- | Set response header to not cache
lib/snap/default.nixdeleted−17
@@ -1,17 +0,0 @@
1−{ mkDerivation, base, bytestring, data-default, diagrams-lib
2−, diagrams-svg, filepath, lens, lucid, monad-control
3−, obelisk-asset-serve, raw-strings-qq, semigroups, snap, snap-core
4−, stdenv, svg-builder, text, transformers-base
5−}:
6−mkDerivation {
7− pname = "obelisk-snap";
8− version = "0.1";
9− src = ./.;
10− libraryHaskellDepends = [
11− base bytestring data-default diagrams-lib diagrams-svg filepath
12− lens lucid monad-control obelisk-asset-serve raw-strings-qq
13− semigroups snap snap-core svg-builder text transformers-base
14− ];
15− description = "Project Synopsis Here";
16− license = stdenv.lib.licenses.bsd3;
17−}
lib/snap/obelisk-snap.cabaldeleted−39
@@ -1,39 +0,0 @@
1−Name: obelisk-snap
2−Version: 0.1
3−Synopsis: Project Synopsis Here
4−Description: Project Description Here
5−License: BSD3
6−Author: Obsidian Systems
7−Maintainer: maintainer@obsidian.systems
8−Stability: Experimental
9−Category: Web
10−Build-type: Simple
11−Cabal-version: >=1.2
12−
13−library
14− hs-source-dirs: src
15−
16− build-depends:
17− base,
18− bytestring,
19− data-default,
20− diagrams-lib,
21− diagrams-svg,
22− filepath,
23− lens,
24− lucid,
25− monad-control,
26− obelisk-asset-serve,
27− semigroups,
28− raw-strings-qq,
29− snap,
30− snap-core,
31− svg-builder,
32− text,
33− transformers-base
34−
35− exposed-modules:
36− Obelisk.Snap
37−
38− other-extensions: TemplateHaskell
39− ghc-options: -threaded -Wall -fno-warn-unused-do-bind -fwarn-tabs -funbox-strict-fields -O2 -fprof-auto-calls -rtsopts
lib/snap/src/Obelisk/Snap.hsdeleted−158
@@ -1,158 +0,0 @@
1−{-# LANGUAGE TemplateHaskell #-}
2−{-# LANGUAGE QuasiQuotes #-}
3−{-# LANGUAGE OverloadedStrings #-}
4−
5−module Obelisk.Snap where
6−
7−import Obelisk.Asset.Serve
8−
9−import Snap
10−
11−import Control.Lens
12−import Data.ByteString (ByteString)
13−import Data.Default
14−import Data.Maybe
15−import Data.Monoid
16−import Data.String
17−import Data.Text (Text)
18−import qualified Data.Text as T
19−import Diagrams.Prelude (Diagram, renderDia, mkWidth)
20−import Diagrams.Backend.SVG
21−import qualified Graphics.Svg as SVG
22−import Graphics.Svg.Attributes
23−import Lucid
24−import System.FilePath
25−import Text.RawString.QQ
26−import Control.Monad.IO.Class
27−
28−-- Data type for web app configuration
29−data AppConfig m
30− = AppConfig { _appConfig_logo :: Diagram SVG
31− , _appConfig_extraHeadMarkup :: Html ()
32− , _appConfig_initialStyles :: Maybe Text
33− , _appConfig_initialBody :: Maybe (m ByteString)
34− , _appConfig_initialHead :: Maybe ByteString
35− , _appConfig_serveJsexe :: Bool
36− , _appConfig_jsexe :: FilePath
37− }
38−
39−-- Default instance for app configuration
40−instance Default (AppConfig m) where
41− def = AppConfig { _appConfig_logo = mempty
42− , _appConfig_extraHeadMarkup = mempty
43− , _appConfig_initialStyles = mempty
44− , _appConfig_initialBody = Nothing
45− , _appConfig_initialHead = mempty
46− , _appConfig_serveJsexe = True
47− , _appConfig_jsexe = "frontend.jsexe"
48− }
49−
50−{- | Takes a location, app, and an app configuration as arguements and
51− routes the request to the correct handler. If "appConfig_serveJsexe"
52− returns "True", additional js paths and asset paths will be appended to
53− handler. Otherwise, it will return "404 Not Found" -}
54−serveAppAt :: MonadSnap m => ByteString -> FilePath -> AppConfig m -> m ()
55−serveAppAt loc app cfg = do
56− route $ [ (loc, ifTop $ serveStaticIndex cfg)
57− , (loc, serveAssets (app </> "static.assets") (app </> "static"))
58− , (loc <> "/version", doNotCache >> serveFileIfExistsAs "text/plain" (app </> "version"))
59− ]
60− ++ if _appConfig_serveJsexe cfg
61− then [(loc, serveAssets (app </> frontendJsAssetsPath cfg) (app </> frontendJsPath cfg))]
62− else []
63− ++ [ (loc, doNotCache >> error404) ]
64−
65−-- Helper function used in 'serveAppAt', writes a 404 error message in ByteString
66−error404 :: MonadSnap m => m ()
67−error404 = do
68− modifyResponse $ setResponseCode 404
69− writeBS "404 Not Found"
70−
71−-- Partially applied 'serveAppAt', specialized to the root directory
72−serveApp :: MonadSnap m => FilePath -> AppConfig m -> m ()
73−serveApp = serveAppAt ""
74−
75−-- Helper function used in 'serveAppAt', returns a frontendJs/... filepath
76−frontendJsPath :: AppConfig m -> FilePath
77−frontendJsPath (AppConfig { _appConfig_jsexe = jsexe }) = "frontendJs" </> jsexe
78−
79−-- Helper function used in 'serveAppAt', returns a frontendJs.assets/... filepath
80−frontendJsAssetsPath :: AppConfig m -> FilePath
81−frontendJsAssetsPath (AppConfig { _appConfig_jsexe = jsexe }) = "frontendJs.assets" </> jsexe
82−
83−-- Helper funtion used in 'serveAppAt', writes a lazy bytestring to the body of Http response
84−serveStaticIndex :: MonadSnap m => AppConfig m -> m ()
85−serveStaticIndex cfg = do
86− -- Decode, pack, and append asset target to file path
87− appJsPath <- liftIO $ getAssetPath (frontendJsAssetsPath cfg) "/all.js"
88− -- extract initial body from 'AppConfig' or return empty string
89− initialBody <- fromMaybe (return "") $ _appConfig_initialBody cfg
90− -- extract inital head from 'AppConfig' or return empty string
91− let initialHead = fromMaybe "" $ _appConfig_initialHead cfg
92− -- extract initial styles from 'AppConfig' or return empty string
93− let initialStyles = fromMaybe "" $ _appConfig_initialStyles cfg
94−
95− -- Render and write html head and body to response
96− writeLBS $ renderBS $ doctypehtml_ $ do
97− head_ $ do
98− meta_ [charset_ "utf-8"] -- meta-data charset description
99− meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1.0"] -- meta-data viewport description
100− _appConfig_extraHeadMarkup cfg -- any additional <head> html from 'AppConfig' type
101− toHtmlRaw initialHead -- HtmlT monad wrapper
102− style_ initialStyles -- generate style element/attribute
103− body_ $ do -- <body>
104− toHtmlRaw initialBody -- HtmlT monad wrapper
105− script_ [type_ "text/javascript", src_ (maybe "/all.js" T.pack appJsPath), defer_ "defer"] ("" :: String)
106− -- create <script> element
107− return ()
108−
109−{- | Takes an AppConfig monad and uses it to generate & write Lazy ByteString
110− to the body of the https response. This one comes with hard coded values
111− for the logo -}
112−serveIndex :: MonadSnap m => AppConfig m -> m ()
113−serveIndex cfg = do
114− appJsPath <- liftIO $ getAssetPath (frontendJsAssetsPath cfg) "all.js"
115− writeLBS $ renderBS $ doctypehtml_ $ do
116− head_ $ do
117− meta_ [charset_ "utf-8"]
118− meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1.0"]
119− _appConfig_extraHeadMarkup cfg
120− style_ [r|
121− #preload-logo {
122− position: fixed;
123− left: 25%;
124− top: 25%;
125− width: 50%;
126− height: 50%;
127− -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
128− -moz-animation: fadein 2s; /* Firefox < 16 */
129− -ms-animation: fadein 2s; /* Internet Explorer */
130− -o-animation: fadein 2s; /* Opera < 12.1 */
131− animation: fadein 2s;
132− }
133− @keyframes fadein {
134− from { opacity: 0; }
135− to { opacity: 1; }
136− }
137− /* Firefox < 16 */
138− @-moz-keyframes fadein {
139− from { opacity: 0; }
140− to { opacity: 1; }
141− }
142− /* Safari, Chrome and Opera > 12.1 */
143− @-webkit-keyframes fadein {
144− from { opacity: 0; }
145− to { opacity: 1; }
146− }
147− /* Internet Explorer */
148− @-ms-keyframes fadein {
149− from { opacity: 0; }
150− to { opacity: 1; }
151− }
152− |]
153− body_ $ do
154− let svgOpts = SVGOptions (mkWidth 400) Nothing "preload-logo-" [bindAttr Id_ "preload-logo"] False
155− toHtml $ SVG.renderBS $ renderDia SVG svgOpts $ _appConfig_logo cfg
156− script_ [type_ "text/javascript", src_ (maybe "/all.js" T.pack appJsPath), defer_ "defer"] ("" :: String)
157−
158−makeLenses ''AppConfig
lib/tabulation/CHANGELOG.mdnew file+5
@@ -0,0 +1,5 @@
1+# Revision history for tabulation
2+
3+## 0.1.0.0 -- 2019-05-24
4+
5+* First version. Basically carve out this library as a place for the HasFields class.
lib/tabulation/LICENSEnew file+30
@@ -0,0 +1,30 @@
1+Copyright (c) 2019, Cale Gibbard
2+
3+All rights reserved.
4+
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
7+
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
10+
11+ * Redistributions in binary form must reproduce the above
12+ copyright notice, this list of conditions and the following
13+ disclaimer in the documentation and/or other materials provided
14+ with the distribution.
15+
16+ * Neither the name of Cale Gibbard nor the names of other
17+ contributors may be used to endorse or promote products derived
18+ from this software without specific prior written permission.
19+
20+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
lib/tabulation/Setup.hsnew file+2
@@ -0,0 +1,2 @@
1+import Distribution.Simple
2+main = defaultMain
lib/tabulation/src/Data/Tabulation.hsnew file+21
@@ -0,0 +1,21 @@
1+{-# LANGUAGE TypeFamilies #-}
2+{-# LANGUAGE RankNTypes #-}
3+
4+module Data.Tabulation where
5+
6+import Control.Lens
7+
8+-- | This is a class for record types whose fields can be enumerated by an associated GADT. It's closely related to the concept of a representable functor, except without the functor part, and the fields are not all the same type.
9+class HasFields a where
10+ type Field a :: * -> *
11+
12+ fieldLens :: Field a x -> Lens' a x
13+ tabulateFieldsA :: Applicative f => (forall x. Field a x -> f x) -> f a
14+
15+ tabulateFields :: (forall x. Field a x -> x) -> a
16+ tabulateFields f = runIdentity (tabulateFieldsA (Identity . f))
17+ traverseWithField :: Applicative m => (forall x. Field a x -> x -> m x) -> a -> m a
18+ traverseWithField t r = tabulateFieldsA (\f -> t f (indexField r f))
19+ indexField :: a -> Field a x -> x
20+ indexField a f = a ^. fieldLens f
21+ {-# MINIMAL fieldLens, tabulateFieldsA #-}
lib/tabulation/tabulation.cabalnew file+26
@@ -0,0 +1,26 @@
1+cabal-version: >=1.10
2+-- Initial package description 'tabulation.cabal' generated by 'cabal
3+-- init'. For further documentation, see
4+-- http://haskell.org/cabal/users-guide/
5+
6+name: tabulation
7+version: 0.1.0.0
8+synopsis: A library for types that can be completely reconstructed by fields as specified by a GADT.
9+-- description:
10+-- bug-reports:
11+license: BSD3
12+license-file: LICENSE
13+author: Cale Gibbard
14+maintainer: cale.gibbard@obsidian.systems
15+-- copyright:
16+category: Data
17+build-type: Simple
18+extra-source-files: CHANGELOG.md
19+
20+library
21+ exposed-modules: Data.Tabulation
22+ -- other-modules:
23+ -- other-extensions:
24+ build-depends: base, lens
25+ hs-source-dirs: src
26+ default-language: Haskell2010
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+}
release.nix+7−18
@@ -1,21 +1,10 @@
1−{ self ? import ./. {}
1+{
2−, pkgs ? self.nixpkgs
2+ supportedSystems ? [ "x86_64-linux" "x86_64-darwin" ]
3}:
3}:
4+rec {
5+ recurseForDerivations = true;
6+ build = import ./all-builds.nix { inherit supportedSystems; };
7+ test = import ./all-tests.nix { inherit supportedSystems; };
4
8
5−with pkgs;
9+ inherit (build) metaCache;
6−
7−{
8− tests = {
9− #TODO: Doesn't work; see discussion in https://www.pivotaltracker.com/story/show/157265140
10− ob-init = runCommand "ob-init" {
11− nativeBuildInputs = [
12− self.command
13− nix
14− ];
15− } ''
16− mkdir $out
17− cd $out
18− ob init --symlink=${self.path}
19− '';
20− };
21}
10}
skeleton/.gitignore+14−1
@@ -1,2 +1,15 @@
1+.attr-cache
2+.cabal-sandbox
3+*.hi
4+*.o
5+cabal.project.local
6+cabal.sandbox.config
7+ctags
1−dist-newstyle
8+dist-newstyle/
9+dist/
10+ghcid-output.txt
11+profile/
2result
12result
13+result-*
14+tags
15+TAGS
skeleton/.obelisk/.gitignorenew file+3
@@ -0,0 +1,3 @@
1+/impl
2+!/impl/default.nix
3+!/impl/github.json
skeleton/backend/backend.cabal+10−2
@@ -5,17 +5,25 @@ build-type: Simple
5
5
6library
6library
7 hs-source-dirs: src
7 hs-source-dirs: src
8+ if impl(ghcjs)
9+ buildable: False
8 build-depends: base
10 build-depends: base
9 , common
11 , common
12+ , frontend
10 , obelisk-backend
13 , obelisk-backend
14+ , obelisk-route
11 exposed-modules:
15 exposed-modules:
12 Backend
16 Backend
13− ghc-options: -Wall
17+ ghc-options: -Wall -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O -fno-show-valid-hole-fits
14
18
15executable backend
19executable backend
16 main-is: main.hs
20 main-is: main.hs
17− hs-source-dirs: src
21+ hs-source-dirs: src-bin
22+ ghc-options: -Wall -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O -threaded -fno-show-valid-hole-fits
23+ if impl(ghcjs)
24+ buildable: False
18 build-depends: base
25 build-depends: base
19 , backend
26 , backend
20 , common
27 , common
28+ , frontend
21 , obelisk-backend
29 , obelisk-backend
skeleton/backend/frontendJs/frontend.jsexenew file+1
@@ -0,0 +1 @@
1+../../frontend-js/bin/frontend.jsexe
skeleton/backend/src-bin/main.hsnew file+6
@@ -0,0 +1,6 @@
1+import Backend
2+import Frontend
3+import Obelisk.Backend
4+
5+main :: IO ()
6+main = runBackend backend frontend
skeleton/backend/src/Backend.hs+7−4
@@ -1,7 +1,10 @@
1module Backend where
1module Backend where
2
2
3−import Common.Api
3+import Common.Route
4−import qualified Obelisk.Backend as Ob
4+import Obelisk.Backend
5
5
6−backend :: IO ()
6+backend :: Backend BackendRoute FrontendRoute
7−backend = Ob.backend Ob.def
7+backend = Backend
8+ { _backend_run = \serve -> serve $ const $ return ()
9+ , _backend_routeEncoder = fullRouteEncoder
10+ }
skeleton/backend/src/main.hsdeleted−5
@@ -1,5 +0,0 @@
1−import Backend
2−
3−main :: IO ()
4−main = backend
5−
skeleton/cabal.project+1
@@ -1,2 +1,3 @@
1optional-packages:
1optional-packages:
2 *
2 *
3+write-ghc-environment-files: never
skeleton/common/common.cabal+5−1
@@ -6,6 +6,10 @@ build-type: Simple
6library
6library
7 hs-source-dirs: src
7 hs-source-dirs: src
8 build-depends: base
8 build-depends: base
9−
9+ , obelisk-route
10+ , mtl
11+ , text
10 exposed-modules:
12 exposed-modules:
11 Common.Api
13 Common.Api
14+ Common.Route
15+ ghc-options: -Wall -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O -fno-show-valid-hole-fits
skeleton/common/src/Common/Api.hs+1−1
@@ -1,4 +1,4 @@
1module Common.Api where
1module Common.Api where
2
2
3commonStuff :: String
3commonStuff :: String
4−commonStuff = "here is a common string"
4+commonStuff = "Here is a string defined in Common.Api"
skeleton/common/src/Common/Route.hsnew file+47
@@ -0,0 +1,47 @@
1+{-# LANGUAGE EmptyCase #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE KindSignatures #-}
6+{-# LANGUAGE LambdaCase #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE OverloadedStrings #-}
9+{-# LANGUAGE RankNTypes #-}
10+{-# LANGUAGE TemplateHaskell #-}
11+{-# LANGUAGE TypeFamilies #-}
12+module Common.Route where
13+
14+{- -- You will probably want these imports for composing Encoders.
15+import Prelude hiding (id, (.))
16+import Control.Category
17+-}
18+
19+import Data.Text (Text)
20+import Data.Functor.Identity
21+
22+import Obelisk.Route
23+import Obelisk.Route.TH
24+
25+data BackendRoute :: * -> * where
26+ -- | Used to handle unparseable routes.
27+ BackendRoute_Missing :: BackendRoute ()
28+ -- You can define any routes that will be handled specially by the backend here.
29+ -- i.e. These do not serve the frontend, but do something different, such as serving static files.
30+
31+data FrontendRoute :: * -> * where
32+ FrontendRoute_Main :: FrontendRoute ()
33+ -- This type is used to define frontend routes, i.e. ones for which the backend will serve the frontend.
34+
35+fullRouteEncoder
36+ :: Encoder (Either Text) Identity (R (FullRoute BackendRoute FrontendRoute)) PageName
37+fullRouteEncoder = mkFullRouteEncoder
38+ (FullRoute_Backend BackendRoute_Missing :/ ())
39+ (\case
40+ BackendRoute_Missing -> PathSegment "missing" $ unitEncoder mempty)
41+ (\case
42+ FrontendRoute_Main -> PathEnd $ unitEncoder mempty)
43+
44+concat <$> mapM deriveRouteComponent
45+ [ ''BackendRoute
46+ , ''FrontendRoute
47+ ]
skeleton/config/common/examplenew file+1
@@ -0,0 +1 @@
1+This string comes from config/common/example
skeleton/config/common/routenew file+1
@@ -0,0 +1 @@
1+http://localhost:8000
skeleton/default.nix+17−2
@@ -1,5 +1,20 @@
1−{ system ? builtins.currentSystem }: # TODO: Get rid of this system cruft
1+{ system ? builtins.currentSystem
2−with import ./.obelisk/impl { inherit system; };
2+, obelisk ? import ./.obelisk/impl {
3+ inherit system;
4+ iosSdkVersion = "13.2";
5+
6+ # You must accept the Android Software Development Kit License Agreement at
7+ # https://developer.android.com/studio/terms in order to build Android apps.
8+ # Uncomment and set this to `true` to indicate your acceptance:
9+ # config.android_sdk.accept_license = false;
10+
11+ # In order to use Let's Encrypt for HTTPS deployments you must accept
12+ # their terms of service at https://letsencrypt.org/repository/.
13+ # Uncomment and set this to `true` to indicate your acceptance:
14+ # terms.security.acme.acceptTerms = false;
15+ }
16+}:
17+with obelisk;
3project ./. ({ ... }: {
18project ./. ({ ... }: {
4 android.applicationId = "systems.obsidian.obelisk.examples.minimal";
19 android.applicationId = "systems.obsidian.obelisk.examples.minimal";
5 android.displayName = "Obelisk Minimal Example";
20 android.displayName = "Obelisk Minimal Example";
skeleton/frontend/frontend.cabal+16−10
@@ -7,24 +7,30 @@ library
7 hs-source-dirs: src
7 hs-source-dirs: src
8 build-depends: base
8 build-depends: base
9 , common
9 , common
10+ , obelisk-frontend
11+ , obelisk-route
12+ , jsaddle
10 , reflex-dom
13 , reflex-dom
14+ , obelisk-executable-config-lookup
11− , static
15+ , obelisk-generated-static
12 , text
16 , text
13− if !impl(ghcjs)
14− build-depends: obelisk-run-frontend
15−
16 exposed-modules:
17 exposed-modules:
17 Frontend
18 Frontend
18− ghc-options: -Wall
19+ ghc-options: -Wall -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -O -fno-show-valid-hole-fits
19
20
20executable frontend
21executable frontend
21 main-is: main.hs
22 main-is: main.hs
22− hs-source-dirs: src
23+ hs-source-dirs: src-bin
23 build-depends: base
24 build-depends: base
24 , common
25 , common
26+ , obelisk-frontend
27+ , obelisk-route
25 , reflex-dom
28 , reflex-dom
26− , static
29+ , obelisk-generated-static
27− , text
28 , frontend
30 , frontend
29− --TODO: Make these ghc-options optional
31+ ghc-options: -threaded -O -Wall -Wredundant-constraints -Wincomplete-uni-patterns -Wincomplete-record-updates -fno-show-valid-hole-fits
30− ghc-options: -threaded
32+ if impl(ghcjs)
33+ ghc-options: -dedupe
34+ cpp-options: -DGHCJS_BROWSER
35+ if os(darwin)
36+ ghc-options: -dynamic
skeleton/frontend/src-bin/main.hsnew file+10
@@ -0,0 +1,10 @@
1+import Frontend
2+import Common.Route
3+import Obelisk.Frontend
4+import Obelisk.Route.Frontend
5+import Reflex.Dom
6+
7+main :: IO ()
8+main = do
9+ let Right validFullEncoder = checkEncoder fullRouteEncoder
10+ run $ runFrontend validFullEncoder frontend
skeleton/frontend/src/Frontend.hs+39−9
@@ -1,18 +1,48 @@
1+{-# LANGUAGE DataKinds #-}
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE TypeApplications #-}
3{-# LANGUAGE TypeApplications #-}
3−{-# LANGUAGE DataKinds #-}
4−module Frontend where
5
4
6−import Reflex.Dom
5+module Frontend where
7
6
7+import Control.Monad
8import qualified Data.Text as T
8import qualified Data.Text as T
9+import qualified Data.Text.Encoding as T
10+import Language.Javascript.JSaddle (eval, liftJSM)
11+
12+import Obelisk.Frontend
13+import Obelisk.Configs
14+import Obelisk.Route
15+import Obelisk.Generated.Static
16+
17+import Reflex.Dom.Core
9
18
10−import Static
11import Common.Api
19import Common.Api
20+import Common.Route
21+
12
22
13−frontend :: Widget x ()
23+-- This runs in a monad that can be run on the client or the server.
24+-- To run code in a pure client or pure server context, use one of the
25+-- `prerender` functions.
26+frontend :: Frontend (R FrontendRoute)
14−frontend = do
27+frontend = Frontend
28+ { _frontend_head = do
29+ el "title" $ text "Obelisk Minimal Example"
30+ elAttr "link" ("href" =: static @"main.css" <> "type" =: "text/css" <> "rel" =: "stylesheet") blank
31+ , _frontend_body = do
15− text "Welcome to Obelisk!"
32+ el "h1" $ text "Welcome to Obelisk!"
16− el "p" $ text $ T.pack commonStuff
33+ el "p" $ text $ T.pack commonStuff
17− elAttr "img" ("src" =: static @"obelisk.jpg") blank
34+
35+ -- `prerender` and `prerender_` let you choose a widget to run on the server
36+ -- during prerendering and a different widget to run on the client with
37+ -- JavaScript. The following will generate a `blank` widget on the server and
38+ -- print "Hello, World!" on the client.
39+ prerender_ blank $ liftJSM $ void $ eval ("console.log('Hello, World!')" :: T.Text)
18
40
41+ elAttr "img" ("src" =: static @"obelisk.jpg") blank
42+ el "div" $ do
43+ exampleConfig <- getConfig "common/example"
44+ case exampleConfig of
45+ Nothing -> text "No config file found in config/common/example"
46+ Just s -> text $ T.decodeUtf8 s
47+ return ()
48+ }
skeleton/frontend/src/main.hsdeleted−5
@@ -1,5 +0,0 @@
1−import Reflex.Dom
2−import Frontend
3−
4−main :: IO ()
5−main = mainWidget frontend
skeleton/static/main.cssnew file+3
@@ -0,0 +1,3 @@
1+p {
2+ color: red;
3+}