how to simply import a groovy file in another groovy script - groovy

~/groovy
% tree
.
├── lib
│   ├── GTemplate.class
│   └── GTemplate.groovy
└── Simple.groovy
class GTemplate {
static def toHtml() {
this.newInstance().toHtml1()
}
def toHtml1() {
"test"
}
}
import lib.*
class Simple extends GTemplate {
}
Error:
% groovyc Simple.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: Compilation incomplete: expected to find the class
lib.GTemplate in /home/bhaarat/groovy/lib/GTemplate.groovy, but the
file contains the classes: GTemplate 1 error

It looks like you are confusing Groovy with PHP-like techniques.
Because it's closer to Java, if a class exists within a subfolder, it needs to exist within a package of the same name. In your example, you could add this line to the top of GTemplate.groovy and recompile the file:
package lib
However, this means that the fully-qualified name for GTemplate is now actually lib.GTemplate. This may not be what you want.
Alternatively, if you want to use the files from a subfolder without using packages, you could remove the import statement from Simple.groovy, and instead compile and run the class like so:
groovyc -classpath $CLASSPATH:./lib/ Simple.groovy
groovy -classpath $CLASSPATH:./lib/ Simple
NOTE: If you don't have a CLASSPATH already set, you can simply use:
groovyc -classpath ./lib/ Simple.groovy
groovy -classpath ./lib/ Simple
Also, for windows machines, change $CLASSPATH: to %CLASSPATH%;
I strongly recommend learning about packages and understanding how they work. Look at this Wikipedia article on Java packages for a starting point.

Related

Is it possible to create a Groovy package that can be used in a script without compilation?

I'm using groovy as a stand-alone scripting language (not compiling it) and am struggling with how
to structure multiple files with the package keyword but still be able to import them in other
files. An example of this would be the following:
Directory structure:
+-- Project
+-- Example.groovy
+-- ExampleTest.groovy
With the current setup, without any package keywords I can have the following:
// Example.groovy
class Example {
String message
def Example(input = "placeholder") {
this.message = input
}
}
//ExampleTest.groovy
import Example
class ExampleTest extends GroovyTestCase {
void testInitialiserWithoutArg() {
def object = new Example()
assertEquals(object.message, "placeholder")
}
void testInitialiserWithArg() {
def object = new Example("test")
assertEquals(object.message, "test")
}
}
With this, I can add a script in the project directory to use the example class or run the tests
on the commandline with groovy ExampleTest.groovy (groovy bin is in PATH).
How do I then go about putting the Example class into a package so that a script can import the
example class and I can run the unit tests on commandline? eg:
+-- Project
+-- some
| +-- random
| +-- main
| | +-- Example.groovy
| +-- test
| +-- ExampleTest.groovy
+-- UseExample.groovy
I added package some.random to both Example.groovy and ExampleTest.groovy but even with
Example.groovy and ExampleTest.groovy just in the /Project/some/random directory, I can't
seem to work out how to import the Example class in ExampleTest.groovy to run the tests from
the commandline or how to import the whole some.random package in a separate script like
UseExample.groovy.
Is this possible or do I have to compile the package before I can use it?
you have to config your ide to start/test your project. if you want to do it as bin/groovy then here is a simple command line:
java.exe -classpath ".\embeddable\groovy-all-2.4.11.jar;.\my\test;.\my\main" groovy.ui.GroovyMain .\my\test\pack\Test.groovy
where:
.\embeddable\groovy-all-2.4.11.jar
path(s) to groovy libs
.\my\test
path to your test classes/scripts
.\my\main
path to your main classes/scripts
groovy.ui.GroovyMain
groovy script launcher/loader
.\my\test\pack\Test.groovy
your entry point script that will be executed.
even it is in classpath you have to specify full or relative to current directory path.
file struct:
my
main
pack
A.groovy
test
pack
Test.groovy
A.groovy
package pack
public class A{
def f(p){
println p
}
}
Test.groovy
package pack
new A().f("hello")
Daggett's answer worked but required all additional libraries that were imported (and available in groovy) be added to the classpath list. I then found that the groovy executable also has a classpath argument so the following is a simplified version of Daggett's answer for when groovy scripts aren't being run with the java executable:
groovy -classpath "./path/to/ExampleClass.groovy" ./scriptThatUsesExampleClass.groovy
I also noticed that the classpath needs to point to the top directory of a package eg:
+-- Project
+-- main
| +-- my
| +-- example
| +-- ExampleClass.groovy
+-- test
| +-- my
| +-- example
| +-- TestExampleClass.groovy
+-- UseExampleClass.groovy
Where UseExampleClass.groovy contains import my.example.ExampleClass, the java command would be:
path\to\Project:
> java -classpath %GROOVY_HOME%\lib\*;main groovy.ui.GroovyMain UseExampleClass.groovy
And for the groovy binary:
path\to\Project:
> groovy -classpath main UseExampleClass.groovy
Using -classpath main\my\example resulted in unable to resolve class my.example....

Scons Explicit Dependency

I have a simple .cpp file that depends on jsoncpp. As a part of my build process I want Scons to untar jsoncpp (if it isn't already) and build it (if it isn't already) before attempting to compile app.cpp since app.cpp depends on some .h files that are zipped up inside of jsoncpp.tar.gz.
This is what I've tried so far:
env = Environment()
env.Program('app', 'app.cpp')
env.Depends('app.cpp', 'jsoncpp')
def build_jsoncpp(target, source, env):
shutil.rmtree("jsoncpp", ignore_errors=True)
mytar = tarfile.open(str(source[0]))
mytar.extractall()
print("Extracted jsoncpp")
env.Command("jsoncpp", ['jsoncpp.tar.gz'], build_jsoncpp)
However, Scons never prints "Extracted jsoncpp"... it always attempts to compile app.cpp and then promptly fails.
If I were using make, I could simply do something like:
app: jsoncpp.tar.gz
# Build app
jsoncpp.tar.gz:
# Extract and build here
And the order would be guaranteed.
You should take a look at the UnTarBuilder, as a means to extract a tarfile and have all of the extracted files be properly inserted into the dependency tree. But the following will get what you have working.
You want to avoid explicit dependencies, if possible. One of the many joys of SCons is letting it take care of your dependencies for you. So just list the source file you are depending on as one of the targets of your untar command builder.
To test this I created a tar file called jsoncpp.tar.gz containing just one file, app.cpp, with the following contents.
#include <iostream>
int main() {
std::cout << "Hello World" << std::endl;
return 0;
}
And updated your SConstruct to the following.
import shutil
import tarfile
env = Environment()
env.Program('app', 'app.cpp')
def build_jsoncpp(target, source, env):
shutil.rmtree("jsoncpp", ignore_errors=True)
mytar = tarfile.open(str(source[0]))
mytar.extractall()
print("Extracted jsoncpp")
env.Command(["app.cpp"], ['jsoncpp.tar.gz'], build_jsoncpp)
Because you list the required source file you depend on as a target of your command builder, it will handle the dependencies for you.
And when you run, you will see the following.
>> scons --version
SCons by Steven Knight et al.:
script: v2.3.4, 2014/09/27 12:51:43, by garyo on lubuntu
engine: v2.3.4, 2014/09/27 12:51:43, by garyo on lubuntu
engine path: ['/usr/lib/scons/SCons']
Copyright (c) 2001 - 2014 The SCons Foundation
>> tree
.
├── jsoncpp.tar.gz
└── SConstruct
0 directories, 2 files
>> scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
build_jsoncpp(["app.cpp"], ["jsoncpp.tar.gz"])
Extracted jsoncpp
g++ -o app.o -c app.cpp
g++ -o app app.o
scons: done building targets.
>> tree
.
├── app
├── app.cpp
├── app.o
├── jsoncpp.tar.gz
└── SConstruct
0 directories, 5 files
>> ./app
Hello World
The reason why your code does not work is because you are listing jsoncpp as the target of your untar command builder. Which is not a file that compiling app.cpp will depend on, even if you list that action as an explicit dependency.
While this doesn't exactly answer your question, I hope it provides a solution to what you are trying to accomplish.
It might help if you aligned the name of your builder function with your argument to the Command() method. ;)

`cargo package`: error: main function not found

I'm trying to package a library using the cargo package manager for Rust. When I try to run cargo package per the documentation, I get the following output:
error: main function not found
error: aborting due to previous error
failed to verify package tarball
I'm confused. I'm trying to package a library (with useful external functions), so I expect that I don't need a main function. Here is my Cargo.toml:
[package]
name = "package-name"
version = "0.0.1"
authors = [ "Kevin Burke <kev#inburke.com>" ]
Here is my directory structure:
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
What am I missing?
Ah! If you are packaging a library for other programs to use (as I am trying to do), you need to name your file lib.rs.
Alternatively, if you are packaging a binary, name your file main.rs (this was my mistake).

Haxe can't find std libraries

I am trying to setup Haxe with IntelliJ and my Linux box. I downloaded Linux 64bit binaries from haxe(haxe 3.1.3) site and community edition intellij. I installed Haxe plugin in intellij and then created a new Haxe Module. For sdk I picked the haxe folder I donwloaded from haxe site. I created a new configuration to compile and run but It gives me an error that It can't locate standard library. Why is that happenning?
Haxe Directory Tree
haxe-3.1.3
├── extra
└── std
├── cpp
├── cs
├── flash
├── flash8
├── haxe
├── java
├── js
├── neko
├── php
├── sys
└── tools
haxe-3.1.3 was the directory I chose for haxe toolbox in intellij. Creating a new Haxe project lets me choose Haxe 3.1.3 (meaning that toolkit is set up correctly since its recognized). External Libraries in intellij project includes Haxe dir with std (when expanding the folder to see what it contains).
In "Project structure" dialog in the SDK i see that libraries are setup correctly (haxe-3.1.3/std) and the haxe executable also(haxe-3.1.3/haxelib). Classpath contains the Library directory
When I compile it using openFl and with flash as target I get the following error
Error:compilation failed
/home/avlahop/development/Haxe/haxe-3.1.3/haxelib
Error:libneko.so: cannot open shared object file: No such file or directory
When I switch to Haxe compiler and Neko or Javascript I get the following
Information:Compilation completed with 1 error and 1 warning in 0 sec
Information:1 error
Information:1 warning
Error:compilation failed
Warning:Standard library not found
My Class
package ;
class Test3 {
public function new() {
}
public static function main(): Void{
trace("Hello from haxe and IntelliJ IDEA");
}
}
I really want to get in to it but cannot start...
Manually go into /usr/lib and look for libneko.so. Sometimes installs might throw a one at the end or something aka libneko.so.1.
Rename the file correctly. You may have to use a newer version of neko, I had to compile from the git to get it to work: https://github.com/HaxeFoundation/neko
If you don't notice anything off, make sure your environment variables are correct. Open up /etc/environment in the text editor of your choosing
export HAXE_STD_PATH=/usr/local/haxe/std:. # path to std + :.
export HAXE_HOME=/usr/whatever/haxe # path to haxe
export NEKOPATH=/usr/local/neko # path to neko
Note that if you used HAXE_LIBRARY_PATH, that's been changed to HAXE_STD_PATH in later versions of Haxe. You also need the reference to this file, open your /etc/profile with sudo and check for:
. /etc/environment
That's all I got. Hope it works out for you.
Based on #johnink anwser, this work for me in linux commandline mode :
I downloaded linux binaries from https://haxe.org/download/ and uncompress in some path like
/some/folder/haxe-tool
I added this lines to my ~/bashrc
export HAXE_STD_PATH="/some/folder/haxe-tool/std"
export HAXE_HOME="/some/folder/haxe-tool"
export PATH=$PATH":"$HAXE_HOME
And tested with this cmd:
haxe -main HelloWorld --interp
Also I converted to javascript with this cmd
haxe -js HelloWorld.js -main HelloWorld
Using this file :
class Main {
static public function main():Void {
trace("Hello World");
}
}
Following the "Hello World" example :
https://code.haxe.org/category/beginner/hello-world.html

Class not found : helloworld.Main

I just began to learn Haxe, but I have encountered Compile error.
Main.hx
package helloworld;
import js.Lib;
class Main {
static function main() {
Lib.alert("Hello World");
}
}
Please be careful about the target class is helloworld.Main.
build.hxml
-js bin/HelloWorld.js
-cp src
-main helloworld.Main
-debug
Build process log
Building HelloWorld_p140627
Running Pre-Build Command Line...
cmd: C:\HaxeToolkit\haxe\haxe.exe X:\tmp\HelloWorld_p140627\build.hxml
Class not found : helloworld.Main
Build halted with errors.
Done(1)
Why? The class helloworld.Main is surely exist. I cannot even say "hello, world"?
Update now that I can see a screenshot of your project:
You are trying to compile "helloworld.Main", that means a class called "Main" in the package "helloworld", so Haxe will be looking for a file called "helloworld/Main.hx" in your "src/" directory.
However you have "src/Main.hx", not "src/helloworld/Main.hx". Create a subfolder called "helloworld", move "Main.hx" in there and you will be fine. The package you use in Haxe must match the directory structure.
Make sure your package aligns with your folders, and your file name with your class name. And all of these should be inside one of your "-cp" class path folders.
For your example above, the code looks fine, I would expect your layout to look like:
build.hxml <-- build file
src/helloworld/Main.hx <-- classpath/package/class.Hx
bin/ <-- output folder
bin/HelloWorld.js <-- will be created once it compiles
And then you'd run haxe build.hxml. If that doesn't work for you please post the exact file structure of your project (which folders and which directories), and the command you use to build it, and the output.
Hope that helps,

Resources