├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.sbt ├── notes ├── 0.5.0.markdown ├── 0.6.0.markdown ├── 0.6.1.markdown ├── 0.6.2.markdown ├── 0.7.0.markdown ├── 0.7.1.markdown ├── 0.7.2.markdown ├── 0.8.0.markdown ├── about.markdown └── color-screenshot.png ├── project ├── build.properties └── plugins.sbt ├── publish.sbt └── src ├── main └── scala │ └── spray │ └── revolver │ ├── Actions.scala │ ├── AppProcess.scala │ ├── DebugSettings.scala │ ├── RevolverKeys.scala │ ├── RevolverPlugin.scala │ ├── RevolverState.scala │ ├── SysoutLogger.scala │ └── Utilities.scala └── sbt-test └── sbt-revolver └── env-vars ├── build.sbt ├── project └── plugins.sbt ├── src └── main │ └── scala │ └── TestService.scala └── test /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /project/boot/ 3 | /project/plugins/project 4 | target/ 5 | lib_managed/ 6 | src_managed/ 7 | test-output/ 8 | *.iml 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Version 0.9.2 (unreleased) 2 | 3 | ## Version 0.9.1 (2017-10-25) 4 | * [#79](https://github.com/spray/sbt-revolver/issues/79): 0.9.0 contained some old class files that lead to 5 | compatibility problems in combination with other plugins. 0.9.1 was cleanly rebuilt from the same sources 6 | and republished to fix the issue. 7 | 8 | ## Version 0.9.0 (2017-08-15) 9 | * First version that supports sbt 1.0.x 10 | * Allow setting `envVars in reStart` to customize environment variables 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | _sbt-revolver_ is a plugin for [SBT] enabling a super-fast development turnaround for your Scala applications. 2 | 3 | It sports the following features: 4 | 5 | * Starting and stopping your application in the background of your interactive SBT shell (in a forked JVM) 6 | * Triggered restart: automatically restart your application as soon as some of its sources have been changed 7 | 8 | Even though _sbt-revolver_ works great with [spray] on [spray-can] there is nothing _spray_-specific to it. It can 9 | be used with any Scala application as long as there is some object with a `main` method. 10 | 11 | 12 | ## Installation 13 | 14 | _sbt-revolver_ requires [SBT] 1.x or greater. Add the following dependency to your `project/plugins.sbt`: 15 | 16 | ```scala 17 | addSbtPlugin("io.spray" % "sbt-revolver" % "0.10.0") 18 | ``` 19 | 20 | sbt-revolver is an auto plugin, so you don't need any additional configuration in your build.sbt nor in Build.scala 21 | to make it work. In multi-module builds it will be enabled for each module. To disable sbt-revolver for some submodules use `Project(...).disablePlugins(RevolverPlugin)` in your build file. 22 | 23 | For older versions of sbt see version [0.9.1](https://github.com/spray/sbt-revolver/tree/v0.9.1). 24 | 25 | ## Usage 26 | 27 | _sbt-revolver_ defines three new commands (SBT tasks) in its own `re` configuration: 28 | 29 | * `reStart --- ` starts your application in a forked JVM. 30 | The optionally specified (JVM) arguments are appended to the ones configured via the `reStartArgs`/ 31 | `reStart::javaOptions` setting (see the "Configuration" section below). If the application is already running it 32 | is first stopped before being restarted. 33 | 34 | * `reStop` stops application. 35 | This is done by simply force-killing the forked JVM. Note, that this means that [shutdown hooks] are not run (see 36 | [#20](https://github.com/spray/sbt-revolver/issues/20)). 37 | 38 | * `reStatus` shows an informational message about the current running state of the application. 39 | 40 | #### Triggered Restart 41 | 42 | You can use `~reStart` to go into "triggered restart" mode. Your application starts up and SBT watches for changes in 43 | your source (or resource) files. If a change is detected SBT recompiles the required classes and _sbt-revolver_ 44 | automatically restarts your application. 45 | When you press <ENTER> SBT leaves "triggered restart" and returns to the normal prompt keeping your application running. 46 | 47 | To customize which files should be watched for triggered restart see the sbt documentation about [Triggered Execution](http://www.scala-sbt.org/0.13/docs/Triggered-Execution.html). 48 | 49 | ## Configuration 50 | 51 | The following SBT settings defined by _sbt-revolver_ are of potential interest: 52 | 53 | * `reStartArgs`, a `SettingKey[Seq[String]]`, which lets you define arguments that _sbt-revolver_ should pass to your 54 | application on every start. Any arguments given to the `reStart` task directly will be appended to this setting. 55 | * `reStart / mainClass`, which lets you optionally define a main class to run in `reStart` independently of the 56 | one set for running the project normally. This value defaults to the value of `compile:run::mainClass`. If you 57 | don't specify a value here explicitly the same logic as for the normal run main class applies: If only one main class 58 | is found it one is chosen. Otherwise, the main-class chooser is shown to the user. 59 | * `reStart / javaOptions`, a `SettingKey[Seq[String]]`, which lets you define the options to pass to the forked JVM 60 | when starting your application 61 | * `reStart / baseDirectory`, a `SettingKey[File]`, which lets you customize the base directory independently from 62 | what `run` assumes. 63 | * `reStart / fullClasspath`, which lets you customize the full classpath path for running with `reStart`. 64 | * `reStart / envVars`, which lets you customize the environment variables for running the application. 65 | * `reJrebelJar`, a `SettingKey[String]`, which lets you override the value of the `JREBEL_PATH` env variable. 66 | * `reColors`, a `SettingKey[Seq[String]]`, which lets you change colors used to tag output from running processes. 67 | There are some pre-defined color schemes, see the example section below. 68 | * `reLogTag`, a `SettingKey[String]`, which lets you change the log tag shown in front of log messages. Default is the 69 | project name. 70 | * `debugSettings`, a `SettingKey[Option[DebugSettings]]` to specify remote debugger settings. There's a convenience 71 | helper `Revolver.enableDebugging` to simplify to enable debugging (see examples). 72 | 73 | Examples: 74 | 75 | To configure a 2 GB memory limit for your app when started with `reStart`: 76 | 77 | reStart / javaOptions += "-Xmx2g" 78 | 79 | To set a special main class for your app when started with `reStart`: 80 | 81 | reStart / mainClass := Some("com.example.Main") 82 | 83 | To set fixed start arguments (than you can still append to with the `reStart` task): 84 | 85 | reStartArgs := Seq("-x") 86 | 87 | To enable debugging with the specified options: 88 | 89 | Revolver.enableDebugging(port = 5050, suspend = true) 90 | 91 | To change set of colors used to tag output from multiple processes: 92 | 93 | reColors := Seq("blue", "green", "magenta") 94 | 95 | There are predefined color schemes to use with `reColors`: `Revolver.noColors`, `Revolver.basicColors`, 96 | `Revolver.basicColorsAndUnderlined`. 97 | 98 | To add environment variables when running the application: 99 | 100 | reStart / envVars := Map("USER_TOKEN" -> "2359298356239") 101 | 102 | #### Hot Reloading 103 | 104 | *Note: JRebel support in sbt-revolver is not actively supported any more.* 105 | 106 | If you have JRebel installed you can let _sbt-revolver_ know where to find the `jrebel.jar`. You can do this 107 | either via the `Revolver.jRebelJar` setting directly in your SBT config or via a shell environment variable with the 108 | name `JREBEL_PATH` (which is the recommended way, since it doesn't pollute your SBT config with system-specific settings). 109 | For example, on OSX you would add the following line to your shell startup script: 110 | 111 | export JREBEL_PATH=/Applications/ZeroTurnaround/JRebel/jrebel.jar 112 | 113 | With JRebel _sbt-revolver_ supports hot reloading: 114 | 115 | * Start your application with `reStart`. 116 | * Enter "triggered compilation" with `~products`. SBT watches for changes in your source (and resource) files. 117 | If a change is detected SBT recompiles the required classes and JRebel loads these classes right into your running 118 | application. Since your application is not restarted the time required to bring changes online is minimal (see 119 | the "Understanding JRebel" section below for more details). When you press <ENTER> SBT leaves triggered compilation 120 | and returns to the normal prompt keeping your application running. 121 | * If you changed your application in a way that requires a full restart (see below) press <ENTER> to leave 122 | triggered compilation and `reStart`. 123 | * Of course you always stop the application with `reStop`. 124 | 125 | ## License 126 | 127 | _sbt-revolver_ is licensed under [APL 2.0]. 128 | 129 | 130 | ## Patch Policy 131 | 132 | Feedback and contributions to the project, no matter what kind, are always very welcome. 133 | However, patches can only be accepted from their original author. 134 | Along with any patches, please state that the patch is your original work and that you license the work to the 135 | _sbt-revolver_ project under the project’s open source license. 136 | 137 | 138 | [SBT]: https://github.com/harrah/xsbt/wiki 139 | [JRebel]: http://zeroturnaround.com/software/jrebel/ 140 | [xsbt-web-plugin]: https://github.com/aolshevskiy/xsbt-web-plugin 141 | [spray]: http://spray.io 142 | [spray-can]: https://github.com/spray/spray-can 143 | [shutdown hooks]: http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread) 144 | [JRebel FAQ]: http://zeroturnaround.com/software/jrebel/learn/faq/ 145 | [APL 2.0]: http://www.apache.org/licenses/LICENSE-2.0 146 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | enablePlugins(SbtPlugin) 2 | 3 | scalacOptions := Seq("-deprecation", "-encoding", "utf8") 4 | 5 | scriptedLaunchOpts += s"-Dplugin.version=${version.value}" 6 | scriptedBufferLog := false 7 | Test / test := (Test / test).dependsOn(scripted.toTask("")).value 8 | -------------------------------------------------------------------------------- /notes/0.5.0.markdown: -------------------------------------------------------------------------------- 1 | [sbt-revolver][] is an [SBT][] plugin for dangerously fast development turnaround in Scala. 2 | 3 | It sports the following features: 4 | 5 | * Starting and stopping your application in the background of your interactive SBT shell (in a forked JVM) 6 | * Triggered restart: automatically restart your application as soon as some of its sources have been changed 7 | * Hot reloading: automatically reload the respective classes into your running application as soon as some 8 | of its sources have been changed, no restart necessary (requires [JRebel][], which is free for Scala development) 9 | 10 | [sbt-revolver]: https://github.com/spray/sbt-revolver 11 | [SBT]: https://github.com/harrah/xsbt/wiki 12 | [JRebel]: http://zeroturnaround.com/jrebel/ 13 | -------------------------------------------------------------------------------- /notes/0.6.0.markdown: -------------------------------------------------------------------------------- 1 | This second release addresses a few problems: 2 | 3 | - Renamed `re:start`, `re:stop` and `re:status` tasks to `re-start`, `re-stop` and `re-status` respectively 4 | for more key "uniqueness" (i.e. decreased likelyhood of key-name collisions) 5 | - Added option for configuring mainClass independently for `re-start` task 6 | - Fixed #3 (Not working if there are multiple main classes) 7 | - Closed #5 (Add option to specify CLI args for the forked JVM) 8 | - Improved documentation -------------------------------------------------------------------------------- /notes/0.6.1.markdown: -------------------------------------------------------------------------------- 1 | This is a small maintenance release: 2 | 3 | - Fixed #10 (Bad type for Revolver.settings) 4 | - Upgraded to Scala 2.9.2 -------------------------------------------------------------------------------- /notes/0.6.2.markdown: -------------------------------------------------------------------------------- 1 | This is a maintenance release: 2 | 3 | - Group-ID changed from 'cc.spray' to 'io.spray' 4 | - Removed top-level 'cc' package for all classes. If you use sbt full configuration 5 | you have to change your imports to 'import spray.revolver.RevolverPlugin._' 6 | - Fixed #9: re-status now reliably shows if the process is still running 7 | -------------------------------------------------------------------------------- /notes/0.7.0.markdown: -------------------------------------------------------------------------------- 1 | This release adds multi-module support and taps into the rainbow. 2 | 3 | * all tasks work separately for each project 4 | * log output from different processes are color coded for better readability: ![Colorized example](https://github.com/spray/sbt-revolver/raw/c9d54000b045caff5913d1066049bcd74fb6cf86/notes/color-screenshot.png) 5 | 6 | Happy re-starting! 7 | -------------------------------------------------------------------------------- /notes/0.7.1.markdown: -------------------------------------------------------------------------------- 1 | This release fixes [severe bug][#21] occurring with multi-module projects where sbt-revolver could easily lose 2 | track of started processes. 3 | 4 | Other changes: 5 | 6 | * [#23][]: Customizable log tags to show in front of log messages (instead of project name). 7 | * [#24][]: Make colors configurable. Thanks to [@rogach][] for this contribution. 8 | * [#25][]: Colors are never assigned twice as long as there are colors in the pool. 9 | 10 | [#21]: https://github.com/spray/sbt-revolver/issues/21 11 | [#23]: https://github.com/spray/sbt-revolver/issues/23 12 | [#24]: https://github.com/spray/sbt-revolver/issues/24 13 | [#25]: https://github.com/spray/sbt-revolver/issues/25 14 | [@rogach]: https://github.com/Rogach 15 | -------------------------------------------------------------------------------- /notes/0.7.2.markdown: -------------------------------------------------------------------------------- 1 | This is a maintenance release: 2 | 3 | * [#30][]: Allow configuration of full classpath specially for re-start (use `fullClasspath in reStart`) 4 | * [#31][]: Fix: Make sure `reLogTag` isn't applied globally in a multi-module project 5 | * [#32][]: Allow configuration of base directory specially for re-start (use `baseDirectory in reStart`) 6 | 7 | [#30]: https://github.com/spray/sbt-revolver/issues/30 8 | [#31]: https://github.com/spray/sbt-revolver/issues/31 9 | [#32]: https://github.com/spray/sbt-revolver/issues/32 10 | -------------------------------------------------------------------------------- /notes/0.8.0.markdown: -------------------------------------------------------------------------------- 1 | sbt-revolver 0.8.0 is now an AutoPlugin. 2 | 3 | Other changes: 4 | 5 | - [#45][]: Added AutoPlugin support and dropped support for older sbt versions in the process, allowing some cleanup of the code. Thanks, [@alkersan][]! 6 | - [#40][]: Removed RED color from list of colors. Thanks, [@jedesah](https://github.com/jedesah)! 7 | - [#36][]: Fixed issue with JNI libraries by using Fork.java instead of Fork.scala. Thanks, [@kanterov](https://github.com/kanterov)! 8 | 9 | [#36]: https://github.com/spray/sbt-revolver/issues/36 10 | [#40]: https://github.com/spray/sbt-revolver/issues/40 11 | [#45]: https://github.com/spray/sbt-revolver/issues/45 12 | [@alkersan]: https://github.com/alkersan -------------------------------------------------------------------------------- /notes/about.markdown: -------------------------------------------------------------------------------- 1 | [sbt-revolver][] is an [SBT][] plugin for dangerously fast development turnaround in Scala. 2 | 3 | It sports the following features: 4 | 5 | * Starting and stopping your application in the background of your interactive SBT shell (in a forked JVM) 6 | * Triggered restart: automatically restart your application as soon as some of its sources have been changed 7 | 8 | [sbt-revolver]: https://github.com/spray/sbt-revolver 9 | [SBT]: https://github.com/harrah/xsbt/wiki 10 | -------------------------------------------------------------------------------- /notes/color-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spray/sbt-revolver/eecac7d83cc557fb3d54eb23dc158fc51d4208e9/notes/color-screenshot.png -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.8.2 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.18") 2 | addSbtPlugin("com.dwijnand" % "sbt-dynver" % "4.1.1") 3 | addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.2.1") 4 | -------------------------------------------------------------------------------- /publish.sbt: -------------------------------------------------------------------------------- 1 | name := "sbt-revolver" 2 | 3 | organization := "io.spray" 4 | 5 | description := "An SBT plugin for dangerously fast development turnaround in Scala" 6 | 7 | startYear := Some(2011) 8 | 9 | homepage := Some(url("http://github.com/spray/sbt-revolver")) 10 | 11 | organizationHomepage := Some(url("http://spray.io")) 12 | 13 | licenses += "Apache License 2.0" -> url("https://github.com/spray/sbt-revolver/raw/master/LICENSE") 14 | 15 | publishTo := { 16 | val nexus = "https://oss.sonatype.org/" 17 | Some { 18 | if (version.value.trim.contains("+")) "snapshots" at nexus + "content/repositories/snapshots" 19 | else "releases" at nexus + "service/local/staging/deploy/maven2" 20 | } 21 | } 22 | 23 | publishMavenStyle := true 24 | Test / publishArtifact := false 25 | pomIncludeRepository := { _ => false } 26 | 27 | scmInfo := Some( 28 | ScmInfo( 29 | browseUrl = url("https://github.com/spray/sbt-revolver"), 30 | connection = "scm:git:git@github.com:spray/sbt-revolver.git" 31 | ) 32 | ) 33 | 34 | developers := List( 35 | Developer( 36 | "sbt-revolver-contributors", 37 | "Sbt Revolver Contributors", 38 | "", 39 | url("https://github.com/spray/sbt-revolver/graphs/contributors")) 40 | ) 41 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/Actions.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2012 Johannes Rudolph and Mathias Doenitz 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package spray.revolver 18 | 19 | import sbt.Keys._ 20 | import sbt.{Fork, ForkOptions, LoggedOutput, Logger, Path, ProjectRef, State, complete} 21 | import java.io.File 22 | import scala.sys.process.Process 23 | 24 | object Actions { 25 | import Utilities._ 26 | 27 | def restartApp(streams: TaskStreams, logTag: String, project: ProjectRef, option: ForkOptions, mainClass: Option[String], 28 | cp: Classpath, args: Seq[String], startConfig: ExtraCmdLineOptions): AppProcess = { 29 | stopAppWithStreams(streams, project) 30 | startApp(streams, logTag, project, option, mainClass, cp, args, startConfig) 31 | } 32 | 33 | def startApp(streams: TaskStreams, logTag: String, project: ProjectRef, options: ForkOptions, mainClass: Option[String], 34 | cp: Classpath, args: Seq[String], startConfig: ExtraCmdLineOptions): AppProcess = { 35 | assert(!revolverState.getProcess(project).exists(_.isRunning)) 36 | 37 | // fail early 38 | val theMainClass = mainClass.getOrElse(sys.error("No main class detected!")) 39 | val color = updateStateAndGet(_.takeColor) 40 | val logger = new SysoutLogger(logTag, color, streams.log.ansiCodesSupported) 41 | colorLogger(streams.log).info("[YELLOW]Starting application %s in the background ..." format formatAppName(project.project, color)) 42 | 43 | val appProcess= 44 | AppProcess(project, color, logger) { 45 | forkRun(options, theMainClass, cp.map(_.data), args ++ startConfig.startArgs, logger, startConfig.jvmArgs) 46 | } 47 | registerAppProcess(project, appProcess) 48 | appProcess 49 | } 50 | 51 | def stopAppWithStreams(streams: TaskStreams, project: ProjectRef) = stopApp(colorLogger(streams.log), project) 52 | 53 | def stopApp(log: Logger, project: ProjectRef): Unit = { 54 | revolverState.getProcess(project) match { 55 | case Some(appProcess) => 56 | if (appProcess.isRunning) { 57 | log.info("[YELLOW]Stopping application %s (by killing the forked JVM) ..." format formatApp(appProcess)) 58 | 59 | appProcess.stop() 60 | } 61 | case None => 62 | log.info("[YELLOW]Application %s not yet started" format formatAppName(project.project, "[BOLD]")) 63 | } 64 | unregisterAppProcess(project) 65 | } 66 | 67 | def stopApps(log: Logger): Unit = 68 | revolverState.runningProjects.foreach(stopApp(log, _)) 69 | 70 | def showStatus(streams: TaskStreams, project: ProjectRef): Unit = 71 | colorLogger(streams.log).info { 72 | revolverState.getProcess(project).find(_.isRunning) match { 73 | case Some(appProcess) => 74 | "[GREEN]Application %s is currently running" format formatApp(appProcess, color = "[GREEN]") 75 | case None => 76 | "[YELLOW]Application %s is currently NOT running" format formatAppName(project.project, "[BOLD]") 77 | } 78 | } 79 | 80 | def createJRebelAgentOption(log: Logger, path: String): Option[String] = { 81 | if (!path.trim.isEmpty) { 82 | val file = new File(path) 83 | if (!file.exists || !file.isFile) { 84 | val file2 = new File(file, "jrebel.jar") 85 | if (!file2.exists || !file2.isFile) { 86 | log.warn("jrebel.jar: " + path + " not found") 87 | None 88 | } else Some("-javaagent:" + file2.getAbsolutePath) 89 | } else Some("-javaagent:" + path) 90 | } else None 91 | } 92 | 93 | def updateState(f: RevolverState => RevolverState): Unit = GlobalState.update(f) 94 | def updateStateAndGet[T](f: RevolverState => (RevolverState, T)): T = GlobalState.updateAndGet(f) 95 | def revolverState: RevolverState = GlobalState.get() 96 | 97 | def registerAppProcess(project: ProjectRef, process: AppProcess) = 98 | updateState { state => 99 | // before we overwrite the process entry we have to make sure the old 100 | // project is really closed to avoid the unlikely (impossible?) race condition that we 101 | // have started two processes concurrently but only register the second one 102 | val oldProcess = state.getProcess(project) 103 | if (oldProcess.exists(_.isRunning)) oldProcess.get.stop() 104 | 105 | state.addProcess(project, process) 106 | } 107 | 108 | def unregisterAppProcess(project: ProjectRef) = updateState(_.removeProcessAndColor(project)) 109 | 110 | case class ExtraCmdLineOptions(jvmArgs: Seq[String], startArgs: Seq[String]) 111 | 112 | import complete.Parsers._ 113 | import complete.Parser._ 114 | val spaceDelimitedWithoutDashes = 115 | (token(Space) ~> and(token(NotSpace, ""), not("---", "Excluded."))).* <~ SpaceClass.* 116 | /* 117 | * A parser which parses additional options to the start task of the form 118 | * ... --- ... 119 | */ 120 | val startArgsParser: State => complete.Parser[ExtraCmdLineOptions] = { (state: State) => 121 | (spaceDelimitedWithoutDashes ~ (SpaceClass.* ~ "---" ~ SpaceClass.* ~> spaceDelimited("")).?) map { 122 | case (a, b) => 123 | ExtraCmdLineOptions(b.getOrElse(Nil), a) 124 | } 125 | } 126 | 127 | def formatApp(process: AppProcess, color: String = "[YELLOW]"): String = 128 | formatAppName(process.projectName, process.consoleColor, color) 129 | def formatAppName(projectName: String, projectColor: String, color: String = "[YELLOW]"): String = 130 | "[RESET]%s%s[RESET]%s" format (projectColor, projectName, color) 131 | 132 | def forkRun(config: ForkOptions, mainClass: String, classpath: Seq[File], options: Seq[String], log: Logger, extraJvmArgs: Seq[String]): Process = { 133 | log.info(options.mkString("Starting " + mainClass + ".main(", ", ", ")")) 134 | val scalaOptions = "-classpath" :: Path.makeString(classpath) :: mainClass :: options.toList 135 | val newOptions = config 136 | .withOutputStrategy(config.outputStrategy getOrElse LoggedOutput(log)) 137 | .withRunJVMOptions(config.runJVMOptions ++ extraJvmArgs) 138 | 139 | Fork.java.fork(newOptions, scalaOptions) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/AppProcess.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2012 Johannes Rudolph and Mathias Doenitz 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package spray.revolver 18 | 19 | import java.lang.{Runtime => JRuntime} 20 | import sbt.{Logger, ProjectRef} 21 | 22 | import scala.sys.process.Process 23 | 24 | /** 25 | * A token which we put into the SBT state to hold the Process of an application running in the background. 26 | */ 27 | case class AppProcess(projectRef: ProjectRef, consoleColor: String, log: Logger)(process: Process) { 28 | val shutdownHook = createShutdownHook("... killing ...") 29 | 30 | def createShutdownHook(msg: => String) = 31 | new Thread(new Runnable { 32 | def run() { 33 | if (isRunning) { 34 | log.info(msg) 35 | process.destroy() 36 | } 37 | } 38 | }) 39 | 40 | @volatile var finishState: Option[Int] = None 41 | 42 | val watchThread = { 43 | val thread = new Thread(new Runnable { 44 | def run() { 45 | val code = process.exitValue() 46 | finishState = Some(code) 47 | log.info("... finished with exit code %d" format code) 48 | unregisterShutdownHook() 49 | Actions.unregisterAppProcess(projectRef) 50 | } 51 | }) 52 | thread.start() 53 | thread 54 | } 55 | def projectName: String = projectRef.project 56 | 57 | registerShutdownHook() 58 | 59 | def stop() { 60 | unregisterShutdownHook() 61 | process.destroy() 62 | process.exitValue() 63 | } 64 | 65 | def registerShutdownHook() { 66 | JRuntime.getRuntime.addShutdownHook(shutdownHook) 67 | } 68 | 69 | def unregisterShutdownHook() { 70 | JRuntime.getRuntime.removeShutdownHook(shutdownHook) 71 | } 72 | 73 | def isRunning: Boolean = 74 | finishState.isEmpty 75 | } 76 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/DebugSettings.scala: -------------------------------------------------------------------------------- 1 | package spray.revolver 2 | 3 | case class DebugSettings(port: Int = 5005, suspend: Boolean = false) { 4 | def toCmdLineArg: String = 5 | "-agentlib:jdwp=transport=dt_socket,server=y,suspend=%s,address=%d".format(b2str(suspend), port) 6 | 7 | private def b2str(b: Boolean) = if (b) "y" else "n" 8 | } 9 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/RevolverKeys.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2012 Johannes Rudolph and Mathias Doenitz 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package spray.revolver 18 | 19 | import sbt._ 20 | 21 | trait RevolverKeys { 22 | 23 | val reStart = InputKey[AppProcess]("re-start", "Starts the application in a forked JVM (in the background). " + 24 | "If it is already running the application is first stopped and then restarted.") 25 | 26 | val reStop = TaskKey[Unit]("re-stop", "Stops the application if it is currently running in the background") 27 | 28 | val reStatus = TaskKey[Unit]("re-status", "Shows information about the application that is potentially running") 29 | 30 | val reStartArgs = SettingKey[Seq[String]]("re-start-args", 31 | "The arguments to be passed to the applications main method when being started") 32 | 33 | val reForkOptions = TaskKey[ForkOptions]("re-fork-options", "The options needed for the start task for forking") 34 | 35 | val reJRebelJar = SettingKey[String]("re-jrebel-jar", "The path to the JRebel JAR. Automatically initialized to " + 36 | "value of the `JREBEL_PATH` environment variable.") 37 | 38 | val reColors = SettingKey[Seq[String]]("re-colors", "Colors used for tagging output from different processes") 39 | 40 | // we need this strange setup to make sure we can define a project specific default 41 | // we cannot put the project specific one `in Global` as it isn't Global 42 | val reLogTagUnscoped = SettingKey[String]("re-log-tag", "The tag used in front of log messages for this project") 43 | // users should set this one, while we put the default into the unscoped variant 44 | val reLogTag = reLogTagUnscoped in reStart 45 | 46 | val debugSettings = SettingKey[Option[DebugSettings]]("debug-settings", "Settings for enabling remote JDWP debugging.") 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/RevolverPlugin.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2012 Johannes Rudolph and Mathias Doenitz 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package spray.revolver 18 | 19 | import sbt._ 20 | import sbt.Keys._ 21 | import Actions._ 22 | import Utilities._ 23 | object RevolverPlugin extends AutoPlugin { 24 | 25 | object autoImport extends RevolverKeys { 26 | object Revolver { 27 | def settings = RevolverPlugin.settings 28 | 29 | def enableDebugging(port: Int = 5005, suspend: Boolean = false) = 30 | debugSettings in reStart := Some(DebugSettings(port, suspend)) 31 | 32 | def noColors: Seq[String] = Nil 33 | def basicColors = Seq("BLUE", "MAGENTA", "CYAN", "YELLOW", "GREEN") 34 | def basicColorsAndUnderlined = basicColors ++ basicColors.map("_"+_) 35 | } 36 | 37 | val revolverSettings = RevolverPlugin.settings 38 | } 39 | import autoImport._ 40 | 41 | lazy val settings = Seq( 42 | 43 | mainClass in reStart := (mainClass in run in Compile).value, 44 | 45 | fullClasspath in reStart := (fullClasspath in Runtime).value, 46 | 47 | reColors in Global in reStart := Revolver.basicColors, 48 | 49 | reStart := Def.inputTask{ 50 | restartApp( 51 | streams.value, 52 | reLogTag.value, 53 | thisProjectRef.value, 54 | reForkOptions.value, 55 | (mainClass in reStart).value, 56 | (fullClasspath in reStart).value, 57 | reStartArgs.value, 58 | startArgsParser.parsed 59 | ) 60 | }.dependsOn(products in Compile).evaluated, 61 | 62 | reStop := stopAppWithStreams(streams.value, thisProjectRef.value), 63 | 64 | reStatus := showStatus(streams.value, thisProjectRef.value), 65 | 66 | // default: no arguments to the app 67 | reStartArgs in Global := Seq.empty, 68 | 69 | // initialize with env variable 70 | reJRebelJar in Global := Option(System.getenv("JREBEL_PATH")).getOrElse(""), 71 | 72 | debugSettings in Global := None, 73 | 74 | reLogTagUnscoped := thisProjectRef.value.project, 75 | 76 | // bake JRebel activation into java options for the forked JVM 77 | changeJavaOptionsWithExtra(debugSettings in reStart) { (jvmOptions, jrJar, debug) => 78 | jvmOptions ++ createJRebelAgentOption(SysoutLogger, jrJar).toSeq ++ 79 | debug.map(_.toCmdLineArg).toSeq 80 | }, 81 | 82 | // bundles the various parameters for forking 83 | reForkOptions := { 84 | taskTemporaryDirectory.value 85 | ForkOptions( 86 | javaHome = javaHome.value, 87 | outputStrategy = outputStrategy.value, 88 | bootJars = Vector.empty[File], // bootJars is empty by default because only jars on the user's classpath should be on the boot classpath 89 | workingDirectory = Option((baseDirectory in reStart).value), 90 | runJVMOptions = (javaOptions in reStart).value.toVector, 91 | connectInput = false, 92 | envVars = (envVars in reStart).value 93 | ) 94 | }, 95 | 96 | // stop a possibly running application if the project is reloaded and the state is reset 97 | onUnload in Global ~= { onUnload => state => 98 | stopApps(colorLogger(state)) 99 | onUnload(state) 100 | }, 101 | 102 | onLoad in Global := { state => 103 | val colorTags = (reColors in reStart).value.map(_.toUpperCase formatted "[%s]") 104 | GlobalState.update(_.copy(colorPool = collection.immutable.Queue(colorTags: _*))) 105 | (onLoad in Global).value.apply(state) 106 | } 107 | ) 108 | 109 | override def requires = sbt.plugins.JvmPlugin 110 | override def trigger = allRequirements 111 | override def projectSettings = settings 112 | 113 | /** 114 | * Changes javaOptions by using transformer function 115 | * (javaOptions, jrebelJarPath) => newJavaOptions 116 | */ 117 | def changeJavaOptions(f: (Seq[String], String) => Seq[String]): Setting[_] = 118 | changeJavaOptionsWithExtra(sbt.Keys.baseDirectory /* just an ignored dummy */)((jvmArgs, path, _) => f(jvmArgs, path)) 119 | 120 | def changeJavaOptionsWithExtra[T](extra: SettingKey[T])(f: (Seq[String], String, T) => Seq[String]): Setting[_] = 121 | javaOptions in reStart := f(javaOptions.value, reJRebelJar.value, extra.value) 122 | } 123 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/RevolverState.scala: -------------------------------------------------------------------------------- 1 | package spray.revolver 2 | 3 | import sbt.ProjectRef 4 | import java.util.concurrent.atomic.AtomicReference 5 | import scala.annotation.tailrec 6 | import scala.collection.immutable.Queue 7 | 8 | case class RevolverState(processes: Map[ProjectRef, AppProcess], colorPool: Queue[String]) { 9 | def addProcess(project: ProjectRef, process: AppProcess): RevolverState = copy(processes = processes + (project -> process)) 10 | private[this] def removeProcess(project: ProjectRef): RevolverState = copy(processes = processes - project) 11 | def removeProcessAndColor(project: ProjectRef): RevolverState = 12 | getProcess(project) match { 13 | case Some(process) => removeProcess(project).offerColor(process.consoleColor) 14 | case None => this 15 | } 16 | 17 | def exists(project: ProjectRef): Boolean = processes.contains(project) 18 | def runningProjects: Seq[ProjectRef] = processes.keys.toSeq 19 | def getProcess(project: ProjectRef): Option[AppProcess] = processes.get(project) 20 | 21 | def takeColor: (RevolverState, String) = 22 | if (colorPool.nonEmpty) { 23 | val (color, nextPool) = colorPool.dequeue 24 | (copy(colorPool = nextPool), color) 25 | } else (this, "") 26 | 27 | def offerColor(color: String): RevolverState = 28 | if (color.nonEmpty) copy(colorPool = colorPool.enqueue(color)) 29 | else this 30 | } 31 | 32 | object RevolverState { 33 | def initial = RevolverState(Map.empty, Queue.empty) 34 | } 35 | 36 | /** 37 | * Manages global state. This is not a full-blown STM so be cautious not to lose 38 | * state when doing several updates depending on another. 39 | */ 40 | object GlobalState { 41 | private[this] val state = new AtomicReference(RevolverState.initial) 42 | 43 | @tailrec def update(f: RevolverState => RevolverState): RevolverState = { 44 | val originalState = state.get() 45 | val newState = f(originalState) 46 | if (!state.compareAndSet(originalState, newState)) update(f) 47 | else newState 48 | } 49 | @tailrec def updateAndGet[T](f: RevolverState => (RevolverState, T)): T = { 50 | val originalState = state.get() 51 | val (newState, value) = f(originalState) 52 | if (!state.compareAndSet(originalState, newState)) updateAndGet(f) 53 | else value 54 | } 55 | 56 | def get(): RevolverState = state.get() 57 | } 58 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/SysoutLogger.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2012 Johannes Rudolph and Mathias Doenitz 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package spray.revolver 18 | 19 | import sbt._ 20 | 21 | /** 22 | * A logger which logs directly with println to be used in situations where no streams are available 23 | */ 24 | class SysoutLogger(appName: String, color: String, ansiCodesSupported: Boolean = false) extends Logger { 25 | 26 | def trace(t: => Throwable) { 27 | t.printStackTrace() 28 | println(t) 29 | } 30 | 31 | def success(message: => String) { 32 | println(Utilities.colorize(ansiCodesSupported, "%s%s[RESET] success: " format (color, appName)) + message) 33 | } 34 | 35 | def log(level: Level.Value, message: => String) { 36 | val levelStr = level match { 37 | case Level.Info => "" 38 | case Level.Error => "[ERROR]" 39 | case x@_ => x.toString 40 | } 41 | println(Utilities.colorize(ansiCodesSupported, "%s%s[RESET]%s " format (color, appName, levelStr)) + message) 42 | } 43 | } 44 | 45 | object SysoutLogger extends SysoutLogger("app", "[BOLD]", false) 46 | -------------------------------------------------------------------------------- /src/main/scala/spray/revolver/Utilities.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2012 Johannes Rudolph and Mathias Doenitz 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package spray.revolver 18 | 19 | import sbt._ 20 | import scala.Console._ 21 | 22 | object Utilities { 23 | def colorLogger(state: State): Logger = colorLogger(state.log) 24 | 25 | def colorLogger(logger: Logger): Logger = new Logger { 26 | def trace(t: => Throwable) { logger.trace(t) } 27 | def success(message: => String) { success(message) } 28 | def log(level: Level.Value, message: => String): Unit = 29 | logger.log(level, colorize(logger.ansiCodesSupported, message)) 30 | } 31 | 32 | val simpleColors = 33 | Seq( 34 | "RED" -> RED, 35 | "GREEN" -> GREEN, 36 | "YELLOW" -> YELLOW, 37 | "BLUE" -> BLUE, 38 | "MAGENTA" -> MAGENTA, 39 | "CYAN" -> CYAN, 40 | "WHITE" -> WHITE 41 | ) 42 | val rgbColors = (0 to 255) map rgb 43 | val ansiTagMapping: Seq[(String, String)] = 44 | ( 45 | Seq( 46 | "BOLD" -> BOLD, 47 | "RESET" -> RESET 48 | ) ++ 49 | simpleColors ++ 50 | simpleColors.map(reversed) ++ 51 | simpleColors.map(underlined) ++ 52 | rgbColors 53 | ).map(delimited("[", "]")) 54 | 55 | def reversed(color: (String, String)): (String, String) = 56 | ("~"+color._1) -> (color._2+REVERSED) 57 | def underlined(color: (String, String)): (String, String) = 58 | ("_"+color._1) -> (color._2+UNDERLINED) 59 | def delimited(before: String, after: String)(mapping: (String, String)): (String, String) = 60 | (before+mapping._1+after, mapping._2) 61 | def rgb(idx: Int): (String, String) = ("RGB"+idx, "\u001b[38;5;"+idx+"m") 62 | 63 | def replaceAll(message: String, replacer: String => String) = 64 | ansiTagMapping.foldLeft(message)((msg, tag) => msg.replaceAll(java.util.regex.Pattern.quote(tag._1), replacer(tag._2))) 65 | 66 | def colorize(ansiCodesSupported: Boolean, message: String): String = 67 | replaceAll(message, if (ansiCodesSupported) identity else _ => "") 68 | } 69 | -------------------------------------------------------------------------------- /src/sbt-test/sbt-revolver/env-vars/build.sbt: -------------------------------------------------------------------------------- 1 | scalaVersion := "2.11.12" 2 | 3 | libraryDependencies ++= Seq( 4 | "com.typesafe.akka" %% "akka-actor" % "2.4.7", 5 | "io.spray" %% "spray-can" % "1.3.2", 6 | "io.spray" %% "spray-routing" % "1.3.2" 7 | ) 8 | 9 | enablePlugins(RevolverPlugin) 10 | 11 | envVars in reStart += "TEST_VAR" -> "OK" 12 | -------------------------------------------------------------------------------- /src/sbt-test/sbt-revolver/env-vars/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("io.spray" % "sbt-revolver" % System.getProperty("plugin.version")) 2 | -------------------------------------------------------------------------------- /src/sbt-test/sbt-revolver/env-vars/src/main/scala/TestService.scala: -------------------------------------------------------------------------------- 1 | package spray.revolver.test 2 | 3 | import akka.actor.{ Actor, ActorSystem, Props } 4 | import akka.io.IO 5 | import akka.pattern.ask 6 | import akka.util.Timeout 7 | import spray.can.Http 8 | import spray.routing.HttpServiceActor 9 | 10 | import scala.concurrent.duration._ 11 | 12 | object TestService extends App { 13 | implicit val system = ActorSystem("test-system") 14 | import system.dispatcher 15 | 16 | implicit val timeout = Timeout(5.seconds) 17 | 18 | val service = system.actorOf(Props(classOf[TestServiceActor]), "service") 19 | IO(Http) ? Http.Bind(service, interface = "0.0.0.0", port = 8888) 20 | } 21 | 22 | class TestServiceActor extends HttpServiceActor { 23 | override def receive = runRoute(route) 24 | 25 | val route = { 26 | get { 27 | complete(sys.env("TEST_VAR")) 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/sbt-test/sbt-revolver/env-vars/test: -------------------------------------------------------------------------------- 1 | > reStart 2 | $ sleep 2000 3 | $ exec curl http://0.0.0.0:8888 4 | > reStop 5 | --------------------------------------------------------------------------------