Is there any way of getting version from build.gradle of a kotlin project? - intellij-idea

I want to get the version of my project inside my project which I have set in build.gradle. Is there any method to get the version inside my project as I need to show the version inside my software and used for compairing update info, so that I don't need to change twice every time I release a update. Is there any way to make it?
group 'ProjectName.group'
version "ProjectVersion"

You typically do that by loading a properties file, and configuring gradle to filter your properties file in the processResources task.
Example:
build.gradle:
version = '1.5.0'
processResources {
def properties = ['version': project.version]
inputs.properties(properties)
filesMatching('version.properties') {
expand(properties)
}
}
version.properties:
version=${version}
App.java:
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(App.class.getResourceAsStream("/version.properties"));
System.out.println(properties.getProperty("version"));
}

Related

How to resolve a Maven project?

I have a Maven project using lombok and other external dependencies. I would like to add it to the resolver so that I can work on any of the generated Java files. So far I have tried JavaParserTypeSolver and JarTypeSolver and even tried delomboking the entire codebase, however even with that the external dependencies are not getting resolved.
I feel it's a very common setup (Maven project + lombok + other depencencies), is there a way to easily set-up the resolver for this?
Exception in thread "main" UnsolvedSymbolException{context='org.slf4j.LoggerFactory.getLogger(MyClass.class)', name='org.slf4j.LoggerFactory', cause='UnsolvedSymbolException{context='null', name='LoggerFactory', cause='null'}'}
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.findTypeDeclarations(AbstractJavaParserContext.java:222)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.MethodCallExprContext.solveMethod(MethodCallExprContext.java:166)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solve(JavaParserFacade.java:317)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solve(JavaParserFacade.java:179)
at com.github.javaparser.symbolsolver.JavaSymbolSolver.resolveDeclaration(JavaSymbolSolver.java:161)
at com.github.javaparser.ast.expr.MethodCallExpr.resolve(MethodCallExpr.java:317)
at org.javaparser.examples.chapter2.MyMethodPrinter.lambda$main$0(MyMethodPrinter.java:38)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.javaparser.examples.chapter2.MyMethodPrinter.main(MyMethodPrinter.java:37)
Caused by: UnsolvedSymbolException{context='null', name='LoggerFactory', cause='null'}
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:279)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:71)
at com.github.javaparser.ast.expr.FieldAccessExpr.accept(FieldAccessExpr.java:90)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getTypeConcrete(JavaParserFacade.java:547)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:394)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:376)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.findTypeDeclarations(AbstractJavaParserContext.java:213)
public class MyMethodPrinter {
private static final String FILE_PATH = "/Users/john.doe/myproj1/src-delomboked/main/java/com/somepackage/MyClass.java";
public static void main(String[] args) throws Exception {
TypeSolver myTypeSolver = new CombinedTypeSolver(
new ReflectionTypeSolver(),
new JavaParserTypeSolver("/Users/john.doe/myproj1/target/generated-sources/delombok"),
new JarTypeSolver("/Users/john.doe/myproj1/target/myproj1-1.0.0.jar")
);
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(myTypeSolver);
StaticJavaParser
.getConfiguration()
.setSymbolResolver(symbolSolver);
CompilationUnit cu = StaticJavaParser.parse(new File(FILE_PATH));
cu.findAll(MethodCallExpr.class).forEach(mce ->
System.out.println(mce.resolve().getQualifiedSignature()));
}

IntelliJ - how to get the classpath for a module

I'm new to IntelliJ and working on a big project with hundreds of modules, I was just wondering how would I get the classpath for a specific module?
It might help you. Because each module has its own independent classpath. You can combine the classpaths of all modules in the project, and that's what that method did, but trying to use that classpath is unlikely to result in correct behavior in multi-module projects.
public static String getFullClassPath(Module m){
String cp = "";
cp += CompilerPaths.getModuleOutputPath(m,false);
for(VirtualFile vf : OrderEnumerator.orderEntries(m).recursively().getClassesRoots()){
String entry = new File(vf.getPath()).getAbsolutePath();
if(entry.endsWith("!/")){ //not sure why it happens in the returned paths
entry = entry.substring(0,entry.length()-2);
}
if(entry.endsWith("!")){
entry = entry.substring(0,entry.length()-1);
}
cp += File.pathSeparator + entry;
}
return cp;
}

Setting the version number for .NET Core projects

What are the options for setting a project version with .NET Core / ASP.NET Core projects?
Found so far:
Set the version property in project.json. Source: DNX Overview, Working with DNX projects. This seems to set the AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion unless overridden by an attribute (see next point).
Setting the AssemblyVersion, AssemblyFileVersion, AssemblyInformationalVersion attributes also seems to work and override the version property specified in project.json.
For example, including 'version':'4.1.1-*' in project.json and setting [assembly:AssemblyFileVersion("4.3.5.0")] in a .cs file will result in AssemblyVersion=4.1.1.0, AssemblyInformationalVersion=4.1.1.0 and AssemblyFileVersion=4.3.5.0
Is setting the version number via attributes, e.g. AssemblyFileVersion, still supported?
Have I missed something - are there other ways?
Context
The scenario I'm looking at is sharing a single version number between multiple related projects. Some of the projects are using .NET Core (project.json), others are using the full .NET Framework (.csproj). All are logically part of a single system and versioned together.
The strategy we used up until now is having a SharedAssemblyInfo.cs file at the root of our solution with the AssemblyVersion and AssemblyFileVersion attributes. The projects include a link to the file.
I'm looking for ways to achieve the same result with .NET Core projects, i.e. have a single file to modify.
You can create a Directory.Build.props file in the root/parent folder of your projects and set the version information there.
However, now you can add a new property to every project in one step by defining it in a single file called Directory.Build.props in the root folder that contains your source. When MSBuild runs, Microsoft.Common.props searches your directory structure for the Directory.Build.props file (and Microsoft.Common.targets looks for Directory.Build.targets). If it finds one, it imports the property. Directory.Build.props is a user-defined file that provides customizations to projects under a directory.
For example:
<Project>
<PropertyGroup>
<Version>0.0.0.0</Version>
<FileVersion>0.0.0.0</FileVersion>
<InformationalVersion>0.0.0.0.myversion</InformationalVersion>
</PropertyGroup>
</Project>
Another option for setting version info when calling build or publish is to use the undocumented /p option.
dotnet command internally passes these flags to MSBuild.
Example:
dotnet publish ./MyProject.csproj /p:Version="1.2.3" /p:InformationalVersion="1.2.3-qa"
See here for more information: https://github.com/dotnet/docs/issues/7568
Not sure if this helps, but you can set version suffixes at publish time. Our versions are usually datetime driven, so that developers don't have to remember to update them.
If your json has something like "1.0-*"
"dotnet publish --version-suffix 2016.01.02" will make it "1.0-2016.01.02".
It's important to stick to "semvar" standards, or else you'll get errors. Dotnet publish will tell you.
Why not just change the value in the project.json file. Using CakeBuild you could do something like this (optimizations probably possible)
Task("Bump").Does(() => {
var files = GetFiles(config.SrcDir + "**/project.json");
foreach(var file in files)
{
Information("Processing: {0}", file);
var path = file.ToString();
var trg = new StringBuilder();
var regExVersion = new System.Text.RegularExpressions.Regex("\"version\":(\\s)?\"0.0.0-\\*\",");
using (var src = System.IO.File.OpenRead(path))
{
using (var reader = new StreamReader(src))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if(line == null)
continue;
line = regExVersion.Replace(line, string.Format("\"version\": \"{0}\",", config.SemVer));
trg.AppendLine(line);
}
}
}
System.IO.File.WriteAllText(path, trg.ToString());
}
});
Then if you have e.g. a UnitTest project that takes a dependency on the project, use "*" for dependency resolution.
Also, do the bump before doing dotnet restore. My order is as follows:
Task("Default")
.IsDependentOn("InitOutDir")
.IsDependentOn("Bump")
.IsDependentOn("Restore")
.IsDependentOn("Build")
.IsDependentOn("UnitTest");
Task("CI")
.IsDependentOn("Default")
.IsDependentOn("Pack");
Link to full build script: https://github.com/danielwertheim/Ensure.That/blob/3a278f05d940d9994f0fde9266c6f2c41900a884/build.cake
The actual values, e.g. the version is coming from importing a separate build.config file, in the build script:
#load "./buildconfig.cake"
var config = BuildConfig.Create(Context, BuildSystem);
The config file looks like this (taken from https://github.com/danielwertheim/Ensure.That/blob/3a278f05d940d9994f0fde9266c6f2c41900a884/buildconfig.cake):
public class BuildConfig
{
private const string Version = "5.0.0";
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string Branch { get; private set; }
public string SemVer { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var branch = context.Argument("branch", string.Empty);
var branchIsRelease = branch.ToLower() == "release";
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
Branch = branch,
SemVer = Version + (branchIsRelease ? string.Empty : "-b" + buildRevision),
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
}
If you still want to have the Solution Level SharedVersionInfo.cs you can do it by adding these lines to your project.json file:
"buildOptions": {
"compile": {
"includeFiles": [
"../../SharedVersionInfo.cs"
]
}
}
Your relative path may vary, of course.
use external version.txt file with version, and prebuild step to publish this version in projects

How do I launch a certain project using SWTBot

Not every plugin can be tested without project. For example, I want to test CDT-Plug-in, therefore I need to import a C-project. But there is no such point in Run Configuration and when I'm trying to record importing actions via SWT Plug-in Test recorder SWTBot can't replay them afterwards. Google is silent on this topic. How do I do that?
A nice way to do this is using the eclipse recource model
Have a look at the package
org.eclipse.core.resources
Here is a method, that creates a new project in the workspace
private IProject getNewOpenProject(IWorkspace wks, String name)
throws CoreException {
System.out.print("Creating project " + name + "...");
IProjectDescription prj1ProjectDescription = wks
.newProjectDescription(name);
IProject prj = wks.getRoot().getProject(name);
prj.create(prj1ProjectDescription, null);
prj.open(null);
System.out.println(" [OK]");
return prj;
}
This method will import your content into the eclipse project
private void importDirIntoProject(File srcPath, IProject prj,
IOverwriteQuery overwriteQuery) throws InvocationTargetException,
InterruptedException {
ImportOperation op = new ImportOperation(prj.getFullPath(), srcPath,
FileSystemStructureProvider.INSTANCE, overwriteQuery);
op.setCreateContainerStructure(false);
op.run(new NullProgressMonitor());
}
This approach uses native eclipse mechanisms. I think this is better than using the inconvenient way over SWTBot.
It's the responsibility of your test to create the necessary resources in its setup method, and clean them after. It's not something to configure in the Run Configuration, but to code in your test.
You can either use SWTBot to import/create a C project, or use the project APIs suggested by beanie.

Eclipse: Within a plug-in, how to access another plug-ins preference store?

I have an Eclipse plug-in with a checkbox in the plug-in's preference page.
This checkbox is used for enabling and disabling an editor, which is being launched from this plug-in.
However, the problem is, I would also like to be able to enable and disable this 'editor-launch' from another plug-in, by having actions which change the value of the checkbox in the above mentioned preference page.
Here's the problem, how do I access that local preference store from another plug-in?
I've tried things like..
View myView = (View) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("ViewID");
But this 'myView' always seems to be null.. And also, what would I do with the view since it's the Plug-in I want.
Platform.getBundle('bundleName')...
Same here, want the Plugin, not the bundle corresponding to is.
No matter what I try nothing seems to work.
Does anyone have any ideas?
There are two ways of doing this:
Please refer to http://www.vogella.com/tutorials/EclipsePreferences/article.html#preferences_pluginaccess
Using .getPluginPreferences(). For example, there is a plugin class "com.xxx.TestPlugin" which extends org.eclipse.ui.plugin.AbstractUIPlugin.Plugin, in order to get access to the preferences of TestPlugin. The plugin code could be below:
public class TestPlugin extends AbstractUIPlugin {
private static TestPlugin plugin;
public static final String PREF_TEST = "test_preference";
/**
* The constructor.
*/
public TestPlugin() {
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static TestPlugin getDefault() {
return plugin;
}
}
To access the preference of TestPlugin, the code could be:
TestPlugin.getDefault().getPluginPreferences().getDefaultBoolean(TestPlugin.PREF_TEST);
Or have a look at this answer: Writing Eclipse plugin to modify Editor Preferences
This thread recommend the use of a Service tracker:
ServiceTracker tracker = new ServiceTracker(ToolkitPlugin.getDefault().getBundle().getBundleContext(),
IProxyService.class.getName(), null);
tracker.open();
proxyService = (IProxyService) tracker.getService();
proxyService.addProxyChangeListener(this);
This may work.
Prefs stores are found per plugin. This is one way to get a prefs store for the plugin whose activator class is ActivatorA.
IPreferenceStore store = ActivatorA.getDefault().getPreferenceStore();
If you want another plugin to refer to the same store, perhaps you could expose some api on ActivatorA for it to get there, e.g.
public IPreferenceStore getSharedPrefs() {
return ActivatorA.getDefault().getPreferenceStore();
}
The second plugin would find the shared store by doing this
IPreferenceStore sharedPrefs = ActivatorA.getSharedPrefs();
Good luck.