Automatically clearing the screen on recompile in sbt - sbt

I am using sbt with the sbt-revolver plugin and I want to clear the terminal screen (^L) when the project is recompiled (~ re-start). How can this be done?

You could define new command clear, which would use jline to clear the screen. Sbt is using jline internally so you shouldn't have to include any extra dependency.
build.sbt
def clearConsoleCommand = Command.command("clear") { state =>
val cr = new jline.console.ConsoleReader()
cr.clearScreen
state
}
val root = project.in(file(".")).settings(commands += clearConsoleCommand)
Now you could run your compile like this ~;clear;compile. This will trigger clear the console followed by compile on each file change (assuming this is what you want).

Another solution, based on #SethTisue answer:
alias clearScreen=eval "\u001B[2J\u001B[0\u003B0H"
This line should be added to ~/.sbtrc, so that sbt will have knowledge of a "clearScreen" command. You can either just invoke the command with ~;clearScreen;compile
Or make an additional alias like alias cc=~;clearScreen;compile

On Twitter, Paul Phillips suggested this method:
alias cc = ~ ;eval "\u001B[2J\u001B[0\u003B0H" ;compile
source: https://twitter.com/extempore2/status/403564233775775744

This specifically helps when you're doing something in continuous mode, ala `compile:
maxErrors := 5
triggeredMessage := Watched.clearWhenTriggered
This works as of 0.13.7. The second line clears the screen before each command runs. The first line limits the number of errors. With this config, you only ever have one screen full of errors to work through. Obviously could adjust maxErrors depending on your sbt window.

Related

How to set the value of a SettingKey based on different sbt commands?

There's the command sbt flywayMigrate from flywaydb.org. The command requires use to set flywayUrl, flywayUser, and flywayPassword beforehand. It was good so far.
Now I want to be able to use sbt flywayMigrate for two different environment; Their variables should be different.
I tried to make two new commands: sbt flywayMigrateDev and sbt flywayMigrateProd. I couldn't figure out how to connect the new commands to flywayMigrate.
I tried creating a new scope. But I couldn't figure out how to wire the variables and tasks properly.
I wonder if anyone can give me an example on how to do this. I'd like to see a code example.
We can simplify the problem to:
There's the command sbt flywayMigrate that depends on flywayUrl. How do we allow the command to use different flywayUrls by calling sbt commands (or any other way is good, too)?
Thank you!
You should use config for this.
Example .sbt file contents:
// Set up your configs.
lazy val prodConfig = config("prod")
lazy val devConfig = config("dev")
// Set up any configuration that's common between dev and prod.
val commonFlyway = Seq(
// For the sake of example, a couple of shared settings.
flywayUser := "pg_admin",
flywayLocations := Seq("filesystem:migrations")
)
// Set up prod and dev.
inConfig(prodConfig)(flywayBaseSettings(prodConfig) ++ commonFlyway)
flywayUrl.in(prodConfig) := "jdbc:etc:proddb.somecompany.com"
// Or however you want to load your production password.
flywayPassword.in(prodConfig) := sys.env.getOrElse("PROD_PASSWD", "(unset)")
inConfig(devConfig)(flywayBaseSettings(prodConfig) ++ commonFlyway)
flywayUrl.in(devConfig) := "jdbc:etc:devdb.somecompany.com"
flywayPassword.in(devConfig) := "development_passwd"
Now you can run prod:flywayMigrate and dev:flywayMigrate to migrate production and development, respectively.
See the Flyway docs page for other examples.

How to set fork in Test when -jvm-debug given on command line?

Is there a way to conditionally disable forking if the project is run in debug mode:
sbt -jvm-debug 9999
Then in my build:
fork in Test := {
//find a key that lets me know if debugging in set up
!isDebugging.value
}
Specifying flywayUrl through system property in SBT should be of some help.
Add the following to build.sbt:
lazy val isDebugging = settingKey[Boolean]("true when xdebug is true; false otherwise")
isDebugging := System.getProperty("xdebug") == "true"
fork in Test := !isDebugging.value
When you execute sbt -Dxdebug=true it gives you what you want.
BTW I see no references to jvm-debug in the SBT sources, but it is indeed in the shell script I'm using to fire it up. It could be that you'd have to change sbt-launch-lib.bash to accommodate the change to add xdebug when -Xdebug is set.
Jacek's suggestion is pointing to the right direction, but couldn't work for me (or even at all?). System.getProperty cannot retrieve -Xdebug flag set by an sbt's Bash script basically - when calling System.getProperties, -Xdebug is not listed there, likewise any other non-standard JVM property (like -Xmx for example).
What's worked for me is this:
lazy val isDebug = settingKey[Boolean]("true when -Xdebug is set, false otherwise")
isDebug := ManagementFactory.getRuntimeMXBean.getInputArguments.contains("-Xdebug")
fork in Test := !isDebug.value
Cheers!

Does sbt have something like gradle's processResources task with ReplaceTokens support?

We are moving into Scala/SBT from a Java/Gradle stack. Our gradle builds were leveraging a task called processResources and some Ant filter thing named ReplaceTokens to dynamically replace tokens in a checked-in .properties file without actually changing the .properties file (just changing the output). The gradle task looks like:
processResources {
def whoami = System.getProperty( 'user.name' );
def hostname = InetAddress.getLocalHost().getHostName()
def buildTimestamp = new Date().format('yyyy-MM-dd HH:mm:ss z')
filter ReplaceTokens, tokens: [
"buildsig.version" : project.version,
"buildsig.classifier" : project.classifier,
"buildsig.timestamp" : buildTimestamp,
"buildsig.user" : whoami,
"buildsig.system" : hostname,
"buildsig.tag" : buildTag
]
}
This task locates all the template files in the src/main/resources directory, performs the requisite substitutions and outputs the results at build/resources/main. In other words it transforms src/main/resources/buildsig.properties from...
buildsig.version=#buildsig.version#
buildsig.classifier=#buildsig.classifier#
buildsig.timestamp=#buildsig.timestamp#
buildsig.user=#buildsig.user#
buildsig.system=#buildsig.system#
buildsig.tag=#buildsig.tag#
...to build/resources/main/buildsig.properties...
buildsig.version=1.6.5
buildsig.classifier=RELEASE
buildsig.timestamp=2013-05-06 09:46:52 PDT
buildsig.user=jenkins
buildsig.system=bobk-mbp.local
buildsig.tag=dev
Which, ultimately, finds its way into the WAR file at WEB-INF/classes/buildsig.properties. This works like a champ to record build specific information in a Properties file which gets loaded from the classpath at runtime.
What do I do in SBT to get something like this done? I'm new to Scala / SBT so please forgive me if this seems a stupid question. At the end of the day what I need is a means of pulling some information from the environment on which I build and placing that information into a properties file that is classpath loadable at runtime. Any insights you can give to help me get this done are greatly appreciated.
The sbt-buildinfo is a good option. The README shows an example of how to define custom mappings and mappings that should run on each compile. In addition to the straightforward addition of normal settings like version shown there, you want a section like this:
buildInfoKeys ++= Seq[BuildInfoKey](
"hostname" -> java.net.InetAddress.getLocalHost().getHostName(),
"whoami" -> System.getProperty("user.name"),
BuildInfoKey.action("buildTimestamp") {
java.text.DateFormat.getDateTimeInstance.format(new java.util.Date())
}
)
Would the following be what you're looking for:
sbt-editsource: An SBT plugin for editing files
sbt-editsource is a text substitution plugin for SBT 0.11.x and
greater. In a way, it’s a poor man’s sed(1), for SBT. It provides the
ability to apply line-by-line substitutions to a source text file,
producing an edited output file. It supports two kinds of edits:
Variable substitution, where ${var} is replaced by a value. sed-like
regular expression substitution.
This is from Community Plugins.

Setting default make options for Qt Creator?

How can i override default make parameters , which is:
make -w
Each time i create a project , i had to modify project settings , adding -j4 to make parameters.
Can i set make -w -j4 by default ?
EDIT
The best way to do this is setting MAKEFLAGS environment variable , i'm picking the only answer as the best only to shut this thread down.
To set this for UNIX, modify the *.desktop file of Qt Creator , prefix the line entitled Exec= with env MAKEFLAGS=-j4 , but be aware that you won't be able to cease building in QtCreator immediately after setting to multithread.
To make it global and permanent go to
Tools > Options > Build & Run > Kits > (pick your toolchain)
and fill your predefined env settings: MAKEFLAGS=-j4
In the qtcreator go to the "Projects tab" and set "Make arguments" as you like:
If you want -jx parameter to be default each time you create a new or open some project, you must add enviroment variable MAKEFLAGS to your system with value -jx.
For example, at ubuntu for 8 - threding compilation this options can be realized by adding
MAKEFLAGS="-j8"
to /etc/enviroments
Result will be:
After attempting implement the fix described in the question I eventually found the following (clearly this in only a solution to linux's that use the freedesktop concept of .desktop files):
The line in "/usr/local/share/applications/Nokia-QtCreator.desktop" was:
Exec=/opt/qtcreator-2.5.2/bin/qtcreator.sh %F
I changed it to:
Exec=env MAKEFLAGS=-j16 /opt/qtcreator-2.5.2/bin/qtcreator.sh %F
And got the functionality requested in the question.
Ok, I have no idea why following the instructions in the question I didn't get there but I didn't. I hope this explanation will help someone.

Compile Flex application without debug? Optimisation options for flex compiler?

I have created a simple test application
with the following code
var i : int;
for (i=0; i<3000000; i++){
trace(i);
}
When I run the application, it's very slow to load, which means the "trace" is running.
I check the flash player by right-clicking, the debugger option is not enable.
So I wonder if there is an option to put in compiler to exclude the trace.
Otherwise, I have to remove manually all the trace in the program.
Are there any other options of compiler to optimize the flex application in a maximum way?
There is a really sweet feature built into Flex called the logging API (you can read more about it here http://livedocs.adobe.com/flex/3/html/logging_09.html).
Basically, you log (trace) things in a different way, admittedly with slightly more code than a standard trace, but it allows you much greater flexibility. This is an example:
import mx.logging.Log;
Log.getLogger("com.edibleCode.logDemo").info("This is some info");
Log.getLogger("com.edibleCode.logDemo").error("This is an error");
Then all you need to do is create a trace target in your main application file, something like:
<mx:TraceTarget id="logTarget" fieldSeparator=" - " includeCategory="true" includeLevel="true" includeTime="true">
<mx:filters>
<mx:Array>
<mx:String>*</mx:String>
</mx:Array>
</mx:filters>
<!--
0 = ALL, 2 = DEBUG, 4 = INFO, 6 = WARN, 8 = ERROR, 1000 = FATAL
-->
<mx:level>0</mx:level>
</mx:TraceTarget>
And register the trace with:
Log.addTarget(logTarget);
This provides several benefits over the normal trace:
You can filter (turn off) traces to only see what you want:
Either by modifying the filters array
Or the level to show only error or fatal messages
You can replace the trace target with any other type of logging interface, e.g.
A TextField
A text file
Use conditional compilation, more here.
In your code set:
CONFIG::debugging {
trace(i);
}
Then go to Project->Properties->Flex Compiler and add
-define=CONFIG::debugging,false
or
-define=CONFIG::debugging,true
You could do a find/replace on the entire project. search for 'trace(' and replace with '//trace('. That would be quick enough and easily undone.
The mxmlc argument debug allows you to add or remove debug features from SWF files. The value of the debug argument is false by default for the command line compiler, but in Flex Builder, you have to manually create a non-debug SWF. According to the documentation on compiler arguments, debug information added to the SWF includes "line numbers and filenames of all the source files". There is no mention of trace() function calls, and I don't think there's a way to remove them through a compiler argument, but you're welcome to check the linked document for the entire list of available arguments.
There are two compiler options that you should set: -debug=false -optimize=true. In Flex Builder or Eclipse, look under Project->Properties->Flex Compiler and fill in the box labeled "Additional compiler arguments."
Go to your flex code base directory (and shut down Flex Builder if its running - it gets uppity if you change things while it's running). Run this to change all your trace statements. I recommend checking the tree into git or something first and then running a diff afterwards (or cp -r the tree to do a diff -r or something). The only major case this will mess up is if you have semicolons inside trace strings:
find . -name '*.as' -exec perl -pe 'BEGIN{ undef $/; }s/trace([^;]*);/CONFIG::debugging { trace $1 ; };/smg;' -i {} \;
find . -name '*.mxml' -exec perl -pe 'BEGIN{ undef $/; }s/trace([^;]*);/CONFIG::debugging { trace $1 ; };/smg;' -i {} \;
Then set up the following in your Project->Properties->Flex Compiler->Additional compiler arguments:
-define=CONFIG::debugging,true -define=CONFIG::release,false
And use:
CONFIG::release { /* code */ }
for the "#else" clause. This was the solution I picked after reading this question and answer set.
Also beware this:
if( foo )
{
/*code*/
}
else
CONFIG::debugging { trace("whoops no braces around else-clause"); };
I.e. if you have ONLY one of these in an if or else or whatever block, and its a naked block with no braces, then regardless of whether it's compiled out, it will complain.
Something else you could do is define a boolean named debugMode or something in an external constants .as file somewhere and include this file in any project you use. Then, before any trace statement, you could check the status of this boolean first. This is similar to zdmytriv's answer.
Have to say, I like edibleCode's answer and look forward to trying it some time.

Resources