diff options
author | Alexander Kurtakov | 2014-04-15 08:12:46 +0000 |
---|---|---|
committer | Alexander Kurtakov | 2014-04-15 09:05:54 +0000 |
commit | 0e0aedcff6d079d4d7e7b5cab09c152b9eb77787 (patch) | |
tree | c27c6f2bcef25bf87da35ead9fbab11ae15cec54 /rpm/org.eclipse.linuxtools.rpmstubby | |
parent | 09c28358fd2b12790ee9514fd20dd49e1065ce8e (diff) | |
download | org.eclipse.linuxtools-0e0aedcff6d079d4d7e7b5cab09c152b9eb77787.tar.gz org.eclipse.linuxtools-0e0aedcff6d079d4d7e7b5cab09c152b9eb77787.tar.xz org.eclipse.linuxtools-0e0aedcff6d079d4d7e7b5cab09c152b9eb77787.zip |
rpm: Sonar warning fixes.
Change-Id: Iea6c3e579225da9e0582a3ff005ebc3c80ac0df2
Signed-off-by: Alexander Kurtakov <akurtako@redhat.com>
Reviewed-on: https://git.eclipse.org/r/25026
Tested-by: Hudson CI
Diffstat (limited to 'rpm/org.eclipse.linuxtools.rpmstubby')
28 files changed, 3156 insertions, 3208 deletions
diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/AbstractGenerator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/AbstractGenerator.java index 2f2f9ddc0a..ab1bc87864 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/AbstractGenerator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/AbstractGenerator.java @@ -33,77 +33,74 @@ import org.eclipse.ui.ide.IDE; /** * Abstract class holding the common part of generators. - * */ public abstract class AbstractGenerator { - String projectName; - String specfileName; + String projectName; + String specfileName; - /** - * Writes the given contents to a file with the given fileName in the - * specified project. - */ - public void writeContent() { - String contents = generateSpecfile(); - InputStream contentInputStream = new ByteArrayInputStream( - contents.getBytes()); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IResource resource = root.findMember(new Path(projectName)); - if (!resource.exists() || !(resource instanceof IContainer)) { - IStatus status = new Status(IStatus.ERROR, StubbyPlugin.PLUGIN_ID, - IStatus.OK, "Project \"" + projectName + "\" does not exist.", null); - StubbyLog.logError(new CoreException(status)); - } - IContainer container = (IContainer) resource; - IResource specsFolder = container.getProject().findMember("SPECS"); //$NON-NLS-1$ - IFile file = container.getFile(new Path(specfileName)); - if (specsFolder != null) { - file = ((IFolder) specsFolder).getFile(new Path(specfileName)); - } - final IFile openFile = file; - try { - InputStream stream = contentInputStream; - if (file.exists()) { - file.setContents(stream, true, true, null); - } else { - file.create(stream, true, null); - } - stream.close(); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (CoreException e) { - StubbyLog.logError(e); - } - Display.getCurrent().asyncExec(new Runnable() { - @Override - public void run() { - IWorkbenchPage page = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow().getActivePage(); - try { - IDE.openEditor(page, openFile, true); - } catch (PartInitException e) { - StubbyLog.logError(e); - } - } - }); - } + /** + * Writes the given contents to a file with the given fileName in the + * specified project. + */ + public void writeContent() { + String contents = generateSpecfile(); + InputStream contentInputStream = new ByteArrayInputStream( + contents.getBytes()); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IResource resource = root.findMember(new Path(projectName)); + if (!resource.exists() || !(resource instanceof IContainer)) { + IStatus status = new Status(IStatus.ERROR, StubbyPlugin.PLUGIN_ID, + IStatus.OK, "Project \"" + projectName + "\" does not exist.", null); + StubbyLog.logError(new CoreException(status)); + } + IContainer container = (IContainer) resource; + IResource specsFolder = container.getProject().findMember("SPECS"); //$NON-NLS-1$ + IFile file = container.getFile(new Path(specfileName)); + if (specsFolder != null) { + file = ((IFolder) specsFolder).getFile(new Path(specfileName)); + } + final IFile openFile = file; + try { + InputStream stream = contentInputStream; + if (file.exists()) { + file.setContents(stream, true, true, null); + } else { + file.create(stream, true, null); + } + stream.close(); + } catch (IOException|CoreException e) { + StubbyLog.logError(e); + } + Display.getCurrent().asyncExec(new Runnable() { + @Override + public void run() { + IWorkbenchPage page = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, openFile, true); + } catch (PartInitException e) { + StubbyLog.logError(e); + } + } + }); + } - /** - * The method that returns the string representation of the spec file. - * - * @return The specfile. - */ - public abstract String generateSpecfile(); + /** + * The method that returns the string representation of the spec file. + * + * @return The specfile. + */ + public abstract String generateSpecfile(); - /** - * Generate changelog - * - * @param buffer Buffer to write content to - */ - protected static void generateChangelog(StringBuilder buffer) { - buffer.append("%changelog\n"); - buffer.append("#FIXME\n"); - } + /** + * Generate changelog + * + * @param buffer Buffer to write content to + */ + protected static void generateChangelog(StringBuilder buffer) { + buffer.append("%changelog\n"); + buffer.append("#FIXME\n"); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/FeatureVisitor.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/FeatureVisitor.java index 387dff2234..8353cd44af 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/FeatureVisitor.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/FeatureVisitor.java @@ -20,29 +20,25 @@ import org.eclipse.core.resources.IResourceVisitor; /** * Visitor for filtering only feature.xml files. - * */ public class FeatureVisitor implements IResourceVisitor { - private static final String FEATURE_XML = "feature.xml"; - private List<IFile> featureFiles = new ArrayList<>(); + private static final String FEATURE_XML = "feature.xml"; + private List<IFile> featureFiles = new ArrayList<>(); - /** - * @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core.resources.IResource) - */ - @Override - public boolean visit(IResource resource) { - if (resource instanceof IFile - && resource.getName().equals(FEATURE_XML)) { - featureFiles.add((IFile)resource); - } - return true; - } + @Override + public boolean visit(IResource resource) { + if (resource instanceof IFile + && resource.getName().equals(FEATURE_XML)) { + featureFiles.add((IFile)resource); + } + return true; + } - /** - * @return All the feature.xml files found. - */ - public List<IFile> getFeatures() { - return featureFiles; - } -}
\ No newline at end of file + /** + * @return All the feature.xml files found. + */ + public List<IFile> getFeatures() { + return featureFiles; + } +} diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyEggGenerator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyEggGenerator.java index e8e367bd70..05e6cb49ab 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyEggGenerator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyEggGenerator.java @@ -21,172 +21,172 @@ import org.eclipse.linuxtools.internal.rpmstubby.model.EggModel; */ public class StubbyEggGenerator extends AbstractGenerator { - private EggModel model; - - /** - * Creates the generator by parsing the setup.py file. - * - * @param eggFile - * The setup.py file to generate specfile for. - */ - public StubbyEggGenerator(IFile eggFile) { - parse(eggFile); - specfileName = model.getPackageName().toLowerCase() + ".spec"; - projectName = eggFile.getProject().getName(); - } - - /** - * Creates the model which contains the information - * - * @param eggFile The setup.py file - */ - private void parse(IFile eggFile) { - model = new EggModel(eggFile); - } - - /** - * Generates a RPM specfile based on the parsed data from the setup.py file. - * - * @return The generated specfile. - */ - @Override - public String generateSpecfile() { - StringBuilder buffer = new StringBuilder(); - generateSiteLibSiteArch(buffer); - String packageName = model.getPackageName(); - buffer.append("Name: " + packageName.toLowerCase() + "\n"); - buffer.append("Version: " + model.getVersion() + "\n"); - buffer.append("Release: 1%{?dist}" + "\n"); - buffer.append("Summary: " + model.getSummary() + "\n\n"); - - buffer.append("Group: Development/Libraries\n"); - buffer.append("License: " + model.getLicense() + "\n"); - buffer.append("URL: " + model.getURL() + "\n"); - buffer.append("Source0: #FIXME\n\n"); - - buffer.append("BuildArch: noarch\n"); - generateRequires(buffer); - buffer.append("\n%description\n" + model.getDescription() + "\n\n"); - - generatePython3SubPackage(buffer); - generatePrepSection(buffer); - generateBuildSection(buffer); - generateInstallSection(buffer); - generateFilesSections(buffer); - generateChangelog(buffer); - - return buffer.toString(); - } - - /** - * Generate python_sitelib depending on fedora release and srcname of package - * - * @param buffer Buffer to write content to - */ - private void generateSiteLibSiteArch(StringBuilder buffer) { - buffer.append("%if 0%{?fedora} > 12\n"); - buffer.append("%global with_python3 1\n"); - buffer.append("%else\n"); - buffer.append("%{!?python_sitelib: %global python_sitelib %(%{__python} -c \"from distutils.sysconfig import get_python_lib; print (get_python_lib())\")}\n"); - buffer.append("%endif\n\n"); - buffer.append("%global srcname " + model.getSimplePackageName().toLowerCase() +"\n\n"); - } - - /** - * Generate requires - * - * @param buffer Buffer to write content to - */ - private void generateRequires(StringBuilder buffer) { - buffer.append("BuildRequires: python2-devel\n"); - buffer.append("%if 0%{?with_python3}\n"); - buffer.append("BuildRequires: python3-devel\n"); - buffer.append("%endif # if with_python3\n\n"); - - List<String> requireList = model.getInstallRequiresList(); - for (String require : requireList) { - buffer.append("Requires: " + require + "\n"); - } - } - - /** - * Generate the python 3 subpackage - * - * @param buffer Buffer to write content to - */ - private void generatePython3SubPackage(StringBuilder buffer) { - buffer.append("%if 0%{?with_python3}\n"); - buffer.append("%package -n python3-" + model.getPackageName().toLowerCase() + "\n\n"); - - buffer.append("Summary: " + model.getSummary() + "\n"); - buffer.append("Group: Development/Libraries\n"); - - buffer.append("\n%description -n python3-" + model.getPackageName().toLowerCase() + "\n" + model.getDescription() + "\n"); - buffer.append("%endif # with_python3\n\n"); - } - - /** - * Generate prep - * - * @param buffer Buffer to write content to - */ - private static void generatePrepSection(StringBuilder buffer) { - buffer.append("\n%prep\n"); - buffer.append("%setup -q -n %{srcname}-%{version} #You may need to update this according to your Source0\n\n"); - - buffer.append("%if 0%{?with_python3}\n"); - buffer.append("rm -rf %{py3dir}\n"); - buffer.append("cp -a . %{py3dir}\n"); - buffer.append("%endif # with_python3\n\n\n"); - } - - /** - * Generate build - * - * @param buffer Buffer to write content to - */ - private static void generateBuildSection(StringBuilder buffer) { - buffer.append("%build\n"); - buffer.append("%{__python} setup.py build\n\n"); - - buffer.append("%if 0%{?with_python3}\n"); - buffer.append("pushd %{py3dir}\n"); - buffer.append("%{__python3} setup.py build\n"); - buffer.append("popd\n"); - buffer.append("%endif # with_python3\n\n\n"); - } - - /** - * Generate install - * - * @param buffer Buffer to write content to - */ - private static void generateInstallSection(StringBuilder buffer) { - buffer.append("%install\n"); - - buffer.append("%if 0%{?with_python3}\n"); - buffer.append("pushd %{py3dir}\n"); - buffer.append("%{__python3} setup.py install --skip-build --root %{buildroot}\n"); - buffer.append("popd\n"); - buffer.append("%endif # with_python3\n\n"); - - buffer.append("%{__python} setup.py install --skip-build --root %{buildroot}\n\n\n"); - } - - /** - * Generate files - * - * @param buffer Buffer to write content to - */ - private void generateFilesSections(StringBuilder buffer) { - buffer.append("%files\n"); - buffer.append("%{python_sitelib}/*\n\n"); - - buffer.append("%if 0%{?with_python3}\n"); - buffer.append("%files -n python3-" + model.getPackageName().toLowerCase() +"\n"); - buffer.append("%{python3_sitelib}/*\n"); - buffer.append("%endif # with_python3\n\n\n"); - } + private EggModel model; + + /** + * Creates the generator by parsing the setup.py file. + * + * @param eggFile + * The setup.py file to generate specfile for. + */ + public StubbyEggGenerator(IFile eggFile) { + parse(eggFile); + specfileName = model.getPackageName().toLowerCase() + ".spec"; + projectName = eggFile.getProject().getName(); + } + + /** + * Creates the model which contains the information + * + * @param eggFile The setup.py file + */ + private void parse(IFile eggFile) { + model = new EggModel(eggFile); + } + + /** + * Generates a RPM specfile based on the parsed data from the setup.py file. + * + * @return The generated specfile. + */ + @Override + public String generateSpecfile() { + StringBuilder buffer = new StringBuilder(); + generateSiteLibSiteArch(buffer); + String packageName = model.getPackageName(); + buffer.append("Name: " + packageName.toLowerCase() + "\n"); + buffer.append("Version: " + model.getVersion() + "\n"); + buffer.append("Release: 1%{?dist}" + "\n"); + buffer.append("Summary: " + model.getSummary() + "\n\n"); + + buffer.append("Group: Development/Libraries\n"); + buffer.append("License: " + model.getLicense() + "\n"); + buffer.append("URL: " + model.getURL() + "\n"); + buffer.append("Source0: #FIXME\n\n"); + + buffer.append("BuildArch: noarch\n"); + generateRequires(buffer); + buffer.append("\n%description\n" + model.getDescription() + "\n\n"); + + generatePython3SubPackage(buffer); + generatePrepSection(buffer); + generateBuildSection(buffer); + generateInstallSection(buffer); + generateFilesSections(buffer); + generateChangelog(buffer); + + return buffer.toString(); + } + + /** + * Generate python_sitelib depending on fedora release and srcname of package + * + * @param buffer Buffer to write content to + */ + private void generateSiteLibSiteArch(StringBuilder buffer) { + buffer.append("%if 0%{?fedora} > 12\n"); + buffer.append("%global with_python3 1\n"); + buffer.append("%else\n"); + buffer.append("%{!?python_sitelib: %global python_sitelib %(%{__python} -c \"from distutils.sysconfig import get_python_lib; print (get_python_lib())\")}\n"); + buffer.append("%endif\n\n"); + buffer.append("%global srcname " + model.getSimplePackageName().toLowerCase() +"\n\n"); + } + + /** + * Generate requires + * + * @param buffer Buffer to write content to + */ + private void generateRequires(StringBuilder buffer) { + buffer.append("BuildRequires: python2-devel\n"); + buffer.append("%if 0%{?with_python3}\n"); + buffer.append("BuildRequires: python3-devel\n"); + buffer.append("%endif # if with_python3\n\n"); + + List<String> requireList = model.getInstallRequiresList(); + for (String require : requireList) { + buffer.append("Requires: " + require + "\n"); + } + } + + /** + * Generate the python 3 subpackage + * + * @param buffer Buffer to write content to + */ + private void generatePython3SubPackage(StringBuilder buffer) { + buffer.append("%if 0%{?with_python3}\n"); + buffer.append("%package -n python3-" + model.getPackageName().toLowerCase() + "\n\n"); + + buffer.append("Summary: " + model.getSummary() + "\n"); + buffer.append("Group: Development/Libraries\n"); + + buffer.append("\n%description -n python3-" + model.getPackageName().toLowerCase() + "\n" + model.getDescription() + "\n"); + buffer.append("%endif # with_python3\n\n"); + } + + /** + * Generate prep + * + * @param buffer Buffer to write content to + */ + private static void generatePrepSection(StringBuilder buffer) { + buffer.append("\n%prep\n"); + buffer.append("%setup -q -n %{srcname}-%{version} #You may need to update this according to your Source0\n\n"); + + buffer.append("%if 0%{?with_python3}\n"); + buffer.append("rm -rf %{py3dir}\n"); + buffer.append("cp -a . %{py3dir}\n"); + buffer.append("%endif # with_python3\n\n\n"); + } + + /** + * Generate build + * + * @param buffer Buffer to write content to + */ + private static void generateBuildSection(StringBuilder buffer) { + buffer.append("%build\n"); + buffer.append("%{__python} setup.py build\n\n"); + + buffer.append("%if 0%{?with_python3}\n"); + buffer.append("pushd %{py3dir}\n"); + buffer.append("%{__python3} setup.py build\n"); + buffer.append("popd\n"); + buffer.append("%endif # with_python3\n\n\n"); + } + + /** + * Generate install + * + * @param buffer Buffer to write content to + */ + private static void generateInstallSection(StringBuilder buffer) { + buffer.append("%install\n"); + + buffer.append("%if 0%{?with_python3}\n"); + buffer.append("pushd %{py3dir}\n"); + buffer.append("%{__python3} setup.py install --skip-build --root %{buildroot}\n"); + buffer.append("popd\n"); + buffer.append("%endif # with_python3\n\n"); + + buffer.append("%{__python} setup.py install --skip-build --root %{buildroot}\n\n\n"); + } + + /** + * Generate files + * + * @param buffer Buffer to write content to + */ + private void generateFilesSections(StringBuilder buffer) { + buffer.append("%files\n"); + buffer.append("%{python_sitelib}/*\n\n"); + + buffer.append("%if 0%{?with_python3}\n"); + buffer.append("%files -n python3-" + model.getPackageName().toLowerCase() +"\n"); + buffer.append("%{python3_sitelib}/*\n"); + buffer.append("%endif # with_python3\n\n\n"); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGemGenerator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGemGenerator.java index 967ead8516..ae484882c2 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGemGenerator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGemGenerator.java @@ -21,157 +21,157 @@ import org.eclipse.linuxtools.internal.rpmstubby.model.GemModel; */ public class StubbyGemGenerator extends AbstractGenerator { - private GemModel model; - - private static final String FIX_ME = "#FIXME"; - - /** - * Creates the generator by parsing the gemspec file. - * - * @param gemFile - * The gemspec file to generate specfile for. - */ - public StubbyGemGenerator(IFile gemFile) { - parse(gemFile); - specfileName = model.getPackageName().toLowerCase() + ".spec"; - projectName = gemFile.getProject().getName(); - } - - /** - * Creates the model which contains the information - * - * @param gemFile The gemspec file - */ - private void parse(IFile gemFile) { - model = new GemModel(gemFile); - } - - /** - * Generates a RPM specfile based on the parsed data from the gemspec file. - * - * @return The generated specfile. - */ - @Override - public String generateSpecfile() { - StringBuilder buffer = new StringBuilder(); - generateDefines(buffer); - String packageName = model.getPackageName(); - buffer.append("Name: " + packageName.toLowerCase() + "\n"); - buffer.append("Version: " + model.getVersion() + "\n"); - buffer.append("Release: 1%{?dist}" + "\n"); - buffer.append("Summary: " + model.getSummary() + "\n\n"); - - buffer.append("Group: Development/Libraries\n"); - buffer.append("License: " + model.getLicense() + "\n"); - buffer.append("URL: " + model.getURL() + "\n"); - buffer.append("Source0: #FIXME\n\n"); - - generateRequires(buffer); - - buffer.append("BuildArch: noarch\n"); - buffer.append("Provides: rubygem(%{gem_name}) = %{version}\n\n\n"); - - buffer.append("%description\n" + model.getDescription() + "\n\n\n"); - generatePrepSection(buffer); - generateBuildSection(buffer); - generateInstallSection(buffer); - generateFilesSections(buffer); - generateChangelog(buffer); - - return buffer.toString(); - } - - private void generateDefines(StringBuilder buffer) { - buffer.append("%global gem_name " + model.getSimplePackageName().toLowerCase() +"\n\n"); - } - - /** - * Generate requires - * - * @param buffer Buffer to write content to - */ - private void generateRequires(StringBuilder buffer) { - buffer.append("BuildRequires: rubygems-devel\n"); - List<String> requireList = model.getBuildRequiresList(); - for (String require : requireList) { - buffer.append("BuildRequires: " + require + "\n"); - } - buffer.append("Requires: ruby(release)\n"); - - String rubyGemsVersion = model.getGemVersion(); - if (rubyGemsVersion.equals(FIX_ME)) { - buffer.append("Requires: rubygems\n"); - } else { - buffer.append("Requires: rubygems == " + rubyGemsVersion +"\n"); - } - - requireList = model.getInstallRequiresList(); - for (String require : requireList) { - buffer.append("Requires: " + require + "\n"); - } - buffer.append("\n"); - } - - /** - * Generate prep - * - * @param buffer Buffer to write content to - */ - private static void generatePrepSection(StringBuilder buffer) { - buffer.append("%prep\n"); - buffer.append("gem unpack %{SOURCE0}\n"); - buffer.append("%setup -q -D -T -n %{gem_name}-%{version} #You may need to update this according to your Source0\n\n"); - - buffer.append("gem spec %{SOURCE0} -l --ruby > %{gem_name}.gemspec\n\n\n"); - } - - /** - * Generate build - * - * @param buffer Buffer to write content to - */ - private static void generateBuildSection(StringBuilder buffer) { - buffer.append("%build\n"); - buffer.append("gem build %{gem_name}.gemspec\n\n"); - - buffer.append("%gem_install\n\n\n"); - } - - /** - * Generate install - * - * @param buffer Buffer to write content to - */ - private void generateInstallSection(StringBuilder buffer) { - buffer.append("%install\n"); - buffer.append("mkdir -p %{buildroot}%{gem_dir}\n"); - buffer.append("cp -a ./%{gem_dir}/* %{buildroot}%{gem_dir}/\n\n"); - - buffer.append("mkdir -p %{buildroot}%{_bindir}\n"); - buffer.append("cp -a ./%{_bindir}/* %{buildroot}%{_bindir}\n\n"); - - List<String> requirePaths = model.getRequirePaths(); - if (!requirePaths.isEmpty()) { - buffer.append("mkdir -p %{buildroot}%{gem_extdir_mri}/"+ requirePaths.get(0) +"\n"); - buffer.append("mv %{buildroot}%{gem_instdir}/"+requirePaths.get(0)+"/shared_object.so %{buildroot}%{gem_extdir_mri}/"+ requirePaths.get(0)+"/\n\n"); - } - - buffer.append("\n"); - } - - /** - * Generate files - * - * @param buffer Buffer to write content to - */ - private static void generateFilesSections(StringBuilder buffer) { - buffer.append("%files\n"); - buffer.append("%dir %{gem_instdir}\n"); - buffer.append("%{gem_libdir}\n"); - buffer.append("%{gem_spec}\n\n"); - - buffer.append("%files doc\n"); - buffer.append("%doc %{gem_docdir}\n\n\n"); - } - -}
\ No newline at end of file + private GemModel model; + + private static final String FIX_ME = "#FIXME"; + + /** + * Creates the generator by parsing the gemspec file. + * + * @param gemFile + * The gemspec file to generate specfile for. + */ + public StubbyGemGenerator(IFile gemFile) { + parse(gemFile); + specfileName = model.getPackageName().toLowerCase() + ".spec"; + projectName = gemFile.getProject().getName(); + } + + /** + * Creates the model which contains the information + * + * @param gemFile The gemspec file + */ + private void parse(IFile gemFile) { + model = new GemModel(gemFile); + } + + /** + * Generates a RPM specfile based on the parsed data from the gemspec file. + * + * @return The generated specfile. + */ + @Override + public String generateSpecfile() { + StringBuilder buffer = new StringBuilder(); + generateDefines(buffer); + String packageName = model.getPackageName(); + buffer.append("Name: " + packageName.toLowerCase() + "\n"); + buffer.append("Version: " + model.getVersion() + "\n"); + buffer.append("Release: 1%{?dist}" + "\n"); + buffer.append("Summary: " + model.getSummary() + "\n\n"); + + buffer.append("Group: Development/Libraries\n"); + buffer.append("License: " + model.getLicense() + "\n"); + buffer.append("URL: " + model.getURL() + "\n"); + buffer.append("Source0: #FIXME\n\n"); + + generateRequires(buffer); + + buffer.append("BuildArch: noarch\n"); + buffer.append("Provides: rubygem(%{gem_name}) = %{version}\n\n\n"); + + buffer.append("%description\n" + model.getDescription() + "\n\n\n"); + generatePrepSection(buffer); + generateBuildSection(buffer); + generateInstallSection(buffer); + generateFilesSections(buffer); + generateChangelog(buffer); + + return buffer.toString(); + } + + private void generateDefines(StringBuilder buffer) { + buffer.append("%global gem_name " + model.getSimplePackageName().toLowerCase() +"\n\n"); + } + + /** + * Generate requires + * + * @param buffer Buffer to write content to + */ + private void generateRequires(StringBuilder buffer) { + buffer.append("BuildRequires: rubygems-devel\n"); + List<String> requireList = model.getBuildRequiresList(); + for (String require : requireList) { + buffer.append("BuildRequires: " + require + "\n"); + } + buffer.append("Requires: ruby(release)\n"); + + String rubyGemsVersion = model.getGemVersion(); + if (rubyGemsVersion.equals(FIX_ME)) { + buffer.append("Requires: rubygems\n"); + } else { + buffer.append("Requires: rubygems == " + rubyGemsVersion +"\n"); + } + + requireList = model.getInstallRequiresList(); + for (String require : requireList) { + buffer.append("Requires: " + require + "\n"); + } + buffer.append("\n"); + } + + /** + * Generate prep + * + * @param buffer Buffer to write content to + */ + private static void generatePrepSection(StringBuilder buffer) { + buffer.append("%prep\n"); + buffer.append("gem unpack %{SOURCE0}\n"); + buffer.append("%setup -q -D -T -n %{gem_name}-%{version} #You may need to update this according to your Source0\n\n"); + + buffer.append("gem spec %{SOURCE0} -l --ruby > %{gem_name}.gemspec\n\n\n"); + } + + /** + * Generate build + * + * @param buffer Buffer to write content to + */ + private static void generateBuildSection(StringBuilder buffer) { + buffer.append("%build\n"); + buffer.append("gem build %{gem_name}.gemspec\n\n"); + + buffer.append("%gem_install\n\n\n"); + } + + /** + * Generate install + * + * @param buffer Buffer to write content to + */ + private void generateInstallSection(StringBuilder buffer) { + buffer.append("%install\n"); + buffer.append("mkdir -p %{buildroot}%{gem_dir}\n"); + buffer.append("cp -a ./%{gem_dir}/* %{buildroot}%{gem_dir}/\n\n"); + + buffer.append("mkdir -p %{buildroot}%{_bindir}\n"); + buffer.append("cp -a ./%{_bindir}/* %{buildroot}%{_bindir}\n\n"); + + List<String> requirePaths = model.getRequirePaths(); + if (!requirePaths.isEmpty()) { + buffer.append("mkdir -p %{buildroot}%{gem_extdir_mri}/"+ requirePaths.get(0) +"\n"); + buffer.append("mv %{buildroot}%{gem_instdir}/"+requirePaths.get(0)+"/shared_object.so %{buildroot}%{gem_extdir_mri}/"+ requirePaths.get(0)+"/\n\n"); + } + + buffer.append("\n"); + } + + /** + * Generate files + * + * @param buffer Buffer to write content to + */ + private static void generateFilesSections(StringBuilder buffer) { + buffer.append("%files\n"); + buffer.append("%dir %{gem_instdir}\n"); + buffer.append("%{gem_libdir}\n"); + buffer.append("%{gem_spec}\n\n"); + + buffer.append("%files doc\n"); + buffer.append("%doc %{gem_docdir}\n\n\n"); + } + +} diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGenerator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGenerator.java index e4cc9a99d1..3699677133 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGenerator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyGenerator.java @@ -30,174 +30,167 @@ import org.xml.sax.SAXException; /** * Generates the RPM specfile and the fetch script based on the feature and user * preferences. - * */ public class StubbyGenerator extends AbstractGenerator { - private FeatureModel model; - private IFile featureFile; - private boolean pomExists; - - /** - * Creates the specfile and fetch script generator for the given packages. - * - * @param featureFile - * The feature.xml file to generate from. - */ - public StubbyGenerator(IFile featureFile) { - this.featureFile = featureFile; - parse(featureFile); - specfileName = model.getPackageName().toLowerCase() + ".spec"; - projectName = featureFile.getProject().getName(); - pomExists = new RPMStubbyUtils().findPom(featureFile.getParent().getLocation()); - } - - private void parse(IFile featureFile) { - DocumentBuilderFactory docfactory = DocumentBuilderFactory - .newInstance(); - IPath featureDir = featureFile.getLocation().removeLastSegments(1); - String featurePropertiesFile = featureDir.toOSString() - + "/feature.properties"; - Properties featureProperties = new Properties(); - try { - featureProperties.load(new FileInputStream(featurePropertiesFile)); - } catch (FileNotFoundException e) { - // Do nothing if the feature.properties is not found - } catch (IOException e) { - StubbyLog.logError(e); - } - DocumentBuilder docbuilder; - try { - docbuilder = docfactory.newDocumentBuilder(); - Document docroot = docbuilder.parse(featureFile.getContents()); - model = new FeatureModel(docroot, featureProperties); - - } catch (ParserConfigurationException e) { - StubbyLog.logError(e); - } catch (SAXException e) { - StubbyLog.logError(e); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (CoreException e) { - StubbyLog.logError(e); - } - } - - /** - * Generates a RPM specfile based on the parsed data from the pom file. - * - * @return The generated specfile. - */ - @Override - public String generateSpecfile() { - StringBuilder buffer = new StringBuilder(); - buffer.append("%global install_loc %{_datadir}/eclipse/dropins/" - + model.getSimplePackageName() + "\n\n"); - buffer.append("Name: " + model.getPackageName().toLowerCase() - + "\n"); - buffer.append("Version: " + model.getVersion() + "\n"); - buffer.append("Release: 1%{?dist}" + "\n"); - buffer.append("Summary: " + model.getSummary() + "\n\n"); - buffer.append("Group: Development/Tools\n"); - buffer.append("License: " + model.getLicense() + "\n"); - buffer.append("URL: " + model.getURL() + "\n"); - buffer.append("Source0: #FIXME\n"); - buffer.append("BuildArch: noarch\n\n"); - generateRequires(buffer); - buffer.append("%description\n" + model.getDescription() + "\n"); - generatePrepSection(buffer); - generateBuildSection(buffer); - generateInstallSection(buffer); - generateFilesSections(buffer); - generateChangelog(buffer); - - return buffer.toString(); - } - - private static void generateRequires(StringBuilder buffer) { - buffer.append("Requires: eclipse-platform >= 3.4.0\n"); - buffer.append("BuildRequires: maven-local\n"); - buffer.append("\n\n"); - } - - private void generateInstallSection(StringBuilder buffer) { - buffer.append("%install\n"); - if (!pomExists) { - generateTempPom(buffer); - } - buffer.append("mvn-rpmbuild "); - if (!pomExists) { - buffer.append("-f temp/pom.xml "); - } - buffer.append("org.fedoraproject:feclipse-maven-plugin:install \\" + "\n"); - buffer.append("\t" + "-DsourceRepo=#FIXME \\" + "\n"); - buffer.append("\t" + "-DtargetLocation=%{buildroot}%{install_loc}/eclipse" + "\n"); - buffer.append("\n\n"); - } - - private void generateFilesSections(StringBuilder buffer) { - buffer.append("%files\n"); - buffer.append("%{install_loc}\n"); - String docsRoot = featureFile.getLocation().removeLastSegments(1) - .lastSegment(); - String[] files = featureFile.getLocation().removeLastSegments(1) - .toFile().list(); - for (String file : files) { - if (file.matches("(epl-.*|license)\\.html")) { - buffer.append("%doc " + docsRoot + "/" + file + "\n"); - } - } - buffer.append("\n\n"); - } - - private static void generatePrepSection(StringBuilder buffer) { - buffer.append("\n%prep\n"); - buffer.append("%setup -q #You may need to update this according to your Source0\n"); - buffer.append("\n\n"); - } - - private void generateBuildSection(StringBuilder buffer) { - buffer.append("%build\n"); - if (!pomExists) { - generateTempPom(buffer); - } - buffer.append("mvn-rpmbuild "); - if (!pomExists) { - buffer.append("-f temp/pom.xml "); - } - buffer.append("install\n"); - buffer.append("\n\n"); - } - - /** - * Returns the last meaningful part of the feature id before the feature - * substring. - * - * @param packageName - * The feature id from which to extract the name. - * @return The part of the feature id to be used for package name. - */ - public String getPackageName(String packageName) { - String[] packageItems = packageName.split("\\."); - String name = packageItems[packageItems.length - 1]; - if (name.equalsIgnoreCase("feature")) { - name = packageItems[packageItems.length - 2]; - } - return "eclipse-" + name; - } - - private static void generateTempPom(StringBuilder buffer) { - buffer.append("mkdir temp\n"); - buffer.append("pushd temp\n"); - buffer.append("cat > pom.xml << EOF\n"); - buffer.append("<project>\n"); - buffer.append(" <modelVersion>4.0.0</modelVersion>\n"); - buffer.append(" <name>Maven Default Project</name>\n"); - buffer.append(" <groupId>org.fedoraproject</groupId>\n"); - buffer.append(" <artifactId>dummy</artifactId>\n"); - buffer.append(" <version>1.0.0</version>\n"); - buffer.append("</project>\n"); - buffer.append("EOF\n"); - buffer.append("popd\n"); - } + private FeatureModel model; + private IFile featureFile; + private boolean pomExists; + + /** + * Creates the specfile and fetch script generator for the given packages. + * + * @param featureFile + * The feature.xml file to generate from. + */ + public StubbyGenerator(IFile featureFile) { + this.featureFile = featureFile; + parse(featureFile); + specfileName = model.getPackageName().toLowerCase() + ".spec"; + projectName = featureFile.getProject().getName(); + pomExists = new RPMStubbyUtils().findPom(featureFile.getParent().getLocation()); + } + + private void parse(IFile featureFile) { + DocumentBuilderFactory docfactory = DocumentBuilderFactory + .newInstance(); + IPath featureDir = featureFile.getLocation().removeLastSegments(1); + String featurePropertiesFile = featureDir.toOSString() + + "/feature.properties"; + Properties featureProperties = new Properties(); + try { + featureProperties.load(new FileInputStream(featurePropertiesFile)); + } catch (FileNotFoundException e) { + // Do nothing if the feature.properties is not found + } catch (IOException e) { + StubbyLog.logError(e); + } + DocumentBuilder docbuilder; + try { + docbuilder = docfactory.newDocumentBuilder(); + Document docroot = docbuilder.parse(featureFile.getContents()); + model = new FeatureModel(docroot, featureProperties); + + } catch (ParserConfigurationException|SAXException|IOException|CoreException e) { + StubbyLog.logError(e); + } + } + + /** + * Generates a RPM specfile based on the parsed data from the pom file. + * + * @return The generated specfile. + */ + @Override + public String generateSpecfile() { + StringBuilder buffer = new StringBuilder(); + buffer.append("%global install_loc %{_datadir}/eclipse/dropins/" + + model.getSimplePackageName() + "\n\n"); + buffer.append("Name: " + model.getPackageName().toLowerCase() + + "\n"); + buffer.append("Version: " + model.getVersion() + "\n"); + buffer.append("Release: 1%{?dist}" + "\n"); + buffer.append("Summary: " + model.getSummary() + "\n\n"); + buffer.append("Group: Development/Tools\n"); + buffer.append("License: " + model.getLicense() + "\n"); + buffer.append("URL: " + model.getURL() + "\n"); + buffer.append("Source0: #FIXME\n"); + buffer.append("BuildArch: noarch\n\n"); + generateRequires(buffer); + buffer.append("%description\n" + model.getDescription() + "\n"); + generatePrepSection(buffer); + generateBuildSection(buffer); + generateInstallSection(buffer); + generateFilesSections(buffer); + generateChangelog(buffer); + + return buffer.toString(); + } + + private static void generateRequires(StringBuilder buffer) { + buffer.append("Requires: eclipse-platform >= 3.4.0\n"); + buffer.append("BuildRequires: maven-local\n"); + buffer.append("\n\n"); + } + + private void generateInstallSection(StringBuilder buffer) { + buffer.append("%install\n"); + if (!pomExists) { + generateTempPom(buffer); + } + buffer.append("mvn-rpmbuild "); + if (!pomExists) { + buffer.append("-f temp/pom.xml "); + } + buffer.append("org.fedoraproject:feclipse-maven-plugin:install \\" + "\n"); + buffer.append("\t" + "-DsourceRepo=#FIXME \\" + "\n"); + buffer.append("\t" + "-DtargetLocation=%{buildroot}%{install_loc}/eclipse" + "\n"); + buffer.append("\n\n"); + } + + private void generateFilesSections(StringBuilder buffer) { + buffer.append("%files\n"); + buffer.append("%{install_loc}\n"); + String docsRoot = featureFile.getLocation().removeLastSegments(1) + .lastSegment(); + String[] files = featureFile.getLocation().removeLastSegments(1) + .toFile().list(); + for (String file : files) { + if (file.matches("(epl-.*|license)\\.html")) { + buffer.append("%doc " + docsRoot + "/" + file + "\n"); + } + } + buffer.append("\n\n"); + } + + private static void generatePrepSection(StringBuilder buffer) { + buffer.append("\n%prep\n"); + buffer.append("%setup -q #You may need to update this according to your Source0\n"); + buffer.append("\n\n"); + } + + private void generateBuildSection(StringBuilder buffer) { + buffer.append("%build\n"); + if (!pomExists) { + generateTempPom(buffer); + } + buffer.append("mvn-rpmbuild "); + if (!pomExists) { + buffer.append("-f temp/pom.xml "); + } + buffer.append("install\n"); + buffer.append("\n\n"); + } + + /** + * Returns the last meaningful part of the feature id before the feature + * substring. + * + * @param packageName + * The feature id from which to extract the name. + * @return The part of the feature id to be used for package name. + */ + public String getPackageName(String packageName) { + String[] packageItems = packageName.split("\\."); + String name = packageItems[packageItems.length - 1]; + if (name.equalsIgnoreCase("feature")) { + name = packageItems[packageItems.length - 2]; + } + return "eclipse-" + name; + } + + private static void generateTempPom(StringBuilder buffer) { + buffer.append("mkdir temp\n"); + buffer.append("pushd temp\n"); + buffer.append("cat > pom.xml << EOF\n"); + buffer.append("<project>\n"); + buffer.append(" <modelVersion>4.0.0</modelVersion>\n"); + buffer.append(" <name>Maven Default Project</name>\n"); + buffer.append(" <groupId>org.fedoraproject</groupId>\n"); + buffer.append(" <artifactId>dummy</artifactId>\n"); + buffer.append(" <version>1.0.0</version>\n"); + buffer.append("</project>\n"); + buffer.append("EOF\n"); + buffer.append("popd\n"); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyLog.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyLog.java index 2731a8b4f2..2b20d9d306 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyLog.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyLog.java @@ -20,19 +20,9 @@ import org.eclipse.core.runtime.Status; */ public final class StubbyLog { - private StubbyLog() { - //don't allow instantiation - } - - /** - * Log the specified information. - * - * @param message A human-readable message, localized to the - * current locale. - */ - public static void logInfo(String message) { - log(IStatus.INFO, IStatus.OK, message, null); - } + private StubbyLog() { + //don't allow instantiation + } /** * Log the specified error. @@ -40,19 +30,7 @@ public final class StubbyLog { * @param exception A low-level exception. */ public static void logError(Throwable exception) { - logError("Unexpected Exception", exception); - } - - /** - * Log the specified error. - * - * @param message A human-readable message, localized to the - * current locale. - * @param exception A low-level exception, or <code>null</code> - * if not applicable. - */ - public static void logError(String message, Throwable exception) { - log(IStatus.ERROR, IStatus.OK, message, exception); + log(IStatus.ERROR, IStatus.OK, "Unexpected Exception", exception); } /** @@ -70,9 +48,8 @@ public final class StubbyLog { * @param exception A low-level exception, or <code>null</code> * if not applicable. */ - public static void log(int severity, int code, String message, + private static void log(int severity, int code, String message, Throwable exception) { - log(createStatus(severity, code, message, exception)); } @@ -92,9 +69,8 @@ public final class StubbyLog { * if not applicable. * @return the status object (not <code>null</code>). */ - public static IStatus createStatus(int severity, int code, + private static IStatus createStatus(int severity, int code, String message, Throwable exception) { - return new Status(severity, StubbyPlugin.PLUGIN_ID, code, message, exception); } @@ -104,7 +80,7 @@ public final class StubbyLog { * * @param status The status to log. */ - public static void log(IStatus status) { - Platform.getLog(Platform.getBundle(StubbyPlugin.PLUGIN_ID)).log(status); + private static void log(IStatus status) { + Platform.getLog(Platform.getBundle(StubbyPlugin.PLUGIN_ID)).log(status); } -}
\ No newline at end of file +} diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyMakefilePLGenerator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyMakefilePLGenerator.java index b40a9331cd..f5f9221795 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyMakefilePLGenerator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyMakefilePLGenerator.java @@ -17,117 +17,116 @@ import org.eclipse.linuxtools.internal.rpmstubby.model.PerlModel; /** * Generator for RPM specfile from perl Makefile.PL. - * */ public class StubbyMakefilePLGenerator extends AbstractGenerator { - private PerlModel model; + private PerlModel model; - /** - * Creates the generator by parsing the Makefile.PL file. - * - * @param makefile - * The Makefile.PL file to generate specfile for. - */ - public StubbyMakefilePLGenerator(IFile makefile) { - parse(makefile); - specfileName = model.getPackageName().toLowerCase() + ".spec"; - projectName = makefile.getProject().getName(); - } + /** + * Creates the generator by parsing the Makefile.PL file. + * + * @param makefile + * The Makefile.PL file to generate specfile for. + */ + public StubbyMakefilePLGenerator(IFile makefile) { + parse(makefile); + specfileName = model.getPackageName().toLowerCase() + ".spec"; + projectName = makefile.getProject().getName(); + } - /** - * Creates the model which contains the information - * - * @param makefile The Makefile.PL file - */ - private void parse(IFile makefile) { - model = new PerlModel(makefile); - } + /** + * Creates the model which contains the information + * + * @param makefile The Makefile.PL file + */ + private void parse(IFile makefile) { + model = new PerlModel(makefile); + } - /** - * Generates a RPM specfile based on the parsed data from the Makefile.PL file. - * - * @return The generated Makefile.PL. - */ - @Override - public String generateSpecfile() { - StringBuilder buffer = new StringBuilder(); - String packageName = model.getPackageName(); - buffer.append("Name: " + packageName.toLowerCase() + "\n"); - buffer.append("Version: " + model.getVersion() + "\n"); - buffer.append("Release: 1%{?dist}" + "\n"); - buffer.append("Summary: " + model.getSummary() + "\n\n"); + /** + * Generates a RPM specfile based on the parsed data from the Makefile.PL file. + * + * @return The generated Makefile.PL. + */ + @Override + public String generateSpecfile() { + StringBuilder buffer = new StringBuilder(); + String packageName = model.getPackageName(); + buffer.append("Name: " + packageName.toLowerCase() + "\n"); + buffer.append("Version: " + model.getVersion() + "\n"); + buffer.append("Release: 1%{?dist}" + "\n"); + buffer.append("Summary: " + model.getSummary() + "\n\n"); - buffer.append("Group: Development/Libraries\n"); - buffer.append("License: GPL+ or Artistic\n"); - buffer.append("URL: "+model.getURL() + "\n"); // e.g., Net-XMPP/ for Net::XMPP - buffer.append("Source0: #FIXME\n\n"); - buffer.append("BuildArch: noarch\n"); - generateRequires(buffer); - buffer.append("%{?perl_default_filter}\n\n\n"); - buffer.append("%description\n" + model.getDescription() + "\n\n\n"); - generatePrepSection(buffer); - generateBuildSection(buffer); - generateInstallSection(buffer); - generateFilesSections(buffer); - generateChangelog(buffer); + buffer.append("Group: Development/Libraries\n"); + buffer.append("License: GPL+ or Artistic\n"); + buffer.append("URL: "+model.getURL() + "\n"); // e.g., Net-XMPP/ for Net::XMPP + buffer.append("Source0: #FIXME\n\n"); + buffer.append("BuildArch: noarch\n"); + generateRequires(buffer); + buffer.append("%{?perl_default_filter}\n\n\n"); + buffer.append("%description\n" + model.getDescription() + "\n\n\n"); + generatePrepSection(buffer); + generateBuildSection(buffer); + generateInstallSection(buffer); + generateFilesSections(buffer); + generateChangelog(buffer); - return buffer.toString(); - } + return buffer.toString(); + } - /** - * Generate requires - * - * @param buffer Buffer to write content to - */ - private void generateRequires(StringBuilder buffer) { - buffer.append("BuildRequires: perl(ExtUtils::MakeMaker)\n"); - List<String> requires = model.getInstallRequires() ; - if (!requires.isEmpty()) { - for (String str : requires) { - buffer.append("BuildRequires: " + str + "\n"); - } - } - buffer.append("Requires: perl(:MODULE_COMPAT_%(eval \"`%{__perl} -V:version`\"; echo $version))\n\n"); - } + /** + * Generate requires + * + * @param buffer Buffer to write content to + */ + private void generateRequires(StringBuilder buffer) { + buffer.append("BuildRequires: perl(ExtUtils::MakeMaker)\n"); + List<String> requires = model.getInstallRequires() ; + if (!requires.isEmpty()) { + for (String str : requires) { + buffer.append("BuildRequires: " + str + "\n"); + } + } + buffer.append("Requires: perl(:MODULE_COMPAT_%(eval \"`%{__perl} -V:version`\"; echo $version))\n\n"); + } - /** - * Generate prep - * - * @param buffer Buffer to write content to - */ - private static void generatePrepSection(StringBuilder buffer) { - buffer.append("%prep\n"); - buffer.append("%setup -q #You may need to update this according to your Source0\n\n\n"); - } + /** + * Generate prep + * + * @param buffer Buffer to write content to + */ + private static void generatePrepSection(StringBuilder buffer) { + buffer.append("%prep\n"); + buffer.append("%setup -q #You may need to update this according to your Source0\n\n\n"); + } - /** - * Generate build - * - * @param buffer Buffer to write content to - */ - private static void generateBuildSection(StringBuilder buffer) { - buffer.append("%build\n"); - buffer.append("%{__perl} Makefile.PL INSTALLDIRS=vendor\n\n\n"); - } + /** + * Generate build + * + * @param buffer Buffer to write content to + */ + private static void generateBuildSection(StringBuilder buffer) { + buffer.append("%build\n"); + buffer.append("%{__perl} Makefile.PL INSTALLDIRS=vendor\n\n\n"); + } - /** - * Generate install - * - * @param buffer Buffer to write content to - */ - private static void generateInstallSection(StringBuilder buffer) { - buffer.append("%install\n"); - buffer.append("make pure_install PERL_INSTALL_ROOT=$RPM_BUILD_ROOT\n\n\n"); - } + /** + * Generate install + * + * @param buffer Buffer to write content to + */ + private static void generateInstallSection(StringBuilder buffer) { + buffer.append("%install\n"); + buffer.append("make pure_install PERL_INSTALL_ROOT=$RPM_BUILD_ROOT\n\n\n"); + } - /** - * Generate files - * - * @param buffer Buffer to write content to - */ - private static void generateFilesSections(StringBuilder buffer) { - buffer.append("%files\n"); - buffer.append("%{perl_vendorlib}/*\n\n\n"); - } -}
\ No newline at end of file + /** + * Generate files + * + * @param buffer Buffer to write content to + */ + private static void generateFilesSections(StringBuilder buffer) { + buffer.append("%files\n"); + buffer.append("%{perl_vendorlib}/*\n\n\n"); + } +} diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPlugin.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPlugin.java index 14766025ef..2bbe4106c0 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPlugin.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPlugin.java @@ -10,13 +10,12 @@ *******************************************************************************/ package org.eclipse.linuxtools.internal.rpmstubby; - /** * The Stubby constants. */ public interface StubbyPlugin { - /** The plug-in ID. */ - String PLUGIN_ID = "org.eclipse.linuxtools.internal.rpmstubby"; + /** The plug-in ID. */ + String PLUGIN_ID = "org.eclipse.linuxtools.internal.rpmstubby"; } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPomGenerator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPomGenerator.java index 06dd0eb42c..3c2eb2729a 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPomGenerator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/StubbyPomGenerator.java @@ -25,110 +25,103 @@ import org.xml.sax.SAXException; /** * Generator for RPM specfile from maven pom.xml. - * */ public class StubbyPomGenerator extends AbstractGenerator { - private PomModel model; - - /** - * Creates the generator by parsing the pom.xml file. - * - * @param pomFile - * The pom.xml file to generate specfile for. - */ - public StubbyPomGenerator(IFile pomFile) { - parse(pomFile); - specfileName = model.getPackageName().toLowerCase() + ".spec"; - projectName = pomFile.getProject().getName(); - } - - private void parse(IFile pomFile) { - DocumentBuilderFactory docfactory = DocumentBuilderFactory - .newInstance(); - DocumentBuilder docbuilder; - try { - docbuilder = docfactory.newDocumentBuilder(); - Document docroot = docbuilder.parse(pomFile.getContents()); - model = new PomModel(docroot); - } catch (ParserConfigurationException e) { - StubbyLog.logError(e); - } catch (SAXException e) { - StubbyLog.logError(e); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (CoreException e) { - StubbyLog.logError(e); - } - } - - /** - * Generates a RPM specfile based on the parsed data from the pom file. - * - * @return The generated specfile. - */ - @Override - public String generateSpecfile() { - StringBuilder buffer = new StringBuilder(); - String packageName = model.getPackageName(); - buffer.append("Name: " + packageName.toLowerCase() + "\n"); - buffer.append("Version: " + model.getVersion() + "\n"); - buffer.append("Release: 1%{?dist}" + "\n"); - buffer.append("Summary: " + model.getSummary() + "\n\n"); - buffer.append("Group: Development/Libraries\n"); - buffer.append("License: " + model.getLicense() + "\n"); - buffer.append("URL: " + model.getURL() + "\n"); - buffer.append("Source0: #FIXME\n"); - buffer.append("BuildArch: noarch\n\n"); - generateRequires(buffer); - buffer.append("\n%description\n" + model.getDescription() + "\n\n"); - generateJavadocSubpackage(buffer); - generatePrepSection(buffer); - generateBuildSection(buffer); - generateInstallSection(buffer); - generateFilesSections(buffer); - generateChangelog(buffer); - - return buffer.toString(); - } - - private void generateRequires(StringBuilder buffer) { - for (Map.Entry<String, String> entry : model.getDependencies() - .entrySet()) { - buffer.append("BuildRequires: mvn(" + entry.getKey() + ":" - + entry.getValue() + ")\n"); - } - buffer.append("BuildRequires: maven-local\n"); - } - - private static void generateJavadocSubpackage(StringBuilder buffer) { - buffer.append("%package javadoc\n"); - buffer.append("Group: Documentation\n"); - buffer.append("Summary: Javadoc for %{name}\n\n"); - buffer.append("%description javadoc\n"); - buffer.append("API documentation for %{name}.\n\n"); - - } - - private static void generateInstallSection(StringBuilder buffer) { - buffer.append("%install\n"); - buffer.append("%mvn_install\n\n"); - } - - private static void generateFilesSections(StringBuilder buffer) { - buffer.append("%files -f .mfiles\n"); - buffer.append("%dir %{_javadir}/%{name}\n\n"); - buffer.append("%files javadoc -f .mfiles-javadoc\n\n"); - } - - private static void generatePrepSection(StringBuilder buffer) { - buffer.append("\n%prep\n"); - buffer.append("%setup -q #You may need to update this according to your Source0\n\n"); - } - - private static void generateBuildSection(StringBuilder buffer) { - buffer.append("%build\n"); - buffer.append("%mvn_build\n\n"); - } - -}
\ No newline at end of file + private PomModel model; + + /** + * Creates the generator by parsing the pom.xml file. + * + * @param pomFile + * The pom.xml file to generate specfile for. + */ + public StubbyPomGenerator(IFile pomFile) { + parse(pomFile); + specfileName = model.getPackageName().toLowerCase() + ".spec"; + projectName = pomFile.getProject().getName(); + } + + private void parse(IFile pomFile) { + DocumentBuilderFactory docfactory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder docbuilder; + try { + docbuilder = docfactory.newDocumentBuilder(); + Document docroot = docbuilder.parse(pomFile.getContents()); + model = new PomModel(docroot); + } catch (ParserConfigurationException|SAXException|IOException|CoreException e) { + StubbyLog.logError(e); + } + } + + /** + * Generates a RPM specfile based on the parsed data from the pom file. + * + * @return The generated specfile. + */ + @Override + public String generateSpecfile() { + StringBuilder buffer = new StringBuilder(); + String packageName = model.getPackageName(); + buffer.append("Name: " + packageName.toLowerCase() + "\n"); + buffer.append("Version: " + model.getVersion() + "\n"); + buffer.append("Release: 1%{?dist}" + "\n"); + buffer.append("Summary: " + model.getSummary() + "\n\n"); + buffer.append("Group: Development/Libraries\n"); + buffer.append("License: " + model.getLicense() + "\n"); + buffer.append("URL: " + model.getURL() + "\n"); + buffer.append("Source0: #FIXME\n"); + buffer.append("BuildArch: noarch\n\n"); + generateRequires(buffer); + buffer.append("\n%description\n" + model.getDescription() + "\n\n"); + generateJavadocSubpackage(buffer); + generatePrepSection(buffer); + generateBuildSection(buffer); + generateInstallSection(buffer); + generateFilesSections(buffer); + generateChangelog(buffer); + + return buffer.toString(); + } + + private void generateRequires(StringBuilder buffer) { + for (Map.Entry<String, String> entry : model.getDependencies() + .entrySet()) { + buffer.append("BuildRequires: mvn(" + entry.getKey() + ":" + + entry.getValue() + ")\n"); + } + buffer.append("BuildRequires: maven-local\n"); + } + + private static void generateJavadocSubpackage(StringBuilder buffer) { + buffer.append("%package javadoc\n"); + buffer.append("Group: Documentation\n"); + buffer.append("Summary: Javadoc for %{name}\n\n"); + buffer.append("%description javadoc\n"); + buffer.append("API documentation for %{name}.\n\n"); + + } + + private static void generateInstallSection(StringBuilder buffer) { + buffer.append("%install\n"); + buffer.append("%mvn_install\n\n"); + } + + private static void generateFilesSections(StringBuilder buffer) { + buffer.append("%files -f .mfiles\n"); + buffer.append("%dir %{_javadir}/%{name}\n\n"); + buffer.append("%files javadoc -f .mfiles-javadoc\n\n"); + } + + private static void generatePrepSection(StringBuilder buffer) { + buffer.append("\n%prep\n"); + buffer.append("%setup -q #You may need to update this according to your Source0\n\n"); + } + + private static void generateBuildSection(StringBuilder buffer) { + buffer.append("%build\n"); + buffer.append("%mvn_build\n\n"); + } + +} diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/EggModel.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/EggModel.java index c38e713653..27a8bedfc2 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/EggModel.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/EggModel.java @@ -26,194 +26,194 @@ import org.eclipse.linuxtools.internal.rpmstubby.parser.ValidLicenses; */ public class EggModel { - private static final String[] VALID_LICENSES = { - ValidLicenses.GPL, - ValidLicenses.ARTISTIC, - ValidLicenses.MIT, - ValidLicenses.APACHE, - ValidLicenses.PUBLIC_DOMAIN, - ValidLicenses.ZLIB, - ValidLicenses.RICOH_SOURCE_CODE, - ValidLicenses.VOVIDA_SOFTWARE, - ValidLicenses.INTEL_OPEN_SOURCE, - ValidLicenses.LGPL, - ValidLicenses.BSD, - ValidLicenses.QPL, - ValidLicenses.IBM_PUBLIC, - ValidLicenses.PHP, - ValidLicenses.MODIFIED_CNRI_OPEN_SOURCE, - ValidLicenses.CVW, - ValidLicenses.PYTHON, - ValidLicenses.SUN_INTERNET_STANDARDS_SOURCE, - ValidLicenses.JABBER_OPEN_SOURCE - }; - - private static final String LONG_DESCRIPTION = "long_description"; - private static final String CLASSIFIERS = "classifiers"; - private static final String INSTALL_REQUIRES = "install_requires"; - - private static final String FIX_ME = "#FIXME"; - - private PythonEggParser pyEggParser; - - /** - * Python egg setup.py file - * - * @param file The Python setup.py file - */ - public EggModel(IFile file) { - try { - pyEggParser = new PythonEggParser(file); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (CoreException e) { - StubbyLog.logError(e); - } - } - - /** - * Get the value from one of the setup options. - * If the value is empty, it will return #FIXME - * It will also return #FIX_ME if it looks like a function - * - * @param option The option from the setup(...) function to get value of - * @return The value of the option - */ - private String getValue(String option) { - String str = pyEggParser.getValue(option); - - if (str.isEmpty() || pyEggParser.checkFunction(str)) { - str = FIX_ME; - } - - return str; - } - - /** - * Get the values from the classifiers option and - * check to see if the keyword is in one of them - * - * @param keyword What to check for within the list of values in classifiers - * @return The value within classifiers that contains the keyword - */ - private String getClassifiersList(String keyword) { - String rc = ""; - List<String> list = pyEggParser.getValueList(CLASSIFIERS); - - for (String str : list) { - if (str.toLowerCase().contains(keyword)) { - rc = str; - } - } - - return rc; - } - - /** - * Get the values from the install_requires option - * - * @return The values within install_requires - */ - public List<String> getInstallRequiresList() { - return pyEggParser.getValueList(INSTALL_REQUIRES); - } - - /** - * Returns the package name. - * - * @return The package name. - */ - public String getSimplePackageName() { - return getValue(CommonMetaData.NAME); - } - - /** - * The simple package name with "python-" prepended to make better RPM package name. - * - * @return The package - */ - public String getPackageName() { - String simpleName = getSimplePackageName(); - if (simpleName.startsWith("python-")) { - return simpleName; - } - return "python-"+simpleName; - } - - /** - * Returns the version - * - * @return The version - */ - public String getVersion() { - String version = getValue(CommonMetaData.VERSION); - - if (!hasDigits(version)) { - version = "1 " + FIX_ME; - } - - return version; - } - - /** - * Utitlity method to try and see if a string contains - * digits within it - * - * @param str The string to check if it has digits - * @return True if string contains digits - */ - public boolean hasDigits(String str) { - return str.matches(".*\\d.*"); - } - - /** - * Returns the summary - * - * @return The package summary - */ - public String getSummary() { - return getValue(LONG_DESCRIPTION); - } - - /** - * Returns the license - * - * @return The license - */ - public String getLicense() { - String rawLicense = getClassifiersList(CommonMetaData.LICENSE).toLowerCase(); - String license = ""; - - for (String valid : VALID_LICENSES) { - if (rawLicense.contains(valid.toLowerCase())) { - license += valid + ", "; - } - } - - if (!license.isEmpty()) { - license = license.substring(0, license.length()-2); - } else { - license = FIX_ME; - } - - return license; - } - - /** - * Returns the url - * - * @return The url - */ - public String getURL() { - return getValue(CommonMetaData.URL); - } - - /** - * Returns the description - * - * @return The description - */ - public String getDescription() { - return getValue(CommonMetaData.DESCRIPTION); - } + private static final String[] VALID_LICENSES = { + ValidLicenses.GPL, + ValidLicenses.ARTISTIC, + ValidLicenses.MIT, + ValidLicenses.APACHE, + ValidLicenses.PUBLIC_DOMAIN, + ValidLicenses.ZLIB, + ValidLicenses.RICOH_SOURCE_CODE, + ValidLicenses.VOVIDA_SOFTWARE, + ValidLicenses.INTEL_OPEN_SOURCE, + ValidLicenses.LGPL, + ValidLicenses.BSD, + ValidLicenses.QPL, + ValidLicenses.IBM_PUBLIC, + ValidLicenses.PHP, + ValidLicenses.MODIFIED_CNRI_OPEN_SOURCE, + ValidLicenses.CVW, + ValidLicenses.PYTHON, + ValidLicenses.SUN_INTERNET_STANDARDS_SOURCE, + ValidLicenses.JABBER_OPEN_SOURCE + }; + + private static final String LONG_DESCRIPTION = "long_description"; + private static final String CLASSIFIERS = "classifiers"; + private static final String INSTALL_REQUIRES = "install_requires"; + + private static final String FIX_ME = "#FIXME"; + + private PythonEggParser pyEggParser; + + /** + * Python egg setup.py file + * + * @param file The Python setup.py file + */ + public EggModel(IFile file) { + try { + pyEggParser = new PythonEggParser(file); + } catch (IOException e) { + StubbyLog.logError(e); + } catch (CoreException e) { + StubbyLog.logError(e); + } + } + + /** + * Get the value from one of the setup options. + * If the value is empty, it will return #FIXME + * It will also return #FIX_ME if it looks like a function + * + * @param option The option from the setup(...) function to get value of + * @return The value of the option + */ + private String getValue(String option) { + String str = pyEggParser.getValue(option); + + if (str.isEmpty() || pyEggParser.checkFunction(str)) { + str = FIX_ME; + } + + return str; + } + + /** + * Get the values from the classifiers option and + * check to see if the keyword is in one of them + * + * @param keyword What to check for within the list of values in classifiers + * @return The value within classifiers that contains the keyword + */ + private String getClassifiersList(String keyword) { + String rc = ""; + List<String> list = pyEggParser.getValueList(CLASSIFIERS); + + for (String str : list) { + if (str.toLowerCase().contains(keyword)) { + rc = str; + } + } + + return rc; + } + + /** + * Get the values from the install_requires option + * + * @return The values within install_requires + */ + public List<String> getInstallRequiresList() { + return pyEggParser.getValueList(INSTALL_REQUIRES); + } + + /** + * Returns the package name. + * + * @return The package name. + */ + public String getSimplePackageName() { + return getValue(CommonMetaData.NAME); + } + + /** + * The simple package name with "python-" prepended to make better RPM package name. + * + * @return The package + */ + public String getPackageName() { + String simpleName = getSimplePackageName(); + if (simpleName.startsWith("python-")) { + return simpleName; + } + return "python-"+simpleName; + } + + /** + * Returns the version + * + * @return The version + */ + public String getVersion() { + String version = getValue(CommonMetaData.VERSION); + + if (!hasDigits(version)) { + version = "1 " + FIX_ME; + } + + return version; + } + + /** + * Utitlity method to try and see if a string contains + * digits within it + * + * @param str The string to check if it has digits + * @return True if string contains digits + */ + public boolean hasDigits(String str) { + return str.matches(".*\\d.*"); + } + + /** + * Returns the summary + * + * @return The package summary + */ + public String getSummary() { + return getValue(LONG_DESCRIPTION); + } + + /** + * Returns the license + * + * @return The license + */ + public String getLicense() { + String rawLicense = getClassifiersList(CommonMetaData.LICENSE).toLowerCase(); + String license = ""; + + for (String valid : VALID_LICENSES) { + if (rawLicense.contains(valid.toLowerCase())) { + license += valid + ", "; + } + } + + if (!license.isEmpty()) { + license = license.substring(0, license.length()-2); + } else { + license = FIX_ME; + } + + return license; + } + + /** + * Returns the url + * + * @return The url + */ + public String getURL() { + return getValue(CommonMetaData.URL); + } + + /** + * Returns the description + * + * @return The description + */ + public String getDescription() { + return getValue(CommonMetaData.DESCRIPTION); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/FeatureModel.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/FeatureModel.java index 50e80e259b..d864e794a2 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/FeatureModel.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/FeatureModel.java @@ -23,143 +23,143 @@ import org.w3c.dom.Document; * */ public class FeatureModel { - - private Document docroot; - private XPath xpath; - private Properties featureProperties; - - /** - * Instantiates the model with the given XML document and preparing the - * XPath evaluation environment. - * - * @param docroot - * The document to query. - * @param featureProperties The properties as loaded by feature.properties. - */ - public FeatureModel(Document docroot, Properties featureProperties) { - this.docroot = docroot; - this.featureProperties = featureProperties; - xpath = XPathFactory.newInstance().newXPath(); - } - - private String xpathEval(String path) { - String result = ""; - try { - result = xpath.evaluate(path, docroot); - } catch (XPathExpressionException e) { - //ignore, empty string is fine on missing path - } - return result; - } - - /** - * Get value for a given key from the feature.properties file, if the key - * don't start with '%' we just return the given key. - * - * @param key - * to find in feature.properties - * @return the value - */ - private String resolveFeatureProperties(String key) { - if (key != null && key.trim().startsWith("%")) { - return featureProperties.getProperty(key.trim().replaceAll("%", "")); - } else { - return key; - } - } - - /** - * Returns the package name. - * It is calculated by using the feature id last segment unless the last segment - * is feature in which case the previous one is used. - * @return The package name. - */ - public String getSimplePackageName() { - String packageName = xpathEval("/feature/@id"); - String[] packageItems = packageName.split("\\."); - String name = packageItems[packageItems.length - 1]; - if (name.equalsIgnoreCase("feature")) { - name = packageItems[packageItems.length - 2]; - } - - return name; - } - - /** - * The simple package name with "eclipse-" prepended to make better RPM package name. - * @return The package - */ - public String getPackageName() { - return "eclipse-"+getSimplePackageName(); - } - - /** - * Returns the feature id as retrieved with /feature/@id xpath. - * @return The feature id. - */ - public String getFeatureId() { - return xpathEval("/feature/@id"); - } - - /** - * Returns the version as retrieved by /feature/@version xpath with .qualifier removed if any. - * - * @return The version of the feature. - */ - public String getVersion() { - String version = xpathEval("/feature/@version"); - version = version.replaceAll(".qualifier", ""); - return version; - } - - /** - * Returns the summary as retrieved by /feature/@label xpath. - * - * @return The package summary. - */ - public String getSummary() { - return resolveFeatureProperties(xpathEval("/feature/@label")); - } - - /** - * Returns the license. - * The algorithm is to look at /feature/license and/or /feature/license/@url and look for epl or cpl. - * Otherwise #FIX ME comment is returned - * @return The license of the feature. - */ - public String getLicense() { - String urlString = resolveFeatureProperties(xpathEval("/feature/license/@url")); - String urlAnotation = resolveFeatureProperties(xpathEval("/feature/license")); - String license = "#FIXME"; - if ((urlString != null && urlAnotation != null)) { - if ((urlString.indexOf("epl") > -1 || urlAnotation - .indexOf("epl") > -1)) { - license = "EPL"; - } else if ((urlString.indexOf("cpl") > -1 || urlAnotation - .indexOf("cpl") > -1)) { - license = "CPL"; - } - } - return license; - } - - - - /** - * Returns the url as fetched from /feature/description/@url xpath if any. - * @return The url. - */ - public String getURL() { - return xpathEval("/feature/description/@url"); - } - - /** - * Returns the description as fetched by /feature/description and resolved from feature.properties if needed. - * - * @return The description. - */ - public String getDescription() { - return resolveFeatureProperties(xpathEval("/feature/description")); - } + + private Document docroot; + private XPath xpath; + private Properties featureProperties; + + /** + * Instantiates the model with the given XML document and preparing the + * XPath evaluation environment. + * + * @param docroot + * The document to query. + * @param featureProperties The properties as loaded by feature.properties. + */ + public FeatureModel(Document docroot, Properties featureProperties) { + this.docroot = docroot; + this.featureProperties = featureProperties; + xpath = XPathFactory.newInstance().newXPath(); + } + + private String xpathEval(String path) { + String result = ""; + try { + result = xpath.evaluate(path, docroot); + } catch (XPathExpressionException e) { + //ignore, empty string is fine on missing path + } + return result; + } + + /** + * Get value for a given key from the feature.properties file, if the key + * don't start with '%' we just return the given key. + * + * @param key + * to find in feature.properties + * @return the value + */ + private String resolveFeatureProperties(String key) { + if (key != null && key.trim().startsWith("%")) { + return featureProperties.getProperty(key.trim().replaceAll("%", "")); + } else { + return key; + } + } + + /** + * Returns the package name. + * It is calculated by using the feature id last segment unless the last segment + * is feature in which case the previous one is used. + * @return The package name. + */ + public String getSimplePackageName() { + String packageName = xpathEval("/feature/@id"); + String[] packageItems = packageName.split("\\."); + String name = packageItems[packageItems.length - 1]; + if (name.equalsIgnoreCase("feature")) { + name = packageItems[packageItems.length - 2]; + } + + return name; + } + + /** + * The simple package name with "eclipse-" prepended to make better RPM package name. + * @return The package + */ + public String getPackageName() { + return "eclipse-"+getSimplePackageName(); + } + + /** + * Returns the feature id as retrieved with /feature/@id xpath. + * @return The feature id. + */ + public String getFeatureId() { + return xpathEval("/feature/@id"); + } + + /** + * Returns the version as retrieved by /feature/@version xpath with .qualifier removed if any. + * + * @return The version of the feature. + */ + public String getVersion() { + String version = xpathEval("/feature/@version"); + version = version.replaceAll(".qualifier", ""); + return version; + } + + /** + * Returns the summary as retrieved by /feature/@label xpath. + * + * @return The package summary. + */ + public String getSummary() { + return resolveFeatureProperties(xpathEval("/feature/@label")); + } + + /** + * Returns the license. + * The algorithm is to look at /feature/license and/or /feature/license/@url and look for epl or cpl. + * Otherwise #FIX ME comment is returned + * @return The license of the feature. + */ + public String getLicense() { + String urlString = resolveFeatureProperties(xpathEval("/feature/license/@url")); + String urlAnotation = resolveFeatureProperties(xpathEval("/feature/license")); + String license = "#FIXME"; + if ((urlString != null && urlAnotation != null)) { + if ((urlString.indexOf("epl") > -1 || urlAnotation + .indexOf("epl") > -1)) { + license = "EPL"; + } else if ((urlString.indexOf("cpl") > -1 || urlAnotation + .indexOf("cpl") > -1)) { + license = "CPL"; + } + } + return license; + } + + + + /** + * Returns the url as fetched from /feature/description/@url xpath if any. + * @return The url. + */ + public String getURL() { + return xpathEval("/feature/description/@url"); + } + + /** + * Returns the description as fetched by /feature/description and resolved from feature.properties if needed. + * + * @return The description. + */ + public String getDescription() { + return resolveFeatureProperties(xpathEval("/feature/description")); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/GemModel.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/GemModel.java index 719f998016..6878bb5c38 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/GemModel.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/GemModel.java @@ -26,243 +26,243 @@ import org.eclipse.linuxtools.internal.rpmstubby.parser.RubyGemParser; */ public class GemModel { - private static final String FIX_ME = "#FIXME"; - - private static final String SUMMARY = "summary"; - private static final String RUBYGEMS_VERSION = "rubygems_version"; - private static final String REQUIRE_PATHS = "require_paths"; - private static final String DEPENDENCY = "add_dependency"; - private static final String DEVELOPMENT_DEPENDENCY = "add_development_dependency"; - private static final String RUNTIME_DEPENDENCY = "add_runtime_dependency"; - private static final String HOMEPAGE = "homepage"; - - /** - * Options in the gemspec file that are supposed to only have 1 value - * - */ - private static final String[] SINGLE_VALUES = { CommonMetaData.DESCRIPTION, - CommonMetaData.NAME, CommonMetaData.VERSION, - CommonMetaData.LICENSE, SUMMARY, RUBYGEMS_VERSION, HOMEPAGE }; - - private RubyGemParser rubyGemParser; - - /** - * Ruby gemspec file - * - * @param file - * The Ruby gemspec file - */ - public GemModel(IFile file) { - try { - rubyGemParser = new RubyGemParser(file); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (CoreException e) { - StubbyLog.logError(e); - } - } - - /** - * Get the value from one of the gemspec attributes. If the value is empty, it - * will return #FIXME - * - * @param attr - * The gemspec attribute to get value of - * @return The value of the option - */ - private String getValue(String attr) { - List<String> list = rubyGemParser.getValueList(attr); - String rc = ""; - boolean single = false; - - for (String str : SINGLE_VALUES) { - if (str.equals(attr)) { - single = true; - break; - } - } - - if (!list.isEmpty() && single) { - rc = list.get(0); - } else { - rc = FIX_ME; - } - - return rc; - } - - /** - * Get the install requires in the gemspec file - * - * @param key - * Either the dependencies or the development dependencies option - * @return A list of the values taken from the gemspec - */ - public List<String> getDependencies(String key) { - List<String> rc = new ArrayList<>(); - List<String> temp = rubyGemParser.getValueList(key); - - if (!temp.isEmpty()) { - for (String tmp : temp) { - rc.add(tmp - .replaceFirst("(?:%q|%Q)(?:([\\W])([^\\W]+)[\\W])", - "$2").replaceAll("(\"|'|\\[|\\])", "") - .replaceAll(",", "")); - } - } - return rc; - } - - /** - * Get the values from the add_dependency option - * - * @return The values within add_dependency - */ - public List<String> getInstallRequiresList() { - List<String> rc = getDependencies(DEPENDENCY); - rc.addAll(getDependencies(RUNTIME_DEPENDENCY)); - return getDependencies(DEPENDENCY); - } - - /** - * Get the values from the add_development_dependency option - * - * @return The values within add_development_dependency - */ - public List<String> getBuildRequiresList() { - return getDependencies(DEVELOPMENT_DEPENDENCY); - } - - /** - * Returns the package name. - * - * @return The package name. - */ - public String getSimplePackageName() { - return getValue(CommonMetaData.NAME); - } - - /** - * The simple package name with "rubygem-" prepended to make better RPM - * package name. - * - * @return The package - */ - public String getPackageName() { - String simpleName = getSimplePackageName(); - if (simpleName.startsWith("rubygem-")) { - return simpleName; - } - return "rubygem-"+simpleName; - } - - /** - * Returns the version - * - * @return The version - */ - public String getVersion() { - String version = getValue(CommonMetaData.VERSION); - - if (!hasDigits(version)) { - version = "1 " + FIX_ME; - } - - return version; - } - - /** - * Returns the RubyGems version - * - * @return The RubyGems version - */ - public String getGemVersion() { - String version = getValue(RUBYGEMS_VERSION); - - if (!hasDigits(version)) { - version = FIX_ME; - } - - return version; - } - - /** - * Utility method to try and see if a string contains digits within it - * - * @param str - * The string to check if it has digits - * @return True if string contains digits - */ - public boolean hasDigits(String str) { - return str.matches(".*\\d.*"); - } - - /** - * Returns the summary - * - * @return The package summary - */ - public String getSummary() { - return getValue(SUMMARY); - } - - /** - * Returns the license - * - * @return The license - */ - public String getLicense() { - String license = getValue("license"); - List<String> list = rubyGemParser.getValueList("licenses"); - - if (license.equals(FIX_ME) && !list.isEmpty()) { - license = ""; - for (String str : list) { - license = license.concat(str + ", "); - license = license.replaceAll("(\"|')", ""); - } - license = license.substring(0, license.length() - 2); - } - - return license; - } - - /** - * Returns the url - * - * @return The url - */ - public String getURL() { - return getValue(HOMEPAGE); - } - - /** - * Returns the description - * - * @return The description - */ - public String getDescription() { - return getValue(CommonMetaData.DESCRIPTION); - } - - /** - * Return the require paths - * - * @return The require paths - */ - public List<String> getRequirePaths() { - List<String> rc = new ArrayList<>(); - List<String> temp = rubyGemParser.getValueList(REQUIRE_PATHS); - - if (!temp.isEmpty()) { - for (String tmp : temp) { - rc.add(tmp - .replaceFirst("(?:%q|%Q)(?:([\\W])([^\\W]+)[\\W])", - "$2").replaceAll("(\"|'|\\[|\\])", "") - .replaceAll(",", "")); - } - } - - return rc; - } + private static final String FIX_ME = "#FIXME"; + + private static final String SUMMARY = "summary"; + private static final String RUBYGEMS_VERSION = "rubygems_version"; + private static final String REQUIRE_PATHS = "require_paths"; + private static final String DEPENDENCY = "add_dependency"; + private static final String DEVELOPMENT_DEPENDENCY = "add_development_dependency"; + private static final String RUNTIME_DEPENDENCY = "add_runtime_dependency"; + private static final String HOMEPAGE = "homepage"; + + /** + * Options in the gemspec file that are supposed to only have 1 value + * + */ + private static final String[] SINGLE_VALUES = { CommonMetaData.DESCRIPTION, + CommonMetaData.NAME, CommonMetaData.VERSION, + CommonMetaData.LICENSE, SUMMARY, RUBYGEMS_VERSION, HOMEPAGE }; + + private RubyGemParser rubyGemParser; + + /** + * Ruby gemspec file + * + * @param file + * The Ruby gemspec file + */ + public GemModel(IFile file) { + try { + rubyGemParser = new RubyGemParser(file); + } catch (IOException e) { + StubbyLog.logError(e); + } catch (CoreException e) { + StubbyLog.logError(e); + } + } + + /** + * Get the value from one of the gemspec attributes. If the value is empty, it + * will return #FIXME + * + * @param attr + * The gemspec attribute to get value of + * @return The value of the option + */ + private String getValue(String attr) { + List<String> list = rubyGemParser.getValueList(attr); + String rc = ""; + boolean single = false; + + for (String str : SINGLE_VALUES) { + if (str.equals(attr)) { + single = true; + break; + } + } + + if (!list.isEmpty() && single) { + rc = list.get(0); + } else { + rc = FIX_ME; + } + + return rc; + } + + /** + * Get the install requires in the gemspec file + * + * @param key + * Either the dependencies or the development dependencies option + * @return A list of the values taken from the gemspec + */ + public List<String> getDependencies(String key) { + List<String> rc = new ArrayList<>(); + List<String> temp = rubyGemParser.getValueList(key); + + if (!temp.isEmpty()) { + for (String tmp : temp) { + rc.add(tmp + .replaceFirst("(?:%q|%Q)(?:([\\W])([^\\W]+)[\\W])", + "$2").replaceAll("(\"|'|\\[|\\])", "") + .replaceAll(",", "")); + } + } + return rc; + } + + /** + * Get the values from the add_dependency option + * + * @return The values within add_dependency + */ + public List<String> getInstallRequiresList() { + List<String> rc = getDependencies(DEPENDENCY); + rc.addAll(getDependencies(RUNTIME_DEPENDENCY)); + return getDependencies(DEPENDENCY); + } + + /** + * Get the values from the add_development_dependency option + * + * @return The values within add_development_dependency + */ + public List<String> getBuildRequiresList() { + return getDependencies(DEVELOPMENT_DEPENDENCY); + } + + /** + * Returns the package name. + * + * @return The package name. + */ + public String getSimplePackageName() { + return getValue(CommonMetaData.NAME); + } + + /** + * The simple package name with "rubygem-" prepended to make better RPM + * package name. + * + * @return The package + */ + public String getPackageName() { + String simpleName = getSimplePackageName(); + if (simpleName.startsWith("rubygem-")) { + return simpleName; + } + return "rubygem-"+simpleName; + } + + /** + * Returns the version + * + * @return The version + */ + public String getVersion() { + String version = getValue(CommonMetaData.VERSION); + + if (!hasDigits(version)) { + version = "1 " + FIX_ME; + } + + return version; + } + + /** + * Returns the RubyGems version + * + * @return The RubyGems version + */ + public String getGemVersion() { + String version = getValue(RUBYGEMS_VERSION); + + if (!hasDigits(version)) { + version = FIX_ME; + } + + return version; + } + + /** + * Utility method to try and see if a string contains digits within it + * + * @param str + * The string to check if it has digits + * @return True if string contains digits + */ + public boolean hasDigits(String str) { + return str.matches(".*\\d.*"); + } + + /** + * Returns the summary + * + * @return The package summary + */ + public String getSummary() { + return getValue(SUMMARY); + } + + /** + * Returns the license + * + * @return The license + */ + public String getLicense() { + String license = getValue("license"); + List<String> list = rubyGemParser.getValueList("licenses"); + + if (license.equals(FIX_ME) && !list.isEmpty()) { + license = ""; + for (String str : list) { + license = license.concat(str + ", "); + license = license.replaceAll("(\"|')", ""); + } + license = license.substring(0, license.length() - 2); + } + + return license; + } + + /** + * Returns the url + * + * @return The url + */ + public String getURL() { + return getValue(HOMEPAGE); + } + + /** + * Returns the description + * + * @return The description + */ + public String getDescription() { + return getValue(CommonMetaData.DESCRIPTION); + } + + /** + * Return the require paths + * + * @return The require paths + */ + public List<String> getRequirePaths() { + List<String> rc = new ArrayList<>(); + List<String> temp = rubyGemParser.getValueList(REQUIRE_PATHS); + + if (!temp.isEmpty()) { + for (String tmp : temp) { + rc.add(tmp + .replaceFirst("(?:%q|%Q)(?:([\\W])([^\\W]+)[\\W])", + "$2").replaceAll("(\"|'|\\[|\\])", "") + .replaceAll(",", "")); + } + } + + return rc; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PerlModel.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PerlModel.java index 7bbe800b92..a4d0d7a64e 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PerlModel.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PerlModel.java @@ -26,157 +26,157 @@ import org.eclipse.linuxtools.internal.rpmstubby.parser.PerlMakefileParser; */ public class PerlModel { - private static final String FIX_ME = "#FIXME"; - - private static final String LICENSE_REQ = "GPL+ or Artistic"; - private static final String CPAN_URL = "http://search.cpan.org/dist/"; - - private static final String ABSTRACT = "abstract"; - private static final String REQUIRES = "prereq_pm"; - - private PerlMakefileParser perlMakefileParser; - - /** - * Perl makefile - * - * @param file - * The Perl makefile - */ - public PerlModel(IFile file) { - try { - perlMakefileParser = new PerlMakefileParser(file); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (CoreException e) { - StubbyLog.logError(e); - } - } - - /** - * Get the value from one of the makefile attributes. If the value is empty, it - * will return #FIXME - * - * @param key - * The makefile attribute to get value of - * @return The value of the option - */ - private String getValue(String key) { - String rc = perlMakefileParser.getValue(key); - if (rc.isEmpty()) { - rc = FIX_ME; - } - return rc; - } - - /** - * Get the install requires in the makefile - * - * @return A list of the values taken from the makefile - */ - public List<String> getInstallRequires() { - List<String> rc = new ArrayList<>(); - List<String> temp = perlMakefileParser.getValueList(REQUIRES); - String ver = ""; - if (!temp.isEmpty()) { - for (String str : temp) { - ver = str.substring(str.indexOf("=>")+2, str.length()); - str = str.substring(0, str.indexOf("=>")); - str = str.replaceAll("(\\S+)", "perl($1)"); - if (!ver.isEmpty() && hasDigits(ver)) { - str = str.concat(">= " + ver); - } - rc.add(str); - ver = ""; - } - } - return rc; - } - - /** - * Returns the package name. - * - * @return The package name. - */ - public String getSimplePackageName() { - String rc = ""; - rc = getValue(CommonMetaData.NAME); - if (!rc.equals(FIX_ME)) { - rc = rc.replaceAll("::", "-"); - } - return rc; - } - - /** - * The simple package name with "perl-" prepended to make better RPM - * package name. - * - * @return The package - */ - public String getPackageName() { - String simpleName = getSimplePackageName(); - if (simpleName.startsWith("perl-")) { - return simpleName; - } - return "perl-"+simpleName; - } - - /** - * Returns the version - * - * @return The version - */ - public String getVersion() { - String version = getValue(CommonMetaData.VERSION); - if (!hasDigits(version)) { - version = "1 " + FIX_ME; - } - return version; - } - - /** - * Utility method to try and see if a string contains digits within it - * - * @param str - * The string to check if it has digits - * @return True if string contains digits - */ - public boolean hasDigits(String str) { - return str.matches(".*\\d.*"); - } - - /** - * Returns the summary - * - * @return The package summary - */ - public String getSummary() { - return getValue(ABSTRACT); - } - - /** - * Returns the license - * - * @return The license - */ - public String getLicense() { - return LICENSE_REQ; - } - - /** - * Returns the url - * - * @return The url - */ - public String getURL() { - return CPAN_URL+getSimplePackageName(); - } - - /** - * Returns the description - * - * @return The description - */ - public String getDescription() { - return getValue(ABSTRACT); - } + private static final String FIX_ME = "#FIXME"; + + private static final String LICENSE_REQ = "GPL+ or Artistic"; + private static final String CPAN_URL = "http://search.cpan.org/dist/"; + + private static final String ABSTRACT = "abstract"; + private static final String REQUIRES = "prereq_pm"; + + private PerlMakefileParser perlMakefileParser; + + /** + * Perl makefile + * + * @param file + * The Perl makefile + */ + public PerlModel(IFile file) { + try { + perlMakefileParser = new PerlMakefileParser(file); + } catch (IOException e) { + StubbyLog.logError(e); + } catch (CoreException e) { + StubbyLog.logError(e); + } + } + + /** + * Get the value from one of the makefile attributes. If the value is empty, it + * will return #FIXME + * + * @param key + * The makefile attribute to get value of + * @return The value of the option + */ + private String getValue(String key) { + String rc = perlMakefileParser.getValue(key); + if (rc.isEmpty()) { + rc = FIX_ME; + } + return rc; + } + + /** + * Get the install requires in the makefile + * + * @return A list of the values taken from the makefile + */ + public List<String> getInstallRequires() { + List<String> rc = new ArrayList<>(); + List<String> temp = perlMakefileParser.getValueList(REQUIRES); + String ver = ""; + if (!temp.isEmpty()) { + for (String str : temp) { + ver = str.substring(str.indexOf("=>")+2, str.length()); + str = str.substring(0, str.indexOf("=>")); + str = str.replaceAll("(\\S+)", "perl($1)"); + if (!ver.isEmpty() && hasDigits(ver)) { + str = str.concat(">= " + ver); + } + rc.add(str); + ver = ""; + } + } + return rc; + } + + /** + * Returns the package name. + * + * @return The package name. + */ + public String getSimplePackageName() { + String rc = ""; + rc = getValue(CommonMetaData.NAME); + if (!rc.equals(FIX_ME)) { + rc = rc.replaceAll("::", "-"); + } + return rc; + } + + /** + * The simple package name with "perl-" prepended to make better RPM + * package name. + * + * @return The package + */ + public String getPackageName() { + String simpleName = getSimplePackageName(); + if (simpleName.startsWith("perl-")) { + return simpleName; + } + return "perl-"+simpleName; + } + + /** + * Returns the version + * + * @return The version + */ + public String getVersion() { + String version = getValue(CommonMetaData.VERSION); + if (!hasDigits(version)) { + version = "1 " + FIX_ME; + } + return version; + } + + /** + * Utility method to try and see if a string contains digits within it + * + * @param str + * The string to check if it has digits + * @return True if string contains digits + */ + public boolean hasDigits(String str) { + return str.matches(".*\\d.*"); + } + + /** + * Returns the summary + * + * @return The package summary + */ + public String getSummary() { + return getValue(ABSTRACT); + } + + /** + * Returns the license + * + * @return The license + */ + public String getLicense() { + return LICENSE_REQ; + } + + /** + * Returns the url + * + * @return The url + */ + public String getURL() { + return CPAN_URL+getSimplePackageName(); + } + + /** + * Returns the description + * + * @return The description + */ + public String getDescription() { + return getValue(ABSTRACT); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PomModel.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PomModel.java index 9b46bc6272..c248d518e8 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PomModel.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/model/PomModel.java @@ -28,121 +28,121 @@ import org.w3c.dom.NodeList; */ public class PomModel { - private Document docroot; - private XPath xpath; + private Document docroot; + private XPath xpath; - /** - * Instantiates the model with the given XML document and preparing the - * XPath evaluation environment. - * - * @param docroot - * The document to query. - */ - public PomModel(Document docroot) { - this.docroot = docroot; - xpath = XPathFactory.newInstance().newXPath(); - } + /** + * Instantiates the model with the given XML document and preparing the + * XPath evaluation environment. + * + * @param docroot + * The document to query. + */ + public PomModel(Document docroot) { + this.docroot = docroot; + xpath = XPathFactory.newInstance().newXPath(); + } - /** - * Returns the proposed package name. - * - * @return The proposed package name. - */ - public String getPackageName() { - return xpathEval("/project/artifactId"); - } + /** + * Returns the proposed package name. + * + * @return The proposed package name. + */ + public String getPackageName() { + return xpathEval("/project/artifactId"); + } - /** - * Returns the summary (xpath:/project/name). Maven project name is verbose - * and it corresponds to the RPM specfile Summary tag. - * - * @return The summary. - */ - public String getSummary() { - return xpathEval("/project/name"); - } + /** + * Returns the summary (xpath:/project/name). Maven project name is verbose + * and it corresponds to the RPM specfile Summary tag. + * + * @return The summary. + */ + public String getSummary() { + return xpathEval("/project/name"); + } - /** - * Returns the project version (xpath:/project/version) or the parent version if - * version is not present. - * - * @return The version. - */ - public String getVersion() { - String version = xpathEval("/project/version"); - if (version.equals("")) { - version = xpathEval("/project/parent/version"); - } - return version; - } + /** + * Returns the project version (xpath:/project/version) or the parent version if + * version is not present. + * + * @return The version. + */ + public String getVersion() { + String version = xpathEval("/project/version"); + if (version.equals("")) { + version = xpathEval("/project/parent/version"); + } + return version; + } - /** - * Returns the license (xpath:/project/licenses/license/name). - * - * @return The license name. - */ - public String getLicense() { - return xpathEval("/project/licenses/license/name"); - } + /** + * Returns the license (xpath:/project/licenses/license/name). + * + * @return The license name. + */ + public String getLicense() { + return xpathEval("/project/licenses/license/name"); + } - /** - * Returns the URL (xpath:/project/url) or (xpath:/project/organization/url). - * - * @return The project url. - */ - public String getURL() { - String url = xpathEval("/project/url"); - if (url.equals("")) { - url = xpathEval("/project/organization/url"); - } - return url; - } + /** + * Returns the URL (xpath:/project/url) or (xpath:/project/organization/url). + * + * @return The project url. + */ + public String getURL() { + String url = xpathEval("/project/url"); + if (url.equals("")) { + url = xpathEval("/project/organization/url"); + } + return url; + } - /** - * Returns the project description (xpath:/project/description). - * - * @return The project description. - */ - public String getDescription() { - return xpathEval("/project/description"); - } + /** + * Returns the project description (xpath:/project/description). + * + * @return The project description. + */ + public String getDescription() { + return xpathEval("/project/description"); + } - /** - * Returns the dependencies. - * @return All the dependencies. - */ - public Map<String, String> getDependencies() { - Map<String, String> dependencies = new HashMap<>(); - NodeList nodes = xpathEvalNodes("/project/dependencies/dependency"); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - try { - dependencies.put(xpath.evaluate("groupId", node), xpath.evaluate("artifactId", node)); - } catch (XPathExpressionException e) { - // just no deps generated - } - } - return dependencies; - } + /** + * Returns the dependencies. + * @return All the dependencies. + */ + public Map<String, String> getDependencies() { + Map<String, String> dependencies = new HashMap<>(); + NodeList nodes = xpathEvalNodes("/project/dependencies/dependency"); + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + try { + dependencies.put(xpath.evaluate("groupId", node), xpath.evaluate("artifactId", node)); + } catch (XPathExpressionException e) { + // just no deps generated + } + } + return dependencies; + } - private String xpathEval(String path) { - String result = ""; - try { - result = xpath.evaluate(path, docroot); - } catch (XPathExpressionException e) { - // ignore, nothing that can be read - } - return result; - } + private String xpathEval(String path) { + String result = ""; + try { + result = xpath.evaluate(path, docroot); + } catch (XPathExpressionException e) { + // ignore, nothing that can be read + } + return result; + } - private NodeList xpathEvalNodes(String path) { - NodeList result = null; - try { - result = (NodeList) xpath.evaluate(path, docroot, - XPathConstants.NODESET); - } catch (XPathExpressionException e) { - // ignore, nothing that can be read - } - return result; - } + private NodeList xpathEvalNodes(String path) { + NodeList result = null; + try { + result = (NodeList) xpath.evaluate(path, docroot, + XPathConstants.NODESET); + } catch (XPathExpressionException e) { + // ignore, nothing that can be read + } + return result; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/CommonMetaData.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/CommonMetaData.java index ba24dc2999..e616f35f6b 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/CommonMetaData.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/CommonMetaData.java @@ -16,9 +16,9 @@ package org.eclipse.linuxtools.internal.rpmstubby.parser; */ @SuppressWarnings("javadoc") public interface CommonMetaData { - String NAME = "name"; - String DESCRIPTION = "description"; - String VERSION = "version"; - String LICENSE = "license"; - String URL = "url"; + String NAME = "name"; + String DESCRIPTION = "description"; + String VERSION = "version"; + String LICENSE = "license"; + String URL = "url"; } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PerlMakefileParser.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PerlMakefileParser.java index f2269a88f5..c2e028554e 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PerlMakefileParser.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PerlMakefileParser.java @@ -32,626 +32,626 @@ import org.eclipse.linuxtools.internal.rpmstubby.StubbyLog; */ public class PerlMakefileParser { - /* - * Perl Regular Expressions - * - */ - private static final String WHITE_SPACE = "(?:\\s+)"; - private static final String COMMENT = "#.+"; // # comment - private static final String LINE_WITH_COMMENT = "(?:(.*)#.+)"; // line # comment - private static final String VARIABLE_PARAMS = "(?:my|local|our)"; - - private static final String WORD = "(\\b\\w+\\b)"; // variable - private static final String NON_WHITE_SPACE = "(\\S+)"; - private static final String VARIABLE = "(?:" + VARIABLE_PARAMS - + WHITE_SPACE + ")?(?:\\$|@|%)" + WORD + WHITE_SPACE + "?"; // %variable | my $variable | our @variable - private static final String ASSOCIATIVE_KEY = WHITE_SPACE + "?" - + NON_WHITE_SPACE + WHITE_SPACE + "?"; - - private static final String EXCLUDE_SPECIALS = "(?![=~|\\-\\*\\+\\/])"; - private static final String NON_CONDITIONAL = "(?!(?:\\s*if|elsif|unless))"; - private static final String ASSIGNMENT_OPERATOR = "="; - private static final String ASSOCIATIVE_OPERATOR = "=>"; - private static final String SIMPLE_ASSIGNMENT = NON_CONDITIONAL - + WHITE_SPACE + "?" + VARIABLE + "(?:" + ASSIGNMENT_OPERATOR + ")" - + EXCLUDE_SPECIALS + "(?:(.+))"; // %var = value || [1] = [2] - private static final String ASSOCIATIVE_ASSIGNMENT = ASSOCIATIVE_KEY - + ASSOCIATIVE_OPERATOR + "(?:(.+))"; // 'key' => 'value' || [1] => [2] - - private static final String FUNCTION = "\\s*" + WORD - + "*\\s*?\\((.*)\\)\\s*"; // foo(bar) | foo(foo(bar)) | foo() || [1]([2]) - private static final String BEGIN_END = "(?:[^#]*<<END)"; // [CS] test<<END | <<END - private static final String END_END = "^END$"; // [CS] - private static final String BEGIN_BC = "^=(?!cut)[a-z]\\S+(\\s)?\\S+"; // [CS] =test | =test test - private static final String END_BC = "^=cut$"; // [CS] - - private static final String MAKEFILE_FUNCTION_NAME = "WriteMakefile"; - private static final String MAKEFILE_FUNCTION = "^.*" - + MAKEFILE_FUNCTION_NAME + WHITE_SPACE + "?\\(.*$"; - - /* - * A few common opening characters and their closing counterparts - * - */ - private static final Map<Character, Character> SURROUNDING_CHARACTER; - static { - Map<Character, Character> aMap = new HashMap<>(); - aMap.put('[', ']'); - aMap.put('{', '}'); - aMap.put('(', ')'); - aMap.put(']', '['); - aMap.put('}', '{'); - aMap.put(')', '('); - SURROUNDING_CHARACTER = Collections.unmodifiableMap(aMap); - } - - private static final char SQUARE_BRACKET = '['; - private static final char CURLY_BRACKET = '{'; - private static final char ROUND_BRACKET = '('; - - private static final int IN_BRACKETS = 0x00000001; - private static final int MAKE_FUNCTION = 0x00000002; - - private IFile file; - private Map<String, String> mVariableDefinitions; - private Map<String, String> mMakefileDefinitions; - - /** - * Initialize. - * - * @param file - * The perl Makefile. - * @throws CoreException - * Throws CoreException. - * @throws IOException - * Throws IOException. - */ - public PerlMakefileParser(IFile file) throws IOException, CoreException { - mVariableDefinitions = new HashMap<>(); - mMakefileDefinitions = new HashMap<>(); - if (file.getContents().available() <= 0) { - return; - } - this.file = file; - parse(); - } - - /** - * Parse the perl Makefile. - * - */ - public void parse() { - String content = ""; - String line = ""; - try (Scanner variableScanner = new Scanner(file.getContents())) { - grabSimpleDefinitions(cleanUpContent(variableScanner)); - cleanupVariables(mVariableDefinitions); - resolveVariables(mVariableDefinitions); - - /* - * Going through the makefile function's attributes - */ - if (!mVariableDefinitions.containsKey(MAKEFILE_FUNCTION_NAME)) { - return; - } - try (Scanner makefileScanner = new Scanner( - mVariableDefinitions.get(MAKEFILE_FUNCTION_NAME))) { - makefileScanner.useDelimiter("(?<=,)"); - ArrayList<String> makefileList = new ArrayList<>(); - - while (makefileScanner.hasNext()) { - line = makefileScanner.next(); - if (matchesAssociativeAssignment(line)) { - makefileList.add(line); - } else if (!makefileList.isEmpty()) { - makefileList.set(makefileList.size() - 1, makefileList - .get(makefileList.size() - 1).concat(line)); - } - } - - for (String str : makefileList) { - content = content.concat(str + '\n'); - } - grabAssociativeDefinitions(content); - cleanupVariables(mMakefileDefinitions); - resolveVariables(mMakefileDefinitions); - - } - variableScanner.close(); - } catch (CoreException e) { - StubbyLog.logError(e); - } - } - - /** - * Get the value of the variable. - * - * @param key The variable to get the value of. - * @return The value of the variable. - */ - public String getValue(String key) { - String rc = ""; - if (mMakefileDefinitions.containsKey(key)) { - rc = mMakefileDefinitions.get(key); - } - return rc; - } - - /** - * Get the list of values from the variable. - * - * @param key The variable to get the value of. - * @return The list of values from the variable. - */ - public List<String> getValueList(String key) { - List<String> rc = new ArrayList<>(); - String var = ""; - String[] tmp = {}; - if (mMakefileDefinitions.containsKey(key)) { - var = mMakefileDefinitions.get(key); - tmp = var.split(","); - for (String str : tmp) { - str = cleanUpString(str); - rc.add(str); - } - } - return rc; - } - - /** - * Grab the simple key->value pairs from some content. - * - * @param content - * The content to grab the key->value pairs from. - */ - private void grabSimpleDefinitions(String content) { - try (Scanner scanner = new Scanner(content)) { - Stack<Character> brackets = new Stack<>(); - String key = ""; - String value = ""; - String tempVar = ""; - String line = ""; - String[] tmp; - int flags = 0; - - while (scanner.hasNext()) { - line = scanner.nextLine(); - if (matchesSimpleAssignment(line)) { - tmp = line.split("="); - key = removeVariableSigils(tmp[0]).toLowerCase() - .replaceAll("\\W", ""); - value = tmp[1]; - if (containsOpener(value)) { - flags |= IN_BRACKETS; - } else { - mVariableDefinitions.put(key, value); - } - } else if (containsMakefileFunction(line)) { - flags |= MAKE_FUNCTION; - flags |= IN_BRACKETS; - } - if ((flags & IN_BRACKETS) == IN_BRACKETS) { - checkBrackets(brackets, line); - tempVar = tempVar.concat(line.trim()); - if (brackets.isEmpty()) { - if ((flags & MAKE_FUNCTION) == MAKE_FUNCTION) { - mVariableDefinitions - .putAll(extractFunction(tempVar)); - } else { - tmp = tempVar.split("=[^>]"); - key = removeVariableSigils(tmp[0]).toLowerCase() - .replaceAll("\\W", ""); - value = tmp[1]; - mVariableDefinitions.put(key, value); - } - tempVar = ""; - flags &= 0; - } - } - } - } - } - - /** - * Grab the associative key=>value pairs from some content. - * - * @param content - * The content to grab the key=>value pairs from. - */ - private void grabAssociativeDefinitions(String content) { - try (Scanner scanner = new Scanner(content)) { - Stack<Character> brackets = new Stack<>(); - String key = ""; - String value = ""; - String tempVar = ""; - String line = ""; - String[] tmp; - int flags = 0; - - while (scanner.hasNext()) { - line = scanner.nextLine(); - if (matchesAssociativeAssignment(line) - && (flags & IN_BRACKETS) != IN_BRACKETS) { - tmp = line.split("=>"); - key = removeVariableSigils(tmp[0].toLowerCase().replaceAll( - "\\W", "")); - value = tmp[1]; - if (containsOpener(value)) { - flags |= IN_BRACKETS; - } else { - mMakefileDefinitions.put(key, value); - } - } - if ((flags & IN_BRACKETS) == IN_BRACKETS) { - checkBrackets(brackets, line); - tempVar = tempVar.concat(line.trim()); - if (brackets.isEmpty()) { - key = removeVariableSigils(tempVar - .substring(0, tempVar.indexOf("=>")) - .toLowerCase().replaceAll("\\W", "")); - value = tempVar.substring(tempVar.indexOf("=>") + 2, - tempVar.length()); - mMakefileDefinitions.put(key, value); - tempVar = ""; - flags &= 0; - } - } - } - } - } - - /** - * Check if the line is within a set of brackets. Update the stack tracking - * bracket completeness. - * - * @param brackets - * The stack tracking the bracket completeness. - * @param line - * The line to parse for brackets. - */ - public static void checkBrackets(Stack<Character> brackets, String line) { - for (char c : line.toCharArray()) { - if (c == SQUARE_BRACKET || c == CURLY_BRACKET || c == ROUND_BRACKET) { - brackets.push(c); - } else if (c == SURROUNDING_CHARACTER.get(SQUARE_BRACKET) - || c == SURROUNDING_CHARACTER.get(CURLY_BRACKET) - || c == SURROUNDING_CHARACTER.get(ROUND_BRACKET)) { - if (brackets.peek() == SURROUNDING_CHARACTER.get(c) - && !brackets.isEmpty()) { - brackets.pop(); - } - } - } - } - - /** - * Go through the map of key->value pairings and check and see if a key has - * another key as a value. If so, resolve that. - * - * @param variables - * The key->value pairings. - */ - private void resolveVariables(Map<String, String> variables) { - String tempVal = ""; - for (Entry<String,String> entry : variables.entrySet()) { - tempVal = entry.getValue(); - if (mVariableDefinitions.containsKey(tempVal)) { - variables.put(entry.getKey(), mVariableDefinitions.get(tempVal)); - } - } - } - - /** - * Extract the function name and the contents of the function and return it - * as a key->value pairing. - * - * @param line - * The line to extract the function from. - * @return The key->value pairing of function and parameter(s). - */ - public static Map<String, String> extractFunction(String line) { - Map<String, String> rc = new HashMap<>(); - Pattern pattern = Pattern.compile(FUNCTION, Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.find()) { - rc.put(variableMatcher.group(1), variableMatcher.group(2)); - } - return rc; - } - - /** - * Extract the key->value pairing from an associative assignment. - * - * @param line - * The line to extract the function from. - * @return The key->value pairing of function and parameter(s). - */ - public static Map<String, String> extractKeyValueAssociation(String line) { - Map<String, String> rc = new HashMap<>(); - String[] keyValue = {}; - String key = ""; - String value = ""; - if (matchesAssociativeAssignment(line)) { - keyValue = line.split("=>"); - key = cleanUpString(keyValue[0].toLowerCase()); - value = cleanUpString(keyValue[1]); - rc.put(key, value); - } - return rc; - } - - /** - * Utility to go through the map of variables to clean up their values. - * - * @param variables - * The map of variables to go through. - */ - private static void cleanupVariables(Map<String, String> variables) { - String val = ""; - for (Entry<String,String> entry : variables.entrySet()) { - val = cleanUpString(removeVariableSigils(entry.getValue())) - .trim(); - if (val.startsWith("(") || val.startsWith("[") - || val.startsWith("{")) { - val = val.substring(1, val.length()); - } - if (val.endsWith(")") || val.endsWith("]") || val.endsWith("}")) { - val = val.substring(0, val.length() - 1); - } - val = cleanUpString(val); - variables.put(entry.getKey(), val); - } - } - - /** - * Utility to clean up the line of some unwanted characters. - * - * @param line - * The line to clean up. - * @return The cleaned up version of the line. - */ - private static String cleanUpString(String line) { - String rc = ""; - line = line.trim().replaceAll("('|\")", ""); - if (line.endsWith(";")) { - line = line.substring(0, line.length() - 1); - } - if (line.endsWith(",")) { - line = line.substring(0, line.length() - 1); - } - rc = line; - return rc; - } - - /** - * Remove the variable sigils. - * - * @param variable - * The variable to remove sigils from. - * @return A word only variable with no sigils. - */ - public static String removeVariableSigils(String variable) { - return variable - .replaceAll( - "(\\bmy\\b|\\bour\\b|\\blocal\\b|(\\\\)?\\$|(\\\\)?@|(\\\\)?%)", - ""); - } - - /** - * Clean up the contents of the file and remove all the comments, END - * blocks, and block comments. - * - * @param scanner - * The scanner of the file to be read. - * @return The cleaned up content. - */ - private static String cleanUpContent(Scanner scanner) { - String rc = ""; - String line = ""; - boolean flagEND = true; - boolean flagBC = true; - while (scanner.hasNext()) { - line = scanner.nextLine(); - // ignore lines between ENDS - if (containsBeginEND(line)) { - flagEND = false; - } else if (matchesEndEND(line)) { - line = scanner.nextLine(); - flagEND = true; // true - } - // ignore lines between =someword and =cut - if (matchesBeginBC(line)) { - flagBC = false; - } else if (matchesEndBC(line)) { - line = scanner.nextLine(); - flagBC = true; - } - // remove the comments - if (matchesLineWithComment(line)) { - line = line.replaceAll(COMMENT, ""); - } - // if not empty line or within comment/END block - if (flagEND && flagBC && !line.trim().equals("")) { - rc = rc.concat(line + '\n'); - } - } - return rc; - } - - /** - * Check if a line contains a function. - * - * @param line - * The line to check. - * @return True if the line contains a function. - */ - public static boolean containsFunction(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(FUNCTION, Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.find()) { - rc = true; - } - return rc; - } - - /** - * Check to see if the line contains the WriteMakefile function. - * - * @param line - * The line to check. - * @return True if the line contains the WriteMakefile function. - */ - public static boolean containsMakefileFunction(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(MAKEFILE_FUNCTION, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.find()) { - rc = true; - } - return rc; - } - - /** - * Check to see if the line contains an opening bracket. - * - * @param line - * The line to check. - * @return True if the line contains an opening bracket. - */ - public static boolean containsOpener(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile("(\\(|\\[|\\{)", - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.find()) { - rc = true; - } - return rc; - } - - /** - * Check if a line contains <<END. It is case-sensitive. - * - * @param line - * The line to check. - * @return True if the line contains <<END. - */ - public static boolean containsBeginEND(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(BEGIN_END); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.find()) { - rc = true; - } - return rc; - } - - /** - * Check if a line is a simple assignment of a variable. - * - * @param line - * The line to check. - * @return True if the line is a simple assignment of a variable. - */ - public static boolean matchesSimpleAssignment(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(SIMPLE_ASSIGNMENT, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.matches()) { - rc = true; - } - return rc; - } - - /** - * Check if a line is a simple assignment of a variable. - * - * @param line - * The line to check. - * @return True if the line is a simple assignment of a variable. - */ - public static boolean matchesAssociativeAssignment(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(ASSOCIATIVE_ASSIGNMENT, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.matches()) { - rc = true; - } - return rc; - } - - /** - * Check if a line matches the END. It is case-sensitive. - * - * @param line - * The line to check. - * @return True if the line matches END. - */ - public static boolean matchesEndEND(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(END_END); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.matches()) { - rc = true; - } - return rc; - } - - /** - * Check if a line matches the beginning of a block comment. It is - * case-sensitive. - * - * @param line - * The line to check. - * @return True if the line matches the beginning of a block comment. - */ - public static boolean matchesBeginBC(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(BEGIN_BC); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.matches()) { - rc = true; - } - return rc; - } - - /** - * Check if a line matches the end of a block comment (=cut). It is - * case-sensitive. - * - * @param line - * The line to check. - * @return True if the line matches =cut. - */ - public static boolean matchesEndBC(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(END_BC); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.matches()) { - rc = true; - } - return rc; - } - - /** - * Check if a line matches that of a line with a comment. - * - * @param line - * The line to check. - * @return True if the line matches that of a line with a comment. - */ - public static boolean matchesLineWithComment(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(LINE_WITH_COMMENT, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - if (variableMatcher.matches()) { - rc = true; - } - return rc; - } + /* + * Perl Regular Expressions + * + */ + private static final String WHITE_SPACE = "(?:\\s+)"; + private static final String COMMENT = "#.+"; // # comment + private static final String LINE_WITH_COMMENT = "(?:(.*)#.+)"; // line # comment + private static final String VARIABLE_PARAMS = "(?:my|local|our)"; + + private static final String WORD = "(\\b\\w+\\b)"; // variable + private static final String NON_WHITE_SPACE = "(\\S+)"; + private static final String VARIABLE = "(?:" + VARIABLE_PARAMS + + WHITE_SPACE + ")?(?:\\$|@|%)" + WORD + WHITE_SPACE + "?"; // %variable | my $variable | our @variable + private static final String ASSOCIATIVE_KEY = WHITE_SPACE + "?" + + NON_WHITE_SPACE + WHITE_SPACE + "?"; + + private static final String EXCLUDE_SPECIALS = "(?![=~|\\-\\*\\+\\/])"; + private static final String NON_CONDITIONAL = "(?!(?:\\s*if|elsif|unless))"; + private static final String ASSIGNMENT_OPERATOR = "="; + private static final String ASSOCIATIVE_OPERATOR = "=>"; + private static final String SIMPLE_ASSIGNMENT = NON_CONDITIONAL + + WHITE_SPACE + "?" + VARIABLE + "(?:" + ASSIGNMENT_OPERATOR + ")" + + EXCLUDE_SPECIALS + "(?:(.+))"; // %var = value || [1] = [2] + private static final String ASSOCIATIVE_ASSIGNMENT = ASSOCIATIVE_KEY + + ASSOCIATIVE_OPERATOR + "(?:(.+))"; // 'key' => 'value' || [1] => [2] + + private static final String FUNCTION = "\\s*" + WORD + + "*\\s*?\\((.*)\\)\\s*"; // foo(bar) | foo(foo(bar)) | foo() || [1]([2]) + private static final String BEGIN_END = "(?:[^#]*<<END)"; // [CS] test<<END | <<END + private static final String END_END = "^END$"; // [CS] + private static final String BEGIN_BC = "^=(?!cut)[a-z]\\S+(\\s)?\\S+"; // [CS] =test | =test test + private static final String END_BC = "^=cut$"; // [CS] + + private static final String MAKEFILE_FUNCTION_NAME = "WriteMakefile"; + private static final String MAKEFILE_FUNCTION = "^.*" + + MAKEFILE_FUNCTION_NAME + WHITE_SPACE + "?\\(.*$"; + + /* + * A few common opening characters and their closing counterparts + * + */ + private static final Map<Character, Character> SURROUNDING_CHARACTER; + static { + Map<Character, Character> aMap = new HashMap<>(); + aMap.put('[', ']'); + aMap.put('{', '}'); + aMap.put('(', ')'); + aMap.put(']', '['); + aMap.put('}', '{'); + aMap.put(')', '('); + SURROUNDING_CHARACTER = Collections.unmodifiableMap(aMap); + } + + private static final char SQUARE_BRACKET = '['; + private static final char CURLY_BRACKET = '{'; + private static final char ROUND_BRACKET = '('; + + private static final int IN_BRACKETS = 0x00000001; + private static final int MAKE_FUNCTION = 0x00000002; + + private IFile file; + private Map<String, String> mVariableDefinitions; + private Map<String, String> mMakefileDefinitions; + + /** + * Initialize. + * + * @param file + * The perl Makefile. + * @throws CoreException + * Throws CoreException. + * @throws IOException + * Throws IOException. + */ + public PerlMakefileParser(IFile file) throws IOException, CoreException { + mVariableDefinitions = new HashMap<>(); + mMakefileDefinitions = new HashMap<>(); + if (file.getContents().available() <= 0) { + return; + } + this.file = file; + parse(); + } + + /** + * Parse the perl Makefile. + * + */ + public void parse() { + String content = ""; + String line = ""; + try (Scanner variableScanner = new Scanner(file.getContents())) { + grabSimpleDefinitions(cleanUpContent(variableScanner)); + cleanupVariables(mVariableDefinitions); + resolveVariables(mVariableDefinitions); + + /* + * Going through the makefile function's attributes + */ + if (!mVariableDefinitions.containsKey(MAKEFILE_FUNCTION_NAME)) { + return; + } + try (Scanner makefileScanner = new Scanner( + mVariableDefinitions.get(MAKEFILE_FUNCTION_NAME))) { + makefileScanner.useDelimiter("(?<=,)"); + ArrayList<String> makefileList = new ArrayList<>(); + + while (makefileScanner.hasNext()) { + line = makefileScanner.next(); + if (matchesAssociativeAssignment(line)) { + makefileList.add(line); + } else if (!makefileList.isEmpty()) { + makefileList.set(makefileList.size() - 1, makefileList + .get(makefileList.size() - 1).concat(line)); + } + } + + for (String str : makefileList) { + content = content.concat(str + '\n'); + } + grabAssociativeDefinitions(content); + cleanupVariables(mMakefileDefinitions); + resolveVariables(mMakefileDefinitions); + + } + variableScanner.close(); + } catch (CoreException e) { + StubbyLog.logError(e); + } + } + + /** + * Get the value of the variable. + * + * @param key The variable to get the value of. + * @return The value of the variable. + */ + public String getValue(String key) { + String rc = ""; + if (mMakefileDefinitions.containsKey(key)) { + rc = mMakefileDefinitions.get(key); + } + return rc; + } + + /** + * Get the list of values from the variable. + * + * @param key The variable to get the value of. + * @return The list of values from the variable. + */ + public List<String> getValueList(String key) { + List<String> rc = new ArrayList<>(); + String var = ""; + String[] tmp = {}; + if (mMakefileDefinitions.containsKey(key)) { + var = mMakefileDefinitions.get(key); + tmp = var.split(","); + for (String str : tmp) { + str = cleanUpString(str); + rc.add(str); + } + } + return rc; + } + + /** + * Grab the simple key->value pairs from some content. + * + * @param content + * The content to grab the key->value pairs from. + */ + private void grabSimpleDefinitions(String content) { + try (Scanner scanner = new Scanner(content)) { + Stack<Character> brackets = new Stack<>(); + String key = ""; + String value = ""; + String tempVar = ""; + String line = ""; + String[] tmp; + int flags = 0; + + while (scanner.hasNext()) { + line = scanner.nextLine(); + if (matchesSimpleAssignment(line)) { + tmp = line.split("="); + key = removeVariableSigils(tmp[0]).toLowerCase() + .replaceAll("\\W", ""); + value = tmp[1]; + if (containsOpener(value)) { + flags |= IN_BRACKETS; + } else { + mVariableDefinitions.put(key, value); + } + } else if (containsMakefileFunction(line)) { + flags |= MAKE_FUNCTION; + flags |= IN_BRACKETS; + } + if ((flags & IN_BRACKETS) == IN_BRACKETS) { + checkBrackets(brackets, line); + tempVar = tempVar.concat(line.trim()); + if (brackets.isEmpty()) { + if ((flags & MAKE_FUNCTION) == MAKE_FUNCTION) { + mVariableDefinitions + .putAll(extractFunction(tempVar)); + } else { + tmp = tempVar.split("=[^>]"); + key = removeVariableSigils(tmp[0]).toLowerCase() + .replaceAll("\\W", ""); + value = tmp[1]; + mVariableDefinitions.put(key, value); + } + tempVar = ""; + flags &= 0; + } + } + } + } + } + + /** + * Grab the associative key=>value pairs from some content. + * + * @param content + * The content to grab the key=>value pairs from. + */ + private void grabAssociativeDefinitions(String content) { + try (Scanner scanner = new Scanner(content)) { + Stack<Character> brackets = new Stack<>(); + String key = ""; + String value = ""; + String tempVar = ""; + String line = ""; + String[] tmp; + int flags = 0; + + while (scanner.hasNext()) { + line = scanner.nextLine(); + if (matchesAssociativeAssignment(line) + && (flags & IN_BRACKETS) != IN_BRACKETS) { + tmp = line.split("=>"); + key = removeVariableSigils(tmp[0].toLowerCase().replaceAll( + "\\W", "")); + value = tmp[1]; + if (containsOpener(value)) { + flags |= IN_BRACKETS; + } else { + mMakefileDefinitions.put(key, value); + } + } + if ((flags & IN_BRACKETS) == IN_BRACKETS) { + checkBrackets(brackets, line); + tempVar = tempVar.concat(line.trim()); + if (brackets.isEmpty()) { + key = removeVariableSigils(tempVar + .substring(0, tempVar.indexOf("=>")) + .toLowerCase().replaceAll("\\W", "")); + value = tempVar.substring(tempVar.indexOf("=>") + 2, + tempVar.length()); + mMakefileDefinitions.put(key, value); + tempVar = ""; + flags &= 0; + } + } + } + } + } + + /** + * Check if the line is within a set of brackets. Update the stack tracking + * bracket completeness. + * + * @param brackets + * The stack tracking the bracket completeness. + * @param line + * The line to parse for brackets. + */ + public static void checkBrackets(Stack<Character> brackets, String line) { + for (char c : line.toCharArray()) { + if (c == SQUARE_BRACKET || c == CURLY_BRACKET || c == ROUND_BRACKET) { + brackets.push(c); + } else if (c == SURROUNDING_CHARACTER.get(SQUARE_BRACKET) + || c == SURROUNDING_CHARACTER.get(CURLY_BRACKET) + || c == SURROUNDING_CHARACTER.get(ROUND_BRACKET)) { + if (brackets.peek() == SURROUNDING_CHARACTER.get(c) + && !brackets.isEmpty()) { + brackets.pop(); + } + } + } + } + + /** + * Go through the map of key->value pairings and check and see if a key has + * another key as a value. If so, resolve that. + * + * @param variables + * The key->value pairings. + */ + private void resolveVariables(Map<String, String> variables) { + String tempVal = ""; + for (Entry<String,String> entry : variables.entrySet()) { + tempVal = entry.getValue(); + if (mVariableDefinitions.containsKey(tempVal)) { + variables.put(entry.getKey(), mVariableDefinitions.get(tempVal)); + } + } + } + + /** + * Extract the function name and the contents of the function and return it + * as a key->value pairing. + * + * @param line + * The line to extract the function from. + * @return The key->value pairing of function and parameter(s). + */ + public static Map<String, String> extractFunction(String line) { + Map<String, String> rc = new HashMap<>(); + Pattern pattern = Pattern.compile(FUNCTION, Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.find()) { + rc.put(variableMatcher.group(1), variableMatcher.group(2)); + } + return rc; + } + + /** + * Extract the key->value pairing from an associative assignment. + * + * @param line + * The line to extract the function from. + * @return The key->value pairing of function and parameter(s). + */ + public static Map<String, String> extractKeyValueAssociation(String line) { + Map<String, String> rc = new HashMap<>(); + String[] keyValue = {}; + String key = ""; + String value = ""; + if (matchesAssociativeAssignment(line)) { + keyValue = line.split("=>"); + key = cleanUpString(keyValue[0].toLowerCase()); + value = cleanUpString(keyValue[1]); + rc.put(key, value); + } + return rc; + } + + /** + * Utility to go through the map of variables to clean up their values. + * + * @param variables + * The map of variables to go through. + */ + private static void cleanupVariables(Map<String, String> variables) { + String val = ""; + for (Entry<String,String> entry : variables.entrySet()) { + val = cleanUpString(removeVariableSigils(entry.getValue())) + .trim(); + if (val.startsWith("(") || val.startsWith("[") + || val.startsWith("{")) { + val = val.substring(1, val.length()); + } + if (val.endsWith(")") || val.endsWith("]") || val.endsWith("}")) { + val = val.substring(0, val.length() - 1); + } + val = cleanUpString(val); + variables.put(entry.getKey(), val); + } + } + + /** + * Utility to clean up the line of some unwanted characters. + * + * @param line + * The line to clean up. + * @return The cleaned up version of the line. + */ + private static String cleanUpString(String line) { + String rc = ""; + line = line.trim().replaceAll("('|\")", ""); + if (line.endsWith(";")) { + line = line.substring(0, line.length() - 1); + } + if (line.endsWith(",")) { + line = line.substring(0, line.length() - 1); + } + rc = line; + return rc; + } + + /** + * Remove the variable sigils. + * + * @param variable + * The variable to remove sigils from. + * @return A word only variable with no sigils. + */ + public static String removeVariableSigils(String variable) { + return variable + .replaceAll( + "(\\bmy\\b|\\bour\\b|\\blocal\\b|(\\\\)?\\$|(\\\\)?@|(\\\\)?%)", + ""); + } + + /** + * Clean up the contents of the file and remove all the comments, END + * blocks, and block comments. + * + * @param scanner + * The scanner of the file to be read. + * @return The cleaned up content. + */ + private static String cleanUpContent(Scanner scanner) { + String rc = ""; + String line = ""; + boolean flagEND = true; + boolean flagBC = true; + while (scanner.hasNext()) { + line = scanner.nextLine(); + // ignore lines between ENDS + if (containsBeginEND(line)) { + flagEND = false; + } else if (matchesEndEND(line)) { + line = scanner.nextLine(); + flagEND = true; // true + } + // ignore lines between =someword and =cut + if (matchesBeginBC(line)) { + flagBC = false; + } else if (matchesEndBC(line)) { + line = scanner.nextLine(); + flagBC = true; + } + // remove the comments + if (matchesLineWithComment(line)) { + line = line.replaceAll(COMMENT, ""); + } + // if not empty line or within comment/END block + if (flagEND && flagBC && !line.trim().equals("")) { + rc = rc.concat(line + '\n'); + } + } + return rc; + } + + /** + * Check if a line contains a function. + * + * @param line + * The line to check. + * @return True if the line contains a function. + */ + public static boolean containsFunction(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(FUNCTION, Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.find()) { + rc = true; + } + return rc; + } + + /** + * Check to see if the line contains the WriteMakefile function. + * + * @param line + * The line to check. + * @return True if the line contains the WriteMakefile function. + */ + public static boolean containsMakefileFunction(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(MAKEFILE_FUNCTION, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.find()) { + rc = true; + } + return rc; + } + + /** + * Check to see if the line contains an opening bracket. + * + * @param line + * The line to check. + * @return True if the line contains an opening bracket. + */ + public static boolean containsOpener(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile("(\\(|\\[|\\{)", + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.find()) { + rc = true; + } + return rc; + } + + /** + * Check if a line contains <<END. It is case-sensitive. + * + * @param line + * The line to check. + * @return True if the line contains <<END. + */ + public static boolean containsBeginEND(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(BEGIN_END); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.find()) { + rc = true; + } + return rc; + } + + /** + * Check if a line is a simple assignment of a variable. + * + * @param line + * The line to check. + * @return True if the line is a simple assignment of a variable. + */ + public static boolean matchesSimpleAssignment(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(SIMPLE_ASSIGNMENT, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.matches()) { + rc = true; + } + return rc; + } + + /** + * Check if a line is a simple assignment of a variable. + * + * @param line + * The line to check. + * @return True if the line is a simple assignment of a variable. + */ + public static boolean matchesAssociativeAssignment(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(ASSOCIATIVE_ASSIGNMENT, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.matches()) { + rc = true; + } + return rc; + } + + /** + * Check if a line matches the END. It is case-sensitive. + * + * @param line + * The line to check. + * @return True if the line matches END. + */ + public static boolean matchesEndEND(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(END_END); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.matches()) { + rc = true; + } + return rc; + } + + /** + * Check if a line matches the beginning of a block comment. It is + * case-sensitive. + * + * @param line + * The line to check. + * @return True if the line matches the beginning of a block comment. + */ + public static boolean matchesBeginBC(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(BEGIN_BC); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.matches()) { + rc = true; + } + return rc; + } + + /** + * Check if a line matches the end of a block comment (=cut). It is + * case-sensitive. + * + * @param line + * The line to check. + * @return True if the line matches =cut. + */ + public static boolean matchesEndBC(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(END_BC); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.matches()) { + rc = true; + } + return rc; + } + + /** + * Check if a line matches that of a line with a comment. + * + * @param line + * The line to check. + * @return True if the line matches that of a line with a comment. + */ + public static boolean matchesLineWithComment(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(LINE_WITH_COMMENT, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + if (variableMatcher.matches()) { + rc = true; + } + return rc; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PythonEggParser.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PythonEggParser.java index 77e9364269..2134a81272 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PythonEggParser.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/PythonEggParser.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.linuxtools.internal.rpmstubby.parser; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; @@ -31,353 +30,351 @@ import org.eclipse.linuxtools.internal.rpmstubby.StubbyLog; */ public class PythonEggParser { - private Map<String, String> variables; - private Map<String, String> setupOptions; - private IFile file; - - /** - * Initialize and then parse the file - * - * @param file The Python setup.py file - * @throws CoreException Throws CoreException - * @throws IOException Throws IOException - */ - public PythonEggParser(IFile file) throws IOException, CoreException { - setupOptions = new HashMap<>(); - variables = new HashMap<>(); - // end if file is empty or cannot get its contents - if (file.getContents().available() <= 0) { - return; - } - this.file = file; - parse(); - } - - /** - * Parse the contents of the Python setup.py file and grab - * variables and meta-data from the setup(...) function - * - */ - public void parse() { - String line = ""; - String setupLine = ""; - List<String> vars = new ArrayList<>(); - List<String> list = new ArrayList<>(); - int offset = 0; - try { - RandomAccessFile raf = new RandomAccessFile(file.getRawLocation().makeAbsolute().toFile(), "r"); - - // end if cannot find setup( - long bytesToSkip = findStartSetup(raf); - if (bytesToSkip == -1) { - return; - } - - // end if the end of setup cannot be found - long stop = findEndSetup(raf, bytesToSkip); - if (stop == -1) { - return; - } - - raf.seek(0); - while ((line = raf.readLine()) != null) { - if (!line.trim().startsWith("#")) { - if (isLineSimpleDefinition(line)) { - vars.add(line); - } else if (!vars.isEmpty() && vars.get(vars.size()-1).trim().endsWith("\\") && isLineContinuation(line)){ - offset = vars.get(vars.size()-1).lastIndexOf('\\'); - vars.set(vars.size() -1, vars.get(vars.size() - 1).substring(0, offset)); - vars.set(vars.size() - 1, vars.get(vars.size() - 1) - .concat(line.trim())); - } - } - } - - raf.seek(bytesToSkip); - while ((line = raf.readLine()) != null && raf.getFilePointer() <= stop) { - line = line.trim(); - if (!line.startsWith("#")) { - if (setupLine.equals("")) { - setupLine = line.trim(); - } else { - setupLine = setupLine.concat(line.trim()); - } - } - } - - list = prepareSetupOptions(setupLine); - - for (String str : vars) { - variables.putAll(parseLine(str)); - } - - for (String str : list) { - setupOptions.putAll(parseLine(str)); - } - - resolveVariables(variables, setupOptions); - - raf.close(); - } catch (FileNotFoundException e) { - StubbyLog.logError(e); - } catch (IOException e) { - StubbyLog.logError(e); - } - } - - /** - * Check to see if the string passed in is a function - * - * @param str The string to check - * @return True if the string matches the function regex - */ - public boolean checkFunction(String str) { - boolean rc = false; - Pattern pattern = Pattern.compile("\\s*\\w*\\s*?\\(.*\\)\\s*"); - Matcher variableMatcher = pattern.matcher(str); - - if (variableMatcher.matches()) { - rc = true; - } - - return rc; - } - - /** - * Get the value of the variable - * - * @param key The variable to get the value of - * @return The value of the variable - */ - public String getValue(String key) { - String rc = ""; - Pattern pattern = Pattern.compile("\\s*\\((.+)\\)\\s*"); - Matcher variableMatcher = null; - - if (setupOptions.containsKey(key)) { - rc = setupOptions.get(key).replaceAll("('|\")", "").trim(); - variableMatcher = pattern.matcher(rc); - if (variableMatcher.matches()) { - rc = variableMatcher.group(1); - } - } - - return rc; - } - - /** - * Get the list of strings for a key. - * Use with classifiers, platforms, install_requires, etc. - * - * @param key The variable to get the value of - * @return The value of the variable - */ - public List<String> getValueList(String key) { - List<String> rc = new ArrayList<>(); - Pattern pattern = Pattern.compile("^\\[(.*)\\]"); - String[] temp = {}; - - if (setupOptions.containsKey(key)) { - Matcher variableMatcher = pattern.matcher(setupOptions.get(key).trim()); - if (variableMatcher.find()) { - temp = variableMatcher.group(1).replaceAll("('|\")", "").split(","); - for (String str : temp) { - if (!str.isEmpty() && !str.trim().startsWith("#")) { - rc.add(str.trim()); - } - } - } - } - - return rc; - } - - /** - * Prepare the setup options by returning each comma delimited option - * - * @param setupLine The single string containing all the setup options - * @return A list of setup options - */ - private static List<String> prepareSetupOptions(String setupLine) { - List<String> rc = new ArrayList<>(); - String[] tempList = {}; - // match the setup(...) pattern - Pattern pattern = Pattern.compile("\\bsetup\\b(\\s+)?\\((.*)\\)"); - Matcher variableMatcher = pattern.matcher(setupLine); - - if (variableMatcher.find()) { - setupLine = variableMatcher.group(2); - } - - tempList = setupLine.split("(?=,)"); - - for (String str : tempList) { - if (isOptionLineKeyValuePair(str) && !str.trim().startsWith("#")) { - if (str.startsWith(",")) { - str = str.substring(1, str.length()).trim(); - } - rc.add(str); - } else if (!str.trim().startsWith("#") && !rc.isEmpty()) { - rc.set(rc.size() - 1, rc.get(rc.size() - 1).concat(str.trim())); - } - } - - return rc; - } - - /** - * Resolves the setup option variables if they are referencing a - * define from outside the setup() function. - * - * @param variables The variables outside the setup() function - * @param options The options to be resolved within the setup() function - */ - private static void resolveVariables(Map<String, String> variables, Map<String, String> options) { - for (Entry<String, String> entry : options.entrySet()) { - if (variables.containsKey(entry.getValue())) { - options.put(entry.getKey(), variables.get(entry.getValue())); - } - } - } - - /** - * Check to see if the line in setup option is a new key->value pair - * - * @param line Line to check - * @return True if the line contains a key->value - */ - private static boolean isOptionLineKeyValuePair(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile("(\\w+)(\\s+)?=[^=].*"); - Matcher variableMatcher = pattern.matcher(line.toLowerCase()); - - if (variableMatcher.find()) { - rc = true; - } - - return rc; - } - - /** - * Check to see if the line is a simple variable declaration (var=value) - * - * @param line Line to check - * @return True if it is a simple variable declaration - */ - private static boolean isLineSimpleDefinition(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile("^(\\w+)(\\s+)?=(\\s+)?"); - Matcher variableMatcher = pattern.matcher(line.toLowerCase()); - - if (variableMatcher.find()) { - rc = true; - } - - return rc; - } - - /** - * Check to see if the line is a continuation from the previous. - * It is a continuation from the previous if it starts - * with a ' or " - * - * @param line Line to check - * @return True if the line is a continuation - */ - private static boolean isLineContinuation(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(".*[\'\"](/s+)?$"); - Matcher variableMatcher = pattern.matcher(line.toLowerCase()); - - if (variableMatcher.find()) { - rc = true; - } - - return rc; - } - - /** - * Parse the line and split it into a key->value pair - * - * @param line The line to be parsed - * @return The map containing the key->value pair - */ - private static Map<String, String> parseLine(String line) { - Map<String, String> rc = new HashMap<>(); - Pattern pattern = Pattern.compile("(\\s+)?(\\w+)(\\s+)?=(\\s+)?(.*)"); - Matcher variableMatcher = pattern.matcher(line); - - if (variableMatcher.find()) { - String value = variableMatcher.group(5); - if (value.charAt(value.length()-1) == ',') { - value = value.substring(0, value.length()-1); - } - rc.put(variableMatcher.group(2), value); - } - - return rc; - } - - /** - * Find the offset of when setup(...) starts - * - * @param reader The file reader - * @return The position of the start of setup(... - * @throws IOException - */ - private static long findStartSetup(RandomAccessFile reader) throws IOException { - long rc = -1; - long previous = 0; - Pattern pattern = Pattern.compile("^\\bsetup\\b(\\s+)?(\\()?"); - Matcher variableMatcher = null; - String line = ""; - - reader.seek(0); - while ((line = reader.readLine()) != null && rc == -1) { - variableMatcher = pattern.matcher(line.toLowerCase()); - if (variableMatcher.find()) { - // get the previous line's file pointer location - rc = previous; - } - previous = reader.getFilePointer(); - } - - return rc; - } - - /** - * Find the offset of when setup(...) ends based on the - * position AFTER the closing bracket of setup() - * - * @param reader The file reader - * @param startPosition The position of the start of setup(... - * @return The position of the end of setup ...) - * @throws IOException - */ - private static long findEndSetup(RandomAccessFile reader, long startPosition) throws IOException { - int bracketCounter = 0; - boolean flag = false; - boolean stop = false; - String line = ""; - - reader.seek(startPosition); - while ((line = reader.readLine()) != null && stop == false) { - for (char x : line.toCharArray()) { - if (x == '(') { - bracketCounter++; - } else if (x == ')') { - bracketCounter--; - } - if (flag && bracketCounter == 0) { - stop = true; - } - // prevent ending prematurely - if (bracketCounter != 0) { - flag = true; - } - } - } - - return reader.getFilePointer(); - } + private Map<String, String> variables; + private Map<String, String> setupOptions; + private IFile file; + + /** + * Initialize and then parse the file + * + * @param file The Python setup.py file + * @throws CoreException Throws CoreException + * @throws IOException Throws IOException + */ + public PythonEggParser(IFile file) throws IOException, CoreException { + setupOptions = new HashMap<>(); + variables = new HashMap<>(); + // end if file is empty or cannot get its contents + if (file.getContents().available() <= 0) { + return; + } + this.file = file; + parse(); + } + + /** + * Parse the contents of the Python setup.py file and grab + * variables and meta-data from the setup(...) function + * + */ + public void parse() { + String line = ""; + String setupLine = ""; + List<String> vars = new ArrayList<>(); + List<String> list = new ArrayList<>(); + int offset = 0; + try { + RandomAccessFile raf = new RandomAccessFile(file.getRawLocation().makeAbsolute().toFile(), "r"); + + // end if cannot find setup( + long bytesToSkip = findStartSetup(raf); + if (bytesToSkip == -1) { + return; + } + + // end if the end of setup cannot be found + long stop = findEndSetup(raf, bytesToSkip); + if (stop == -1) { + return; + } + + raf.seek(0); + while ((line = raf.readLine()) != null) { + if (!line.trim().startsWith("#")) { + if (isLineSimpleDefinition(line)) { + vars.add(line); + } else if (!vars.isEmpty() && vars.get(vars.size()-1).trim().endsWith("\\") && isLineContinuation(line)){ + offset = vars.get(vars.size()-1).lastIndexOf('\\'); + vars.set(vars.size() -1, vars.get(vars.size() - 1).substring(0, offset)); + vars.set(vars.size() - 1, vars.get(vars.size() - 1) + .concat(line.trim())); + } + } + } + + raf.seek(bytesToSkip); + while ((line = raf.readLine()) != null && raf.getFilePointer() <= stop) { + line = line.trim(); + if (!line.startsWith("#")) { + if (setupLine.equals("")) { + setupLine = line.trim(); + } else { + setupLine = setupLine.concat(line.trim()); + } + } + } + + list = prepareSetupOptions(setupLine); + + for (String str : vars) { + variables.putAll(parseLine(str)); + } + + for (String str : list) { + setupOptions.putAll(parseLine(str)); + } + + resolveVariables(variables, setupOptions); + + raf.close(); + } catch (IOException e) { + StubbyLog.logError(e); + } + } + + /** + * Check to see if the string passed in is a function + * + * @param str The string to check + * @return True if the string matches the function regex + */ + public boolean checkFunction(String str) { + boolean rc = false; + Pattern pattern = Pattern.compile("\\s*\\w*\\s*?\\(.*\\)\\s*"); + Matcher variableMatcher = pattern.matcher(str); + + if (variableMatcher.matches()) { + rc = true; + } + + return rc; + } + + /** + * Get the value of the variable + * + * @param key The variable to get the value of + * @return The value of the variable + */ + public String getValue(String key) { + String rc = ""; + Pattern pattern = Pattern.compile("\\s*\\((.+)\\)\\s*"); + Matcher variableMatcher = null; + + if (setupOptions.containsKey(key)) { + rc = setupOptions.get(key).replaceAll("('|\")", "").trim(); + variableMatcher = pattern.matcher(rc); + if (variableMatcher.matches()) { + rc = variableMatcher.group(1); + } + } + + return rc; + } + + /** + * Get the list of strings for a key. + * Use with classifiers, platforms, install_requires, etc. + * + * @param key The variable to get the value of + * @return The value of the variable + */ + public List<String> getValueList(String key) { + List<String> rc = new ArrayList<>(); + Pattern pattern = Pattern.compile("^\\[(.*)\\]"); + String[] temp = {}; + + if (setupOptions.containsKey(key)) { + Matcher variableMatcher = pattern.matcher(setupOptions.get(key).trim()); + if (variableMatcher.find()) { + temp = variableMatcher.group(1).replaceAll("('|\")", "").split(","); + for (String str : temp) { + if (!str.isEmpty() && !str.trim().startsWith("#")) { + rc.add(str.trim()); + } + } + } + } + + return rc; + } + + /** + * Prepare the setup options by returning each comma delimited option + * + * @param setupLine The single string containing all the setup options + * @return A list of setup options + */ + private static List<String> prepareSetupOptions(String setupLine) { + List<String> rc = new ArrayList<>(); + String[] tempList = {}; + // match the setup(...) pattern + Pattern pattern = Pattern.compile("\\bsetup\\b(\\s+)?\\((.*)\\)"); + Matcher variableMatcher = pattern.matcher(setupLine); + + if (variableMatcher.find()) { + setupLine = variableMatcher.group(2); + } + + tempList = setupLine.split("(?=,)"); + + for (String str : tempList) { + if (isOptionLineKeyValuePair(str) && !str.trim().startsWith("#")) { + if (str.startsWith(",")) { + str = str.substring(1, str.length()).trim(); + } + rc.add(str); + } else if (!str.trim().startsWith("#") && !rc.isEmpty()) { + rc.set(rc.size() - 1, rc.get(rc.size() - 1).concat(str.trim())); + } + } + + return rc; + } + + /** + * Resolves the setup option variables if they are referencing a + * define from outside the setup() function. + * + * @param variables The variables outside the setup() function + * @param options The options to be resolved within the setup() function + */ + private static void resolveVariables(Map<String, String> variables, Map<String, String> options) { + for (Entry<String, String> entry : options.entrySet()) { + if (variables.containsKey(entry.getValue())) { + options.put(entry.getKey(), variables.get(entry.getValue())); + } + } + } + + /** + * Check to see if the line in setup option is a new key->value pair + * + * @param line Line to check + * @return True if the line contains a key->value + */ + private static boolean isOptionLineKeyValuePair(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile("(\\w+)(\\s+)?=[^=].*"); + Matcher variableMatcher = pattern.matcher(line.toLowerCase()); + + if (variableMatcher.find()) { + rc = true; + } + + return rc; + } + + /** + * Check to see if the line is a simple variable declaration (var=value) + * + * @param line Line to check + * @return True if it is a simple variable declaration + */ + private static boolean isLineSimpleDefinition(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile("^(\\w+)(\\s+)?=(\\s+)?"); + Matcher variableMatcher = pattern.matcher(line.toLowerCase()); + + if (variableMatcher.find()) { + rc = true; + } + + return rc; + } + + /** + * Check to see if the line is a continuation from the previous. + * It is a continuation from the previous if it starts + * with a ' or " + * + * @param line Line to check + * @return True if the line is a continuation + */ + private static boolean isLineContinuation(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(".*[\'\"](/s+)?$"); + Matcher variableMatcher = pattern.matcher(line.toLowerCase()); + + if (variableMatcher.find()) { + rc = true; + } + + return rc; + } + + /** + * Parse the line and split it into a key->value pair + * + * @param line The line to be parsed + * @return The map containing the key->value pair + */ + private static Map<String, String> parseLine(String line) { + Map<String, String> rc = new HashMap<>(); + Pattern pattern = Pattern.compile("(\\s+)?(\\w+)(\\s+)?=(\\s+)?(.*)"); + Matcher variableMatcher = pattern.matcher(line); + + if (variableMatcher.find()) { + String value = variableMatcher.group(5); + if (value.charAt(value.length()-1) == ',') { + value = value.substring(0, value.length()-1); + } + rc.put(variableMatcher.group(2), value); + } + + return rc; + } + + /** + * Find the offset of when setup(...) starts + * + * @param reader The file reader + * @return The position of the start of setup(... + * @throws IOException + */ + private static long findStartSetup(RandomAccessFile reader) throws IOException { + long rc = -1; + long previous = 0; + Pattern pattern = Pattern.compile("^\\bsetup\\b(\\s+)?(\\()?"); + Matcher variableMatcher = null; + String line = ""; + + reader.seek(0); + while ((line = reader.readLine()) != null && rc == -1) { + variableMatcher = pattern.matcher(line.toLowerCase()); + if (variableMatcher.find()) { + // get the previous line's file pointer location + rc = previous; + } + previous = reader.getFilePointer(); + } + + return rc; + } + + /** + * Find the offset of when setup(...) ends based on the + * position AFTER the closing bracket of setup() + * + * @param reader The file reader + * @param startPosition The position of the start of setup(... + * @return The position of the end of setup ...) + * @throws IOException + */ + private static long findEndSetup(RandomAccessFile reader, long startPosition) throws IOException { + int bracketCounter = 0; + boolean flag = false; + boolean stop = false; + String line = ""; + + reader.seek(startPosition); + while ((line = reader.readLine()) != null && stop == false) { + for (char x : line.toCharArray()) { + if (x == '(') { + bracketCounter++; + } else if (x == ')') { + bracketCounter--; + } + if (flag && bracketCounter == 0) { + stop = true; + } + // prevent ending prematurely + if (bracketCounter != 0) { + flag = true; + } + } + } + + return reader.getFilePointer(); + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/RubyGemParser.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/RubyGemParser.java index 12aff68845..c94f1a9428 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/RubyGemParser.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/RubyGemParser.java @@ -24,425 +24,423 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.linuxtools.internal.rpmstubby.StubbyLog; /** - * Class to parse a Ruby gemspec to grab specfile properties - * + * Class to parse a Ruby gemspec to grab specfile properties. */ public class RubyGemParser { - private IFile file; - private String gemVariable; - private Map<String, List<String>> mSetupDefinitions; - private Map<String, ArrayList<String>> mSetupDependencies; - - private static final String SETUP_START = "^gem[:\\.]{1,2}specification[:\\.]{1,2}new(\\s+)?do(\\s+)?\\|(\\s+)?(\\w+)(\\s+)?\\|"; - private static final String STRING = "(?:\\\"([^\\\"]+)\\\"|'([^']+)'|(?:%q|%Q)(?:([^\\w])([^/3].+)[^\\w]))"; // (%q|%Q) "value" | 'value' | {value} - private static final String LIST = "(?!%q|%Q)(?:%w|%W)?(?:([\\W])(.+)[\\W])"; // (%w|%W) [value, value2] | {"value", "value2"} - private static final String STRING_LIST = "(?:\\\"([^\\\"]+)\\\"|'([^']+)')(?:[, ])??"; // "test", "test2" | 'test' 'test2' - private static final String GENERIC_LIST = "(?:\\S+)(?:\\s+)??"; // test, test2 | test test2 - - private static final String REPLACE_ME = "(%REPLACE_ME)"; - private String simpleDefineRx = "(\\s+)?(?!#)(?:\\b(%REPLACE_ME)\\b\\.(\\w+))(\\s+)?=(?!=)(\\s+)?(.*)"; // gem.variable = ... - private String genericDefineRx = "(\\s+)?(?!#)(?:\\b(%REPLACE_ME)\\b\\.(\\w+))(\\s+)?(.*)"; // gem.variable... - private String simpleFunctionRx = "(\\s+)?(?!#)(?:\\b(%REPLACE_ME)\\b\\.(\\w+))(\\s+)?(?:\\((.*)\\))(.*)?"; // gem.variable(...) - - /** - * Initialize - * - * @param file - * The gemspec file - * @throws IOException Could not read from file - * @throws CoreException File is not valid - */ - public RubyGemParser(IFile file) throws IOException, CoreException { - mSetupDefinitions = new HashMap<>(); - mSetupDependencies = new HashMap<>(); - if (file.getContents().available() <= 0) { - return; - } - this.file = file; - gemVariable = ""; - parse(); - } - - /** - * Parse the Ruby gemspec file - * - */ - public void parse() { - List<String> rawSetupDefinitions = new ArrayList<>(); - List<String> lSetupDefinitions = new ArrayList<>(); - String line = ""; - long startPos; - long endPos; - try (RandomAccessFile raf = new RandomAccessFile(file.getRawLocation() - .makeAbsolute().toFile(), "r")) { - startPos = findStart(raf); - endPos = findEnd(raf, startPos); - - raf.seek(startPos); - while ((line = raf.readLine()) != null - && raf.getFilePointer() < endPos) { - rawSetupDefinitions.add(line); - } - - lSetupDefinitions = prepareOptions(rawSetupDefinitions); - - for (String str : lSetupDefinitions) { - parseLine(str); - } - } catch (IOException e) { - StubbyLog.logError(e); - } - } - - /** - * Get the values taken from parsing the file as a list object - * - * @param key - * The gemspec option to get the values for - * @return The values of the gemspec option - */ - public List<String> getValueList(String key) { - List<String> rc = new ArrayList<>(); - - if (mSetupDependencies.containsKey(key)) { - if (!mSetupDependencies.get(key).isEmpty()) { - for (String element : mSetupDependencies.get(key)) { - rc.add(element); - } - } - } else if (mSetupDefinitions.containsKey(key)) { - if (!mSetupDefinitions.get(key).isEmpty()) { - for (String element : mSetupDefinitions.get(key)) { - rc.add(element); - } - } - } - - return rc; - } - - /** - * Parses a line to figure out what type of line it is - * - * @param str - * The line to parse - */ - private void parseLine(String str) { - if (str.matches(simpleDefineRx)) { - parseSimpleDefine(str); - } else if (str.matches(simpleFunctionRx)) { - parseSimpleFunction(str); - } else if (str.matches(genericDefineRx)) { - parseGenericOption(str); - } - } - - /** - * Parses a string to figure its value - * - * @param str - * The string parse - * @return A list of objects that was found - */ - private static List<String> parseValue(String str) { - List<String> rc = new ArrayList<>(); - String temp = str.trim(); - Pattern pattern = null; - Matcher variableMatcher = null; - - if (temp.matches(STRING)) { - pattern = Pattern.compile(STRING, - Pattern.CASE_INSENSITIVE); - variableMatcher = pattern.matcher(temp); - // "" matches group 1 - if (temp.startsWith("\"") && variableMatcher.matches()) { - rc.add(variableMatcher.group(1)); - } // '' matches group 2 - else if (temp.startsWith("'") && variableMatcher.matches()) { - rc.add(variableMatcher.group(2)); - } // %q|%Q match - else if ((temp.startsWith("%q") || temp.startsWith("%Q")) - && variableMatcher.matches()) { - rc.add(variableMatcher.group(4)); - } - } else if (temp.matches(LIST)) { - pattern = Pattern.compile(LIST, - Pattern.CASE_INSENSITIVE); - variableMatcher = pattern.matcher(temp); - if (variableMatcher.matches()) { - rc.addAll(parseList(variableMatcher.group(2))); - } - } - - return rc; - } - - /** - * Parse the long string into a list - * - * @param str - * The string to parse into a list - * @return A list containing the found values - */ - private static List<String> parseList(String str) { - List<String> rc = new ArrayList<>(); - String temp = str.trim(); - Pattern pattern = isPatternFoundList(str); - - if (pattern == null) { - return rc; - } - - Matcher variableMatcher = pattern.matcher(temp); - - if (variableMatcher != null) { - while (variableMatcher.find()) { - rc.add(variableMatcher.group()); - } - } - return rc; - } - - /** - * Check if the string is a list of string values e.g. ["test", "test2"] OR - * ['test' 'test2'] - * - * @param str - * The string containing the list - * @return The pattern of the string - */ - private static Pattern isPatternFoundList(String str) { - Pattern rc = Pattern.compile(""); - Pattern pattern = Pattern.compile(STRING_LIST, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(str); - - if (variableMatcher.find()) { - rc = pattern; - } else { - rc = isGenericFoundList(str); - } - - return rc; - } - - /** - * Check if the string is a list of generic values (non-strings) e.g. [test, - * test2] OR [test test2] - * - * @param str - * The string containing the list - * @return The pattern of the string - */ - private static Pattern isGenericFoundList(String str) { - Pattern rc = Pattern.compile(""); - Pattern pattern = Pattern.compile(GENERIC_LIST, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(str); - - if (variableMatcher.find()) { - rc = pattern; - } - - return rc; - } - - /** - * Parse and grab the value of a simple define. The value taken is anything - * after "gem.variable = ..." - * - * @param str - * The simple define to parse - */ - private void parseSimpleDefine(String str) { - String temp = str.trim(); - Pattern pattern = Pattern.compile(simpleDefineRx, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(temp); - - if (variableMatcher.find()) { - String optionName = variableMatcher.group(2); - List<String> value = parseValue(variableMatcher - .group(5)); - if (!value.isEmpty()) { - mSetupDefinitions.put(optionName, value); - } - } - } - - /** - * Parse and grab the value of a simple function. The value taken is - * anything in "gem.variable(...)" - * - * @param str - * The function to parse - */ - private void parseSimpleFunction(String str) { - String temp = str.trim(); - Pattern pattern = Pattern.compile(simpleFunctionRx, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(temp); - - if (variableMatcher.find()) { - String functionName = variableMatcher.group(2); - ArrayList<String> dependencies = new ArrayList<>(); - dependencies.add(variableMatcher.group(4)); - if (!mSetupDependencies.containsKey(functionName)) { - mSetupDependencies.put(functionName, dependencies); - } else { - if (!mSetupDependencies.get(functionName).containsAll( - dependencies)) { - mSetupDependencies.get(functionName).addAll(dependencies); - } - } - } - } - - /** - * Parse and grab the value of a generic option. The value taken is anything - * after "gem.variable..." - * - * @param str - * The option to parse - */ - private void parseGenericOption(String str) { - String temp = str.trim(); - Pattern pattern = Pattern.compile(genericDefineRx, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(temp); - - if (variableMatcher.find()) { - String functionName = variableMatcher.group(2); - ArrayList<String> dependencies = new ArrayList<>(); - dependencies.add(variableMatcher.group(4)); - if (!mSetupDependencies.containsKey(functionName)) { - mSetupDependencies.put(functionName, dependencies); - } else { - if (!mSetupDependencies.get(functionName).containsAll( - dependencies)) { - mSetupDependencies.get(functionName).addAll(dependencies); - } - } - } - } - - /** - * Prepare the options within the specification by taking multiple lines and - * concatenating them to the option it belongs to - * - * @param list - * The list of options in their raw form - * @return A refined list of options with a single line for each option - */ - private List<String> prepareOptions(List<String> list) { - List<String> rc = new ArrayList<>(); - String temp = ""; - - for (String str : list) { - temp = str.trim(); - if (isLineValidOption(temp)) { - rc.add(str); - } else if (!temp.startsWith("#") && !rc.isEmpty()) { - rc.set(rc.size() - 1, rc.get(rc.size() - 1).concat(str)); - } - } - - return rc; - } - - /** - * Check to see if the line being read is a valid option within the - * specification - * - * @param line - * The line to check - * @return True if the option within the specification is valid - */ - private boolean isLineValidOption(String line) { - boolean rc = false; - Pattern pattern = Pattern.compile(genericDefineRx, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = pattern.matcher(line); - - if (variableMatcher.matches()) { - rc = true; - } - - return rc; - } - - /** - * Find the offset of when the specification starts and also store the - * gemVariable used in the specification - * - * @param reader - * The file reader - * @return The position of the start of the specification - * @throws IOException - */ - private long findStart(RandomAccessFile raf) throws IOException { - long rc = -1; - Pattern pattern = Pattern - .compile( - SETUP_START, - Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = null; - String line = ""; - - raf.seek(0); - while ((line = raf.readLine()) != null && rc == -1) { - variableMatcher = pattern.matcher(line.trim()); - if (variableMatcher.matches()) { - setGemVariable(variableMatcher.group(4)); - rc = raf.getFilePointer(); - } - } - - return rc; - } - - /** - * Find the offset of when specification ends based on the position before - * the end statement - * - * @param reader - * The file reader - * @param startPosition - * The position of the start of the specification - * @return The position of the end of the specification - * @throws IOException - */ - private static long findEnd(RandomAccessFile raf, long startPos) - throws IOException { - long rc = -1; - Pattern pattern = Pattern.compile("^end", Pattern.CASE_INSENSITIVE); - Matcher variableMatcher = null; - String line = ""; - - raf.seek(startPos); - while ((line = raf.readLine()) != null && rc == -1) { - variableMatcher = pattern.matcher(line.trim()); - if (variableMatcher.matches()) { - rc = raf.getFilePointer(); - } - } - - return rc; - } - - /** - * Sets the gemVariable taken from Gem::Specification.new do |gemVariable| - * - * @param str - * The variable to set the gemVariable as - */ - private void setGemVariable(String str) { - if (gemVariable.isEmpty()) { - gemVariable = str.trim(); - simpleDefineRx = simpleDefineRx.replace(REPLACE_ME, gemVariable); - simpleFunctionRx = simpleFunctionRx.replace(REPLACE_ME, gemVariable); - genericDefineRx = genericDefineRx.replace(REPLACE_ME, gemVariable); - } - } + private IFile file; + private String gemVariable; + private Map<String, List<String>> mSetupDefinitions; + private Map<String, ArrayList<String>> mSetupDependencies; + + private static final String SETUP_START = "^gem[:\\.]{1,2}specification[:\\.]{1,2}new(\\s+)?do(\\s+)?\\|(\\s+)?(\\w+)(\\s+)?\\|"; + private static final String STRING = "(?:\\\"([^\\\"]+)\\\"|'([^']+)'|(?:%q|%Q)(?:([^\\w])([^/3].+)[^\\w]))"; // (%q|%Q) "value" | 'value' | {value} + private static final String LIST = "(?!%q|%Q)(?:%w|%W)?(?:([\\W])(.+)[\\W])"; // (%w|%W) [value, value2] | {"value", "value2"} + private static final String STRING_LIST = "(?:\\\"([^\\\"]+)\\\"|'([^']+)')(?:[, ])??"; // "test", "test2" | 'test' 'test2' + private static final String GENERIC_LIST = "(?:\\S+)(?:\\s+)??"; // test, test2 | test test2 + + private static final String REPLACE_ME = "(%REPLACE_ME)"; + private String simpleDefineRx = "(\\s+)?(?!#)(?:\\b(%REPLACE_ME)\\b\\.(\\w+))(\\s+)?=(?!=)(\\s+)?(.*)"; // gem.variable = ... + private String genericDefineRx = "(\\s+)?(?!#)(?:\\b(%REPLACE_ME)\\b\\.(\\w+))(\\s+)?(.*)"; // gem.variable... + private String simpleFunctionRx = "(\\s+)?(?!#)(?:\\b(%REPLACE_ME)\\b\\.(\\w+))(\\s+)?(?:\\((.*)\\))(.*)?"; // gem.variable(...) + + /** + * Initialize + * + * @param file + * The gemspec file + * @throws IOException Could not read from file + * @throws CoreException File is not valid + */ + public RubyGemParser(IFile file) throws IOException, CoreException { + mSetupDefinitions = new HashMap<>(); + mSetupDependencies = new HashMap<>(); + if (file.getContents().available() <= 0) { + return; + } + this.file = file; + gemVariable = ""; + parse(); + } + + /** + * Parse the Ruby gemspec file + */ + public void parse() { + List<String> rawSetupDefinitions = new ArrayList<>(); + List<String> lSetupDefinitions = new ArrayList<>(); + String line = ""; + long startPos; + long endPos; + try (RandomAccessFile raf = new RandomAccessFile(file.getRawLocation() + .makeAbsolute().toFile(), "r")) { + startPos = findStart(raf); + endPos = findEnd(raf, startPos); + + raf.seek(startPos); + while ((line = raf.readLine()) != null + && raf.getFilePointer() < endPos) { + rawSetupDefinitions.add(line); + } + + lSetupDefinitions = prepareOptions(rawSetupDefinitions); + + for (String str : lSetupDefinitions) { + parseLine(str); + } + } catch (IOException e) { + StubbyLog.logError(e); + } + } + + /** + * Get the values taken from parsing the file as a list object + * + * @param key + * The gemspec option to get the values for + * @return The values of the gemspec option + */ + public List<String> getValueList(String key) { + List<String> rc = new ArrayList<>(); + + if (mSetupDependencies.containsKey(key)) { + if (!mSetupDependencies.get(key).isEmpty()) { + for (String element : mSetupDependencies.get(key)) { + rc.add(element); + } + } + } else if (mSetupDefinitions.containsKey(key)) { + if (!mSetupDefinitions.get(key).isEmpty()) { + for (String element : mSetupDefinitions.get(key)) { + rc.add(element); + } + } + } + + return rc; + } + + /** + * Parses a line to figure out what type of line it is + * + * @param str + * The line to parse + */ + private void parseLine(String str) { + if (str.matches(simpleDefineRx)) { + parseSimpleDefine(str); + } else if (str.matches(simpleFunctionRx)) { + parseSimpleFunction(str); + } else if (str.matches(genericDefineRx)) { + parseGenericOption(str); + } + } + + /** + * Parses a string to figure its value + * + * @param str + * The string parse + * @return A list of objects that was found + */ + private static List<String> parseValue(String str) { + List<String> rc = new ArrayList<>(); + String temp = str.trim(); + Pattern pattern = null; + Matcher variableMatcher = null; + + if (temp.matches(STRING)) { + pattern = Pattern.compile(STRING, + Pattern.CASE_INSENSITIVE); + variableMatcher = pattern.matcher(temp); + // "" matches group 1 + if (temp.startsWith("\"") && variableMatcher.matches()) { + rc.add(variableMatcher.group(1)); + } // '' matches group 2 + else if (temp.startsWith("'") && variableMatcher.matches()) { + rc.add(variableMatcher.group(2)); + } // %q|%Q match + else if ((temp.startsWith("%q") || temp.startsWith("%Q")) + && variableMatcher.matches()) { + rc.add(variableMatcher.group(4)); + } + } else if (temp.matches(LIST)) { + pattern = Pattern.compile(LIST, + Pattern.CASE_INSENSITIVE); + variableMatcher = pattern.matcher(temp); + if (variableMatcher.matches()) { + rc.addAll(parseList(variableMatcher.group(2))); + } + } + + return rc; + } + + /** + * Parse the long string into a list + * + * @param str + * The string to parse into a list + * @return A list containing the found values + */ + private static List<String> parseList(String str) { + List<String> rc = new ArrayList<>(); + String temp = str.trim(); + Pattern pattern = isPatternFoundList(str); + + if (pattern == null) { + return rc; + } + + Matcher variableMatcher = pattern.matcher(temp); + + if (variableMatcher != null) { + while (variableMatcher.find()) { + rc.add(variableMatcher.group()); + } + } + return rc; + } + + /** + * Check if the string is a list of string values e.g. ["test", "test2"] OR + * ['test' 'test2'] + * + * @param str + * The string containing the list + * @return The pattern of the string + */ + private static Pattern isPatternFoundList(String str) { + Pattern rc = Pattern.compile(""); + Pattern pattern = Pattern.compile(STRING_LIST, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(str); + + if (variableMatcher.find()) { + rc = pattern; + } else { + rc = isGenericFoundList(str); + } + + return rc; + } + + /** + * Check if the string is a list of generic values (non-strings) e.g. [test, + * test2] OR [test test2] + * + * @param str + * The string containing the list + * @return The pattern of the string + */ + private static Pattern isGenericFoundList(String str) { + Pattern rc = Pattern.compile(""); + Pattern pattern = Pattern.compile(GENERIC_LIST, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(str); + + if (variableMatcher.find()) { + rc = pattern; + } + + return rc; + } + + /** + * Parse and grab the value of a simple define. The value taken is anything + * after "gem.variable = ..." + * + * @param str + * The simple define to parse + */ + private void parseSimpleDefine(String str) { + String temp = str.trim(); + Pattern pattern = Pattern.compile(simpleDefineRx, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(temp); + + if (variableMatcher.find()) { + String optionName = variableMatcher.group(2); + List<String> value = parseValue(variableMatcher + .group(5)); + if (!value.isEmpty()) { + mSetupDefinitions.put(optionName, value); + } + } + } + + /** + * Parse and grab the value of a simple function. The value taken is + * anything in "gem.variable(...)" + * + * @param str + * The function to parse + */ + private void parseSimpleFunction(String str) { + String temp = str.trim(); + Pattern pattern = Pattern.compile(simpleFunctionRx, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(temp); + + if (variableMatcher.find()) { + String functionName = variableMatcher.group(2); + ArrayList<String> dependencies = new ArrayList<>(); + dependencies.add(variableMatcher.group(4)); + if (!mSetupDependencies.containsKey(functionName)) { + mSetupDependencies.put(functionName, dependencies); + } else { + if (!mSetupDependencies.get(functionName).containsAll( + dependencies)) { + mSetupDependencies.get(functionName).addAll(dependencies); + } + } + } + } + + /** + * Parse and grab the value of a generic option. The value taken is anything + * after "gem.variable..." + * + * @param str + * The option to parse + */ + private void parseGenericOption(String str) { + String temp = str.trim(); + Pattern pattern = Pattern.compile(genericDefineRx, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(temp); + + if (variableMatcher.find()) { + String functionName = variableMatcher.group(2); + ArrayList<String> dependencies = new ArrayList<>(); + dependencies.add(variableMatcher.group(4)); + if (!mSetupDependencies.containsKey(functionName)) { + mSetupDependencies.put(functionName, dependencies); + } else { + if (!mSetupDependencies.get(functionName).containsAll( + dependencies)) { + mSetupDependencies.get(functionName).addAll(dependencies); + } + } + } + } + + /** + * Prepare the options within the specification by taking multiple lines and + * concatenating them to the option it belongs to + * + * @param list + * The list of options in their raw form + * @return A refined list of options with a single line for each option + */ + private List<String> prepareOptions(List<String> list) { + List<String> rc = new ArrayList<>(); + String temp = ""; + + for (String str : list) { + temp = str.trim(); + if (isLineValidOption(temp)) { + rc.add(str); + } else if (!temp.startsWith("#") && !rc.isEmpty()) { + rc.set(rc.size() - 1, rc.get(rc.size() - 1).concat(str)); + } + } + + return rc; + } + + /** + * Check to see if the line being read is a valid option within the + * specification + * + * @param line + * The line to check + * @return True if the option within the specification is valid + */ + private boolean isLineValidOption(String line) { + boolean rc = false; + Pattern pattern = Pattern.compile(genericDefineRx, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = pattern.matcher(line); + + if (variableMatcher.matches()) { + rc = true; + } + + return rc; + } + + /** + * Find the offset of when the specification starts and also store the + * gemVariable used in the specification + * + * @param reader + * The file reader + * @return The position of the start of the specification + * @throws IOException + */ + private long findStart(RandomAccessFile raf) throws IOException { + long rc = -1; + Pattern pattern = Pattern + .compile( + SETUP_START, + Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = null; + String line = ""; + + raf.seek(0); + while ((line = raf.readLine()) != null && rc == -1) { + variableMatcher = pattern.matcher(line.trim()); + if (variableMatcher.matches()) { + setGemVariable(variableMatcher.group(4)); + rc = raf.getFilePointer(); + } + } + + return rc; + } + + /** + * Find the offset of when specification ends based on the position before + * the end statement + * + * @param reader + * The file reader + * @param startPosition + * The position of the start of the specification + * @return The position of the end of the specification + * @throws IOException + */ + private static long findEnd(RandomAccessFile raf, long startPos) + throws IOException { + long rc = -1; + Pattern pattern = Pattern.compile("^end", Pattern.CASE_INSENSITIVE); + Matcher variableMatcher = null; + String line = ""; + + raf.seek(startPos); + while ((line = raf.readLine()) != null && rc == -1) { + variableMatcher = pattern.matcher(line.trim()); + if (variableMatcher.matches()) { + rc = raf.getFilePointer(); + } + } + + return rc; + } + + /** + * Sets the gemVariable taken from Gem::Specification.new do |gemVariable| + * + * @param str + * The variable to set the gemVariable as + */ + private void setGemVariable(String str) { + if (gemVariable.isEmpty()) { + gemVariable = str.trim(); + simpleDefineRx = simpleDefineRx.replace(REPLACE_ME, gemVariable); + simpleFunctionRx = simpleFunctionRx.replace(REPLACE_ME, gemVariable); + genericDefineRx = genericDefineRx.replace(REPLACE_ME, gemVariable); + } + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/ValidLicenses.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/ValidLicenses.java index f5ce306476..39d12e8038 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/ValidLicenses.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/parser/ValidLicenses.java @@ -16,24 +16,24 @@ package org.eclipse.linuxtools.internal.rpmstubby.parser; */ @SuppressWarnings("javadoc") public interface ValidLicenses { - String GPL = "GPL"; - String ARTISTIC = "Artistic"; - String MIT = "MIT"; - String MPL = "MPL"; - String APACHE = "Apache"; - String PUBLIC_DOMAIN = "Public"; - String ZLIB = "zlib"; - String RICOH_SOURCE_CODE = "Ricoh"; - String VOVIDA_SOFTWARE = "Vovida"; - String INTEL_OPEN_SOURCE = "Intel"; - String LGPL = "LGPL"; - String BSD = "BSD"; - String QPL = "QPL"; - String IBM_PUBLIC = "IBM"; - String PHP = "PHP"; - String MODIFIED_CNRI_OPEN_SOURCE = "CNRI"; - String CVW = "CVW"; - String PYTHON = "Python"; - String SUN_INTERNET_STANDARDS_SOURCE = "Sun"; - String JABBER_OPEN_SOURCE = "Jabber"; + String GPL = "GPL"; + String ARTISTIC = "Artistic"; + String MIT = "MIT"; + String MPL = "MPL"; + String APACHE = "Apache"; + String PUBLIC_DOMAIN = "Public"; + String ZLIB = "zlib"; + String RICOH_SOURCE_CODE = "Ricoh"; + String VOVIDA_SOFTWARE = "Vovida"; + String INTEL_OPEN_SOURCE = "Intel"; + String LGPL = "LGPL"; + String BSD = "BSD"; + String QPL = "QPL"; + String IBM_PUBLIC = "IBM"; + String PHP = "PHP"; + String MODIFIED_CNRI_OPEN_SOURCE = "CNRI"; + String CVW = "CVW"; + String PYTHON = "Python"; + String SUN_INTERNET_STANDARDS_SOURCE = "Sun"; + String JABBER_OPEN_SOURCE = "Jabber"; } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyEggHandler.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyEggHandler.java index a3fc90119e..02b2285d18 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyEggHandler.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyEggHandler.java @@ -18,9 +18,9 @@ import org.eclipse.linuxtools.rpmstubby.InputType; */ public class StubifyEggHandler extends StubifyHandler { - @Override - protected InputType getInputType() { - return InputType.PYTHON_EGG; - } + @Override + protected InputType getInputType() { + return InputType.PYTHON_EGG; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyFeatureHandler.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyFeatureHandler.java index 562438cd32..81a2237347 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyFeatureHandler.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyFeatureHandler.java @@ -18,9 +18,9 @@ import org.eclipse.linuxtools.rpmstubby.InputType; */ public class StubifyFeatureHandler extends StubifyHandler { - @Override - protected InputType getInputType() { - return InputType.ECLIPSE_FEATURE; - } + @Override + protected InputType getInputType() { + return InputType.ECLIPSE_FEATURE; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyGemHandler.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyGemHandler.java index 543d4d9702..66df8e0aa1 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyGemHandler.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyGemHandler.java @@ -18,9 +18,9 @@ import org.eclipse.linuxtools.rpmstubby.InputType; */ public class StubifyGemHandler extends StubifyHandler { - @Override - protected InputType getInputType() { - return InputType.RUBY_GEM; - } + @Override + protected InputType getInputType() { + return InputType.RUBY_GEM; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyHandler.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyHandler.java index 63ad7b58c8..b33699e8e1 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyHandler.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyHandler.java @@ -27,28 +27,28 @@ import org.eclipse.ui.handlers.HandlerUtil; */ public abstract class StubifyHandler extends AbstractHandler { - protected abstract InputType getInputType(); + protected abstract InputType getInputType(); - @Override - public Object execute(ExecutionEvent event) { + @Override + public Object execute(ExecutionEvent event) { - IFile featureFile = null; - ISelection selection = HandlerUtil.getCurrentSelection(event); - if (selection instanceof IStructuredSelection) { - for (Object element : ((IStructuredSelection) selection).toList()) { - if (element instanceof IFile) { - featureFile = (IFile) element; - } else if (element instanceof IAdaptable) { - featureFile = (IFile) ((IAdaptable) element) - .getAdapter(IFile.class); - } - if (featureFile != null) { - Generator generator = new Generator(getInputType()); - generator.generate(featureFile); - } - } - } - return null; - } + IFile featureFile = null; + ISelection selection = HandlerUtil.getCurrentSelection(event); + if (selection instanceof IStructuredSelection) { + for (Object element : ((IStructuredSelection) selection).toList()) { + if (element instanceof IFile) { + featureFile = (IFile) element; + } else if (element instanceof IAdaptable) { + featureFile = (IFile) ((IAdaptable) element) + .getAdapter(IFile.class); + } + if (featureFile != null) { + Generator generator = new Generator(getInputType()); + generator.generate(featureFile); + } + } + } + return null; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyMakefilePLHandler.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyMakefilePLHandler.java index 34f61c224c..fa519a495c 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyMakefilePLHandler.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyMakefilePLHandler.java @@ -18,9 +18,9 @@ import org.eclipse.linuxtools.rpmstubby.InputType; */ public class StubifyMakefilePLHandler extends StubifyHandler { - @Override - protected InputType getInputType() { - return InputType.PERL_MAKEFILE; - } + @Override + protected InputType getInputType() { + return InputType.PERL_MAKEFILE; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyPomHandler.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyPomHandler.java index f31bcf97b0..efc3485fa6 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyPomHandler.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/internal/rpmstubby/popup/actions/StubifyPomHandler.java @@ -18,9 +18,9 @@ import org.eclipse.linuxtools.rpmstubby.InputType; */ public class StubifyPomHandler extends StubifyHandler { - @Override - protected InputType getInputType() { - return InputType.MAVEN_POM; - } + @Override + protected InputType getInputType() { + return InputType.MAVEN_POM; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/Generator.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/Generator.java index 9237be6329..f498bb0f0b 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/Generator.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/Generator.java @@ -21,48 +21,48 @@ import org.eclipse.linuxtools.internal.rpmstubby.StubbyPomGenerator; /** * Utility API for stubifying spec files for different input types. - * + * */ public class Generator { - private InputType type; + private InputType type; - /** - * Creates the generator for the given input type. - * - * @param type - * The input type for this generator. - */ - public Generator(InputType type) { - this.type = type; - } + /** + * Creates the generator for the given input type. + * + * @param type + * The input type for this generator. + */ + public Generator(InputType type) { + this.type = type; + } - /** - * Generate the spec file for the given input file. - * - * @param file - * The input file. - */ - public void generate(IFile file) { - switch (type) { - case ECLIPSE_FEATURE: - new StubbyGenerator(file).writeContent(); - break; - case MAVEN_POM: - new StubbyPomGenerator(file).writeContent(); - break; - case PYTHON_EGG: - new StubbyEggGenerator(file).writeContent(); - break; - case RUBY_GEM: - new StubbyGemGenerator(file).writeContent(); - break; - case PERL_MAKEFILE: - new StubbyMakefilePLGenerator(file).writeContent(); - break; - default: - break; - } - } + /** + * Generate the spec file for the given input file. + * + * @param file + * The input file. + */ + public void generate(IFile file) { + switch (type) { + case ECLIPSE_FEATURE: + new StubbyGenerator(file).writeContent(); + break; + case MAVEN_POM: + new StubbyPomGenerator(file).writeContent(); + break; + case PYTHON_EGG: + new StubbyEggGenerator(file).writeContent(); + break; + case RUBY_GEM: + new StubbyGemGenerator(file).writeContent(); + break; + case PERL_MAKEFILE: + new StubbyMakefilePLGenerator(file).writeContent(); + break; + default: + break; + } + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/InputType.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/InputType.java index fffca4aca1..32cc0e656e 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/InputType.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/InputType.java @@ -14,34 +14,34 @@ package org.eclipse.linuxtools.rpmstubby; /** * Supported input types and file name patterns for the corresponding files. - * + * */ public enum InputType { - /** Eclipse feature.xml file. */ - ECLIPSE_FEATURE("feature.xml"), - /** Maven pom.xml file. */ - MAVEN_POM("pom.xml"), - /** Python Egg setup.py file */ - PYTHON_EGG("setup.py"), - /** Ruby *.gemspec file */ - RUBY_GEM("*.gemspec"), - /** Perl Makefile.PL file */ - PERL_MAKEFILE("Makefile.PL"); + /** Eclipse feature.xml file. */ + ECLIPSE_FEATURE("feature.xml"), + /** Maven pom.xml file. */ + MAVEN_POM("pom.xml"), + /** Python Egg setup.py file */ + PYTHON_EGG("setup.py"), + /** Ruby *.gemspec file */ + RUBY_GEM("*.gemspec"), + /** Perl Makefile.PL file */ + PERL_MAKEFILE("Makefile.PL"); - private String fileNamePattern; + private String fileNamePattern; - private InputType(String fileName) { - this.fileNamePattern = fileName; - } + private InputType(String fileName) { + this.fileNamePattern = fileName; + } - /** - * Returns the file name pattern for the input type. - * - * @return The pattern for the file name e.g. feature.xml or pom.xml. - */ - public String getFileNamePattern() { - return fileNamePattern; - } + /** + * Returns the file name pattern for the input type. + * + * @return The pattern for the file name e.g. feature.xml or pom.xml. + */ + public String getFileNamePattern() { + return fileNamePattern; + } } diff --git a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/RPMStubbyUtils.java b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/RPMStubbyUtils.java index 70abf96cc7..01cdd4c832 100644 --- a/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/RPMStubbyUtils.java +++ b/rpm/org.eclipse.linuxtools.rpmstubby/src/org/eclipse/linuxtools/rpmstubby/RPMStubbyUtils.java @@ -34,55 +34,55 @@ import org.xml.sax.SAXException; */ public class RPMStubbyUtils { - private DocumentBuilder builder; - private XPath xPath; - private static final String PARENT_NODE = "/project/parent"; + private DocumentBuilder builder; + private XPath xPath; + private static final String PARENT_NODE = "/project/parent"; - /** - * Constructor. - * - */ - public RPMStubbyUtils() { - DocumentBuilderFactory builderFactory = - DocumentBuilderFactory.newInstance(); - builder = null; - try { - builder = builderFactory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - StubbyLog.logError(e); - } - xPath = XPathFactory.newInstance().newXPath(); - } + /** + * Constructor. + * + */ + public RPMStubbyUtils() { + DocumentBuilderFactory builderFactory = + DocumentBuilderFactory.newInstance(); + builder = null; + try { + builder = builderFactory.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + StubbyLog.logError(e); + } + xPath = XPathFactory.newInstance().newXPath(); + } - /** - * Find the parent pom.xml of a file by recursively checking - * the current directory for the parent pom.xml and moving up - * the directory structure if there is none. - * - * @param folderPath The container of the file to check. - * @return The path of the parent pom. Null otherwise. - */ - public boolean findPom(IPath folderPath) { - IPath filePath = folderPath.append(new Path("pom.xml")); - File file = filePath.toFile(); - boolean rc = false; - if (file.exists()) { - try { - Document xmlDocument = builder.parse(new FileInputStream(file)); - String parent = xPath.compile(PARENT_NODE).evaluate(xmlDocument); - if (!parent.equals("")) { - rc = findPom(folderPath.removeLastSegments(1)); - } else { - rc = true; - } - } catch (SAXException e) { - StubbyLog.logError(e); - } catch (IOException e) { - StubbyLog.logError(e); - } catch (XPathExpressionException e) { - StubbyLog.logError(e); - } - } - return rc; - } + /** + * Find the parent pom.xml of a file by recursively checking + * the current directory for the parent pom.xml and moving up + * the directory structure if there is none. + * + * @param folderPath The container of the file to check. + * @return The path of the parent pom. Null otherwise. + */ + public boolean findPom(IPath folderPath) { + IPath filePath = folderPath.append(new Path("pom.xml")); + File file = filePath.toFile(); + boolean rc = false; + if (file.exists()) { + try { + Document xmlDocument = builder.parse(new FileInputStream(file)); + String parent = xPath.compile(PARENT_NODE).evaluate(xmlDocument); + if (!parent.equals("")) { + rc = findPom(folderPath.removeLastSegments(1)); + } else { + rc = true; + } + } catch (SAXException e) { + StubbyLog.logError(e); + } catch (IOException e) { + StubbyLog.logError(e); + } catch (XPathExpressionException e) { + StubbyLog.logError(e); + } + } + return rc; + } } |