pax_global_header00006660000000000000000000000064120217402640014510gustar00rootroot0000000000000052 comment=26e1b4bd9211b31dee26289a6d2725590f36c7dd polyglot-maven-0.8~tobrien+git20120905/000077500000000000000000000000001202174026400175175ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/.gitignore000066400000000000000000000001151202174026400215040ustar00rootroot00000000000000*.versionsBackup *~ target/ .project .classpath .settings/ pmaven-*-SNAPSHOT polyglot-maven-0.8~tobrien+git20120905/README.md000066400000000000000000000027071202174026400210040ustar00rootroot00000000000000Description ----------- Sonatype [Polyglot Maven](http://polyglot.sonatype.org/). License ------- [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) Support ------- To submit an issue, please use the [Sonatype Issue Tracker](https://issues.sonatype.org/browse/PMAVEN). Building -------- ### Requirements * [Maven](http://maven.apache.org) 2+ * [Java](http://java.sun.com/) 5+ Check-out and build: git clone git://github.com/sonatype/polyglot-maven.git cd polyglot-maven mvn install After this completes, you can unzip and play with polyglot maven: unzip pmaven-cli/target/pmaven-*-bin.zip ./pmaven-*/bin/mvn Polyglot maven includes a copy of maven 3.0.3, which isn't 100% backwards compatible with maven 2.0. Specifically, some maven plugins might not work. Virtually all do however, so it is feasible to move the unzipped directory and put that pmaven-*/bin on your path either inplace of or before your existing mvn binary. There is a translate command that will translate between different language's versions of pom.* (and in the case of Clojure, read (not write) Leiningen's project.clj). It works by looking at file extensions, so just give it a source and a destination file as arguments and it will translate between them. You don't normally have to use translate - the mvn command can read any format the translate command can, either by reading any pom.* it can find or using a command line option e.g. mvn -f project.clj. polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/000077500000000000000000000000001202174026400217435ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/.gitignore000066400000000000000000000001041202174026400237260ustar00rootroot00000000000000target/ .project .classpath .settings/ bin/ pmaven-*-SNAPSHOT *.iml polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/pom.xml000066400000000000000000000025341202174026400232640ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-atom Polyglot Maven :: Atom org.sonatype.pmaven pmaven-common polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/000077500000000000000000000000001202174026400225325ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/000077500000000000000000000000001202174026400234565ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/000077500000000000000000000000001202174026400243775ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/000077500000000000000000000000001202174026400251665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/000077500000000000000000000000001202174026400270305ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400301365ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400320075ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/000077500000000000000000000000001202174026400327475ustar00rootroot00000000000000AtomMapping.java000066400000000000000000000022671202174026400357560ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.atom; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.mapping.Mapping; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** * Atom compact grammar model mapping. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ @Component(role = Mapping.class, hint = "atom") public class AtomMapping extends MappingSupport { public AtomMapping() { super("atom"); setPomNames("pom.atom"); setAcceptLocationExtensions(".atom"); setAcceptOptionKeys("atom:4.0.0"); setPriority(1); } }AtomModelReader.java000066400000000000000000000044601202174026400365430ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.atom; import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.IOUtil; import org.sonatype.maven.polyglot.atom.parsing.AtomParser; import org.sonatype.maven.polyglot.atom.parsing.Project; import org.sonatype.maven.polyglot.atom.parsing.Tokenizer; import org.sonatype.maven.polyglot.execute.ExecuteManager; import org.sonatype.maven.polyglot.io.ModelReaderSupport; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.util.Map; /** * Reads a pom.atom and transforms into a Maven {@link Model}. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ @Component(role = ModelReader.class, hint = "atom") public class AtomModelReader extends ModelReaderSupport { @Requirement protected Logger log; @Requirement private ExecuteManager executeManager; public Model read(final Reader input, final Map options) throws IOException { assert input != null; // Parse the token stream from our pom.atom configuration file. Project project = new AtomParser(new Tokenizer(IOUtil.toString(input)).tokenize()).parse(); Model model = project.toMavenModel(); executeManager.install(model); if (log.isDebugEnabled()) { DefaultModelWriter writer = new DefaultModelWriter(); StringWriter buff = new StringWriter(); writer.write(buff, null, model); log.debug("Read atom model: \n" + buff); } return model; } } AtomModelWriter.java000066400000000000000000000057331202174026400366210ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. // */ package org.sonatype.maven.polyglot.atom; import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Map; /** * TODO fix! */ @Component(role=ModelWriter.class, hint="atom") public class AtomModelWriter extends ModelWriterSupport { @Requirement protected Logger log; public void write(final Writer output, final Map options, final Model model) throws IOException { assert output != null; assert model != null; StringWriter buff = new StringWriter(); DefaultModelWriter writer = new DefaultModelWriter(); writer.write(buff, options, model); // Dom2Groovy converter = new Dom2Groovy(new IndentPrinter(new PrintWriter(output), " ")); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(buff.toString()))); Element root = doc.getDocumentElement(); NamedNodeMap attrs = root.getAttributes(); for (int i=0; iJason Dillon * * @since 0.7 */ public class AtomExecuteTask extends ExecuteTaskSupport { private final Object value; private final Map attrs; public AtomExecuteTask(final Object value, final Map attrs) { this.value = value; this.attrs = attrs; } public Object getValue() { return value; } public Map getAttributes() { return attrs; } public void execute(final ExecuteContext context) throws Exception { System.out.println("Executing atom code..."); } @Override public String toString() { return getClass().getSimpleName() + "{" + "id='" + getId() + '\'' + ", phase='" + getPhase() + '\'' + ", value=" + value + ", attrs=" + attrs + '}'; } }000077500000000000000000000000001202174026400343335ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingAtomParser.java000066400000000000000000000233551202174026400372630ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * Parses the atom token stream into an internal model, which can be emitted * as a Maven model. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class AtomParser { // TODO(dhanji): Replace with proper logging/console out private final Logger log = Logger.getLogger(AtomParser.class.getName()); private final List tokens; // Parser state. (current index) private int i = 0; public AtomParser(List tokens) { this.tokens = tokens; } public Project parse() { chewEols(); Repositories repositories = repositories(); if (null == repositories) { log.warning("No repositories specified in atom file, defaulting to Maven Central."); } chewEols(); Project project = project(repositories); return project; } /** * Parsing rule for a single project build definition. * * project := 'project' STRING AT URL EOL */ private Project project(Repositories repositories) { if (match(Token.Kind.PROJECT) == null) { return null; } List signature = match(Token.Kind.STRING); if (null == signature) { log.severe("Expected string describing project after 'project'."); } String projectDescription = signature.get(0).value; String projectUrl = null; signature = match(Token.Kind.AT, Token.Kind.STRING); if (null != signature) { projectUrl = signature.get(1).value; } if (match(Token.Kind.EOL) == null) { log.severe("Expected end of line after project declaration"); return null; } // id definition indent(); if (match(Token.Kind.ID) == null) { log.severe("Expected 'id' after project declaration"); return null; } // Now expect a colon. if (match(Token.Kind.COLON) == null) { log.severe("Expected ':' after 'id'"); return null; } Id projectId = id(); chewEols(); Map dirs = srcs(); chewEols(); List deps = dependencies(); chewEols(); ScmElement scm = scm(); return new Project(projectId, repositories, projectDescription, projectUrl, deps, dirs, scm); } private ScmElement scm() { chewIndents(); if (match(Token.Kind.SCM, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { return null; // no scm element } chewEols(); chewIndents(); String connection = null, developerConnection = null, url = null; List ident; while ((ident = match(Token.Kind.IDENT)) != null) { String label = ident.get(0).value; if (match(Token.Kind.COLON) == null) { throw new RuntimeException("Expected : after label"); } List valueToken = match(Token.Kind.STRING); if (null == valueToken) { throw new RuntimeException("Expected String after :"); } String value = valueToken.get(0).value; if ("connection".equals(label)) connection = value; else if ("developerConnection".equals(label)) developerConnection = value; else if ("url".equals(label)) url = value; chewEols(); chewIndents(); } if (match(Token.Kind.RBRACKET) == null) { throw new RuntimeException("Expected ] after srcs list"); } return new ScmElement(connection, developerConnection, url); } /** * Custom directory structure for maven builds. * */ private Map srcs() { indent(); if (match(Token.Kind.SRCS, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { return null; // No dirs! } chewEols(); chewIndents(); List aMatch = match(Token.Kind.IDENT); if (aMatch == null) { throw new RuntimeException("Expected 'src' or 'test'"); } String srcDir = null; if ("src".equals(aMatch.get(0).value)) { if (null == match(Token.Kind.COLON)) { throw new RuntimeException("Expected : after src"); } List srcDirToken = match(Token.Kind.STRING); if (null == srcDirToken) { throw new RuntimeException("Expected string after src:"); } srcDir = srcDirToken.get(0).value; } aMatch = match(Token.Kind.IDENT); String testDir = null; if (null != aMatch && "test".equals(aMatch.get(0).value)) { if (null == match(Token.Kind.COLON)) { throw new RuntimeException("Expected : after test"); } List testDirToken = match(Token.Kind.STRING); if (null == testDirToken) { throw new RuntimeException("Expected string after test:"); } testDir = testDirToken.get(0).value; } Map dirs = new HashMap(); // Strip quotes and store. if (null != srcDir) dirs.put("src", srcDir.substring(1, srcDir.length() - 1)); if (null != testDir) dirs.put("test", testDir.substring(1, testDir.length() - 1)); if (match(Token.Kind.RBRACKET) == null) { throw new RuntimeException("Expected ] after srcs list"); } return dirs; } /** * Dependencies of a project. The real meat of it. */ private List dependencies() { indent(); if (match(Token.Kind.DEPS, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { return null; // no deps. } List deps = new ArrayList(); chewEols(); chewIndents(); // Slurp up the dep ids. Id id; while ((id = id()) != null) { // Optional additional params at the end. String classifier = classifier(); if (null != classifier) id.setClassifier(classifier); chewEols(); chewIndents(); deps.add(id); } if (match(Token.Kind.RBRACKET) == null) { // ERROR! throw new RuntimeException("Expected ]"); } return deps; } /** * classifier := LPAREN IDENT RPAREN */ private String classifier() { if (match(Token.Kind.LPAREN) == null) { return null; } List classifier = match(Token.Kind.IDENT); if (classifier == null) { log.severe("Expected identifier after '(' in classifier clause"); return null; } if (match(Token.Kind.RPAREN) == null) { log.severe("Expected ')' in classifier clause before end of line"); return null; } return classifier.get(0).value; } /** * Id of a project definition. * * id := IDENT (DOT IDENT)* COLON IDENT COLON IDENT EOL */ private Id id() { String groupId = idFragment(); if (groupId == null) { return null; } // Now expect a colon. if (match(Token.Kind.COLON) == null) { return null; } String artifactId = idFragment(); if (artifactId == null) { return null; } // Now expect a colon. if (match(Token.Kind.COLON) == null) { return null; } String version = idFragment(); if (version == null) { return null; } return new Id(groupId, artifactId, version); } private String idFragment() { StringBuilder fragment = new StringBuilder(); List idFragment; while ((idFragment = match(Token.Kind.IDENT)) != null) { fragment.append(idFragment.get(0).value); if (match(Token.Kind.DOT) != null) { fragment.append('.'); } } return fragment.toString(); } /** * Optional repositories declaration at the top of the file. * * repositories := 'repositories' LEFT_WAVE STRING (COMMA STRING)* */ private Repositories repositories() { if (match(Token.Kind.REPOSITORIES, Token.Kind.LEFT_WAVE) == null) { return null; } List repoUrls = new ArrayList(); List repositories = match(Token.Kind.STRING); if (repositories == null) { // ERROR expected String. throw new RuntimeException("Error: expected URL string after 'respositories"); } // Validate first URL... String url = repositories.get(0).value; // Strip "" repoUrls.add(validateUrl(url)); while ((repositories = match(Token.Kind.COMMA)) != null) { chewEols(); chewIndents(); repositories = match(Token.Kind.STRING); chewEols(); chewIndents(); if (null != repositories) { url = validateUrl(repositories.get(0).value); repoUrls.add(url); } } return new Repositories(repoUrls); } private String validateUrl(String url) { url = url.substring(1, url.length() - 1); // Validate URL... try { new URL(url); } catch (MalformedURLException e) { throw new RuntimeException("Invalid URL: " + url, e); } return url; } // Production tools. private void indent() { if (match(Token.Kind.INDENT, Token.Kind.INDENT) != null) { // ERROR! } } private Token anyOf(Token.Kind... ident) { if (i >= tokens.size()) { return null; } for (Token.Kind kind : ident) { Token token = tokens.get(i); if (kind == token.kind) { i++; return token; } } // No match =( return null; } private List match(Token.Kind... ident) { int cursor = i; for (Token.Kind kind : ident) { // What we want is more than the size of the token stream. if (cursor >= tokens.size()) { return null; } Token token = tokens.get(cursor); if (token.kind != kind) { return null; } cursor++; } // Forward cursor in token stream to match point. int start = i; i = cursor; return tokens.subList(start, i); } private void chewEols() { // Chew up end-of-lines. while (match(Token.Kind.EOL) != null); } private void chewIndents() { // Chew up end-of-lines. while (match(Token.Kind.INDENT) != null); } } Dependencies.java000066400000000000000000000002121202174026400375570ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Dependencies { } Element.java000066400000000000000000000003001202174026400365600ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; /** * Represents a parsed element of an atom build file. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ abstract class Element { } Id.java000066400000000000000000000014551202174026400355370ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Id { private final String group; private final String artifact; private final String version; private String classifier; public Id(String group, String artifact, String version) { this.group = group; this.artifact = artifact; this.version = version; } public String getGroup() { return group; } public String getArtifact() { return artifact; } public String getVersion() { return version; } public String getClassifier() { return classifier; } public void setClassifier(String classifier) { this.classifier = classifier; } @Override public String toString() { return group + ":" + artifact + ":" + version; } } Project.java000066400000000000000000000062541202174026400366130ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; import org.apache.maven.model.*; import java.util.List; import java.util.Map; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Project extends Element { private final Id projectId; private final Repositories repositories; private final String description; private final String url; private List deps; private Map dirs; private static final String MAVEN_CENTRAL_URL = "http://repo1.maven.org/maven2"; private final ScmElement scm; public Project(Id projectId, Repositories repositories, String description, String url, List deps, Map dirs, ScmElement scm) { this.projectId = projectId; this.repositories = repositories; this.description = description; this.url = url; this.deps = deps; this.dirs = dirs; this.scm = scm; } public Id getProjectId() { return projectId; } public Repositories getRepositories() { return repositories; } public String getDescription() { return description; } public String getUrl() { return url; } public List getDeps() { return deps; } public Map getDirs() { return dirs; } public Model toMavenModel() { Model model = new Model(); model.setDescription(description); model.setUrl(url); model.setName(projectId.getArtifact()); model.setGroupId(projectId.getGroup()); model.setVersion(projectId.getVersion()); model.setArtifactId(projectId.getArtifact()); model.setModelVersion("4.0.0"); // Add jar repository urls. if (null == repositories) { // Add maven central if no repos exist. Repository repository = new Repository(); repository.setId("Maven Central"); repository.setUrl(MAVEN_CENTRAL_URL); model.addRepository(repository); } else { for (String repoUrl : repositories.getRepositories()) { Repository repository = new Repository(); repository.setId(Integer.toString(repoUrl.hashCode())); repository.setUrl(repoUrl); model.addRepository(repository); } } // Add project dependencies. for (Id dep : deps) { Dependency dependency = new Dependency(); dependency.setGroupId(dep.getGroup()); dependency.setArtifactId(dep.getArtifact()); dependency.setVersion(dep.getVersion()); if (null != dep.getClassifier()) dependency.setClassifier(dep.getClassifier()); model.addDependency(dependency); } // Optional source dirs customization. if (dirs != null) { Build build = new Build(); String srcDir = dirs.get("src"); String testDir = dirs.get("test"); if (null != srcDir) build.setSourceDirectory(srcDir); if (null != testDir) build.setTestSourceDirectory(testDir); model.setBuild(build); } if (null != scm) { Scm scm = new Scm(); scm.setConnection(this.scm.getConnection()); scm.setDeveloperConnection(this.scm.getDeveloperConnection()); scm.setUrl(this.scm.getUrl()); model.setScm(scm); } return model; } public ScmElement getScm() { return scm; } } Repositories.java000066400000000000000000000007241202174026400376700ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; import java.util.List; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Repositories extends Element { private final List repositories; public Repositories(List repositories) { this.repositories = repositories; } public List getRepositories() { return repositories; } @Override public String toString() { return repositories.toString(); } } ScmElement.java000066400000000000000000000011431202174026400372310ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ class ScmElement { private final String connection; private final String developerConnection; private final String url; ScmElement(String connection, String developerConnection, String url) { this.connection = connection; this.developerConnection = developerConnection; this.url = url; } public String getConnection() { return connection; } public String getDeveloperConnection() { return developerConnection; } public String getUrl() { return url; } } Token.java000066400000000000000000000061261202174026400362630ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; import java.util.HashMap; import java.util.Map; /** * Taken from the Loop programming language compiler pipeline. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Token { public final String value; public final Kind kind; public Token(String value, Kind kind) { this.value = value; this.kind = kind; } public static enum Kind { IDENT, TYPE_IDENT, INTEGER, STRING, REGEX, DOT, COLON, MINUS, DIVIDE, STAR, MODULUS, COMMA, AT, ARROW, HASHROCKET, // Comparison operators EQUALS, LEFT_WAVE, GREATER, LEQ, GEQ, LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, // keywords REQUIRE, SRCS, SCM, PROJECT, REPOSITORIES, OR, AND, NOT, FOR, IN, IF, DEPS, ID, UNLESS, WHERE, WHEN, // specials EOL, INDENT; private static final Map TOKEN_MAP = new HashMap(); static { // can we optimize with chars? TOKEN_MAP.put("@", AT); TOKEN_MAP.put(".", DOT); TOKEN_MAP.put(":", COLON); TOKEN_MAP.put("*", STAR); TOKEN_MAP.put(",", COMMA); TOKEN_MAP.put("->", ARROW); TOKEN_MAP.put("<=", LEQ); TOKEN_MAP.put(">=", GEQ); TOKEN_MAP.put("<<", LEFT_WAVE); TOKEN_MAP.put(">", GREATER); TOKEN_MAP.put("=>", HASHROCKET); TOKEN_MAP.put("(", LPAREN); TOKEN_MAP.put(")", RPAREN); TOKEN_MAP.put("{", LBRACE); TOKEN_MAP.put("}", RBRACE); TOKEN_MAP.put("[", LBRACKET); TOKEN_MAP.put("]", RBRACKET); TOKEN_MAP.put("\n", EOL); TOKEN_MAP.put("deps", DEPS); TOKEN_MAP.put("id", ID); TOKEN_MAP.put("repositories", REPOSITORIES); TOKEN_MAP.put("project", PROJECT); TOKEN_MAP.put("srcs", SRCS); TOKEN_MAP.put("scm", SCM); TOKEN_MAP.put("require", REQUIRE); TOKEN_MAP.put("||", OR); TOKEN_MAP.put("or", OR); TOKEN_MAP.put("&&", AND); TOKEN_MAP.put("and", AND); TOKEN_MAP.put("!", NOT); TOKEN_MAP.put("not", NOT); } /** * from token text, determines kind. */ public static Kind determine(String value) { char first = value.charAt(0); if (first == '"' || first == '\'') return STRING; Kind knownKind = TOKEN_MAP.get(value); if (null != knownKind) return knownKind; return IDENT; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Token token = (Token) o; return (kind == token.kind) && !(value != null ? !value.equals(token.value) : token.value != null); } @Override public int hashCode() { int result = value != null ? value.hashCode() : 0; result = 31 * result + (kind != null ? kind.hashCode() : 0); return result; } @Override public String toString() { return "Token{" + "value='" + value + '\'' + ", kind=" + kind + '}'; } }Tokenizer.java000066400000000000000000000125511202174026400371540ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; import java.util.ArrayList; import java.util.List; /** * Taken from the Loop programming language compiler pipeline. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Tokenizer { private final String input; public Tokenizer(String input) { this.input = input; } private static final int NON = 0; // MUST be zero private static final int SINGLE_TOKEN = 1; private static final int SEQUENCE_TOKEN = 2; private static final int[] DELIMITERS = new int[256]; private static final boolean[] STRING_TERMINATORS = new boolean[256]; static { DELIMITERS['-'] = SEQUENCE_TOKEN; DELIMITERS['+'] = SEQUENCE_TOKEN; DELIMITERS['/'] = SEQUENCE_TOKEN; DELIMITERS['*'] = SEQUENCE_TOKEN; DELIMITERS['>'] = SEQUENCE_TOKEN; DELIMITERS['<'] = SEQUENCE_TOKEN; DELIMITERS['!'] = SEQUENCE_TOKEN; DELIMITERS['?'] = SEQUENCE_TOKEN; // SINGLE token delimiters are one char in length in any context DELIMITERS['\n'] = SINGLE_TOKEN; DELIMITERS['.'] = SINGLE_TOKEN; DELIMITERS[','] = SINGLE_TOKEN; DELIMITERS[':'] = SINGLE_TOKEN; DELIMITERS['('] = SINGLE_TOKEN; DELIMITERS[')'] = SINGLE_TOKEN; DELIMITERS['['] = SINGLE_TOKEN; DELIMITERS[']'] = SINGLE_TOKEN; DELIMITERS['{'] = SINGLE_TOKEN; DELIMITERS['}'] = SINGLE_TOKEN; DELIMITERS['@'] = SINGLE_TOKEN; STRING_TERMINATORS['"'] = true; STRING_TERMINATORS['\''] = true; STRING_TERMINATORS['`'] = true; } public List tokenize() { List tokens = new ArrayList(); char[] input = this.input.toCharArray(); int i = 0, start = 0; boolean inWhitespace = false, inDelimiter = false, inComment = false, leading = true; char inStringSequence = 0; for (; i < input.length; i++) { char c = input[i]; // strings and sequences if (STRING_TERMINATORS[c]) { if (inStringSequence > 0) { // end of the current string sequence. bake. if (inStringSequence == c) { // +1 to include the terminating token. bakeToken(tokens, input, i + 1, start); start = i + 1; inStringSequence = 0; // reset to normal language continue; } // it's a string terminator but it's ok, it's part of the string, ignore... } else { // Also bake if there is any leading tokenage. if (i > start) { bakeToken(tokens, input, i, start); start = i; } inStringSequence = c; // start string } } // skip everything if we're in a string... if (inStringSequence > 0) continue; if (c == '\n') { leading = true; } // Comments beginning with # if (c == '#') { inComment = true; } // We run the comment until the end of the line if (inComment) { if (c == '\n') inComment = false; start = i; continue; } // whitespace is ignored unless it is leading... if (isWhitespace(c)) { inDelimiter = false; if (!inWhitespace) { //bake token bakeToken(tokens, input, i, start); inWhitespace = true; } // leading whitespace is a special token... if (leading) { tokens.add(new Token(" ", Token.Kind.INDENT)); } // skip whitespace start = i + 1; continue; } // any non-whitespace character encountered inWhitespace = false; if (c != '\n') leading = false; // For delimiters that are 1-char long in all contexts, // break early. if (isSingleTokenDelimiter(c)) { bakeToken(tokens, input, i, start); start = i; // Also add the delimiter. bakeToken(tokens, input, i + 1, start); start = i + 1; continue; } // is delimiter if (isDelimiter(c)) { if (!inDelimiter) { bakeToken(tokens, input, i, start); inDelimiter = true; start = i; } continue; } // if coming out of a delimiter, we still need to bake if (inDelimiter) { bakeToken(tokens, input, i, start); start = i; inDelimiter = false; } } // collect residual token if (i > start && !inComment) { // we don't want trailing whitespace bakeToken(tokens, input, i, start); } return tokens; } private static boolean isWhitespace(char c) { return '\n' != c && Character.isWhitespace(c); } static boolean isSingleTokenDelimiter(char c) { return DELIMITERS[c] == SINGLE_TOKEN; } public static String detokenize(List tokens) { StringBuilder builder = new StringBuilder(); for (Token token : tokens) { if (Token.Kind.INDENT == token.kind) builder.append("~"); else builder.append(token.value); builder.append(' '); } return builder.toString().trim(); } private static boolean isDelimiter(char c) { return DELIMITERS[c] != NON; } private static void bakeToken(List tokens, char[] input, int i, int start) { if (i > start) { String value = new String(input, start, i - start); // remove this disgusting hack when you can fix the lexer. tokens.add(new Token(value, Token.Kind.determine(value))); } } }polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/000077500000000000000000000000001202174026400235115ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/000077500000000000000000000000001202174026400255235ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/000077500000000000000000000000001202174026400263125ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/000077500000000000000000000000001202174026400301545ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/maven/000077500000000000000000000000001202174026400312625ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400331335ustar00rootroot00000000000000000077500000000000000000000000001202174026400340145ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/maven/polyglot/atom000077500000000000000000000000001202174026400354575ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/maven/polyglot/atom/parsingAtomParserTest.java000066400000000000000000000047761202174026400412550ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/maven/polyglot/atom/parsingpackage org.sonatype.maven.polyglot.atom.parsing; import junit.framework.TestCase; import org.codehaus.plexus.util.IOUtil; import java.net.MalformedURLException; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class AtomParserTest extends TestCase { private static final String REPO_URLS = "http://repository.codehaus.org," + " http://maven.org/central, http://repo1.maven.org/maven2"; private String pom; @Override protected void setUp() throws Exception { this.pom = IOUtil.toString(AtomParserTest.class.getResourceAsStream("example_pom.atom")); } public final void testRepositoryLineMalformedUrls() { Exception thrown = null; try { new AtomParser(new Tokenizer("repositories << \"...\"\n").tokenize()).parse(); fail("Expected exception for Malformed URL"); } catch (RuntimeException e) { thrown = e; } assertTrue(thrown.getCause() instanceof MalformedURLException); } public final void testRepositoryLineParsing() { Project element = new AtomParser(new Tokenizer(pom).tokenize()).parse(); assertEquals(String.format("[%s]", REPO_URLS), element.getRepositories().toString()); } public final void testProjectParsing() { Project project = new AtomParser(new Tokenizer(pom).tokenize()).parse(); assertEquals("\"Google Guice\"", project.getDescription()); assertEquals("\"http://code.google.com/p/google-guice\"", project.getUrl()); assertEquals("com.google.inject", project.getProjectId().getGroup()); assertEquals("guice", project.getProjectId().getArtifact()); assertEquals("2.0-SNAPSHOT", project.getProjectId().getVersion()); assertEquals(3, project.getDeps().size()); Id id = project.getDeps().get(0); assertEquals("junit:junit:3.8.1", id.toString()); id = project.getDeps().get(1); assertEquals("junit:junit:4.0", id.toString()); id = project.getDeps().get(2); assertEquals("kunit:org.kunit:SNAPSHOT-1.0b", id.toString()); assertEquals("jdk15", id.getClassifier()); assertEquals(2, project.getDirs().size()); assertEquals("src", project.getDirs().get("src")); assertEquals("test", project.getDirs().get("test")); assertEquals("\"url:git:git@github.com:mikebrock/mvel.git\"", project.getScm().getUrl()); assertEquals("\"con:git:git@github.com:mikebrock/mvel.git\"", project.getScm().getConnection()); assertEquals("\"dev:git:git@github.com:mikebrock/mvel.git\"", project.getScm().getDeveloperConnection()); } public final void testScmParsing() { } } example_pom.atom000066400000000000000000000017571202174026400406610ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-atom/src/test/resources/org/sonatype/maven/polyglot/atom/parsing# Example POM in Atom, a concise build grammar for Maven # Author: Dhanji R. Prasanna repositories << "http://repository.codehaus.org", "http://maven.org/central", "http://repo1.maven.org/maven2" project "Google Guice" @ "http://code.google.com/p/google-guice" id: com.google.inject:guice:2.0-SNAPSHOT srcs: [ src: "src" test: "test" ] deps: [ junit:junit:3.8.1 junit:junit:4.0 kunit:org.kunit:SNAPSHOT-1.0b(jdk15) ] scm: [ url: "url:git:git@github.com:mikebrock/mvel.git" connection: "con:git:git@github.com:mikebrock/mvel.git" developerConnection: "dev:git:git@github.com:mikebrock/mvel.git" ] plugin org.apache.maven.plugins:maven-compiler-plugin:2.0.1 source: 1.5 target: 1.5 encoding: UTF-8 plugin org.apache.maven.plugins:maven-surefire-plugin:2.0.1 childDelegation: true properties: [ mvel.disable.jit: "true" file.encoding: "UTF-8" ] includes: [ "**/*Test.java" "**/*Tests.java" ] polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/000077500000000000000000000000001202174026400215525ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/.gitignore000066400000000000000000000000531202174026400235400ustar00rootroot00000000000000target/ .project .classpath .settings/ bin polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/pom.xml000066400000000000000000000105141202174026400230700ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-cli Polyglot Maven :: CLI org.sonatype.pmaven pmaven-common org.sonatype.pmaven pmaven-groovy org.sonatype.pmaven pmaven-atom org.sonatype.pmaven pmaven-yaml org.sonatype.pmaven pmaven-clojure org.sonatype.pmaven pmaven-jruby xml-security xmlsec 1.3.0 org.apache.maven.plugins maven-dependency-plugin process-sources unpack false org.apache.maven apache-maven bin zip org.apache.maven.plugins maven-assembly-plugin package single pmaven-${project.version} src/main/assembly/bin.xml polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/000077500000000000000000000000001202174026400223415ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/000077500000000000000000000000001202174026400232655ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/assembly/000077500000000000000000000000001202174026400251045ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/assembly/bin.xml000066400000000000000000000021341202174026400263760ustar00rootroot00000000000000 bin zip src/main/assembly/common.xml polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/assembly/common.xml000066400000000000000000000121341202174026400271170ustar00rootroot00000000000000 src/main/underlay/bin /bin *.conf dos src/main/underlay/bin /bin translate unix 0755 src/main/underlay/bin /bin translate.bat dos target/dependency/apache-maven-${mavenVersion} / bin/m2.conf bin/m2 bin/mvn bin/mvnDebug bin/mvnyjp target/dependency/apache-maven-${mavenVersion}/bin bin m2 mvn mvnDebug mvnyjp unix 0755 lib true org.sonatype.pmaven:pmaven-common org.sonatype.pmaven:pmaven-cli ext true org.sonatype.pmaven:pmaven-groovy org.codehaus.groovy:groovy antlr:antlr asm:asm asm:asm-util asm:asm-analysis asm:asm-tree ext true org.sonatype.pmaven:pmaven-yaml org.yaml:snakeyaml ext true org.sonatype.pmaven:pmaven-clojure org.clojure:clojure ext true org.sonatype.pmaven:pmaven-atom ext true org.sonatype.pmaven:pmaven-jruby org.jruby:jruby-complete de.saumya.mojo:ruby-tools polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/000077500000000000000000000000001202174026400242065ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/000077500000000000000000000000001202174026400247755ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/apache/000077500000000000000000000000001202174026400262165ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/apache/maven/000077500000000000000000000000001202174026400273245ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/apache/maven/cli/000077500000000000000000000000001202174026400300735ustar00rootroot00000000000000PolyglotMavenCli.java000066400000000000000000000060141202174026400341100ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/apache/maven/cli/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.maven.cli; import org.apache.maven.model.building.ModelProcessor; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; /** * Polgyglot-aware Maven CLI. * * @author Jason Dillon * @since 0.7 */ public class PolyglotMavenCli extends MavenCli { @Override protected void customizeContainer( final PlexusContainer container ) { assert container != null; // HACK: Wedge our processor in as the default final ComponentDescriptor source = container.getComponentDescriptor( ModelProcessor.class.getName(), "polyglot" ); final ComponentDescriptor target = container.getComponentDescriptor( ModelProcessor.class.getName(), "default" ); target.setImplementation( source.getImplementation() ); // delete the old requirements and replace them with the new // with size == 0 is getRequirements is an emptyList which is unmutable if ( target.getRequirements().size() > 0 ) { target.getRequirements().clear(); } for ( final ComponentRequirement requirement : source.getRequirements() ) { target.addRequirement( requirement ); } // TODO this should not be needed final ComponentRequirement manager = new ComponentRequirement(); manager.setFieldName( "manager" ); manager.setRole( "org.sonatype.maven.polyglot.PolyglotModelManager" ); manager.setRoleHint( "default" ); target.addRequirement( manager ); try { container.addComponentDescriptor( target ); } catch ( final CycleDetectedInComponentGraphException e ) { throw new RuntimeException( e ); } } public static void main( final String[] args ) { final int result = main( args, null ); System.exit( result ); } public static int main( final String[] args, final ClassWorld classWorld ) { assert classWorld != null; final PolyglotMavenCli cli = new PolyglotMavenCli(); return cli.doMain( new CliRequest( args, classWorld ) ); } } polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/sonatype/000077500000000000000000000000001202174026400266375ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400277455ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400316165ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/sonatype/maven/polyglot/cli/000077500000000000000000000000001202174026400323655ustar00rootroot00000000000000PolyglotTranslatorCli.java000066400000000000000000000065251202174026400374740ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/java/org/sonatype/maven/polyglot/cli/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.cli; import org.apache.maven.model.building.ModelProcessor; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.util.IOUtil; import org.sonatype.maven.polyglot.PolyglotModelTranslator; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Polgyglot model translator. * * @author Jason Dillon * * @since 0.7 */ public class PolyglotTranslatorCli { private final DefaultPlexusContainer container; private final PolyglotModelTranslator translator; public PolyglotTranslatorCli(ClassWorld classWorld) throws Exception { if (classWorld == null) { classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader()); } ContainerConfiguration cc = new DefaultContainerConfiguration() .setClassWorld(classWorld) .setName("translator"); container = new DefaultPlexusContainer(cc); translator = container.lookup(PolyglotModelTranslator.class); } public PolyglotTranslatorCli() throws Exception { this(null); } public int run(final String[] args) throws Exception { if (args == null || args.length != 2) { System.out.println("usage: translate "); return -1; } File input = new File(args[0]).getCanonicalFile(); File output = new File(args[1]).getCanonicalFile(); System.out.println("Translating " + input + " -> " + output); translate(input, output); return 0; } public void translate(final File input, final File output) throws IOException { assert input != null; assert output != null; translate(input.toURI().toURL(), output.toURI().toURL()); } public void translate(final URL input, final URL output) throws IOException { assert input != null; assert output != null; translator.translate(input, output); } public static void main(final String[] args) throws Exception { int result = main(args, null); System.exit(result); } public static int main(final String[] args, final ClassWorld classWorld) throws Exception { assert classWorld != null; return new PolyglotTranslatorCli(classWorld).run(args); } }polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/underlay/000077500000000000000000000000001202174026400251105ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/underlay/bin/000077500000000000000000000000001202174026400256605ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/underlay/bin/m2.conf000066400000000000000000000003401202174026400270420ustar00rootroot00000000000000main is org.apache.maven.cli.PolyglotMavenCli from plexus.core set maven.home default ${user.home}/m2 set p2-runtimeLocation default ${maven.home}/p2 [plexus.core] load ${maven.home}/ext/*.jar load ${maven.home}/lib/*.jar polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/underlay/bin/translate000066400000000000000000000104361202174026400276040ustar00rootroot00000000000000#!/bin/sh # ---------------------------------------------------------------------------- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # Maven2 Start Up Batch script # # Required ENV vars: # ------------------ # JAVA_HOME - location of a JDK home dir # # Optional ENV vars # ----------------- # M2_HOME - location of maven2's installed home dir # MAVEN_OPTS - parameters passed to the Java VM when running Maven # e.g. to debug Maven itself, use # set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 # ---------------------------------------------------------------------------- # OS specific support. $var _must_ be set to either true or false. cygwin=false; darwin=false; mingw=false case "`uname`" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true if [ -z "$JAVA_VERSION" ] ; then JAVA_VERSION="CurrentJDK" else echo "Using Java version: $JAVA_VERSION" fi if [ -z "$JAVA_HOME" ] ; then JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Home fi ;; esac if [ -z "$JAVA_HOME" ] ; then if [ -r /etc/gentoo-release ] ; then JAVA_HOME=`java-config --jre-home` fi fi if [ -z "$M2_HOME" ] ; then ## resolve links - $0 may be a link to maven's home PRG="$0" # need this for relative symlinks while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG="`dirname "$PRG"`/$link" fi done saveddir=`pwd` M2_HOME=`dirname "$PRG"`/.. # make it fully qualified M2_HOME=`cd "$M2_HOME" && pwd` cd "$saveddir" # echo Using m2 at $M2_HOME fi # For Cygwin, ensure paths are in UNIX format before anything is touched if $cygwin ; then [ -n "$M2_HOME" ] && M2_HOME=`cygpath --unix "$M2_HOME"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --unix "$CLASSPATH"` fi # For Migwn, ensure paths are in UNIX format before anything is touched if $mingw ; then [ -n "$M2_HOME" ] && M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" # TODO classpath? fi if [ -z "$JAVACMD" ] ; then if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi else JAVACMD="`which java`" fi fi if [ ! -x "$JAVACMD" ] ; then echo "Error: JAVA_HOME is not defined correctly." echo " We cannot execute $JAVACMD" exit 1 fi if [ -z "$JAVA_HOME" ] ; then echo "Warning: JAVA_HOME environment variable is not set." fi CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher # For Cygwin, switch paths to Windows format before running java if $cygwin; then [ -n "$M2_HOME" ] && M2_HOME=`cygpath --path --windows "$M2_HOME"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` [ -n "$HOME" ] && HOME=`cygpath --path --windows "$HOME"` fi exec "$JAVACMD" \ $MAVEN_OPTS \ -classpath "${M2_HOME}"/boot/plexus-classworlds-*.jar \ "-Dclassworlds.conf=${M2_HOME}/bin/translate.conf" \ "-Dmaven.home=${M2_HOME}" \ ${CLASSWORLDS_LAUNCHER} "$@" polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/underlay/bin/translate.bat000066400000000000000000000132731202174026400303530ustar00rootroot00000000000000@REM ---------------------------------------------------------------------------- @REM Licensed to the Apache Software Foundation (ASF) under one @REM or more contributor license agreements. See the NOTICE file @REM distributed with this work for additional information @REM regarding copyright ownership. The ASF licenses this file @REM to you under the Apache License, Version 2.0 (the @REM "License"); you may not use this file except in compliance @REM with the License. You may obtain a copy of the License at @REM @REM http://www.apache.org/licenses/LICENSE-2.0 @REM @REM Unless required by applicable law or agreed to in writing, @REM software distributed under the License is distributed on an @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @REM KIND, either express or implied. See the License for the @REM specific language governing permissions and limitations @REM under the License. @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- @REM Maven2 Start Up Batch script @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @REM @REM Optional ENV vars @REM M2_HOME - location of maven2's installed home dir @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @REM e.g. to debug Maven itself, use @REM set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 @REM ---------------------------------------------------------------------------- @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' @echo off @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") @REM Execute a user defined script before this one if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" set ERROR_CODE=0 @REM set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" @setlocal if "%OS%"=="WINNT" @setlocal @REM ==== START VALIDATION ==== if not "%JAVA_HOME%" == "" goto OkJHome echo. echo ERROR: JAVA_HOME not found in your environment. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation echo. goto error :OkJHome if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome echo. echo ERROR: JAVA_HOME is set to an invalid directory. echo JAVA_HOME = "%JAVA_HOME%" echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation echo. goto error :chkMHome if not "%M2_HOME%"=="" goto valMHome if "%OS%"=="Windows_NT" SET "M2_HOME=%~dp0.." if "%OS%"=="WINNT" SET "M2_HOME=%~dp0.." if not "%M2_HOME%"=="" goto valMHome echo. echo ERROR: M2_HOME not found in your environment. echo Please set the M2_HOME variable in your environment to match the echo location of the Maven installation echo. goto error :valMHome :stripMHome if not "_%M2_HOME:~-1%"=="_\" goto checkMBat set "M2_HOME=%M2_HOME:~0,-1%" goto stripMHome :checkMBat if exist "%M2_HOME%\bin\translate.bat" goto init echo. echo ERROR: M2_HOME is set to an invalid directory. echo M2_HOME = "%M2_HOME%" echo Please set the M2_HOME variable in your environment to match the echo location of the Maven installation echo. goto error @REM ==== END VALIDATION ==== :init @REM Decide how to startup depending on the version of windows @REM -- Windows NT with Novell Login if "%OS%"=="WINNT" goto WinNTNovell @REM -- Win98ME if NOT "%OS%"=="Windows_NT" goto Win9xArg :WinNTNovell @REM -- 4NT shell if "%@eval[2+2]" == "4" goto 4NTArgs @REM -- Regular WinNT shell set MAVEN_CMD_LINE_ARGS=%* goto endInit @REM The 4NT Shell from jp software :4NTArgs set MAVEN_CMD_LINE_ARGS=%$ goto endInit :Win9xArg @REM Slurp the command line arguments. This loop allows for an unlimited number @REM of agruments (up to the command line limit, anyway). set MAVEN_CMD_LINE_ARGS= :Win9xApp if %1a==a goto endInit set MAVEN_CMD_LINE_ARGS=%MAVEN_CMD_LINE_ARGS% %1 shift goto Win9xApp @REM Reaching here means variables are defined and arguments have been captured :endInit SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" @REM -- 4NT shell if "%@eval[2+2]" == "4" goto 4NTCWJars @REM -- Regular WinNT shell for %%i in ("%M2_HOME%"\boot\plexus-classworlds-*) do set CLASSWORLDS_JAR="%%i" goto runm2 @REM The 4NT Shell from jp software :4NTCWJars for %%i in ("%M2_HOME%\boot\plexus-classworlds-*") do set CLASSWORLDS_JAR="%%i" goto runm2 @REM Start MAVEN2 :runm2 set CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher %MAVEN_JAVA_EXE% %MAVEN_OPTS% -classpath %CLASSWORLDS_JAR% "-Dclassworlds.conf=%M2_HOME%\bin\translate.conf" "-Dmaven.home=%M2_HOME%" %CLASSWORLDS_LAUNCHER% %MAVEN_CMD_LINE_ARGS% if ERRORLEVEL 1 goto error goto end :error if "%OS%"=="Windows_NT" @endlocal if "%OS%"=="WINNT" @endlocal set ERROR_CODE=1 :end @REM set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" goto endNT if "%OS%"=="WINNT" goto endNT @REM For old DOS remove the set variables from ENV - we assume they were not set @REM before we started - at least we don't leave any baggage around set MAVEN_JAVA_EXE= set MAVEN_CMD_LINE_ARGS= goto postExec :endNT @endlocal & set ERROR_CODE=%ERROR_CODE% :postExec if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" @REM pause the batch file if MAVEN_BATCH_PAUSE is set to 'on' if "%MAVEN_BATCH_PAUSE%" == "on" pause if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% cmd /C exit /B %ERROR_CODE% polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/main/underlay/bin/translate.conf000066400000000000000000000003601202174026400305230ustar00rootroot00000000000000main is org.sonatype.maven.polyglot.cli.PolyglotTranslatorCli from plexus.core set maven.home default ${user.home}/m2 set p2-runtimeLocation default ${maven.home}/p2 [plexus.core] load ${maven.home}/ext/*.jar load ${maven.home}/lib/*.jar polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/000077500000000000000000000000001202174026400233205ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/000077500000000000000000000000001202174026400242415ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/000077500000000000000000000000001202174026400250305ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/sonatype/000077500000000000000000000000001202174026400266725ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/sonatype/maven/000077500000000000000000000000001202174026400300005ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400316515ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/sonatype/maven/polyglot/cli/000077500000000000000000000000001202174026400324205ustar00rootroot00000000000000NoWhitespaceXMLCanonicalizer.java000077500000000000000000000067011202174026400406670ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/sonatype/maven/polyglot/cli/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.cli; import java.io.StringReader; import javax.xml.transform.*; import javax.xml.transform.stream.*; import javax.xml.transform.dom.*; import org.apache.xml.security.c14n.CanonicalizationException; import org.apache.xml.security.c14n.Canonicalizer; import org.apache.xml.security.c14n.InvalidCanonicalizerException; public class NoWhitespaceXMLCanonicalizer { private static boolean securityInitialized = false; private static Transformer noWhitespaceTransformer = null; private static String noWhitespaceXSL = " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "" + ""; private static Canonicalizer c11r = null; /** * Idempotent. Must be called at before the first instance's transform() * method gets called. **/ public synchronized static void initCanonicalizationEngine() { if (!securityInitialized) { try { initApacheC14n(); initNoWhitespaceTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } catch (TransformerFactoryConfigurationError e) { throw new RuntimeException(e); } catch (InvalidCanonicalizerException e) { throw new RuntimeException(e); } } securityInitialized = true; } private static void initNoWhitespaceTransformer() throws TransformerFactoryConfigurationError, TransformerConfigurationException { TransformerFactory factory = TransformerFactory.newInstance(); noWhitespaceTransformer = factory.newTransformer(new StreamSource( new StringReader(noWhitespaceXSL))); } private static void initApacheC14n() throws InvalidCanonicalizerException { org.apache.xml.security.Init.init(); c11r = Canonicalizer .getInstance(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); } public String transform(String input) { initCanonicalizationEngine(); System.out.println("INPUT: " + input); DOMResult domResult = new DOMResult(); try { noWhitespaceTransformer.transform(new StreamSource( new StringReader(input)), domResult); String output = new String(c11r.canonicalizeSubtree(domResult .getNode())); System.out.println("OUTPUT: " + output); return output; } catch (TransformerException e) { throw new RuntimeException(e); } catch (CanonicalizationException e) { throw new RuntimeException(e); } } } PolyglotTranslatorCliTest.java000066400000000000000000000072631202174026400403670ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/java/org/sonatype/maven/polyglot/clipackage org.sonatype.maven.polyglot.cli; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.apache.maven.model.io.DefaultModelWriter; import org.codehaus.plexus.PlexusTestCase; import org.junit.Before; import org.junit.Test; import org.sonatype.maven.polyglot.PolyglotModelManager; import org.junit.Ignore; /** * Tests for {@link PolyglotTranslatorCli}. * * @author Jason Dillon */ public class PolyglotTranslatorCliTest extends PlexusTestCase { private PolyglotModelManager manager; private PolyglotTranslatorCli translator; private ModelWriter writer = new DefaultModelWriter(); @Before protected void setUp() throws Exception { manager = lookup(PolyglotModelManager.class); translator = new PolyglotTranslatorCli(); } private void translate(String input, String ext, String expected) throws Exception { System.out.println( "Translating: " + input ); System.out.println( ext ); System.out.println( expected ); URL url = getClass().getResource(input); assertNotNull(url); //println "Input url:\n${url}" //println "Input text:\n${url.text}" File file = File.createTempFile("pom", ext); file.deleteOnExit(); try { translator.translate(url, file.toURI().toURL()); //println "Translated text file url:\n ${file.toURI().toURL()}" //println "Translated text:\n${file.text}" url = getClass().getResource(expected); assertNotNull(url); Model expectedModel = loadModel(url.openStream(), expected); Model actualModel = loadModel(new FileInputStream(file), file.getName()); assertModelEquals(expectedModel, actualModel); } finally { file.delete(); } } private Model loadModel(final InputStream input, final String location) throws Exception { System.out.println( location ); Map options = new HashMap(); options.put(ModelProcessor.SOURCE, location); ModelReader reader = manager.getReaderFor(options); return reader.read(input, options); } private void assertModelEquals(final Model expected, final Model actual) throws Exception { //...strips all whitespace and canonicalizes XML documents... NoWhitespaceXMLCanonicalizer c11r = new NoWhitespaceXMLCanonicalizer(); Writer swxml1 = new StringWriter(); writer.write(swxml1, null, expected); String xml1 = c11r.transform(swxml1.toString()); Writer swxml2 = new StringWriter(); writer.write(swxml2, null, actual); String xml2 = c11r.transform(swxml2.toString()); assertEquals(xml1, xml2); } @Test @Ignore // FIXME: This test is fundamentally broken public void testFormatInterchange() throws Exception { String[] formats = new String[]{ "xml", //"groovy", "yml", // "scala", // "clj" }; for ( String source : formats) { for ( String target : formats) { //println "Testing $source -> $target" translate("pom1." + source, "." + target, "pom1." + target ); } } } } polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/000077500000000000000000000000001202174026400253325ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/000077500000000000000000000000001202174026400261215ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/000077500000000000000000000000001202174026400277635ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/000077500000000000000000000000001202174026400310715ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400327425ustar00rootroot00000000000000000077500000000000000000000000001202174026400334325ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/clipom1.clj000077500000000000000000000001361202174026400350030ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/cli(defproject main :add-default-plugins false :parent "a:b:c" :packaging "jar") pom1.groovy000066400000000000000000000001361202174026400355550ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/cliproject { parent { artifactId 'b' groupId 'a' version 'c' } } pom1.scala000077500000000000000000000002751202174026400353220ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/cliproject { m => m.packaging = "jar" m.parent { p => p.artifactId = "b" p.groupId = "a" p.relativePath = "../pom.xml" p.version = "c" } } pom1.xml000066400000000000000000000001751202174026400350330ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/cli b a c pom1.yml000066400000000000000000000001311202174026400350240ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-cli/src/test/resources/org/sonatype/maven/polyglot/clipackaging: jar parent: {artifactId: b, groupId: a, relativePath: ../pom.xml, version: c} polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/000077500000000000000000000000001202174026400224465ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/.gitignore000066400000000000000000000000061202174026400244320ustar00rootroot00000000000000targetpolyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/pom.xml000066400000000000000000000047451202174026400237750ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-clojure Polyglot Maven :: Clojure org.sonatype.pmaven pmaven-common org.clojure clojure 1.1.0 com.google.collections google-collections 1.0 org.easytesting fest-assert 1.1 test com.theoryinpractise clojure-maven-plugin 1.3.1 compile testCompile test polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/000077500000000000000000000000001202174026400232355ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/000077500000000000000000000000001202174026400241615ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/000077500000000000000000000000001202174026400256245ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/000077500000000000000000000000001202174026400264135ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/000077500000000000000000000000001202174026400302555ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/000077500000000000000000000000001202174026400313635ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400332345ustar00rootroot00000000000000000077500000000000000000000000001202174026400346205ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure000077500000000000000000000000001202174026400354025ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsldebug.clj000066400000000000000000000033231202174026400371630ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsl(ns org.sonatype.maven.polyglot.clojure.dsl.debug (:require org.sonatype.maven.polyglot.clojure.dsl.reader) (:require org.sonatype.maven.polyglot.clojure.dsl.writer) (:require org.sonatype.maven.polyglot.clojure.dsl.pretty-printer)) (org.sonatype.maven.polyglot.clojure.dsl.reader/defmaven 'org.clojure/clojure "1.2.0-master-SNAPSHOT" :model-version "4.0.0" :name "Lamdras Website" :description "Acumen / LRMDS Integration" :properties { :project.build.sourceEncoding "UTF-8" } :packaging "war" :dependencies ['ring/ring-servlet 'ring/ring-devel 'clj-routing/clj-routing 'clout/clout 'compojure/compojure 'hiccup/hiccup 'org.clojure/clojure 'org.clojure/clojure-contrib 'congomongo/congomongo] :provided-dependencies [['org.mortbay.jetty/servlet-api-2.5 "6.1.14"]] :build [:final-name "website" :plugins [['org.apache.maven.plugins/maven-compiler-plugin "2.1" :source "1.6" :target "1.6"] ['com.theoryinpractise/clojure-maven-plugin "1.3.1" :sourceDirectories ["src/main/java"] :executions [[:id "compile-clojure" :phase "compile" :goals ["compile"]]]] ['org.mortbay.jetty/maven-jetty-plugin "6.1.10" :configuration { :scanIntervalSeconds 10 :stopKey "foo" :stopPort 9999 }]]]) (defn test-pp [] (org.sonatype.maven.polyglot.clojure.dsl.pretty-printer/print-object-to-writer (list* 'defmaven (org.sonatype.maven.polyglot.clojure.dsl.writer/reify-field-value @org.sonatype.maven.polyglot.clojure.dsl.reader/*MODEL*)) *out*) (.write *out* "\n")) leiningen.clj000066400000000000000000000037701202174026400400530ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsl;; ;; Copyright (C) 2010 the original author or authors. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns org.sonatype.maven.polyglot.clojure.dsl.leiningen (:use org.sonatype.maven.polyglot.clojure.dsl.reader)) ; TODO: does the assembly plugin belong in here, given the lein uberjar target? (def *leiningen-defaults* '[:model-version "4.0.0" :repositories [[:id "central" :url "http://repo1.maven.org/maven2"] [:id "clojure" :url "http://build.clojure.org/releases"] [:id "clojure-snapshots" :url "http://build.clojure.org/snapshots"] [:id "clojars" :url "http://clojars.org/repo/"]] :build [:plugins [[com.theoryinpractise/clojure-maven-plugin "1.3.2" :testScript "src/test/clojure/test.clj" :executions [[:id "compile" :phase "compile" :goals ["testCompile"]] [:id "test-compile" :phase "test-compile" :goals ["compile"]] [:id "test" :phase "test" :goals ["test"]]]]]]]) (def *leiningen-valid-properties* [ :dependencies :name :description ]) ; I anticipate this becoming more sophisticated over time. (defmacro defproject [& args] (let [cleaned-args (apply concat (vec (select-keys (apply hash-map (drop 2 args)) *leiningen-valid-properties*))) quoted-args (map #(list 'quote %) (concat (take 2 args) cleaned-args *leiningen-defaults*))] `(defmaven ~@quoted-args))) pretty_printer.clj000066400000000000000000000056351202174026400411770ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsl(ns org.sonatype.maven.polyglot.clojure.dsl.pretty-printer) (comment " keyword -> if not sol then new line at current indent list, vector, map -> if not sol then new line at current indent sol = true scalar -> sol = false ") (defn- write-string [state string] (.write (:writer state) string) (swap! (:position state) + (count string)) (reset! (:start-of-line state) false)) (defn- write-quote [state] (.write (:writer state) "'") (swap! (:position state) + 1) (reset! (:start-of-line state) true)) (defn- write-start-of-line-space [state] (.write (:writer state) " ") (swap! (:position state) + 1) (reset! (:start-of-line state) true)) (defn- write-opening-delimiter [state string] (.write (:writer state) string) (swap! (:indent state) conj (+ @(:position state) (count string))) (swap! (:position state) + (count string)) (reset! (:start-of-line state) true)) (defn- write-closing-delimiter [state string] (write-string state string) (reset! (:start-of-line state) false) (swap! (:indent state) pop)) (defn- write-space-if-not-start-of-line [state] (when-not @(:start-of-line state) (write-string state " "))) (defn- indent-if-not-start-of-line [state] (when-not @(:start-of-line state) (.write (:writer state) "\n") (dotimes [_ (peek @(:indent state))] (.write (:writer state) " ")) (reset! (:position state) (peek @(:indent state))) (reset! (:start-of-line state) true))) (defmulti pretty-print (fn [object state] (class object))) (defmethod pretty-print clojure.lang.Keyword [object state] (indent-if-not-start-of-line state) (write-string state (str object)) (write-start-of-line-space state)) (defmethod pretty-print clojure.lang.IPersistentVector [object state] (indent-if-not-start-of-line state) (write-opening-delimiter state "[") (doseq [o object] (pretty-print o state)) (write-closing-delimiter state "]")) (defmethod pretty-print clojure.lang.ISeq [object state] (if (= (first object) 'quote) (do (write-space-if-not-start-of-line state) (write-quote state) (pretty-print (second object) state)) (do (indent-if-not-start-of-line state) (write-opening-delimiter state "(") (doseq [o object] (pretty-print o state)) (write-closing-delimiter state ")")))) (defmethod pretty-print clojure.lang.IPersistentMap [object state] (indent-if-not-start-of-line state) (write-opening-delimiter state "{") (doseq [[k v] object] (pretty-print k state) (write-space-if-not-start-of-line state) (pretty-print v state)) (write-closing-delimiter state "}")) (defmethod pretty-print :default [object state] (write-space-if-not-start-of-line state) (write-string state (pr-str object))) (defn print-object-to-writer [object writer] (pretty-print object { :writer writer :start-of-line (atom true) :indent (atom '()) :position (atom 0) }))reader.clj000066400000000000000000000155001202174026400373370ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsl(ns org.sonatype.maven.polyglot.clojure.dsl.reader (:use org.sonatype.maven.polyglot.clojure.dsl.util)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Code to support the macro ; ; Non-gensymed symbols are used because a) different fragments are combined ; from different sources; and b) there's a bug with auto gensym that sometimes ; gives a binding different names at different points, especially when ; multiple fragments are combined into one syntax-quote (def *uncoerced-classes* #{ String Boolean/TYPE Integer/TYPE }) (defn- scalar-field-handler [name kw type] `(~kw (~(symbol (str ".set" name)) ~'object ~(if (contains? *uncoerced-classes* type) 'value `(coerce-to-maven ~'value ~type))))) (defn- list-field-handler ([name kw type] `(~kw (doseq [~'v ~'value] (~(symbol (str ".add" (singular-form-of-name name))) ~'object (coerce-to-maven ~'v ~type))))) ([name kw type mutator] `(~kw (doseq [~'v ~'value] (let [~'target (coerce-to-maven ~'v ~type)] ~mutator (~(symbol (str ".add" (singular-form-of-name name))) ~'object ~'target)))))) (defn- dependency-field-handler [] (let [name "Dependencies" type org.apache.maven.model.Dependency] [(list-field-handler name :test-dependencies type `(.setScope ~'target "test")) (list-field-handler name :provided-dependencies type `(.setScope ~'target "provided")) (list-field-handler name :runtime-dependencies type `(.setScope ~'target "runtime")) (list-field-handler name :system-dependencies type `(.setScope ~'target "system")) (list-field-handler name :dependencies type)])) (defn- configuration-field-handler [] [`(:configuration (parse-configuration-node! ~'config (vec ~'value)))]) (defn- field-handlers [klass] (let [introspector (java.beans.Introspector/getBeanInfo klass) descriptors (.getPropertyDescriptors introspector) writable-descriptors (filter #(.getWriteMethod %) descriptors)] (for [descriptor writable-descriptors] (let [name (capitalize-first-letter (.getName descriptor)) kw (keyword (from-camel-case name)) type (.getPropertyType descriptor) list-type (when (= type java.util.List) (list-type klass name))] (cond (= name "Dependencies") (dependency-field-handler) (= name "Configuration") (configuration-field-handler) (= type java.util.List) [(list-field-handler name kw list-type)] :else [(scalar-field-handler name kw type)]))))) (defmacro defmodel-reader [className] (let [klass (Class/forName (str "org.apache.maven.model." className)) name (symbol (.getSimpleName klass)) has-coordinates (has-method? klass "setGroupId") has-configuration (has-method? klass "setConfiguration")] `(do (defn ~name [& ~'args] (let [~(with-meta 'object {:tag (symbol (.getName klass))}) (new ~(symbol (.getName klass))) ~@(when has-configuration `(~'config (org.codehaus.plexus.util.xml.Xpp3Dom. "configuration")))] (loop [[~'key ~'value & rest#] ~(if has-coordinates `(parse-coordinates ~'args ~'object) 'args)] (when ~'key (condp = ~'key ~@(apply concat (apply concat (field-handlers klass))) ~(if has-configuration `(parse-configuration-node! ~'config [~'key ~'value]) `(throw (IllegalArgumentException. (str ~(str name " doesn't have an attribute named ") ~'key))))) (recur rest#))) ~@(when has-configuration [`(.setConfiguration ~'object ~'config)]) ~'object)) (defmethod coerce-to-maven [clojure.lang.IPersistentVector ~klass] [value# ~'_] (apply ~name value#)) ~(if has-coordinates `(defmethod coerce-to-maven [clojure.lang.Symbol ~klass] [value# ~'_] (~name value#)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Code to support the runtime execution ; (defmulti parse-configuration-node! (fn [parent value] (class value))) (defmethod parse-configuration-node! clojure.lang.IPersistentVector [parent [head & tail :as children]] (cond ; TODO: handle namespaced names :a/b -> "a:b" for Xpp3Dom ; TODO: handle attributes i.e. a map as the second element of the list (instance? clojure.lang.Keyword head) (let [node (org.codehaus.plexus.util.xml.Xpp3Dom. (name head))] (doseq [x tail] (parse-configuration-node! node x)) (.addChild parent node)) (instance? String head) (let [wrapper-name (singular-form-of-name (.getName parent))] (doseq [x children] (let [node (org.codehaus.plexus.util.xml.Xpp3Dom. wrapper-name)] (parse-configuration-node! node x) (.addChild parent node)))) :else (doseq [x children] (parse-configuration-node! parent x)))) (defmethod parse-configuration-node! :default [parent value] (.setValue parent (str value))) (defmulti coerce-to-maven (fn [value dest-class] [(class value) dest-class])) (defmethod coerce-to-maven [clojure.lang.Associative java.util.Properties] [value _] (let [properties (java.util.Properties.)] (doseq [[k v] value] (.setProperty properties (name k) v)) properties)) (defmethod coerce-to-maven :default [value _] value) (defmodel-reader Activation) (defmodel-reader ActivationFile) (defmodel-reader ActivationOS) (defmodel-reader ActivationProperty) (defmodel-reader Build) (defmodel-reader BuildBase) (defmodel-reader CiManagement) (defmodel-reader Contributor) (defmodel-reader Dependency) (defmodel-reader DependencyManagement) (defmodel-reader DeploymentRepository) (defmodel-reader Developer) (defmodel-reader DistributionManagement) (defmodel-reader Exclusion) (defmodel-reader Extension) (defmodel-reader IssueManagement) (defmodel-reader License) (defmodel-reader MailingList) (defmodel-reader Model) (defmodel-reader Notifier) (defmodel-reader Organization) (defmodel-reader Parent) (defmodel-reader Plugin) (defmodel-reader PluginExecution) (defmodel-reader PluginManagement) (defmodel-reader Prerequisites) (defmodel-reader Profile) (defmodel-reader Relocation) (defmodel-reader ReportPlugin) (defmodel-reader ReportSet) (defmodel-reader Reporting) (defmodel-reader Repository) (defmodel-reader RepositoryPolicy) (defmodel-reader Resource) (defmodel-reader Scm) (defmodel-reader Site) (def *MODEL* (atom nil)) (defn defmaven [& args] (reset! *MODEL* (apply Model args))) util.clj000066400000000000000000000035431202174026400370560ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsl(ns org.sonatype.maven.polyglot.clojure.dsl.util) (defn singular-form-of-name [#^String plural] "Returns the gramatically singular form of the argument, using a very simple translation of (in order) *ies -> *y, *s -> * and * -> *" (cond (.endsWith plural "ies") (str (.substring plural 0 (- (count plural) 3)) "y") (.endsWith plural "s") (.substring plural 0 (- (count plural) 1)) :else plural)) (defn capitalize-first-letter [s] (str (.toUpperCase (.substring s 0 1)) (.substring s 1))) (defn to-camel-case [#^String name] (apply str (map capitalize-first-letter (.split name "-")))) (defn from-camel-case [#^String name] (apply str (interpose "-" (map #(.toLowerCase %) (re-seq #"\p{Alpha}\p{Lower}*" name))))) (defn list-type [klass property-name] (let [add-method-name (str "add" (singular-form-of-name property-name)) add-methods (filter #(= (.getName %) add-method-name) (.getMethods klass))] (when (seq add-methods) (first (.getParameterTypes (first add-methods)))))) (defn has-method? [klass method-name] (some #(= (.getName %) method-name) (.getMethods klass))) (defmulti parse-coordinates (fn [source _] (class source))) (defmethod parse-coordinates clojure.lang.Symbol [#^clojure.lang.Symbol source destination] (let [artifact (name source) group (if-let [g (namespace source)] g artifact)] (.setGroupId destination group) (.setArtifactId destination artifact))) (defmethod parse-coordinates clojure.lang.Sequential [#^clojure.lang.Sequential source destination] (if (and (> (count source) 0) (instance? clojure.lang.Symbol (first source))) (do (parse-coordinates (first source) destination) (if (and (> (count source) 1) (instance? String (second source))) (do (.setVersion destination (second source)) (drop 2 source)) (drop 1 source))) source))writer.clj000066400000000000000000000220121202174026400374050ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/clojure/org/sonatype/maven/polyglot/clojure/dsl(ns org.sonatype.maven.polyglot.clojure.dsl.writer (:use org.sonatype.maven.polyglot.clojure.dsl.util) (:use org.sonatype.maven.polyglot.clojure.dsl.pretty-printer)) ;;; Copied from clojure-contrib to avoid the dependency ;; group-by written by Rich Hickey; ;; see http://paste.lisp.org/display/64190 (defn- group-by "Returns a sorted map of the elements of coll keyed by the result of f on each element. The value at each key will be a vector of the corresponding elements, in the order they appeared in coll." [f coll] (reduce (fn [ret x] (let [k (f x)] (assoc ret k (conj (get ret k []) x)))) (sorted-map) coll)) ; Most of these are generated by the defmodel-write macro (defmulti reify-field-value class) (defmethod reify-field-value java.util.Properties [value] (apply hash-map (apply concat (for [x (.entrySet value)] [(keyword (.getKey x)) (.getValue x)])))) (defmethod reify-field-value :default [value] value) (defn- reify-scalar-field [accum value kw] (if (nil? value) accum (merge { kw (reify-field-value value) } accum))) (defn- reify-list-field [accum value kw] (if (or (nil? value) (.isEmpty value)) accum (merge { kw (vec (map reify-field-value value)) } accum))) (defn- properties-to-map [value] (apply hash-map (apply concat (for [x (.entrySet value)] [(keyword (.getKey x)) (.getValue x)])))) (defn- reify-properties-field [accum value] (if (or (nil? value) (= 0 (.size value))) accum (merge accum { :properties (properties-to-map value) }))) (defn- child-nodes-can-be-simple-value-vector [parent] (let [required-name (singular-form-of-name (.getName parent))] (every? (fn [n] (and (= 0 (.getChildCount n)) (= required-name (.getName n)))) (.getChildren parent)))) ; TODO namespace names ; TODO attributes (defn- reify-xml-value [value] [ (keyword (.getName value)) (cond (= 0 (.getChildCount value)) (str (.getValue value)) (child-nodes-can-be-simple-value-vector value) (vec (map #(.getValue %) (.getChildren value))) :else (vec (map reify-xml-value (.getChildren value))))]) (defn- class-has-property? [klass property-name] (try (.getMethod klass (str "get" (capitalize-first-letter property-name)) nil) (catch NoSuchMethodException ex false))) (defn- xml-nodes-all-safe-to-hoist [object nodes] (not (some #(class-has-property? (class object) (.getName %)) nodes))) (defn- xml-nodes-all-safe-for-map [nodes] (every? #(= 0 (count (.getAttributeNames %))) nodes)) (defn- reify-configuration-field [accum value object] (cond (or (nil? value) (= 0 (.getChildCount value))) accum (xml-nodes-all-safe-to-hoist object (.getChildren value)) (merge accum (apply hash-map (apply concat (map reify-xml-value (.getChildren value))))) (xml-nodes-all-safe-for-map (.getChildren value)) (merge accum { :configuration (apply hash-map (apply concat (map reify-xml-value (.getChildren value)))) }) :else (merge accum { :configuration (vec (map reify-xml-value (.getChildren value))) }) )) (defn- reify-dependency-group [accum value kw] (if value (merge accum { kw value }) accum)) (defn- reify-dependencies-field [accum value] (let [scopes (group-by (fn [dep] (or (.getScope dep) "compile")) value)] (-> accum (reify-list-field (scopes "compile") :dependencies) (reify-list-field (scopes "test") :test-dependencies) (reify-list-field (scopes "provided") :provided-dependencies) (reify-list-field (scopes "runtime") :runtime-dependencies) (reify-list-field (scopes "system") :system-dependencies)))) (defn- reify-field [accum object descriptor] (let [name (capitalize-first-letter (.getName descriptor)) kw (keyword (from-camel-case name)) value (.invoke (.getReadMethod descriptor) object (make-array Object 0))] (cond (= name "Properties") (reify-properties-field accum value) (= name "Dependencies") (reify-dependencies-field accum value) (= name "Configuration") (reify-configuration-field accum value object) (instance? java.util.List value) (reify-list-field accum value kw) :else (reify-scalar-field accum value kw)))) (defn- reify-fields [object] (let [introspector (java.beans.Introspector/getBeanInfo (class object)) descriptors (.getPropertyDescriptors introspector) writable-descriptors (filter #(.getWriteMethod %) descriptors)] (reduce (fn [accum d] (reify-field accum object d)) {} writable-descriptors))) (defn- remove-default-fields [fields defaults] (reduce (fn [f [k v]] (if (or (= v (f k)) (= v :any)) (dissoc f k) f)) fields defaults)) (defn- map-to-vector-with-order [a-map order] (let [reducer (fn [[head mid tail] key] (if (= key :*) [tail mid head] (if (contains? mid key) [head (dissoc mid key) (conj (conj tail key) (key mid))] [head mid tail]))) [head mid tail] (reduce reducer [[] a-map []] order)] (concat head (apply concat (vec mid)) tail))) (defn- convert-fields-to-vector [fields field-order] (let [artifact-id (:artifact-id fields) [header f] (if artifact-id (let [group-id (:group-id fields) ga-symbol (list 'quote (if (or (nil? group-id) (= group-id artifact-id)) (symbol artifact-id) (symbol group-id artifact-id))) version (:version fields)] [(if version [ga-symbol version] [ga-symbol]) (dissoc fields :group-id :artifact-id :version)]) [[] fields])] (vec (concat header (map-to-vector-with-order f field-order))))) ; TODO: hoist configuration after removing default fields so that hoisted ; configuration keys don't accidentally removed. (defn- reify-model-object [object default-fields field-order] (convert-fields-to-vector (remove-default-fields (reify-fields object) default-fields) field-order)) (defmacro defmodel-writer [class-name default-fields field-order] (let [full-class-name (str "org.apache.maven.model." class-name)] `(defmethod reify-field-value ~(symbol full-class-name) [v#] (reify-model-object v# ~default-fields ~field-order)))) ; These may need to be refined further on a per-object basis (def *field-defaults* {:inherited true :type "jar" :priority 0 :optional false :extensions false :model-encoding "UTF-8"}) (def *field-order* []) (defmodel-writer Activation *field-defaults* *field-order*) (defmodel-writer ActivationFile *field-defaults* *field-order*) (defmodel-writer ActivationOS *field-defaults* *field-order*) (defmodel-writer ActivationProperty *field-defaults* *field-order*) (defmodel-writer Build *field-defaults* *field-order*) (defmodel-writer BuildBase *field-defaults* *field-order*) (defmodel-writer CiManagement *field-defaults* *field-order*) (defmodel-writer Contributor *field-defaults* *field-order*) (defmodel-writer Dependency (merge {:scope :any} *field-defaults*) *field-order*) (defmodel-writer DependencyManagement *field-defaults* *field-order*) (defmodel-writer DeploymentRepository *field-defaults* *field-order*) (defmodel-writer Developer *field-defaults* *field-order*) (defmodel-writer DistributionManagement *field-defaults* *field-order*) (defmodel-writer Exclusion *field-defaults* *field-order*) (defmodel-writer Extension *field-defaults* *field-order*) (defmodel-writer IssueManagement *field-defaults* *field-order*) (defmodel-writer License *field-defaults* *field-order*) (defmodel-writer MailingList *field-defaults* *field-order*) (defmodel-writer Model *field-defaults* [:model-version :name :description :packaging :properties :dependencies :test-dependencies :runtime-dependences :provided-dependencies :system-dependencies :* :build]) (defmodel-writer Notifier *field-defaults* *field-order*) (defmodel-writer Organization *field-defaults* *field-order*) (defmodel-writer Parent *field-defaults* *field-order*) (defmodel-writer Plugin *field-defaults* [ :* :executions ]) (defmodel-writer PluginExecution *field-defaults* [ :id :phase :goals :* ]) (defmodel-writer PluginManagement *field-defaults* *field-order*) (defmodel-writer Prerequisites *field-defaults* *field-order*) (defmodel-writer Profile *field-defaults* *field-order*) (defmodel-writer Relocation *field-defaults* *field-order*) (defmodel-writer ReportPlugin *field-defaults* *field-order*) (defmodel-writer ReportSet *field-defaults* *field-order*) (defmodel-writer Reporting *field-defaults* *field-order*) (defmodel-writer Repository (merge { :layout "default" } *field-defaults*) [ :id :url :* ]) (defmodel-writer RepositoryPolicy *field-defaults* *field-order*) (defmodel-writer Resource *field-defaults* *field-order*) (defmodel-writer Scm *field-defaults* *field-order*) (defmodel-writer Site *field-defaults* *field-order*) (defn write-model [#^org.apache.maven.model.Model model #^java.io.Writer writer] (print-object-to-writer (list* 'defmaven (reify-field-value model)) writer) (.flush writer))polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/000077500000000000000000000000001202174026400251025ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/000077500000000000000000000000001202174026400256715ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/000077500000000000000000000000001202174026400275335ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400306415ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400325125ustar00rootroot00000000000000000077500000000000000000000000001202174026400340765ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/maven/polyglot/clojureClojureMapping.java000066400000000000000000000024671202174026400376710ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/* * Copyright (C) 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.clojure; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.mapping.Mapping; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** * Clojure model mapping. * * @author Mark Derricutt * @author Antony Blakey * * @since 0.7 */ @Component(role=Mapping.class, hint="clojure") public class ClojureMapping extends MappingSupport { public ClojureMapping() { super("clojure"); setPomNames("pom.clj", "projwct.clj"); setAcceptLocationExtensions(".clj"); setAcceptOptionKeys("clojure:4.0.0"); } }ClojureModelReader.java000066400000000000000000000051251202174026400404530ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/* * Copyright (C) 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.clojure; import clojure.lang.Atom; import clojure.lang.Namespace; import clojure.lang.RT; import clojure.lang.Symbol; import clojure.lang.Var; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.PolyglotModelUtil; import org.sonatype.maven.polyglot.io.ModelReaderSupport; import java.io.IOException; import java.io.Reader; import java.util.Map; /** * Reads a pom.clj and transforms into a Maven {@link Model}. * * @author Mark Derricutt * @author Antony Blakey * @since 0.7 */ @Component(role = ModelReader.class, hint = "clojure") public class ClojureModelReader extends ModelReaderSupport { //@Requirement //protected Logger log; //@Requirement //private ModelBuilder builder; //@Requirement //private ExecuteManager executeManager; public Model read(final Reader input, final Map options) throws IOException { assert input != null; try { String location = PolyglotModelUtil.getLocation(options); final Var USE = Var.intern(RT.CLOJURE_NS, Symbol.create("use")); final Symbol READER = Symbol.create("org.sonatype.maven.polyglot.clojure.dsl.reader"); final Symbol LEININGEN = Symbol.create("org.sonatype.maven.polyglot.clojure.dsl.leiningen"); USE.invoke(READER); USE.invoke(LEININGEN); clojure.lang.Compiler.load(input, location, location); final Var MODEL = Var.intern(Namespace.findOrCreate(READER), Symbol.create("*MODEL*")); return (Model) ((Atom) MODEL.get()).deref(); } catch (Exception e) { // Don't use new IOException(e) because it doesn't exist in Java 5 throw (IOException) new IOException(e.toString()).initCause(e); } } } ClojureModelWriter.java000066400000000000000000000041471202174026400405300ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/* * Copyright (C) 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.clojure; import clojure.lang.Namespace; import clojure.lang.RT; import clojure.lang.Symbol; import clojure.lang.Var; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import java.io.IOException; import java.io.Writer; import java.util.Map; /** * Writes a Maven {@link org.apache.maven.model.Model} to a pom.clj. * * @author Mark Derricutt * @author Antony Blakey * * @since 0.7 */ @Component(role = ModelWriter.class, hint = "clojure") public class ClojureModelWriter extends ModelWriterSupport { public void write(Writer writer, Map stringObjectMap, Model model) throws IOException { try { final Var REQUIRE = Var.intern(RT.CLOJURE_NS, Symbol.create("require")); final Symbol REFLECTOR = Symbol.create("org.sonatype.maven.polyglot.clojure.dsl.writer"); REQUIRE.invoke(REFLECTOR); final Var WRITER = Var.intern(Namespace.findOrCreate(REFLECTOR), Symbol.create("write-model")); WRITER.invoke(model, writer); } catch (Exception e) { e.printStackTrace(); // Don't use new IOException(e) because it doesn't exist in Java 5 throw (IOException) new IOException(e.toString()).initCause(e); } } } polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/000077500000000000000000000000001202174026400242145ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/000077500000000000000000000000001202174026400251355ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/000077500000000000000000000000001202174026400257245ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/sonatype/000077500000000000000000000000001202174026400275665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/sonatype/maven/000077500000000000000000000000001202174026400306745ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400325455ustar00rootroot00000000000000000077500000000000000000000000001202174026400341315ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/sonatype/maven/polyglot/clojureClojureModelReaderTest.java000066400000000000000000000057261202174026400413550ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/sonatype/maven/polyglot/clojurepackage org.sonatype.maven.polyglot.clojure; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.PlexusTestCase; import org.junit.Test; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Tests for {@link ClojureModelReader}. * * @author Mark Derricutt */ public class ClojureModelReaderTest extends PlexusTestCase { @Test public void testReading() throws Exception { Model model = readClojureModel("test1.clj"); assertNotNull(model); System.out.println(model.getModelVersion()); assertEquals("UTF-8", model.getModelEncoding()); assertEquals("jar", model.getPackaging()); // assertEquals("4.0.0", model.getModelVersion()); assertEquals("a", model.getGroupId()); assertEquals("b", model.getArtifactId()); assertEquals("c", model.getVersion()); assertNotNull(model.getDependencyManagement()); assertEquals(model.getDependencyManagement().getDependencies().isEmpty(), false); assertNotNull(model.getDependencies()); Dependency dependency = model.getDependencies().get(0); assertEquals("org.clojure", dependency.getGroupId()); assertNotNull(model.getBuild()); assertNotNull(model.getBuild().getPlugins()); assertEquals(false, model.getBuild().getPlugins().isEmpty()); assertEquals(2, model.getBuild().getPlugins().size()); Plugin plugin = model.getBuild().getPlugins().get(1); assertNotNull(plugin); assertEquals("clojure-maven-plugin", plugin.getArtifactId()); assertEquals("1.2-SNAPSHOT", plugin.getVersion()); } @Test public void testScripted() throws Exception { Model model = readClojureModel("test2.clj"); assertNotNull(model); boolean hasTestNg = false; for (Dependency dependency : model.getDependencies()) { if ("testng".equals(dependency.getArtifactId())) { hasTestNg = true; } } assertEquals(true, hasTestNg); } @Test public void testNoGroupOrArtifact() throws Exception { Model model = readClojureModel("test3.clj"); assertNotNull(model); } @Test public void testReadsLeiningen() throws Exception { Model model = readClojureModel("test.leiningen.1.clj"); assertNotNull(model); } private Model readClojureModel(final String sourceFile) throws Exception { ModelReader reader = lookup(ModelReader.class, "clojure"); URL input = getClass().getResource(sourceFile); assertNotNull(input); Map options = new HashMap(); options.put(ModelProcessor.SOURCE, input); return reader.read(input.openStream(), options); } } ClojureModelWriterTest.java000066400000000000000000000024501202174026400414160ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/java/org/sonatype/maven/polyglot/clojurepackage org.sonatype.maven.polyglot.clojure; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.PlexusTestCase; import org.junit.Test; import java.io.StringWriter; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Tests for {@link ClojureModelWriter}. * * @author Mark Derricutt */ public class ClojureModelWriterTest extends PlexusTestCase { @Test public void testModelPrinting() throws Exception { Model model = readClojureModel("test1.clj"); assertNotNull(model); ClojureModelWriter writer = new ClojureModelWriter(); StringWriter sw = new StringWriter(); writer.write(sw, new HashMap(), model); System.out.println(sw.getBuffer().toString()); } private Model readClojureModel(final String sourceFile) throws Exception { ModelReader reader = lookup(ModelReader.class, "clojure"); URL input = getClass().getResource(sourceFile); assertNotNull(input); Map options = new HashMap(); options.put(ModelProcessor.SOURCE, input); return reader.read(input.openStream(), options); } } polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/000077500000000000000000000000001202174026400262265ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/000077500000000000000000000000001202174026400270155ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/000077500000000000000000000000001202174026400306575ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/000077500000000000000000000000001202174026400317655ustar00rootroot00000000000000000077500000000000000000000000001202174026400335575ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/polyglot000077500000000000000000000000001202174026400352225ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/polyglot/clojuretest.leiningen.1.clj000066400000000000000000000010051202174026400407750ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/polyglot/clojure(defproject org.clojars.the-kenny/clojure-couchdb "0.2" :description "Simple Clojure interface to Apache CouchDB, fork of the original project with function arguments instead of *server* and some other changes." :dependencies [[org.clojure/clojure "1.1.0-master-SNAPSHOT"] [org.clojure/clojure-contrib "1.0-SNAPSHOT"] [org.clojure/clojure-http-client "1.0.0-SNAPSHOT"]] :dev-dependencies [[lein-clojars "0.5.0-SNAPSHOT"] [org.clojure/swank-clojure "1.0"]])test1.clj000066400000000000000000000014461202174026400367610ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/polyglot/clojure(defmaven 'a/b "c" :name "Polyglot Test" :description "Maven 3 Clojure based Polyglot test" :properties {:test "test"} :dependency-management [:dependencies [['org.apache.maven/apache-maven "${mavenVersion}" :classifier "bin" :type "zip"]]] :dependencies [['org.clojure/clojure "1.1.0-alpha-SNAPSHOT"] 'org.clojure/clojure-contrib] :test-dependencies [['org.junit/junit "4.0"]] :build [:plugins [['org.apache.maven.plugins/maven-compiler-plugin :source "1.5" :target "1.5"] ['com.theoryinpractise/clojure-maven-plugin "1.2-SNAPSHOT" :testScript "src/test/clojure/test.clj" :executions [[:id "compile" :phase "compile" :goals ["compile"]] [:id "test" :phase "test" :goals ["test"]]]] ]]) test2.clj000066400000000000000000000004041202174026400367530ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/polyglot/clojure(defmaven 'a/b "c" :dependencies [['org.clojure/clojure "1.1.0-alpha-SNAPSHOT"] ['org.clojure/clojure-contrib "1.0-SNAPSHOT"]]) ; Use the provided API to add a new dependency (.addDependency @*MODEL* (Dependency 'org.testng/testng "5.10")) test3.clj000066400000000000000000000002261202174026400367560ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-clojure/src/test/resources/org/sonatype/maven/polyglot/clojure(defmaven :name "Polyglot Test" :parent ['some/artifact "1.0"] :description "Maven 3 Clojure based Polyglot test" :properties {:test "test"}) polyglot-maven-0.8~tobrien+git20120905/pmaven-common/000077500000000000000000000000001202174026400222735ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/.gitignore000066400000000000000000000000531202174026400242610ustar00rootroot00000000000000target/ .project .classpath .settings/ bin polyglot-maven-0.8~tobrien+git20120905/pmaven-common/pom.xml000066400000000000000000000027531202174026400236170ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-common Polyglot Maven :: Common org.apache.maven maven-model-builder org.apache.maven maven-embedder polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/000077500000000000000000000000001202174026400230625ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/000077500000000000000000000000001202174026400240065ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/000077500000000000000000000000001202174026400247275ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/000077500000000000000000000000001202174026400255165ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/000077500000000000000000000000001202174026400273605ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400304665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400323375ustar00rootroot00000000000000PolyglotArtifactFilterDelegate.java000066400000000000000000000026161202174026400412200ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot; import org.apache.maven.ArtifactFilterManagerDelegate; import org.codehaus.plexus.component.annotations.Component; import java.util.Set; /** * Additional filter required for using {@link org.sonatype.maven.polyglot.execute} bits from plugins. * * @author Jason Dillon * * @since 0.7 */ @Component(role=ArtifactFilterManagerDelegate.class, hint="polyglot") public class PolyglotArtifactFilterDelegate implements ArtifactFilterManagerDelegate { public void addExcludes(final Set strings) { assert strings != null; strings.add("pmaven-common"); } public void addCoreExcludes(final Set strings) { assert strings != null; strings.add("pmaven-common"); } } PolyglotModelManager.java000066400000000000000000000052651202174026400372200ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.apache.maven.model.locator.ModelLocator; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.sonatype.maven.polyglot.mapping.Mapping; import java.io.File; import java.util.List; import java.util.Map; /** * Manages the mapping for polyglot model support. * * @author Jason Dillon * * @since 0.7 */ @Component(role=PolyglotModelManager.class) public class PolyglotModelManager implements ModelLocator { @Requirement protected Logger log; @Requirement(role=Mapping.class) private List mappings; public void addMapping(final Mapping mapping) { assert mapping != null; mappings.add(mapping); } public ModelReader getReaderFor(final Map options) { for (Mapping mapping : mappings) { if (mapping.accept(options)) { return mapping.getReader(); } } throw new RuntimeException("Unable determine model input format; options=" + options); } public ModelWriter getWriterFor(final Map options) { for (Mapping mapping : mappings) { if (mapping.accept(options)) { return mapping.getWriter(); } } throw new RuntimeException("Unable determine model output format; options=" + options); } public File locatePom(final File dir) { assert dir != null; File pomFile = null; float mappingPriority = Float.MIN_VALUE; for ( Mapping mapping : mappings ) { File file = mapping.locatePom( dir ); if ( file != null && ( pomFile == null || mappingPriority < mapping.getPriority() ) ) { pomFile = file; mappingPriority = mapping.getPriority(); } } return pomFile; } } PolyglotModelProcessor.java000066400000000000000000000052521202174026400376210ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelParseException; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.IOUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Map; /** * Polyglot model processor. * * @author Jason Dillon * * @since 0.7 */ @Component(role=ModelProcessor.class, hint="polyglot") public class PolyglotModelProcessor implements ModelProcessor { @Requirement protected Logger log; @Requirement private PolyglotModelManager manager; public File locatePom(final File dir) { assert manager != null; File pomFile = manager.locatePom(dir); // behave like proper maven in case there is no pom from manager return pomFile == null? new File( dir, "pom.xml" ) : pomFile; } public Model read(final File input, final Map options) throws IOException, ModelParseException { Model model; Reader reader = new BufferedReader(new FileReader(input)); try { model = read(reader, options); model.setPomFile(input); } finally { IOUtil.close(reader); } return model; } public Model read(final InputStream input, final Map options) throws IOException, ModelParseException { return read(new InputStreamReader(input), options); } public Model read(final Reader input, final Map options) throws IOException, ModelParseException { assert manager != null; ModelReader reader = manager.getReaderFor(options); return reader.read(input, options); } } PolyglotModelTranslator.java000066400000000000000000000116261202174026400377750ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelParseException; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Translates between polyglot model formats. * * @author Jason Dillon * * @since 0.7 */ @Component(role=PolyglotModelTranslator.class) public class PolyglotModelTranslator { @Requirement protected Logger log; @Requirement private PolyglotModelManager manager; public void translate(final File input, final File output) throws IOException, ModelParseException { assert input != null; assert output != null; Map inputOptions = new HashMap(); inputOptions.put(ModelProcessor.SOURCE, input); Map outputOptions = new HashMap(); outputOptions.put(ModelProcessor.SOURCE, output); translate(input, inputOptions, output, outputOptions); } @SuppressWarnings({"unchecked"}) public void translate(final File input, final Map inputOptions, final File output, final Map outputOptions) throws IOException, ModelParseException { assert input != null; assert output != null; ModelReader reader = manager.getReaderFor(inputOptions); Model model = reader.read(input, inputOptions); ModelWriter writer = manager.getWriterFor(outputOptions); writer.write(output, (Map) outputOptions, model); } public void translate(final URL input, final URL output) throws IOException, ModelParseException { assert input != null; assert output != null; Map inputOptions = new HashMap(); inputOptions.put(ModelProcessor.SOURCE, input); Map outputOptions = new HashMap(); outputOptions.put(ModelProcessor.SOURCE, output); translate(input, inputOptions, output, outputOptions); } public void translate(final URL input, final Map inputOptions, final URL output, final Map outputOptions) throws IOException, ModelParseException { assert input != null; assert output != null; OutputStream out; if (output.getProtocol().equals("file")) { File file = new File(output.getPath()); out = new BufferedOutputStream(new FileOutputStream(file)); } else { out = output.openConnection().getOutputStream(); } try { translate(input.openStream(), inputOptions, out, outputOptions); } finally { out.flush(); } } @SuppressWarnings({"unchecked"}) public void translate(final InputStream input, final Map inputOptions, final OutputStream output, final Map outputOptions) throws IOException, ModelParseException { assert input != null; assert output != null; ModelReader reader = manager.getReaderFor(inputOptions); Model model = reader.read(input, inputOptions); ModelWriter writer = manager.getWriterFor(outputOptions); writer.write(output, (Map) outputOptions, model); } @SuppressWarnings({"unchecked"}) public void translate(final Reader input, final Map inputOptions, final Writer output, final Map outputOptions) throws IOException, ModelParseException { assert input != null; assert output != null; ModelReader reader = manager.getReaderFor(inputOptions); Model model = reader.read(input, inputOptions); ModelWriter writer = manager.getWriterFor(outputOptions); writer.write(output, (Map) outputOptions, model); } }PolyglotModelUtil.java000066400000000000000000000035321202174026400365560ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.building.ModelSource; import java.io.File; import java.net.URL; import java.util.Map; /** * Support for models. * * @author Jason Dillon * @since 0.7 */ public class PolyglotModelUtil { /** * Gets the location, as configured via the {@link ModelProcessor#SOURCE} key. * * Supports values of: *
    *
  • String *
  • File *
  • URL *
  • ModelSource *
* * @return The model location; or null. */ public static String getLocation(final Map options) { if (options != null) { Object tmp = options.get(ModelProcessor.SOURCE); if (tmp instanceof String) { return (String)tmp; } else if (tmp instanceof URL) { return ((URL)tmp).toExternalForm(); } else if (tmp instanceof File) { return ((File)tmp).getAbsolutePath(); } else if (tmp instanceof ModelSource) { return ((ModelSource)tmp).getLocation(); } } return null; } }PolyglotRealmDelegate.java000066400000000000000000000032421202174026400373510ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot; import org.apache.maven.classrealm.ClassRealmManagerDelegate; import org.apache.maven.classrealm.ClassRealmRequest; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.annotations.Component; /** * Additional class realm setup required for using {@link org.sonatype.maven.polyglot.execute} bits from plugins. * * @author Jason Dillon * * @since 0.7 */ @Component(role=ClassRealmManagerDelegate.class, hint="polyglot") public class PolyglotRealmDelegate implements ClassRealmManagerDelegate { public void setupRealm(final ClassRealm realm, final ClassRealmRequest request) { assert realm != null; if (!ClassRealmRequest.RealmType.Project.equals(request.getType())) { try { realm.importFrom("plexus.core", "org.sonatype.maven.polyglot.execute"); } catch (Exception e) { throw new IllegalStateException("Could not import Polyglot extensions", e); } } } } 000077500000000000000000000000001202174026400337225ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/executeExecuteContext.java000066400000000000000000000016211202174026400375340ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/execute/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.execute; import org.apache.maven.project.MavenProject; /** * Provides context for {@link ExecuteTask}s. * * @author Jason Dillon * * @since 0.7 */ public interface ExecuteContext { MavenProject getProject(); }ExecuteManager.java000066400000000000000000000020111202174026400374540ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/execute/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.execute; import org.apache.maven.model.Model; import java.util.List; /** * Manages {@link ExecuteTask}s for a project. * * @author Jason Dillon * * @since 0.7 */ public interface ExecuteManager { void register(Model model, List tasks); List getTasks(Model model); void install(Model model); }ExecuteManagerImpl.java000066400000000000000000000073351202174026400403140ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/execute/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.execute; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Default implementation of the {@link ExecuteManager} component. * * @author Jason Dillon * * @since 0.7 */ @Component(role=ExecuteManager.class, instantiationStrategy="singleton") public class ExecuteManagerImpl implements ExecuteManager { @Requirement protected Logger log; private final Map> modelTasks = new HashMap>(); public void register(final Model model, final List tasks) { assert model != null; assert tasks != null; // Need to copy the contents to avoid the elements List copy = new ArrayList(tasks.size()); copy.addAll(tasks); modelTasks.put(model.getId(), Collections.unmodifiableList(copy)); if (log.isDebugEnabled()) { log.debug("Registered tasks for: " + model.getId() + "=" + tasks); } } public List getTasks(final Model model) { assert model != null; List tasks = modelTasks.get(model.getId()); if (tasks == null) { return Collections.emptyList(); } return tasks; } public void install(final Model model) { assert model != null; List tasks = getTasks(model); if (tasks.isEmpty()) { return; } if (log.isDebugEnabled()) { log.debug("Registering tasks for: " + model.getId()); } if (model.getBuild() == null) { model.setBuild(new Build()); } // FIMXE: Should not need to hard-code the version here Plugin plugin = new Plugin(); plugin.setGroupId("org.sonatype.pmaven"); plugin.setArtifactId("pmaven-maven-plugin"); plugin.setVersion("0.8-SNAPSHOT"); model.getBuild().addPlugin(plugin); List goals = Collections.singletonList("execute"); for (ExecuteTask task : tasks) { if (log.isDebugEnabled()) { log.debug("Registering task: " + task); } String id = task.getId(); PluginExecution execution = new PluginExecution(); execution.setId(id); execution.setPhase(task.getPhase()); execution.setGoals(goals); Xpp3Dom config = new Xpp3Dom("configuration"); execution.setConfiguration(config); Xpp3Dom child = new Xpp3Dom("taskId"); child.setValue(id); config.addChild(child); plugin.addExecution(execution); } } }ExecuteTask.java000066400000000000000000000016611202174026400370160ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/execute/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.execute; /** * Represents a language specific task to be executed. * * @author Jason Dillon * * @since 0.7 */ public interface ExecuteTask { String getId(); String getPhase(); void execute(ExecuteContext context) throws Exception; }ExecuteTaskSupport.java000066400000000000000000000022521202174026400404100ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/execute/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.execute; /** * Support for {@link ExecuteTask} implementations. * * @author Jason Dillon * * @since 0.7 */ public abstract class ExecuteTaskSupport implements ExecuteTask { private String id; private String phase; public String getId() { return id; } public void setId(final String id) { this.id = id; } public String getPhase() { return phase; } public void setPhase(final String phase) { this.phase = phase; } }polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/io/000077500000000000000000000000001202174026400327465ustar00rootroot00000000000000ModelReaderSupport.java000066400000000000000000000035641202174026400373220ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/io/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.io; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelParseException; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.IOUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Map; /** * Support for {@link ModelReader} implementations. * * @author Jason Dillon * * @since 0.7 */ public abstract class ModelReaderSupport implements ModelReader { public Model read(final File input, final Map options) throws IOException { Model model; Reader reader = new BufferedReader(new FileReader(input)); try { model = read(reader, options); model.setPomFile(input); } finally { IOUtil.close(reader); } return model; } public Model read(final InputStream input, final Map options) throws IOException { return read(new InputStreamReader(input), options); } }ModelWriterSupport.java000066400000000000000000000035151202174026400373700ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/io/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.io; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.util.IOUtil; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Map; /** * Support for {@link ModelWriter} implementations. * * @author Jason Dillon * * @since 0.7 */ public abstract class ModelWriterSupport implements ModelWriter { public void write(final File file, final Map options, final Model model) throws IOException { assert file != null; assert model != null; OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { write(out, options, model); out.flush(); } finally { IOUtil.close(out); } } public void write(final OutputStream output, final Map options, final Model model) throws IOException { assert output != null; assert model != null; write(new OutputStreamWriter(output), options, model); } }000077500000000000000000000000001202174026400337135ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/mappingMapping.java000066400000000000000000000021521202174026400361510ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/mapping/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.mapping; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import java.io.File; import java.util.Map; /** * Provides a mapping to polyglot specific models. * * @author Jason Dillon * * @since 0.7 */ public interface Mapping { File locatePom(File dir); boolean accept(Map options); ModelReader getReader(); ModelWriter getWriter(); float getPriority(); }MappingSupport.java000066400000000000000000000100051202174026400375420ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/mapping/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.mapping; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.sonatype.maven.polyglot.PolyglotModelUtil; import java.io.File; import java.util.Map; /** * Support for {@link Mapping} implementations. * * @author Jason Dillon * * @since 0.7 */ public abstract class MappingSupport implements Mapping { private static final String[] EMPTY = {}; private String roleHint; private String[] pomNames = EMPTY; private String[] acceptOptionKeys = EMPTY; private String[] acceptLocationExtensions = EMPTY; private float priority; @Requirement private PlexusContainer container; private ModelReader reader; private ModelWriter writer; protected MappingSupport(final String roleHint) { this.roleHint = roleHint == null? "default" : roleHint; } public ModelReader getReader() { if (reader == null) { try { assert container != null; reader = container.lookup(ModelReader.class, roleHint); } catch (ComponentLookupException e) { throw new RuntimeException(e); } } return reader; } public ModelWriter getWriter() { if (writer == null) { try { assert container != null; writer = container.lookup(ModelWriter.class, roleHint); } catch (ComponentLookupException e) { throw new RuntimeException(e); } } return writer; } public String[] getAcceptLocationExtensions() { return acceptLocationExtensions; } public void setAcceptLocationExtensions(final String... accept) { this.acceptLocationExtensions = accept; } public String[] getAcceptOptionKeys() { return acceptOptionKeys; } public void setAcceptOptionKeys(final String... accept) { this.acceptOptionKeys = accept; } public String[] getPomNames() { return pomNames; } public void setPomNames(final String... names) { this.pomNames = names; } public File locatePom(final File dir) { assert dir != null; for (String name : getPomNames()) { File file = new File(dir, name); if (file.exists()) { return file; } } return null; } public boolean accept(final Map options) { if (options != null) { for (String key : getAcceptOptionKeys()) { if (options.containsKey(key)) { return true; } } String location = PolyglotModelUtil.getLocation(options); if (location != null) { for (String ext : getAcceptLocationExtensions()) { if (location.endsWith(ext)) { return true; } } } } return false; } public float getPriority() { return priority; } protected void setPriority( float priority ) { this.priority = priority; } } XmlMapping.java000066400000000000000000000021321202174026400366300ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/main/java/org/sonatype/maven/polyglot/mapping/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.mapping; import org.codehaus.plexus.component.annotations.Component; /** * Xml model mapping. * * @author Jason Dillon * * @since 0.7 */ @Component(role=Mapping.class, hint="xml") public class XmlMapping extends MappingSupport { public XmlMapping() { super(null); setPomNames("pom.xml"); setAcceptLocationExtensions(".xml", ".pom"); setAcceptOptionKeys("xml:4.0.0"); } }polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/000077500000000000000000000000001202174026400240415ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/000077500000000000000000000000001202174026400253665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/org/000077500000000000000000000000001202174026400261555ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/org/sonatype/000077500000000000000000000000001202174026400300175ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/org/sonatype/maven/000077500000000000000000000000001202174026400311255ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400327765ustar00rootroot00000000000000PolyglotModelManagerTest.groovy000066400000000000000000000023321202174026400411130ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/org/sonatype/maven/polyglotpackage org.sonatype.maven.polyglot import org.apache.maven.model.io.DefaultModelReader import org.codehaus.plexus.PlexusTestCase import org.junit.Before import org.junit.Test import static org.apache.maven.model.building.ModelProcessor.SOURCE /** * Tests for {@link org.sonatype.maven.polyglot.PolyglotModelManager}. * * @author Jason Dillon */ public class PolyglotModelManagerTest extends PlexusTestCase { private org.sonatype.maven.polyglot.PolyglotModelManager manager @Before void setUp() { manager = lookup(org.sonatype.maven.polyglot.PolyglotModelManager.class) } private void expectReader(def key, def value, def type) { def options = [:] options.put(key, value) def reader = manager.getReaderFor(options) assertNotNull(reader) assertEquals(type, reader.getClass()) } @Test void testAcceptLocationXml() { expectReader(SOURCE, "foo.xml", DefaultModelReader) } @Test void testAcceptLocationPom() { expectReader(SOURCE, "foo.pom", DefaultModelReader) } @Test void testAcceptKeyXml() { expectReader("xml:4.0.0", "xml:4.0.0", DefaultModelReader) } } PolyglotModelTransformerTest.groovy000066400000000000000000000027561202174026400420550ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/groovy/org/sonatype/maven/polyglotpackage org.sonatype.maven.polyglot import org.codehaus.plexus.PlexusTestCase import org.junit.Before import org.junit.Test import static org.apache.maven.model.building.ModelProcessor.SOURCE /** * Tests for {@link PolyglotModelTranslator}. * * @author Jason Dillon */ public class PolyglotModelTranslatorTest extends PlexusTestCase { private PolyglotModelTranslator translator @Before void setUp() { translator = lookup(PolyglotModelTranslator.class) } private String translate(final String input, final String output) { assertNotNull(input) assertNotNull(output) def url = getClass().getResource(input) assertNotNull(url) def inputOptions = [:] inputOptions.put(SOURCE, url.path) def buff = new StringWriter() def outputOptions = [:] outputOptions.put(SOURCE, output) translator.translate(url.newReader(), inputOptions, buff, outputOptions) return buff.toString() } @Test void testXml2Xml() { def text = translate("pom1.xml", "pom.xml") def expect = getClass().getResource("pom1.xml").text assertEqualsXml(expect, text) } private void assertEqualsXml( String expected, String actual ) { // TODO: Use XmlUnit def text = actual.replaceAll( "(\r\n)|(\r)|(\n)", "\n" ) def expect = expected.replaceAll( "(\r\n)|(\r)|(\n)", "\n" ) assertEquals(expect, text) } } polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/resources/000077500000000000000000000000001202174026400260535ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/resources/org/000077500000000000000000000000001202174026400266425ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/resources/org/sonatype/000077500000000000000000000000001202174026400305045ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/resources/org/sonatype/maven/000077500000000000000000000000001202174026400316125ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/resources/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400334635ustar00rootroot00000000000000pom1.xml000066400000000000000000000005321202174026400350020ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-common/src/test/resources/org/sonatype/maven/polyglot b a c polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/000077500000000000000000000000001202174026400215535ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/pom.xml000066400000000000000000000070731202174026400230770ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-gem gem Polyglot Maven :: GEM 0.26.0 ${project.parent.version}.${mavenVersion}.${jruby.plugins.version} ${project.build.directory}/ruby-maven-${gem.version} ruby-maven-${gem.version}-java.gem ${gem.basedir}/pmaven-${project.parent.version} ${project.basedir}/src/main/resources org.apache.maven.plugins maven-dependency-plugin process-sources unpack false org.sonatype.pmaven pmaven-cli bin zip ${gem.basedir} de.saumya.mojo gem-maven-plugin ${jruby.plugins.version} true ${project.basedir}/src/main/gemspec/maven.gemspec ${gem.basedir}/pmaven-${project.parent.version} polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/000077500000000000000000000000001202174026400223425ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/000077500000000000000000000000001202174026400232665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/gemspec/000077500000000000000000000000001202174026400247115ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/gemspec/maven.gemspec000066400000000000000000000025541202174026400273720ustar00rootroot00000000000000# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{ruby-maven} s.version = "#{File.basename(File.expand_path('..')).sub(/-SNAPSHOT/, '').sub(/[a-zA-Z-]+-/, '').gsub(/-/, '.')}" s.platform = 'java' s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.authors = ["mkristian"] s.description = %q{maven support for rubygems based on maven 3.0. it allows to use xyz.gemspec file as pom file or the usual pom.xml files. with a rails3 application with a Gemfile (suitable for jruby) you can run jetty as development server. this gem is a stripped polyglot-maven which includes only the jruby part. the executable runs only with jruby.} s.email = ["m.kristian@web.de"] s.extra_rdoc_files = ["NOTICE.txt", "LICENSE.txt", "README.txt"] s.files = Dir.glob("*.txt") + Dir.glob("bin/jetty-run") + Dir.glob("bin/rmvn") + Dir.glob("bin/m2.conf") + Dir.glob("boot/*") + Dir.glob("conf/*") + Dir.glob("lib/*") ext = Dir.glob("ext/*ruby*") ext.delete(ext.detect{ |f| f =~ /jruby-complete/ }) s.files += ext s.bindir = "bin" s.executables = ['rmvn', 'jetty-run'] s.homepage = %q{http://github.com/sonatype/polyglot-maven} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ['none'] s.rubygems_version = %q{1.3.5} s.summary = %q{maven support for rubygems} end polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/resources/000077500000000000000000000000001202174026400253005ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/resources/bin/000077500000000000000000000000001202174026400260505ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/resources/bin/jetty-run000077500000000000000000000015261202174026400277430ustar00rootroot00000000000000#!/usr/bin/env jruby if ARGV.size > 4 || ARGV[0] == "--help" || ARGV[0] == "-h" puts "usage: #{File.basename($0)} [-e ] [--war [warfile]]" puts "\tdefault environment: development" exit 1 end args = ["jetty:run"] if ARGV.size == 2 && ARGV[0] == "-e" args << "-Drails.env=#{ARGV[1]}" args << "-Prun" elsif ARGV.size == 1 && ARGV[0] == "--war" args = ["jetty:run-war", "-Pwar"] elsif ARGV.size == 2 && ARGV[0] == "--war" args = ["jetty:deploy-war", "-DwebApp=#{ARGV[1]}", "-Pwar"] elsif ARGV.size == 3 && ARGV[0] == "-e" && ARGV[2] == "--war" args = ["jetty:run-war", "-Pwar", "-Drails.env=#{ARGV[1]}"] elsif ARGV.size == 4 && ARGV[0] == "-e" && ARGV[2] == "--war" args = ["jetty:deploy-war", "-Pwar", "-DwebApp=#{ARGV[3]}", "-Drails.env=#{ARGV[1]}"] end ARGV.replace(args) load File.join(File.dirname(__FILE__), "rmvn") polyglot-maven-0.8~tobrien+git20120905/pmaven-gem/src/main/resources/bin/rmvn000077500000000000000000000051731202174026400267660ustar00rootroot00000000000000#!/usr/bin/env jruby begin require 'java' rescue LoadError => e raise "this executable need jruby. quit." end bin = File.dirname(__FILE__) boot = File.join(bin, "..", "boot") ext = File.join(bin, "..", "ext") classpath = (Dir.glob(boot + "/*jar") + Dir.glob(ext + "/ruby-tools*jar")).join(":") java.lang.System.setProperty("classworlds.conf", File.join(bin, "m2.conf")) java.lang.System.setProperty("maven.home", File.join(bin, "..")) classpath.split(":").each do |path| require path end # make the command line for the goals of the jruby-maven-plugins nicer plugins = { :rake => [:rake], :ruby => [:jruby, :compile], :gem => [:package, :install, :push, :exec, :pom, :initialize, :irb], :gemify => [:gemify, :versions], :rails2 => [:new, :generate, :rake, :server, :console], :rails3 => [:new, :generate, :rake, :server, :console, :dbconsole, :pom], :cucumber => [:test], :rspec => [:test], :runit => [:test], :bundler => [:install] } aliases = {:jruby => :ruby, :spec => :rspec, :rails => :rails3, :bundle => :bundler} if ARGV.size > 0 name = ARGV[0].to_sym name = aliases[name] || name if plugins.member?(name) start = 1 if ARGV.size > 1 if plugins[name].member? ARGV[1].to_sym goal = ARGV[1].to_sym start = 2 else goal = plugins[name][0] end else goal = plugins[name][0] end args = if index = ARGV.index("--") ARGV[index + 1, 1000] else [] end ruby_args = (ARGV[start, (index || 1000) - start] || []).join(' ') # determine the version and delete from ARGV if given version = ARGV.detect do |a| a =~ /^-Dplugin.version=/ end if version args.delete(version) version.sub!(/^-Dplugin.version=/, ':') end args << "de.saumya.mojo:#{name}-maven-plugin#{version}:#{goal}" args << "-Dargs=#{ruby_args}" if ruby_args.size > 0 ARGV.replace(args) else ARGV.delete("--") end end if ARGV.size == 0 || ARGV[0] == "--help" puts "usage: rmvn [| [] [-- ] | [| ] | --help" ARGV.replace(["--help"]) plugins.each do |name, goals| puts print "plugin #{name}" print " - alias: #{aliases[name]}" if aliases[name] puts if goals.size > 1 print "\tgoals : #{goals.join(',')}" puts end print "\tdefault goal: #{goals[0]}" puts end puts end print "maven commandline: " args = ARGV.dup ARGV.clear # clean up in case another script gets executed with clean ARGV puts args.join ' ' org.codehaus.plexus.classworlds.launcher.Launcher.main(args) polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/000077500000000000000000000000001202174026400223305ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/.gitignore000066400000000000000000000000531202174026400243160ustar00rootroot00000000000000target/ .project .classpath .settings/ bin polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/pom.xml000066400000000000000000000032471202174026400236530ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-groovy Polyglot Maven :: Groovy org.sonatype.pmaven pmaven-common org.codehaus.groovy groovy commons-logging commons-logging 1.1.1 polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/000077500000000000000000000000001202174026400231175ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/000077500000000000000000000000001202174026400240435ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/000077500000000000000000000000001202174026400253705ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/org/000077500000000000000000000000001202174026400261575ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/org/sonatype/000077500000000000000000000000001202174026400300215ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/org/sonatype/maven/000077500000000000000000000000001202174026400311275ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400330005ustar00rootroot00000000000000000077500000000000000000000000001202174026400342465ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/org/sonatype/maven/polyglot/groovyMacros.groovy000066400000000000000000000027631202174026400367510ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/groovy/org/sonatype/maven/polyglot/groovypackage org.sonatype.maven.polyglot.groovy /** * Default pom macros. * * @author Jason Dillon * * @since 0.7 */ def vars = binding.properties.variables parseArtifact = {String... items -> assert items != null && items.size() != 0 if (items.size() == 1 && items[0].contains(':')) { return parseArtifact(items[0].split(':')) } def map = [:] switch (items.size()) { case 5: map.groupId = items[0] map.artifactId = items[1] map.type = items[2] map.classifier = items[3] map.version = items[4] break case 4: map.groupId = items[0] map.artifactId = items[1] map.classifier = items[2] map.version = items[3] break case 3: map.groupId = items[0] map.artifactId = items[1] map.version = items[2] break case 2: map.groupId = items[0] map.artifactId = items[1] break default: throw new IllegalArgumentException("Unable to parse artifact for: $items") } return map } vars.'$artifact' = {builder, String... items -> def map = parseArtifact(items) map.each { builder."${it.key}" it.value } } vars.'$configuration' = {builder, Map items -> builder.configuration { for (item in items) { "${item.key}"(item.value) } } }polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/000077500000000000000000000000001202174026400247645ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/000077500000000000000000000000001202174026400255535ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/000077500000000000000000000000001202174026400274155ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400305235ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400323745ustar00rootroot00000000000000000077500000000000000000000000001202174026400336425ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovyDom2Groovy.java000066400000000000000000000310621202174026400365160ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy; import groovy.util.IndentPrinter; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.PrintWriter; import java.io.Reader; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; // // NOTE: Augmented from Groovy's DomToGroovy. // /** * A SAX handler for turning XML into Groovy scripts * * @author James Strachan * @author paulk * @author Jason Dillon * * @since 0.7 */ public class Dom2Groovy { // FIXME: Re-extend from DomToGroovy once version us is released // FIXME: Need the full list, look at Types for hints on how to generate a full list protected final List keywords = Arrays.asList( "class", "extends", "implements", "package", "return", "def", "try", "finally", "this", "new", "catch", "switch", "case", "default", "while", "if", "else", "elseif", "private", "protected", "final", "for", "in", "byte", "short", "break", "instanceof", "synchronized", "const", "float", "null", "throws", "do", "super", "with", "threadsafe", "transient", "native", "interface", "any", "double", "volatile", "as", "assert", "goto", "enum", "int", "boolean", "char", "false", "true", "static", "abstract", "continue", "import", "void", "long" ); protected final IndentPrinter out; protected boolean inMixed = false; // FIXME: Do not quote things like 'true', 'false' or numbers protected String qt = "'"; public Dom2Groovy(final PrintWriter out) { this(new IndentPrinter(out)); } public Dom2Groovy(final IndentPrinter out) { assert out != null; this.out = out; } public void print(final Document document) { printChildren(document, new HashMap()); } public void print(final Reader input) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(input)); print(doc); } protected void print(final Node node, final Map namespaces, final boolean endWithComma) { switch (node.getNodeType()) { case Node.ELEMENT_NODE : printElement((Element) node, namespaces, endWithComma); break; case Node.PROCESSING_INSTRUCTION_NODE : printPI((ProcessingInstruction) node, endWithComma); break; case Node.TEXT_NODE : printText((Text) node, endWithComma); break; case Node.COMMENT_NODE : printComment((Comment) node, endWithComma); break; } } protected void printElement(final Element element, Map namespaces, final boolean endWithComma) { namespaces = defineNamespaces(element, namespaces); element.normalize(); printIndent(); String prefix = element.getPrefix(); boolean hasPrefix = prefix != null && prefix.length() > 0; String localName = getLocalName(element); boolean isKeyword = checkEscaping(localName); if (isKeyword || hasPrefix) print(qt); if (hasPrefix) { print(prefix); print("."); } print(localName); if (isKeyword || hasPrefix) print(qt); boolean hasAttributes = printAttributes(element); // // FIXME: Allow omitting () from empty attributes... needs some more work, // move back to DomToGroovy once sorted // NodeList list = element.getChildNodes(); int length = list.getLength(); if (length == 0) { printEnd("", endWithComma); } else { print(" "); Node node = list.item(0); if (length == 1 && node instanceof Text) { Text textNode = (Text) node; String text = getTextNodeData(textNode); if (hasAttributes) print(", "); printQuoted(text); printEnd("", endWithComma); } else if (mixedContent(list)) { println("{"); out.incrementIndent(); boolean oldInMixed = inMixed; inMixed = true; for (node = element.getFirstChild(); node != null; node = node.getNextSibling()) { print(node, namespaces, false); } inMixed = oldInMixed; out.decrementIndent(); printIndent(); printEnd("}", endWithComma); } else { println("{"); out.incrementIndent(); printChildren(element, namespaces); out.decrementIndent(); printIndent(); printEnd("}", endWithComma); } } } protected void printQuoted(final String text) { if (text.contains("\n")) { print("'''"); print(text); print("'''"); } else { print(qt); print(escapeQuote(text)); print(qt); } } protected void printPI(final ProcessingInstruction instruction, final boolean endWithComma) { printIndent(); print("mkp.pi(" + qt); print(instruction.getTarget()); print(qt + ", " + qt); print(instruction.getData()); printEnd(qt + ");", endWithComma); } protected void printComment(final Comment comment, final boolean endWithComma) { String text = comment.getData().trim(); if (text.length() >0) { printIndent(); print("/* "); print(text); printEnd(" */", endWithComma); } } protected void printText(final Text node, final boolean endWithComma) { String text = getTextNodeData(node); if (text.length() > 0) { printIndent(); if (inMixed) print("mkp.yield "); printQuoted(text); printEnd("", endWithComma); } } protected String escapeQuote(final String text) { return text.replaceAll("\\\\", "\\\\\\\\").replaceAll(qt, "\\\\" + qt); } protected Map defineNamespaces(final Element element, final Map namespaces) { Map answer = null; String prefix = element.getPrefix(); if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { answer = new HashMap(namespaces); defineNamespace(answer, prefix, element.getNamespaceURI()); } NamedNodeMap attributes = element.getAttributes(); int length = attributes.getLength(); for (int i = 0; i < length; i++) { Attr attribute = (Attr) attributes.item(i); prefix = attribute.getPrefix(); if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { if (answer == null) { answer = new HashMap(namespaces); } defineNamespace(answer, prefix, attribute.getNamespaceURI()); } } return (answer != null) ? answer : namespaces; } protected void defineNamespace(final Map namespaces, final String prefix, final String uri) { namespaces.put(prefix, uri); if (!prefix.equals("xmlns") && !prefix.equals("xml")) { printIndent(); print("mkp.declareNamespace("); print(prefix); print(":" + qt); print(uri); println(qt + ")"); } } protected boolean printAttributes(final Element element) { boolean hasAttribute = false; NamedNodeMap attributes = element.getAttributes(); int length = attributes.getLength(); if (length > 0) { print("("); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < length; i++) { printAttributeWithPrefix((Attr) attributes.item(i), buffer); } for (int i = 0; i < length; i++) { hasAttribute = printAttributeWithoutPrefix((Attr) attributes.item(i), hasAttribute); } if (buffer.length() > 0) { if (hasAttribute) { print(", "); } print(buffer.toString()); hasAttribute = true; } print(")"); } return hasAttribute; } protected void printAttributeWithPrefix(final Attr attribute, final StringBuffer buffer) { String prefix = attribute.getPrefix(); if (prefix != null && prefix.length() > 0 && !prefix.equals("xmlns")) { if (buffer.length() > 0) { buffer.append(", "); } buffer.append(qt); buffer.append(prefix); buffer.append(":"); buffer.append(getLocalName(attribute)); buffer.append(qt + ":" + qt); buffer.append(escapeQuote(getAttributeValue(attribute))); buffer.append(qt); } } protected String getAttributeValue(final Attr attribute) { return attribute.getValue(); } protected boolean printAttributeWithoutPrefix(final Attr attribute, boolean hasAttribute) { String prefix = attribute.getPrefix(); if (prefix == null || prefix.length() == 0) { if (!hasAttribute) { hasAttribute = true; } else { print(", "); } String localName = getLocalName(attribute); boolean needsEscaping = checkEscaping(localName); if (needsEscaping) print(qt); print(localName); if (needsEscaping) print(qt); print(":"); printQuoted(getAttributeValue(attribute)); } return hasAttribute; } protected boolean checkEscaping(final String localName) { return keywords.contains(localName) || localName.contains("-") || localName.contains(".") || localName.contains(":"); } protected String getTextNodeData(final Text node) { return node.getData().trim(); } protected boolean mixedContent(final NodeList list) { boolean hasText = false; boolean hasElement = false; for (int i = 0, size = list.getLength(); i < size; i++) { Node node = list.item(i); if (node instanceof Element) { hasElement = true; } else if (node instanceof Text) { String text = getTextNodeData((Text) node); if (text.length() > 0) { hasText = true; } } } return hasText && hasElement; } protected void printChildren(final Node parent, final Map namespaces) { for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) { print(node, namespaces, false); } } protected String getLocalName(final Node node) { String answer = node.getLocalName(); if (answer == null) { answer = node.getNodeName(); } return answer.trim(); } protected void printEnd(final String text, final boolean endWithComma) { if (endWithComma) { print(text); println(","); } else { println(text); } } protected void println(final String text) { out.println(text); } protected void print(final String text) { out.print(text); } protected void printIndent() { out.printIndent(); } } GroovyMapping.java000066400000000000000000000024051202174026400373070ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.mapping.Mapping; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** * Groovy model mapping. * * @author Jason Dillon * * @since 0.7 */ @Component(role=Mapping.class, hint="groovy") public class GroovyMapping extends MappingSupport { public GroovyMapping() { super("groovy"); setPomNames("pom.groovy", "pom.gy"); setAcceptLocationExtensions(".groovy", ".gy"); setAcceptOptionKeys("groovy:4.0.0"); setPriority( -1 ); } }GroovyModelReader.java000066400000000000000000000107541202174026400401050ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy; import groovy.lang.GroovyCodeSource; import groovy.lang.GroovyShell; import groovy.lang.Script; import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.apache.maven.model.io.ModelReader; import org.codehaus.groovy.runtime.StackTraceUtils; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.IOUtil; import org.sonatype.maven.polyglot.PolyglotModelUtil; import org.sonatype.maven.polyglot.execute.ExecuteManager; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; import org.sonatype.maven.polyglot.io.ModelReaderSupport; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.util.Map; /** * Reads a pom.groovy and transforms into a Maven {@link Model}. * * @author Jason Dillon * * @since 0.7 */ @Component(role=ModelReader.class, hint="groovy") public class GroovyModelReader extends ModelReaderSupport { @Requirement protected Logger log; @Requirement private ModelBuilder builder; @Requirement private ExecuteManager executeManager; public Model read(final Reader input, final Map options) throws IOException { assert input != null; Model model; try { model = doRead(input, options); } catch (Throwable t) { t = StackTraceUtils.sanitize(t); if (t instanceof IOException) { throw (IOException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } if (t instanceof Error) { throw (Error)t; } throw new RuntimeException(t); } // FIXME: Looks like there are cases where the model is loaded more than once executeManager.install(model); if (log.isDebugEnabled()) { DefaultModelWriter writer = new DefaultModelWriter(); StringWriter buff = new StringWriter(); writer.write(buff, null, model); log.debug("Read groovy model: \n" + buff); } return model; } private Model doRead(final Reader input, final Map options) throws IOException { assert input != null; GroovyShell shell = new GroovyShell(); String text = IOUtil.toString(input); String location = PolyglotModelUtil.getLocation(options); Script script = shell.parse(new GroovyCodeSource(text, location, location)); /* FIXME: Bring this back as pure java def include = {source -> assert source != null def include // TODO: Support String, support loading from resource if (source instanceof Class) { include = source.newInstance() } else if (source instanceof File) { include = shell.parse((File)source) } else if (source instanceof URL) { include = shell.parse(((URL)source).openStream()) } else { throw new IllegalArgumentException("Invalid include source: $source") } include.run() // Include each closure variable which starts with '$' and curry in the builder include.binding.properties.variables.each { if (it.value instanceof Closure && it.key.startsWith('$')) { binding.setVariable(it.key, it.value.curry(builder)) } } } include(Macros) binding.setProperty('$include', include) */ assert builder != null; return (Model) builder.build(script); } } GroovyModelWriter.java000066400000000000000000000062551202174026400401600ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy; import groovy.util.IndentPrinter; import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Map; /** * Writes a Maven {@link org.apache.maven.model.Model} to a pom.groovy. * * @author Jason Dillon * * @since 0.7 */ @Component(role=ModelWriter.class, hint="groovy") public class GroovyModelWriter extends ModelWriterSupport { @Requirement protected Logger log; public void write(final Writer output, final Map options, final Model model) throws IOException { assert output != null; assert model != null; StringWriter buff = new StringWriter(); DefaultModelWriter writer = new DefaultModelWriter(); writer.write(buff, options, model); Dom2Groovy converter = new Dom2Groovy(new IndentPrinter(new PrintWriter(output), " ")); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(buff.toString()))); Element root = doc.getDocumentElement(); NamedNodeMap attrs = root.getAttributes(); for (int i=0; iJason Dillon * * @since 0.7 */ @Component(role=ModelBuilder.class) public class ModelBuilder extends FactoryBuilderSupport implements Initializable { @Requirement protected Logger log; private final Set factoryNames = new HashSet(); private final Set factoryTypes = new HashSet(); private final List tasks = new ArrayList(); @Requirement private ExecuteManager executeManager; public void initialize() throws InitializationException { registerFactories(); } @Override protected void setClosureDelegate(final Closure c, final Object o) { c.setDelegate(this); c.setResolveStrategy(Closure.DELEGATE_FIRST); } @Override public void setVariable(final String name, final Object value) { InvokerHelper.setProperty(getCurrent(), name, value); } public ExecuteManager getExecuteManager() { return executeManager; } public List getTasks() { return tasks; } public void registerFactories() { registerStringFactory("module"); registerStringFactory("filter"); registerStringFactory("include"); registerStringFactory("exclude"); registerStringFactory("goal"); registerStringFactory("role"); registerStringFactory("otherArchive"); registerStringFactory("activeByDefault"); registerStringFactory("report"); registerFactory(new PluginFactory()); registerFactoriesFor(Plugin.class); registerFactory(new ModulesFactory()); registerFactory(new ExclusionsFactory()); registerFactory(new ExtensionsFactory()); registerFactory(new IncludesFactory()); registerFactory(new ExcludesFactory()); registerFactory(new GoalsFactory()); registerFactory(new ExecuteFactory()); registerFactory(new ReportSetsFactory()); registerFactory(new ReportsFactory()); registerFactory(new ReportingFactory()); registerFactoriesFor(Reporting.class); registerFactory(new ExecutionFactory()); registerFactoriesFor(PluginExecution.class); registerFactory(new ModelFactory()); registerFactoriesFor(Model.class); registerChildFactory("dependency", Dependency.class); registerChildFactory("exclusion", Exclusion.class); registerChildFactory("extension", Extension.class); registerChildFactory("resource", Resource.class); registerChildFactory("testResource", Resource.class); registerChildFactory("notifier", Notifier.class); registerChildFactory("contributor", Contributor.class); registerChildFactory("developer", Developer.class); registerChildFactory("license", License.class); registerChildFactory("mailingList", MailingList.class); registerChildFactory("profile", Profile.class); registerChildFactory("repository", DeploymentRepository.class); registerChildFactory("pluginRepository", Repository.class); registerChildFactory("reportSet", ReportSet.class); registerChildFactory("activation", Activation.class); } @Override public void registerBeanFactory(final String name, final Class type) { super.registerBeanFactory(name, type); registerFactoriesFor(type); } @Override public void registerFactory(final String name, final String groupName, final Factory factory) { if (log.isDebugEnabled()) { log.debug("Registering factory: " + name + ", factory: " + factory); if (factoryNames.contains(name)) { log.warn("Duplicate factory: " + name); } } factoryNames.add(name); super.registerFactory(name, groupName, factory); } private void registerFactory(final NamedFactory factory) { assert factory != null; registerFactory(factory.getName(), null, factory); } private void registerChildFactory(final String name, final Class type) { registerFactory(createChildFactory(name, type)); registerFactoriesFor(type); } private NamedFactory createChildFactory(final String name, final Class type) { assert name != null; assert type != null; if (type == Parent.class) { return new ParentFactory(); } if (type == Dependency.class) { return new DependencyFactory(); } if (type == Exclusion.class) { return new ExclusionFactory(); } return new ChildFactory(name, type); } private void registerStringFactory(final String name) { registerFactory(new StringFactory(name)); } private void registerListFactory(final String name) { registerFactory(new ListFactory(name)); } private void registerPropertiesFactory(final String name) { registerFactory(new PropertiesFactory(name)); } private void registerObjectFactory(final String name) { registerFactory(new ObjectFactory(name)); } private void registerFactoriesFor(final Class type) { assert type != null; if (factoryTypes.contains(type)) { return; } factoryTypes.add(type); if (log.isDebugEnabled()) { log.debug("Registering factories for type: " + type); } Method[] methods = type.getMethods(); for (Method method : methods) { if (isSetter(method) ){ String name = propertyNameOf(method); if (factoryNames.contains(name)) { continue; } Class param = method.getParameterTypes()[0]; if (param == String.class) { registerStringFactory(name); } else if (param == List.class) { registerListFactory(name); } else if (param == Properties.class) { registerPropertiesFactory(name); } else if (param == Object.class) { registerObjectFactory(name); } else if (param.getName().startsWith("org.apache.maven.model.")) { registerChildFactory(name, param); } else { // Skip setters with unsupported types (model will use string versions) if (log.isDebugEnabled()) { log.debug("Skipping setter with unsupported type: " + method); } } } } } private boolean isSetter(final Method method) { assert method != null; if (!method.getName().startsWith("set")) { return false; } if (method.getParameterTypes().length > 1) { return false; } if (method.getReturnType() != Void.TYPE) { return false; } int m = method.getModifiers(); if (!Modifier.isPublic(m) || Modifier.isStatic(m)) { return false; } return true; } private String propertyNameOf(final Method method) { assert method != null; String name = method.getName(); name = name.substring(3, name.length()); return new StringBuffer(name.length()) .append(Character.toLowerCase(name.charAt(0))) .append(name.substring(1)) .toString(); } public Object findInContext(final String key) { for (Map ctx : getContexts()) { if (ctx.containsKey(key)) { return ctx.get(key); } } return null; } // BEGIN: Kludgy Workaround // Explanation: When I translated the slf4j pom.xml to pom.groovy, I ended up with this: // plugin { // artifactId 'maven-project-info-reports-plugin' // reportSets { // reportSet // } // } // The ModelBuilder saw this, and assumed that it was trying to populate the reportSet method. Note // that this shows up because the slf4j pom.xml includes // a private ReportSet reportSet; public ReportSet getReportSet() { return reportSet; } public void setReportSet(ReportSet reportSet) { this.reportSet = reportSet; } // END: Kludgy Workaround }000077500000000000000000000000001202174026400367375ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factoryChildFactory.java000066400000000000000000000023501202174026400421550ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.Map; /** * Builds child nodes. * * @author Jason Dillon * * @since 0.7 */ public class ChildFactory extends NamedFactory { private final Class type; public ChildFactory(final String name, final Class type) { super(name); this.type = type; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return type.newInstance(); } }DependencyFactory.java000066400000000000000000000046121202174026400432130ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Dependency; import java.util.Map; /** * Builds {@link org.apache.maven.model.Dependency} nodes. * * @author Jason Dillon * * @since 0.7 */ public class DependencyFactory extends NamedFactory { public DependencyFactory() { super("dependency"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { Dependency node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new Dependency(); } return node; } public static Dependency parse(final Object value) { assert value != null; if (value instanceof String) { Dependency node = new Dependency(); String[] items = ((String)value).split(":"); switch (items.length) { case 4: node.setGroupId(items[0]); node.setArtifactId(items[1]); node.setVersion(items[2]); node.setScope(items[3]); return node; case 3: node.setGroupId(items[0]); node.setArtifactId(items[1]); node.setVersion(items[2]); return node; case 2: node.setGroupId(items[0]); node.setArtifactId(items[1]); return node; } } return null; } }ExcludesFactory.java000066400000000000000000000036131202174026400427110ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds excludes nodes. * * @author Jason Dillon * * @since 0.7 */ public class ExcludesFactory extends ListFactory { public ExcludesFactory() { super("excludes"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; List node = new ArrayList(); if (value instanceof String) { node.add(value); return node; } else if (value instanceof List) { for (Object item : (List)value) { node.add(String.valueOf(item)); } return node; } return null; } }ExclusionFactory.java000066400000000000000000000036761202174026400431170ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Exclusion; import java.util.Map; /** * Builds {@link org.apache.maven.model.Exclusion} nodes. * * @author Jason Dillon * * @since 0.7 */ public class ExclusionFactory extends NamedFactory { public ExclusionFactory() { super("exclusion"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { Exclusion node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new Exclusion(); } return node; } public static Exclusion parse(final Object value) { assert value != null; if (value instanceof String) { Exclusion node = new Exclusion(); String[] items = ((String)value).split(":"); switch (items.length) { case 2: node.setGroupId(items[0]); node.setArtifactId(items[1]); return node; } } return null; } }ExclusionsFactory.java000066400000000000000000000043511202174026400432710ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Exclusion; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds exclusions nodes. * * @author Jason Dillon * * @since 0.7 */ public class ExclusionsFactory extends ListFactory { public ExclusionsFactory() { super("exclusions"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; if (value instanceof String) { Exclusion child = ExclusionFactory.parse(value); if (child != null) { List node = new ArrayList(); node.add(child); return node; } } else if (value instanceof List) { List node = new ArrayList(); for (Object item : (List)value) { Exclusion child = ExclusionFactory.parse(item); if (child == null) { return null; } node.add(child); } return node; } return null; } }ExecuteFactory.java000066400000000000000000000052301202174026400425340ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.lang.Closure; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Build; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; import org.sonatype.maven.polyglot.groovy.execute.GroovyExecuteTask; import java.util.List; import java.util.Map; /** * Builds {@link GroovyExecuteTask}s. * * @author Jason Dillon * * @since 0.7 */ public class ExecuteFactory extends NamedFactory { public ExecuteFactory() { super("$execute"); } @Override public boolean isHandlesNodeChildren() { return true; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return new GroovyExecuteTask(value, attrs); } @Override public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (parent instanceof Build) { GroovyExecuteTask task = (GroovyExecuteTask) child; List tasks = ((ModelBuilder) builder).getTasks(); tasks.add(task); } else { throw new IllegalStateException("The " + getName() + " element must only be defined under 'build'"); } } @Override public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { GroovyExecuteTask task = (GroovyExecuteTask) node; task.setClosure(content); return false; } @Override public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { GroovyExecuteTask task = (GroovyExecuteTask) node; if (task.getId() == null) { throw new IllegalStateException("Execute task is missing attribute 'id'"); } if (task.getPhase() == null) { throw new IllegalStateException("Execute task is missing attribute 'phase'"); } } }ExecutionFactory.java000066400000000000000000000041771202174026400431060ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.PluginExecution; import java.util.Collections; import java.util.List; import java.util.Map; /** * Builds {@link org.apache.maven.model.PluginExecution} nodes. * * @author Jason Dillon * @since 0.7 */ public class ExecutionFactory extends NamedFactory { public ExecutionFactory() { super("execution"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return new PluginExecution(); } @Override public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object current, Map attrs) { PluginExecution node = (PluginExecution) current; // Custom handling for 'goal' and 'goals' attributes if (attrs.containsKey("goal")) { Object value = attrs.get("goal"); node.setGoals(Collections.singletonList(String.valueOf(value))); attrs.remove("goal"); } else if (attrs.containsKey("goals")) { Object value = attrs.get("goals"); if (value instanceof String) { node.setGoals(Collections.singletonList(String.valueOf(value))); } else if (value instanceof List) { node.setGoals((List) value); } attrs.remove("goals"); } return true; } }ExtensionFactory.java000066400000000000000000000042121202174026400431050ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.Map; import org.apache.maven.model.Extension; /** * Builds {@link org.apache.maven.model.Extension nodes. * * @author Tim O'Brien * * @since 0.8 */ public class ExtensionFactory extends NamedFactory { public ExtensionFactory() { super("extension"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { Extension node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new Extension(); } return node; } public static Extension parse(final Object value) { assert value != null; if (value instanceof String) { Extension node = new Extension(); String[] items = ((String)value).split(":"); switch (items.length) { case 2: node.setGroupId(items[0]); node.setArtifactId(items[1]); return node; case 3: node.setGroupId(items[0]); node.setArtifactId(items[1]); node.setVersion(items[2]); return node; } } return null; } }ExtensionsFactory.java000066400000000000000000000054471202174026400433030ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Exclusion; import org.apache.maven.model.Extension; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds extensions nodes. * * @author Tim O'Brien * * @since 0.8 */ public class ExtensionsFactory extends ListFactory { public ExtensionsFactory() { super("extensions"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { Object node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static Object parse(final Object value) { assert value != null; // This first clause is a kludge. Maybe there is a better way // but we're overloading "extensions" in POMs. if (value instanceof String && isBoolean( (String) value ) ) { return value; } else if( value instanceof String) { Extension child = ExtensionFactory.parse(value); if (child != null) { List node = new ArrayList(); node.add(child); return node; } } else if (value instanceof List) { List node = new ArrayList(); for (Object item : (List)value) { Extension child = ExtensionFactory.parse(item); if (child == null) { return null; } node.add(child); } return node; } return null; } // TOB: Sure, some clever bastard is going to come along and tell me there // is a simpler way to do this. Please, if you have a better solution fix this. private static boolean isBoolean(String value) { return value.equalsIgnoreCase( "true" ) || value.equalsIgnoreCase("false"); } }GoalsFactory.java000066400000000000000000000036271202174026400422070ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds goals nodes. * * @author Jason Dillon * * @since 0.7 */ public class GoalsFactory extends ListFactory { public GoalsFactory() { super("goals"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; List node = new ArrayList(); if (value instanceof String) { node.add((String)value); return node; } else if (value instanceof List) { for (Object item : (List)value) { node.add(String.valueOf(item)); } return node; } return null; } } IncludesFactory.java000066400000000000000000000036431202174026400427060ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds includes nodes. * * @author Jason Dillon * * @since 0.7 */ public class IncludesFactory extends ListFactory { public IncludesFactory() { super("includes"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; List node = new ArrayList(); if (value instanceof String) { node.add((String)value); return node; } else if (value instanceof List) { for (Object item : (List)value) { node.add(String.valueOf(item)); } return node; } return null; } }ListFactory.java000066400000000000000000000022631202174026400420500ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.ArrayList; import java.util.Map; /** * Builds list nodes. * * @author Jason Dillon * * @since 0.7 */ public class ListFactory extends NamedFactory { public ListFactory(final String name) { super(name); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return new ArrayList(); } }ModelFactory.java000066400000000000000000000035261202174026400422000ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Model; import org.sonatype.maven.polyglot.execute.ExecuteManager; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; import java.util.List; import java.util.Map; /** * Builds {@link Model} elements and handles registration of any {@link ExecuteTask}s. * * @author Jason Dillon * * @since 0.7 */ public class ModelFactory extends NamedFactory { public ModelFactory() { super("project"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return new Model(); } @Override public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { Model model = (Model)node; ExecuteManager manager = ((ModelBuilder)builder).getExecuteManager(); List tasks = ((ModelBuilder) builder).getTasks(); manager.register(model, tasks); // Reset the tasks list for sanity tasks.clear(); } }ModulesFactory.java000066400000000000000000000036171202174026400425510ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds modules nodes. * * @author Jason Dillon * * @since 0.7 */ public class ModulesFactory extends ListFactory { public ModulesFactory() { super("modules"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; List node = new ArrayList(); if (value instanceof String) { node.add(value); return node; } else if (value instanceof List) { for (Object item : (List)value) { node.add(String.valueOf(item)); } return node; } return null; } }NamedFactory.java000066400000000000000000000036771202174026400421730ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.AbstractFactory; import groovy.util.FactoryBuilderSupport; import org.codehaus.groovy.runtime.InvokerHelper; import java.util.List; /** * Support for named factories. * * @author Jason Dillon * * @since 0.7 */ public abstract class NamedFactory extends AbstractFactory { private final String name; protected NamedFactory(final String name) { this.name = name; } public String getName() { return name; } @SuppressWarnings({"unchecked"}) @Override public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { if (parent instanceof List) { ((List)parent).add(child); } else { InvokerHelper.setProperty(parent, getName(), child); } } protected static class NodeValueParseException extends IllegalArgumentException { public NodeValueParseException(final NamedFactory factory, final Object value) { super("Unable to parse " + factory.getName() + " for: " + value + " (" + value.getClass() + ")"); } } @Override public String toString() { return getClass().getSimpleName() + "{" + "name='" + name + '\'' + '}'; } }ObjectFactory.java000066400000000000000000000055711202174026400423500ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.lang.Closure; import groovy.util.FactoryBuilderSupport; import groovy.util.Node; import groovy.util.NodeBuilder; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.util.List; import java.util.Map; /** * Builds object nodes. * * @author Jason Dillon * * @since 0.7 */ public class ObjectFactory extends NamedFactory { public ObjectFactory(final String name) { super(name); } @Override public boolean isHandlesNodeChildren() { return true; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return new Xpp3Dom(getName()); } @Override public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { Xpp3Dom dom = (Xpp3Dom)node; NodeBuilder nodes = new NodeBuilder() { @Override protected void setClosureDelegate(final Closure c, final Object o) { c.setDelegate(this); c.setResolveStrategy(Closure.DELEGATE_FIRST); } @Override public void setProperty(final String name, final Object value) { this.invokeMethod(name, value); } }; content.setDelegate(nodes); content.setResolveStrategy(Closure.DELEGATE_FIRST); Node root = (Node) nodes.invokeMethod(getName(), content); for (Node child : (List) root.children()) { dom.addChild(nodeToXpp3(child)); } return false; } private Xpp3Dom nodeToXpp3(final Node node) { Xpp3Dom dom = new Xpp3Dom((String)node.name()); Object value = node.value(); if (value instanceof String) { dom.setValue(String.valueOf(value)); } Map attrs = node.attributes(); for (Object key : attrs.keySet()) { dom.setAttribute(String.valueOf(key), String.valueOf(attrs.get(key))); } for (Object child : node.children()) { if (child instanceof Node) { dom.addChild(nodeToXpp3((Node)child)); } } return dom; } }ParentFactory.java000066400000000000000000000036711202174026400423720ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Parent; import java.util.Map; /** * Builds {@link Parent} nodes. * * @author Jason Dillon * * @since 0.7 */ public class ParentFactory extends NamedFactory { public ParentFactory() { super("parent"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { Parent node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new Parent(); } return node; } public static Parent parse(final Object value) { assert value != null; if (value instanceof String) { Parent node = new Parent(); String[] items = ((String)value).split(":"); switch (items.length) { case 3: node.setGroupId(items[0]); node.setArtifactId(items[1]); node.setVersion(items[2]); return node; } } return null; } }PluginFactory.java000066400000000000000000000047161202174026400424000ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Plugin; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.Reporting; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; import java.util.Map; /** * Builds {@link org.apache.maven.model.Plugin} nodes. * * @author Jason Dillon * * @since 0.7 */ public class PluginFactory extends NamedFactory { public PluginFactory() { super("plugin"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { if (((ModelBuilder)builder).findInContext(Reporting.class.getName()) != null) { return new ReportPlugin(); } else { Plugin node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new Plugin(); } return node; } } public static Plugin parse(final Object value) { assert value != null; if (value instanceof String) { Plugin node = new Plugin(); String[] items = ((String)value).split(":"); switch (items.length) { case 3: node.setGroupId(items[0]); node.setArtifactId(items[1]); node.setVersion(items[2]); return node; case 2: node.setGroupId(items[0]); node.setArtifactId(items[1]); return node; } } return null; } }PropertiesFactory.java000066400000000000000000000057111202174026400432720ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.lang.Closure; import groovy.util.FactoryBuilderSupport; import groovy.util.Node; import groovy.util.NodeBuilder; import java.util.List; import java.util.Map; import java.util.Properties; /** * Builds properties nodes. * * @author Jason Dillon * * @since 0.7 */ public class PropertiesFactory extends NamedFactory { public PropertiesFactory(final String name) { super(name); } @Override public boolean isHandlesNodeChildren() { return true; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { return new Properties(); } @Override public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { Properties props = (Properties)node; NodeBuilder nodes = new NodeBuilder() { @Override protected void setClosureDelegate(final Closure c, final Object o) { c.setDelegate(this); c.setResolveStrategy(Closure.DELEGATE_FIRST); } @Override public void setProperty(final String name, final Object value) { this.invokeMethod(name, value); } }; content.setDelegate(nodes); content.setResolveStrategy(Closure.DELEGATE_FIRST); Node root = (Node) nodes.invokeMethod(getName(), content); for (Node child : (List)root.value()) { merge(props, child, ""); } return false; } private void merge(Properties props, Node node, String prefix) { assert props != null; assert node != null; assert prefix != null; String name = prefix + node.name(); Object value = node.value(); if (value instanceof String) { props.setProperty(name, String.valueOf(value)); } Map attrs = node.attributes(); for (Object key : attrs.keySet()) { props.setProperty(name + "." + key, String.valueOf(attrs.get(key))); } for (Object child : node.children()) { if (child instanceof Node) { merge(props, (Node)child, name + "."); } } } }ReportSetFactory.java000066400000000000000000000037611202174026400430700ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Exclusion; import org.apache.maven.model.ReportSet; import java.util.Map; /** * Builds {@link org.apache.maven.model.ReportSet} nodes. * * @author Tim O'Brien * * @since 0.8 */ public class ReportSetFactory extends NamedFactory { public ReportSetFactory() { super("reportSet"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { ReportSet node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ReportSet(); } return node; } public static ReportSet parse(final Object value) { assert value != null; /** if (value instanceof String) { ReportSet node = new ReportSEt(); String[] items = ((String)value).split(":"); switch (items.length) { case 2: node.setGroupId(items[0]); node.setArtifactId(items[1]); return node; } } **/ return null; } }ReportSetsFactory.java000066400000000000000000000044251202174026400432510ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Exclusion; import org.apache.maven.model.ReportSet; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds reportSets nodes. * * @author Tim O'Brien * * @since 0.8 */ public class ReportSetsFactory extends ListFactory { public ReportSetsFactory() { super("reportSets"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; if (value instanceof String) { ReportSet child = ReportSetFactory.parse(value); if (child != null) { List node = new ArrayList(); node.add(child); return node; } } else if (value instanceof List) { List node = new ArrayList(); for (Object item : (List)value) { ReportSet child = ReportSetFactory.parse(item); if (child == null) { return null; } node.add(child); } return node; } return null; } }ReportingFactory.java000066400000000000000000000027311202174026400431060ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Reporting; import java.util.Map; /** * Builds {@link org.apache.maven.model.Reporting} nodes. * * @author Jason Dillon * * @since 0.7 */ public class ReportingFactory extends NamedFactory { public ReportingFactory() { super("reporting"); } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { builder.getContext().put(Reporting.class.getName(), true); return new Reporting(); } @Override public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { builder.getContext().remove(Reporting.class.getName()); } }ReportsFactory.java000066400000000000000000000043451202174026400425760ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import org.apache.maven.model.Exclusion; import org.apache.maven.model.ReportSet; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Builds reports nodes. * * @author Tim O'Brien * * @since 0.8 */ public class ReportsFactory extends ListFactory { public ReportsFactory() { super("reports"); } @Override public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { List node; if (value != null) { node = parse(value); if (node == null) { throw new NodeValueParseException(this, value); } } else { node = new ArrayList(); } return node; } public static List parse(final Object value) { assert value != null; if (value instanceof String) { String child = (String) value; if (child != null) { List node = new ArrayList(); node.add(child); return node; } } else if (value instanceof List) { List node = new ArrayList(); for (Object item : (List)value) { String child = (String) item; if (child == null) { return null; } node.add(child); } return node; } return null; } }StringFactory.java000066400000000000000000000022651202174026400424050ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; import java.util.Map; /** * Builds string nodes. * * @author Jason Dillon * * @since 0.7 */ public class StringFactory extends NamedFactory { public StringFactory(final String name) { super(name); } @Override public boolean isLeaf() { return true; } public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) { return String.valueOf(value); } }000077500000000000000000000000001202174026400353045ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/executeGroovyExecuteTask.java000066400000000000000000000047161202174026400416120ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/execute/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.groovy.execute; import groovy.lang.Closure; import org.codehaus.groovy.runtime.StackTraceUtils; import org.sonatype.maven.polyglot.execute.ExecuteContext; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.execute.ExecuteTaskSupport; import java.util.Map; /** * Encapsulates a Groovy {@link ExecuteTask}. * * @author Jason Dillon * * @since 0.7 */ public class GroovyExecuteTask extends ExecuteTaskSupport { private final Object value; private final Map attrs; private Closure closure; public GroovyExecuteTask(final Object value, final Map attrs) { this.value = value; this.attrs = attrs; } public Object getValue() { return value; } public Map getAttributes() { return attrs; } public Closure getClosure() { return closure; } public void setClosure(final Closure closure) { this.closure = closure; } public void execute(final ExecuteContext context) throws Exception { try { getClosure().call(); } catch (Throwable t) { t = StackTraceUtils.sanitize(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } if (t instanceof Exception) { throw (Exception)t; } if (t instanceof Error) { throw (Error)t; } throw new RuntimeException(t); } } @Override public String toString() { return getClass().getSimpleName() + "{" + "id='" + getId() + '\'' + ", phase='" + getPhase() + '\'' + ", value=" + value + ", attrs=" + attrs + ", closure=" + closure + '}'; } }polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/000077500000000000000000000000001202174026400240765ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/000077500000000000000000000000001202174026400254235ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/000077500000000000000000000000001202174026400262125ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/000077500000000000000000000000001202174026400300545ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/000077500000000000000000000000001202174026400311625ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400330335ustar00rootroot00000000000000000077500000000000000000000000001202174026400343015ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/polyglot/groovyGroovyModelReaderTest.groovy000066400000000000000000000025761202174026400420130ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/polyglot/groovypackage org.sonatype.maven.polyglot.groovy import org.apache.maven.model.building.ModelProcessor import org.junit.Before import org.junit.Test import org.apache.maven.model.io.ModelReader /** * Tests for {@link GroovyModelReader}. * * @author Jason Dillon */ public class GroovyModelReaderTest extends GroovyModelTestSupport { private GroovyModelReader reader @Before void setUp() { reader = lookup(ModelReader.class, "groovy") } @Test void testReading() { def input = getClass().getResource("test1.groovy") assertNotNull(input) def options = [:] options.put(ModelProcessor.SOURCE, input) def model = reader.read(input.openStream(), options) assertNotNull(model) dump(model) def parent = model.parent assertNotNull(parent) assertEquals("a", parent.groupId) assertEquals("b", parent.artifactId) assertEquals("c", parent.version) assertEquals("../pom.xml", parent.relativePath) } @Test void testExecute() { def input = getClass().getResource("execute1.groovy") assertNotNull(input) def options = [:] options.put(ModelProcessor.SOURCE, input) def model = reader.read(input.openStream(), options) assertNotNull(model) dump(model) } } GroovyModelTestSupport.groovy000066400000000000000000000033631202174026400422600ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/polyglot/groovypackage org.sonatype.maven.polyglot.groovy import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory import org.apache.maven.model.Model import org.apache.maven.model.io.DefaultModelWriter import org.sonatype.maven.polyglot.groovy.Dom2Groovy import org.w3c.dom.Document import org.xml.sax.InputSource import static org.junit.Assert.* import org.sonatype.maven.polyglot.groovy.Dom2Groovy import org.codehaus.plexus.PlexusTestCase /** * Support for model tests. * * @author Jason Dillon */ public class GroovyModelTestSupport extends PlexusTestCase { protected String load(final String name) { assertNotNull(name) def url = getClass().getResource(name) assertNotNull(url) return url.text } protected String chew(final Model model) { assertNotNull(model) def writer = new DefaultModelWriter() def buff = new StringWriter() writer.write(buff, null, model) return buff.toString() } protected void dump(final Model model) { def buff = new StringWriter() Dom2Groovy converter = new Dom2Groovy(new IndentPrinter(new PrintWriter(buff), " ")) DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() Document doc = builder.parse(new InputSource(new StringReader(chew(model)))) def root = doc.documentElement def attrs = root.attributes for (int i=0; iJason Dillon */ public class GroovyModelWriterTest extends GroovyModelTestSupport { private GroovyModelWriter writer @Before void setUp() { writer = lookup(ModelWriter.class, "groovy") } @Test void testWriting() { def model = new Model(parent: new Parent(groupId: "a", artifactId: "b", version: "c")) def buff = new StringWriter() writer.write(buff, null, model) println(buff) def expected = load("test2.groovy") assertEqualsGroovy(expected, buff.toString()) } private void assertEqualsGroovy( String expected, String actual ) { def text = actual.replaceAll( "(\r\n)|(\r)|(\n)", "\n" ) def expect = expected.replaceAll( "(\r\n)|(\r)|(\n)", "\n" ) assertEquals(expect, text) } }000077500000000000000000000000001202174026400357275ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/polyglot/groovy/builderModelBuilderTest.groovy000066400000000000000000000141221202174026400424050ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/groovy/org/sonatype/maven/polyglot/groovy/builderpackage org.sonatype.maven.polyglot.groovy.builder import org.junit.Before import org.junit.Test import static org.junit.Assert.* import org.sonatype.maven.polyglot.groovy.GroovyModelTestSupport /** * Tests for {@link ModelBuilder}. * * @author Jason Dillon */ public class ModelBuilderTest extends GroovyModelTestSupport { private ModelBuilder builder @Before void setUp() { builder = lookup(ModelBuilder.class) } @Test void testBuildWithElements() { def model = builder.project { parent { groupId 'a' artifactId 'b' version 'c' } dependencies { dependency { groupId 'a' artifactId 'b' version 'c' } } } assertNotNull(model) def p = model.parent assertNotNull(p); assertEquals('a', p.groupId) assertEquals('b', p.artifactId) assertEquals('c', p.version) assertNotNull(model.dependencies) assertEquals(1, model.dependencies.size()) def d = model.dependencies[0] assertEquals('a', d.groupId) assertEquals('b', d.artifactId) assertEquals('c', d.version) } @Test void testBuildWithAttributes() { def model = builder.project { parent(groupId: 'a', artifactId :'b', version: 'c') dependencies { dependency(groupId: 'a', artifactId: 'b', version: 'c') } } assertNotNull(model) def p = model.parent assertNotNull(p); assertEquals('a', p.groupId) assertEquals('b', p.artifactId) assertEquals('c', p.version) assertNotNull(model.dependencies) assertEquals(1, model.dependencies.size()) def d = model.dependencies[0] assertEquals('a', d.groupId) assertEquals('b', d.artifactId) assertEquals('c', d.version) } @Test void testBuildWithConfiguration() { def model = builder.project { build { plugins { plugin { configuration { foo 'a' bar """ blah """ } } } } } assertNotNull(model) } @Test void testBuildWithProperties() { def model = builder.project { properties { foo { bar { a "b" } } 'foo.bar.c' "d" ick(poo: "blah") { grr "barf" } v "x" x = "y" } } assertNotNull(model) def p = model?.properties assertNotNull(p) assertEquals("b", p.getProperty("foo.bar.a")) assertEquals("d", p.getProperty("foo.bar.c")) assertEquals("blah", p.getProperty("ick.poo")) assertEquals("barf", p.getProperty("ick.grr")) assertEquals("x", p.getProperty("v")) assertEquals("y", p.getProperty("x")) } @Test void testBuildParseParent() { def model = builder.project { parent("a:b:c") } assertNotNull(model) def p = model.parent assertNotNull(p); assertEquals('a', p.groupId) assertEquals('b', p.artifactId) assertEquals('c', p.version) } @Test void testBuildParseModules() { def model = builder.project { modules('a', 'b', 'c') } assertNotNull(model) def m = model?.modules assertNotNull(m) assertEquals(3, m.size()) assertEquals([ 'a', 'b', 'c' ], m) } @Test void testBuildParseGoals1() { def model = builder.project { build { plugins { plugin { executions { execution { goals("foo") } } } } } } assertNotNull(model) def g = model?.build?.plugins[0]?.executions[0].goals assertNotNull(g) assertEquals(1, g.size()) assertEquals("foo", g[0]) } @Test void testBuildParseGoals2() { def model = builder.project { build { plugins { plugin { executions { execution { goals("foo", "bar", "baz") } } } } } } assertNotNull(model) def g = model?.build?.plugins[0]?.executions[0].goals assertNotNull(g) assertEquals(3, g.size()) assertEquals(["foo", "bar", "baz"], g) } @Test void testBuildParseExclusions1() { def model = builder.project { dependencies { dependency { exclusions("foo:bar") } } } assertNotNull(model) def e = model?.dependencies[0]?.exclusions assertNotNull(e) assertEquals(1, e.size()) assertEquals("foo", e[0].groupId) assertEquals("bar", e[0].artifactId) } @Test void testBuildParseExclusions2() { def model = builder.project { dependencies { dependency { exclusions("foo:bar", "a:b") } } } assertNotNull(model) def e = model?.dependencies[0]?.exclusions assertNotNull(e) assertEquals(2, e.size()) assertEquals("foo", e[0].groupId) assertEquals("bar", e[0].artifactId) assertEquals("a", e[1].groupId) assertEquals("b", e[1].artifactId) } } polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/000077500000000000000000000000001202174026400261105ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/000077500000000000000000000000001202174026400266775ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/000077500000000000000000000000001202174026400305415ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/000077500000000000000000000000001202174026400316475ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400335205ustar00rootroot00000000000000000077500000000000000000000000001202174026400347665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/groovyexecute1.groovy000066400000000000000000000001621202174026400377570ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/groovyproject { build { $execute(id: 'test1', phase: 'compile') { println 'hi' } } }test1.groovy000066400000000000000000000001361202174026400372750ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/groovyproject { parent { groupId "a" artifactId "b" version("c") } }test1.xml000066400000000000000000000005321202174026400365500ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/groovy b a c test2.groovy000066400000000000000000000001361202174026400372760ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/groovyproject { parent { artifactId 'b' groupId 'a' version 'c' } } test4.groovy000066400000000000000000000002421202174026400372760ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-groovy/src/test/resources/org/sonatype/maven/polyglot/groovyproject { modelVersion "4.0.0" groupId "test" artifactId "test" version "test" build { plugins { } } } polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/000077500000000000000000000000001202174026400221365ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/.gitignore000066400000000000000000000000531202174026400241240ustar00rootroot00000000000000target/ .project .classpath .settings/ bin polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/README.md000066400000000000000000000325041202174026400234210ustar00rootroot00000000000000Ruby DSL ========== there are already ruby DSL which cover some functionality maven offers. like a [RubyGems](http://rubygems.org) is a package format which embeds meta data and dependencies about the ruby code. it is like a jar file packed with a pom. or [bundler](http://gembundler.com) deals with dependencies and how to manage them. instead of creating something new for maven the idea is to just take these existing ones use them with polyglot-maven. # Gemspec DSL # with having a gemspec as pom and you can use polyglot maven (pmaven) to run the test (spec or cucumber features), pack it and install as gem artifact. the description of that [RubyGem::Specification](http://docs.rubygems.org/read/chapter/20). a simple example looks like this: Gem::Specification.new do |s| s.name = 'example' s.version = '1.0' s.summary = 'Example gem specification' end with such gemspec in place you can setup the a local gem repository in target/rubygems $ pmvn initialize to run all test, i.e. rspec and cucumber - regular runit test is not yet supported. specs are run if there is a **rspec** dependency and features are run if there is a **cucumber** depdencency in the gemspec file. $ pmvn test or $ pmvn rspec:test $ pmvn cucumber:test package the gem in target $ pmvn package or install into the local maven repository $ pmvn install and finally deploy it or push it to rubygems.org $ pmvn deploy you can also execute a ruby script in context of the gemspec file, i.e. you can use declared gem dependencies. $ pmvn gem:exec -Dexec.script="require 'fileutils'; FileUtils.ln_s('my.gemspec.pom', 'pom.xml')" similar you can start an irb session (i.e. a console) in the gemspec context $ pmvn gem:irb or as swing application $ pmvn gem:irb -Dirb.swing ## dependencies in the ruby world ## the common way of declaring dependencies in ruby is something like: __rspec ~>2.4.1__ which means all version bigger or equals then 2.4.1 and smaller then 2.5.0. so it is a version range and the dependency resolution varies over time depending on the availability of version for a given gem. and this can break your coed !!! bundler does have a possible solution for it - see below. ## getting more Maven along side the gemspec ## if you need more control over what pmaven does you can use the file **Mavenfile** to add more maven specific declarations. for more details see below. # Gemfile from Bundler as Maven Ruby DSL # Gemfile can declare dependencies and can group them into profiles (groups in bundler speak and profile in maven speak but with further small differences too). further it can include the dependencies of one or more gemspec files. one big thing about bundler is that it solves the uncertainty of version ranges. before you can "use" bunlder you need to run `bundle install` to set up the dependencies. this will write out a file _Gemfile.lock_ which contains the version resolution of the _Gemfile_. any successive run will use the versions of that _Gemfile.lock_ instead of resolve them with the latest gems in the repositories. bundler has some more commands to update and check _Gemfile_ and _Gemfile.lock_. pmaven just follows what bundler does in a maven way. the main difference is that with pmaven in general you do not need to run `bundle install` (only if you use gems from a git repository or from the local filesystem directly). when pmaven sees a Gemfile.lock it will obey these versions otherwise pmaven will resolve them with the version ranges from the _Gemfile_. so with pmaven to perform an **update** is to delete _Gemfile.lock_. in this sense _Gemfile.lock_ is part of the DSL and helps to keeps things stable and reproducable. the same goals work with _Gemfile_ in the same manner as with the _gemspec_ from above. ## Gemfile and Rails3 application ## the _Gemfile_ of Rails3 application will be translated to a more suitable pom as in a normal _Gemfile_ project. first the rails3-maven-plugin will be included, the packaging is war not gem as before and it allows to use jetty as development server. # Mavenfile # the name follows the *Gemfile* and you can use the same DSL as you use for Gemfile in Mavenfile. **NOTE:** bundler does use **ONLY** _Gemfile_ and _Gemfile.lock_ and will ignore _Mavenfile_. that _Mavenfile_ is meant for maven stuff ! ## gem dependencies ## ### NAME (required) For each gem requirement, list a single _gem_ line. gem "nokogiri" ### VERSION Each _gem_ *MAY* have one or more version specifiers. gem "nokogiri", ">= 1.4.2" gem "RedCloth", ">= 4.1.0", "< 4.2.0" ## jar or test_jar dependencies ## ### NAME and VERSION (required) For each jar artifact, list a single _jar_ or _test\_jar_ line with version (range). the name is the _groupId:artifactId_ jar "org.slf4r:slf4r-simple", '1.6.2' ### SCOPE or CLASSIFIER jar("org.slf4r:slf4r-simple", '1.6.2').scope = :test jar("org.slf4r:slf4r-simple", '1.6.2').classifier = :source or use the nested block (this time as test_jar) test_jar("org.slf4r:slf4r-simple", '1.6.2') do |simple| simple.scope :test simple.classifier :source end ## meta data ## ### GROUP\_ID, ARTIFACT\_ID, VERSION, PACKAGING group_id "rubygems" artifact_id "one" version "0.1.0" packaging "gem" ### NAME, DESCRIPTION, URL ### name "some name" description "longer description" url "http://github.com" ### DEVELOPERS ### developers.new("my name", "my_email@example.com") or developers.new("my name ") ### LICENSES ### add the license file like licenses.new("MIT-LICENSE.txt") or the url licenses.new("http://www.gnu.org/licenses/gpl.html") ### REPOSITORIES and PLUGIN_REPOSITORIES ## add a repository with defaults repository("rubygems-releases", "http://gems.saumya.de/releases") or a snapshot repository for plugins plugin_repository("sonatype-snapshots") do |sonatype| sonatype.url "http://oss.sonatype.org/content/repositories/snapshots" sonatype.releases(:enabled => false) sonatype.snapshots(:enabled => true) end or a full fledge one repository("jboss-public-repository-group") do |jboss| jboss.name "JBoss Public Maven Repository Group" jboss.url "https://repository.jboss.org/nexus/content/groups/public-jboss/" jboss.releases(:enabled => false, :updatePolicy => :never, :checksumPloicy => :strict) jboss.snapshots(:enabled => true, :updatePolicy => :daily, :checksumPloicy => :ignore) end you can retrieve a hashmap with repositories or plugin repositories with repositories respectively plugin_repositories ### PROPERTIES ### it comes with a few default properties which can be overwritten properties["gem.home"] = "${project.build.directory}/rubygems" properties["gem.path"] = "${project.build.directory}/rubygems" properties["jruby.plugins.version"] = "0.27.0-SNAPSHOT" properties["project.build.sourceEncoding"] = "UTF-8" to deal with ruby and rubygems specific stuff there are several maven plugins which are used: gem-maven-plugin, rspec-maven-plugin, cucumber-maven-plugin, etc. they are carry the version **${jruby.plugins.version}**. you an overwrite this property inside the **Mavenfile**. in general you can set properties like above or properties.merge!({ "gem.home" => "~/gem" }) or replace the existing through new ones properties = { "gem.home" => "~/gem" } ## build process ## in general the _build_ tag of a maven pom gets omited but is actually there. for example `plugin(name)` just delegates to `build.plugin(name)`. ### DEPENDENCIES, DEPENDENCY_MANAGEMENT ### all example are in context of the project or a profile or a plugin dependency_management do |deps| deps.gem "slf4r", "0.4.2" deps.jar "org.slf4j:slf4j-simple", "1.6.2" end and dependencies via the collection dependencies do |d| d.gem "rspec" d.test_jar "org.slf4j:slf4j-noop", "1.6.2" end or the same in direct way gem "rspec" test_jar "org.slf4j:slf4j-noop", "1.6.2" and with exclusions jar 'org.xerial:sqlite-jdbc', '3.6.10' do |j| j.exclude 'org.xerial.thirdparty:nestedvm' end or the same via the exclusions collection jar 'org.xerial:sqlite-jdbc', '3.6.10' do |j| j.exclusions << 'org.xerial.thirdparty:nestedvm' end the latter can also be written differently. the object created can be used to call methods on it. sqlite = gem 'sqlite-jdbc', '3.6.10' sqlite.exclusions << 'nestedvm' a dependency can be retrieved and call further methods on it. gem 'sqlite-jdbc', '3.6.10' gem('sqlite-jdbc').exclusions << 'nestedvm' ### PLUGINS ### add a maven default plugin plugin 'release' or a maven default plugin with version plugin("clean", "2.4.1") or a maven default plugin with configuration plugin(:compile, "2.3.2").with :source => "1.5", :target => "1.5" also the jruby-maven-plugins can have a short name: * `:jruby` or `"jruby"` for jruby-maven-plugin * `:gem` or `"gem"` for gem-maven-plugin * `:cucumber` or `"cucumber"` for cucumber-maven-plugin * `:rspec` or `"rspec"` for rspec-maven-plugin * `:runit` or `"runit"` for runit-maven-plugin * `:rake` or `"rake"` for rake-maven-plugin * `:rails3` or `"rails3"` for rails3-maven-plugin * `:rails2` or `"rails2"` for rails2-maven-plugin * `:bundler` or `"bundler"` for bundler-maven-plugin * `:gemify` or `"gemify"` for gemify-maven-plugin plugin with extentions plugin(:gem).extensions true or any other plugin with execution goals (default execution without id) plugin('org.codehaus.mojo:gwt-maven-plugin', '2.1.0').execution.goals = ["clean", "compile", "test"] or you want to execute a goal in a phase plugin(:gem).in_phase("pre-integration-test").execute_goal(:install) or a goal in a phase with configuration plugin(:cucumber).in_phase("integration-test").execute_goal(:test).with(:cucumberArgs => "--no-colors") if you can not use the short name then the plugin name is the combination of _:_ as with the jar dependencies. use the block notation when you need to do more with the plugin plugin('org.codehaus.mojo:gwt-maven-plugin', '2.1.0') do |gwt| gwt.with({ :extraJvmArgs => "-Xmx512m", :runTarget => "example.html" }) gwt.execution.goals << ["clean", "compile", "test"] end in case the hashmap notation for the configuration part is not sufficient you can pass in XML directly (the hashmap notation does not attributes like _implementation_ in the _connector_ tag) plugin("org.mortbay.jetty:jetty-maven-plugin", "7.2.2.v20101205").with({ :connectors => <<-XML 8080 8443 ${project.basedir}/src/test/resources/server.keystore 123456 123456 XML }) sometimes you a nested array (here _webResources_ has a list of _resource_) plugin(:war).with({ :webResources => Maven::Model::NamedArray.new(:resource) do |l| l << { :directory => "public" } l << { :directory => ".", :targetPath => "WEB-INF", :includes => ['app/**', 'config/**', 'lib/**', 'vendor/**', 'Gemfile'] } l << { :directory => '${gem.path}', :targetPath => 'WEB-INF/gems' } end }) ### EXECUTE\_IN\_PHASE ### you can write ruby code directly inside the _Mavenfile_ which will be executed in the specified phase execute_in_phase(:verify) do puts "all OK" end ## profiles ## profiles and groups from Gemfile are similiar but not the same. in maven you choose one or more profiles to be active and they participate with action you want to perform. the groups with bundler do all participate with dependency resolution so the resovled version are consistent over *all* groups. ### ACTIVATION ### activation of a profile by default profile(:development).activation.by_default or by property profile(:test).activation.property("rails.env", "test") or via OS (triggered by `family` or `arch` or `name` or `version`) profile("mac").activation.os.family = "mac" ### PLUGIN, PROPERTIES, DEPENDENCY, DEPENDENCY_MANAGEMENT ### any of these nested attributes can set with the help of the block notation profile(:production) do |prod| prod.activation.property("rails.env", "production") prod.properties.merge!({ "gem.home" => "${project.build.directory}/rubygems-production", "gem.path" => "${project.build.directory}/rubygems-production" }) prod.plugin("org.mortbay.jetty:jetty-maven-plugin", "${jetty.version}") prod.gem "cucumber", nil prod.dependency_management.gem "cucumber", '0.9.4' end ### GEM, JAR ### the following group notation will add the gem and the jar to the "test" profile: profile :test do gem "enforce-ssl" jar "org.slf4j:slf4j-noop", "1.6.2" end # missing parts from maven # there are still missing parts, like the *parent* tag or the *modules* or all this report related tags. polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/pom.xml000066400000000000000000000022171202174026400234550ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-jruby Polyglot Maven :: JRuby org.sonatype.pmaven pmaven-common org.jruby jruby-complete 1.6.0 de.saumya.mojo ruby-tools 0.26.0 true polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/000077500000000000000000000000001202174026400227255ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/000077500000000000000000000000001202174026400236515ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/000077500000000000000000000000001202174026400245725ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/000077500000000000000000000000001202174026400253615ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/000077500000000000000000000000001202174026400272235ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400303315ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400322025ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/000077500000000000000000000000001202174026400331635ustar00rootroot00000000000000AbstractRubyModelReader.java000066400000000000000000000107651202174026400404710ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import static org.jruby.embed.LocalContextScope.SINGLETON; import static org.jruby.embed.LocalVariableBehavior.PERSISTENT; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.List; import java.util.Map; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.jruby.embed.ScriptingContainer; import org.sonatype.maven.polyglot.io.ModelReaderSupport; /** * Ruby model reader. * * @author mkristian * @since 0.8 */ abstract public class AbstractRubyModelReader extends ModelReaderSupport { private static final String MAVEN_TOOLS_POM_GENERATOR_RB = "maven/tools/pom_generator.rb"; @Requirement( hint = "default" ) private ModelReader xmlReader; private final ScriptingContainer scriptingContainer; private final Object pomReader; private final String method; public AbstractRubyModelReader( final String method ) { this.scriptingContainer = new ScriptingContainer( SINGLETON, PERSISTENT ); final ClassLoader cl = Thread.currentThread().getContextClassLoader(); this.pomReader = this.scriptingContainer.runScriptlet( cl.getResourceAsStream( MAVEN_TOOLS_POM_GENERATOR_RB ), MAVEN_TOOLS_POM_GENERATOR_RB ); this.method = method; } @SuppressWarnings( "unchecked" ) public Model read( final Reader input, final Map options ) throws IOException { IOUtil.close( input ); final Model model; final File inputFile = new File( options.get( "org.apache.maven.model.building.source" ).toString() ); // need pom to install artifact with xml-pom !!! final File pom = new File( inputFile.getAbsoluteFile() + ".pom" ); List files = (List) FileUtils.loadFile( new File( inputFile.getAbsolutePath() + ".files" ) ); if ( !inputFile.getAbsolutePath().endsWith( ".gemspec" )) { String lockfile = inputFile.getName() + ".lock" ; // TODO maybe the lock file must be newer then all files which participated to the pom if (new File(lockfile).lastModified() < inputFile.lastModified()) { new File(lockfile).delete(); } if ( !files.contains( lockfile ) ){ files.add( lockfile ); } } File mavenFile = new File( inputFile.getParentFile(), "Mavenfile" ); if ( mavenFile.exists() && !files.contains( mavenFile.getName() )) { files.add( mavenFile.getAbsolutePath() ); } if ( !files.contains( inputFile.getName() )) { files.add( inputFile.getAbsolutePath() ); } boolean modified = false; for( String file: files ){ File f = new File( file ); modified |= !f.exists() || pom.lastModified() < f.lastModified(); } if ( !pom.exists() || modified ) { final String pomXml = this.scriptingContainer.callMethod( this.pomReader, "read_" + method, inputFile.getAbsolutePath(), String.class ); // keep the generated pom as temp-file in case there is model error for debugging String pomTmp = pom.getAbsolutePath() + ".tmp"; FileUtils.fileWrite( pomTmp, "utf-8", pomXml ); model = this.xmlReader.read( new StringReader( pomXml ), options ); FileUtils.rename( new File( pomTmp ), pom ); } else { model = this.xmlReader.read( new FileReader( pom ), options ); } // not sure if this persists model.setPomFile( pom ); return model; } } AbstractRubyModelWriter.java000066400000000000000000000052671202174026400405440ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.sonatype.maven.polyglot.io.ModelWriterSupport; /** * Ruby model writer. * * @author mkristian * @since 0.8 */ public class AbstractRubyModelWriter extends ModelWriterSupport { private final Templates xslt; public AbstractRubyModelWriter() throws TransformerConfigurationException { // create an instance of TransformerFactory final TransformerFactory factory = TransformerFactory.newInstance(); final Source source = new StreamSource( getClass().getResourceAsStream( "pom2ruby.xsl" ) ); this.xslt = factory.newTemplates( source ); } public void write( final Writer output, final Map options, final Model model ) throws IOException { assert output != null; assert model != null; if( true ) throw new RuntimeException( "write out a ruby DSL is not implemented yet" ); final DefaultModelWriter writer = new DefaultModelWriter(); final StringWriter pom = new StringWriter(); writer.write( pom, options, model ); final Source xmlSource = new StreamSource( new StringReader( pom.toString() ) ); final Result result = new StreamResult( output ); try { this.xslt.newTransformer().transform( xmlSource, result ); } catch ( final TransformerException e ) { throw (IOException) new IOException( "Error producing ruby code from xml" ).initCause( e ); } } } GemfileRubyMapping.java000066400000000000000000000033001202174026400374710ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import java.io.File; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.mapping.Mapping; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** * Ruby model mapping. * * @author Kristian Meier * @since 0.8 */ @Component( role = Mapping.class, hint = "gemfile-ruby" ) public class GemfileRubyMapping extends MappingSupport { public GemfileRubyMapping() { super( "gemfile-ruby" ); setAcceptLocationExtensions( "Gemfile" ); setPomNames( "Gemfile" ); setAcceptOptionKeys( "rb:4.0.0" ); setPriority( 1.7f ); } @Override public File locatePom( final File dir ) { assert dir != null; final File gemfile = new File( dir, "Gemfile" ); if ( gemfile.exists() ) { return gemfile; } for ( final File f : dir.listFiles() ) { if ( f.isFile() && f.getName().contains( "Gemfile" ) ) { return f; } } return null; } }GemfileRubyModelReader.java000066400000000000000000000020321202174026400402620ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Component; /** * Ruby model reader. * * @author mkristian * @since 0.8 */ @Component( role = ModelReader.class, hint = "gemfile-ruby" ) public class GemfileRubyModelReader extends AbstractRubyModelReader { public GemfileRubyModelReader() { super( "gemfile" ); } } GemfileRubyModelWriter.java000066400000000000000000000021771202174026400403460ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import javax.xml.transform.TransformerConfigurationException; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; /** * Ruby model writer. * * @author mkristian * @since 0.8 */ @Component( role = ModelWriter.class, hint = "gemfile-ruby" ) public class GemfileRubyModelWriter extends AbstractRubyModelWriter { public GemfileRubyModelWriter() throws TransformerConfigurationException { super(); } } GemspecRubyMapping.java000066400000000000000000000030261202174026400375110ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import java.io.File; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.mapping.Mapping; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** * Ruby model mapping. * * @author Kristian Meier * @since 0.8 */ @Component( role = Mapping.class, hint = "gemspec-ruby" ) public class GemspecRubyMapping extends MappingSupport { public GemspecRubyMapping() { super( "gemspec-ruby" ); setAcceptLocationExtensions( ".gemspec" ); setAcceptOptionKeys( "rb:4.0.0" ); setPriority( 1.5f ); } @Override public File locatePom( final File dir ) { assert dir != null; for ( final File f : dir.listFiles() ) { if ( f.isFile() && f.getName().endsWith( ".gemspec" ) ) { return f; } } return null; } }GemspecRubyModelReader.java000066400000000000000000000020331202174026400402760ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Component; /** * Ruby model reader. * * @author mkristian * @since 0.8 */ @Component( role = ModelReader.class, hint = "gemspec-ruby" ) public class GemspecRubyModelReader extends AbstractRubyModelReader { public GemspecRubyModelReader() { super( "gemspec" ); } } GemspecRubyModelWriter.java000066400000000000000000000021771202174026400403610ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import javax.xml.transform.TransformerConfigurationException; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; /** * Ruby model writer. * * @author mkristian * @since 0.8 */ @Component( role = ModelWriter.class, hint = "gemspec-ruby" ) public class GemspecRubyModelWriter extends AbstractRubyModelWriter { public GemspecRubyModelWriter() throws TransformerConfigurationException { super(); } } RubyMapping.java000066400000000000000000000023061202174026400362050ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import org.codehaus.plexus.component.annotations.Component; import org.sonatype.maven.polyglot.mapping.Mapping; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** * Ruby model mapping. * * @author Kristian Meier * @since 0.8 */ @Component( role = Mapping.class, hint = "ruby" ) public class RubyMapping extends MappingSupport { public RubyMapping() { super( "ruby" ); setPomNames( "pom.rb" ); setAcceptLocationExtensions( ".rb" ); setAcceptOptionKeys( "rb:4.0.0" ); setPriority( -3 ); } }RubyModelReader.java000066400000000000000000000020131202174026400367700ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.component.annotations.Component; /** * Ruby model reader. * * @author mkristian * @since 0.8 */ @Component( role = ModelReader.class, hint = "ruby" ) public class RubyModelReader extends AbstractRubyModelReader { public RubyModelReader() { super( "pom_reader.rb" ); } } RubyModelWriter.java000066400000000000000000000021511202174026400370450ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import javax.xml.transform.TransformerConfigurationException; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; /** * Ruby model writer. * * @author mkristian * @since 0.8 */ @Component( role = ModelWriter.class, hint = "ruby" ) public class RubyModelWriter extends AbstractRubyModelWriter { public RubyModelWriter() throws TransformerConfigurationException { super(); } }polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/000077500000000000000000000000001202174026400256635ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/org/000077500000000000000000000000001202174026400264525ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/org/sonatype/000077500000000000000000000000001202174026400303145ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/org/sonatype/maven/000077500000000000000000000000001202174026400314225ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400332735ustar00rootroot00000000000000000077500000000000000000000000001202174026400341755ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/org/sonatype/maven/polyglot/rubypom2ruby.xsl000066400000000000000000000054751202174026400365170ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/main/resources/org/sonatype/maven/polyglot/ruby _ ' ' { } ' ' polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/000077500000000000000000000000001202174026400237045ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/000077500000000000000000000000001202174026400246255ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/org/000077500000000000000000000000001202174026400254145ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/org/sonatype/000077500000000000000000000000001202174026400272565ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/org/sonatype/maven/000077500000000000000000000000001202174026400303645ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400322355ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/org/sonatype/maven/polyglot/ruby/000077500000000000000000000000001202174026400332165ustar00rootroot00000000000000RubyModelReaderTest.java000066400000000000000000000167721202174026400377040ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/java/org/sonatype/maven/polyglot/ruby/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.ruby; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; import org.apache.maven.model.IssueManagement; import org.apache.maven.model.Model; import org.apache.maven.model.Parent; import org.apache.maven.model.Plugin; import org.apache.maven.model.Scm; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; public class RubyModelReaderTest extends PlexusTestCase { @Test public void testModelCloning() throws Exception { getModel().clone(); } @Test public void testModelReader() throws Exception { final Model model = getModel(); assertNotNull( model ); final Parent parent = model.getParent(); assertEquals( "org.sonatype.forge", parent.getGroupId() ); assertEquals( "forge-parent", parent.getArtifactId() ); assertEquals( "1.0", parent.getVersion() ); assertEquals( "org.sonatype.pmaven", model.getGroupId() ); assertEquals( "pmaven", model.getArtifactId() ); assertEquals( "0.7-SNAPSHOT", model.getVersion() ); assertEquals( "Polyglot Maven", model.getName() ); // Developers // List developers = model.getDevelopers(); // Developer dev0 = developers.get(0); // assertEquals("jvanzyl", dev0.getId()); // assertEquals("Jason van Zyl", dev0.getName()); // Contributors // List contributors = model.getContributors(); // Contributor con0 = contributors.get(0); // assertEquals("Will Price", con0.getName()); // DependencyManagement final List depManDependencies = model.getDependencyManagement().getDependencies(); assertEquals( 16, depManDependencies.size() ); final Dependency dmd0 = depManDependencies.get( 0 ); assertEquals( "org.apache.maven", dmd0.getGroupId() ); assertEquals( "apache-maven", dmd0.getArtifactId() ); // assertEquals("3.0", dmd0.getVersion()); assertEquals( "zip", dmd0.getType() ); assertEquals( "bin", dmd0.getClassifier() ); final Dependency dmd1 = depManDependencies.get( 1 ); assertEquals( "org.apache.maven", dmd1.getGroupId() ); assertEquals( "maven-model-builder", dmd1.getArtifactId() ); // assertEquals("3.0", dmd1.getVersion()); // Dependencies final List dependencies = model.getDependencies(); assertEquals( 2, dependencies.size() ); final Dependency d0 = dependencies.get( 0 ); assertEquals( "junit", d0.getGroupId() ); assertEquals( "junit", d0.getArtifactId() ); assertEquals( "4.7", d0.getVersion() ); assertEquals( "test", d0.getScope() ); final Dependency d1 = dependencies.get( 1 ); assertEquals( "org.codehaus.groovy", d1.getGroupId() ); assertEquals( "groovy", d1.getArtifactId() ); assertEquals( "4.0", d1.getVersion() ); assertEquals( "test", d1.getScope() ); // Modules final List modules = model.getModules(); assertEquals( 7, modules.size() ); assertEquals( "pmaven-common", modules.get( 0 ) ); assertEquals( "pmaven-maven-plugin", modules.get( 1 ) ); assertEquals( "pmaven-groovy", modules.get( 2 ) ); // Build final Build build = model.getBuild(); final List plugins = build.getPlugins(); assertEquals( 6, plugins.size() ); final Plugin p0 = plugins.get( 0 ); assertEquals( "org.apache.maven.plugins", p0.getGroupId() ); assertEquals( "maven-compiler-plugin", p0.getArtifactId() ); assertEquals( "2.0.2", p0.getVersion() ); final Xpp3Dom configuration = (Xpp3Dom) p0.getConfiguration(); assertNotNull( configuration ); assertEquals( 2, configuration.getChildCount() ); assertEquals( "1.6", configuration.getChild( "source" ).getValue() ); assertEquals( "1.5", configuration.getChild( "target" ).getValue() ); // DistributionManagement // DistributionManagement distMan = // model.getDistributionManagement(); // Site site = distMan.getSite(); // assertEquals("site", site.getId()); // assertEquals("http://www.apache.org", site.getUrl()); // DeploymentRepository releases = distMan.getRepository(); // assertEquals("releases", releases.getId()); // assertEquals("releases", releases.getName()); // assertEquals("http://maven.sonatype.org/releases", // releases.getUrl()); // DeploymentRepository snapshots = // distMan.getSnapshotRepository(); // assertEquals("snapshots", snapshots.getId()); // assertEquals("snapshots", snapshots.getName()); // assertEquals("http://maven.sonatype.org/snapshots", // snapshots.getUrl()); // SCM final Scm scm = model.getScm(); assertEquals( "scm:git:git://github.com/sonatype/polyglot-maven.git", scm.getConnection() ); assertEquals( "scm:git:ssh://git@github.com/sonatype/polyglot-maven.git", scm.getDeveloperConnection() ); assertEquals( "https://github.com/sonatype/polyglot-maven", scm.getUrl() ); // IssueManagement final IssueManagement issueManagement = model.getIssueManagement(); assertEquals( "JIRA", issueManagement.getSystem() ); assertEquals( "https://issues.sonatype.org/browse/PMAVEN", issueManagement.getUrl() ); // CiManagement // CiManagement ciManagement = model.getCiManagement(); // assertEquals("hudson", ciManagement.getSystem()); // assertEquals("http://grid.sonatype.org/ci", ciManagement.getUrl()); // Profiles } @Test public void testModelWriter() throws Exception { final StringWriter sw = new StringWriter(); final ModelWriter writer = new RubyModelWriter(); final Model model = getModel(); final Properties p = new Properties(); p.setProperty( "FOO", "BAR" ); model.setProperties( p ); writer.write( sw, null, model ); System.out.println( sw.toString() ); } protected Model getModel() throws Exception { final ModelReader modelReader = lookup( ModelReader.class, "ruby" ); final URL url = getClass().getResource( "test.rb" ); assertNotNull( url ); final InputStream reader = url.openStream(); final Map options = new HashMap(); options.put( "org.apache.maven.model.building.source", url.getFile() ); return modelReader.read( reader, options ); } } polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/000077500000000000000000000000001202174026400257165ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/org/000077500000000000000000000000001202174026400265055ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/org/sonatype/000077500000000000000000000000001202174026400303475ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/org/sonatype/maven/000077500000000000000000000000001202174026400314555ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400333265ustar00rootroot00000000000000000077500000000000000000000000001202174026400342305ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/org/sonatype/maven/polyglot/rubytest.rb000066400000000000000000000174661202174026400355520ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-jruby/src/test/resources/org/sonatype/maven/polyglot/ruby# # Copyright (C) 2009 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def my_method 0.4 + 0.6 end project { modelVersion '4.0.0' parent { artifactId 'forge-parent' groupId 'org.sonatype.forge' version my_method.to_s } groupId 'org.sonatype.pmaven' artifactId 'pmaven' version '0.7-SNAPSHOT' packaging 'pom' name 'Polyglot Maven' url 'https://docs.sonatype.org/display/PMAVEN' licenses { license { name 'The Apache Software License, Version 2.0' url 'http://www.apache.org/licenses/LICENSE-2.0.txt' distribution 'repo' } } scm { connection 'scm:git:git://github.com/sonatype/polyglot-maven.git' developerConnection 'scm:git:ssh://git@github.com/sonatype/polyglot-maven.git' url 'https://github.com/sonatype/polyglot-maven' } issueManagement { _system 'JIRA' url 'https://issues.sonatype.org/browse/PMAVEN' } build { defaultGoal 'install' plugins { plugin { artifactId 'maven-compiler-plugin' version '2.0.2' configuration { source '1.6' target '1.5' } } plugin { artifactId 'maven-surefire-plugin' version '2.4.3' configuration { redirectTestOutputToFile 'true' forkMode 'once' argLine '-ea' failIfNoTests 'false' workingDirectory '${project.build.directory}' excludes { exclude '**/Abstract*.java' exclude '**/Test*.java' } includes { include '**/*Test.java' } } } plugin { groupId 'org.codehaus.gmaven' artifactId 'gmaven-plugin' version '1.2' executions { execution { goals { goal 'generateStubs' goal 'compile' goal 'generateTestStubs' goal 'testCompile' } } } configuration { providerSelection '1.7' } } plugin { groupId 'org.codehaus.plexus' artifactId 'plexus-component-metadata' version '1.5.1' executions { execution { goals { goal 'generate-metadata' goal 'generate-test-metadata' } } } } plugin { artifactId 'maven-release-plugin' version '2.0-beta-9' configuration { useReleaseProfile 'false' goals 'deploy' arguments '-B -Prelease' autoVersionSubmodules 'true' } } plugin { artifactId 'maven-scm-plugin' version '1.2' } } } modules { _module 'pmaven-common' _module 'pmaven-maven-plugin' _module 'pmaven-groovy' _module 'pmaven-yaml' _module 'pmaven-clojure' _module 'pmaven-scala' _module 'pmaven-cli' } properties { mavenVersion '3.0-alpha-6' 'project.build.sourceEncoding' 'UTF-8' } dependencyManagement { dependencies { dependency { groupId 'org.apache.maven' artifactId 'apache-maven' version '${mavenVersion}' type 'zip' classifier 'bin' } dependency { groupId 'org.apache.maven' artifactId 'maven-model-builder' version '${mavenVersion}' } dependency { groupId 'org.apache.maven' artifactId 'maven-embedder' version '${mavenVersion}' } dependency { groupId 'org.apache.maven' artifactId 'maven-plugin-api' version '${mavenVersion}' } dependency { groupId 'org.codehaus.groovy' artifactId 'groovy' version '1.7.0' exclusions { exclusion { artifactId 'jline' groupId 'jline' } exclusion { artifactId 'junit' groupId 'junit' } exclusion { artifactId 'ant' groupId 'org.apache.ant' } exclusion { artifactId 'ant-launcher' groupId 'org.apache.ant' } } } dependency { groupId 'org.sonatype.gossip' artifactId 'gossip' version '1.2' } dependency { groupId 'com.google.inject' artifactId 'guice' version '2.0' } dependency { groupId 'org.sonatype.grrrowl' artifactId 'grrrowl' version '1.0' } dependency { groupId 'net.java.dev.jna' artifactId 'jna' version '3.2.3' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-common' version '0.7-SNAPSHOT' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-cli' version '0.7-SNAPSHOT' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-maven-plugin' version '0.7-SNAPSHOT' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-groovy' version '0.7-SNAPSHOT' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-yaml' version '0.7-SNAPSHOT' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-clojure' version '0.7-SNAPSHOT' } dependency { groupId 'org.sonatype.pmaven' artifactId 'pmaven-scala' version '0.7-SNAPSHOT' } } } dependencies { dependency { groupId 'junit' artifactId 'junit' version '4.7' scope 'test' } dependency { groupId 'org.codehaus.groovy' artifactId 'groovy' version '4.0' scope 'test' } } } polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/000077500000000000000000000000001202174026400234055ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/.gitignore000066400000000000000000000000531202174026400253730ustar00rootroot00000000000000target/ .project .classpath .settings/ bin polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/pom.xml000066400000000000000000000031151202174026400247220ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-maven-plugin Polyglot Maven :: Maven Plugin maven-plugin org.sonatype.pmaven pmaven-common org.apache.maven maven-plugin-api ${mavenVersion} polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/000077500000000000000000000000001202174026400241745ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/000077500000000000000000000000001202174026400251205ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/000077500000000000000000000000001202174026400260415ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/org/000077500000000000000000000000001202174026400266305ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/org/sonatype/000077500000000000000000000000001202174026400304725ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/org/sonatype/maven/000077500000000000000000000000001202174026400316005ustar00rootroot00000000000000000077500000000000000000000000001202174026400333725ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/org/sonatype/maven/polyglot000077500000000000000000000000001202174026400346705ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/org/sonatype/maven/polyglot/pluginExecuteMojo.java000066400000000000000000000052241202174026400377650ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-maven-plugin/src/main/java/org/sonatype/maven/polyglot/plugin/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.plugin; import org.apache.maven.model.Model; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.sonatype.maven.polyglot.execute.ExecuteContext; import org.sonatype.maven.polyglot.execute.ExecuteManager; import org.sonatype.maven.polyglot.execute.ExecuteTask; import java.util.List; /** * Executes registered {@link org.sonatype.maven.polyglot.execute.ExecuteTask}s. * * @goal execute * * @author Jason Dillon */ public class ExecuteMojo extends AbstractMojo { /** * @component role="org.sonatype.maven.polyglot.execute.ExecuteManager" */ private ExecuteManager manager; /** * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * @parameter expression="${taskId}" * @required */ private String taskId; public void execute() throws MojoExecutionException, MojoFailureException { Log log = getLog(); Model model = project.getModel(); log.debug("Executing task '" + taskId + "' for model: " + model.getId()); assert manager != null; List tasks = manager.getTasks(model); ExecuteContext ctx = new ExecuteContext() { public MavenProject getProject() { return project; } }; for (ExecuteTask task : tasks) { if (taskId.equals(task.getId())) { log.debug("Executing task: " + task); try { task.execute(ctx); return; } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } } throw new MojoFailureException("Unable to find task for id: " + taskId); } }polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/000077500000000000000000000000001202174026400220665ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/.gitignore000077500000000000000000000002611202174026400240600ustar00rootroot00000000000000# Build output target # Local Eclipse junk, in case anyone's using eclipse .classpath .manager .project .settings # Local IntelliJ junk ... .idea *.iml # Mac stuff .DS_Store polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/pom.xml000066400000000000000000000077151202174026400234150ustar00rootroot00000000000000 4.0.0 org.sonatype.pmaven pmaven 0.8-tobrien-SNAPSHOT pmaven-scala Polyglot Maven :: Scala org.sonatype.pmaven pmaven-common org.scala-lang scala-compiler 2.8.0.Beta1-RC5 org.scalatest scalatest 1.0.1-for-scala-2.8.0.Beta1-RC8-SONATYPE-1 test org.apache.maven.plugins maven-surefire-plugin **/*Spec.java org.scala-tools maven-scala-plugin 2.13.1 scala-compile-first process-resources add-source compile scala-test-compile-first process-test-resources testCompile sonatype-public-grid http://repository.sonatype.org/content/groups/sonatype-public-grid/ false polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/000077500000000000000000000000001202174026400226555ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/000077500000000000000000000000001202174026400236015ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/000077500000000000000000000000001202174026400246645ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/000077500000000000000000000000001202174026400254535ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/000077500000000000000000000000001202174026400273155ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/maven/000077500000000000000000000000001202174026400304235ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/maven/polyglot/000077500000000000000000000000001202174026400322745ustar00rootroot00000000000000000077500000000000000000000000001202174026400333005ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/maven/polyglot/scalaApacheModelBeanScalaSerializer.scala000077500000000000000000000157741202174026400422540ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/maven/polyglot/scala/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.scala import scala.collection.JavaConversions._ import scala.collection.mutable.Buffer import scala.collection.mutable.Map import java.beans._ /** * @since 0.7 */ object ApacheModelBeanScalaSerializer { def apply(parentRelativePropRefName: String, a: AnyRef): ApacheModelBeanScalaSerializer = { val bi = apacheModelBeanInfo(a) new ApacheModelBeanScalaSerializer(parentRelativePropRefName, shortInstanceName(bi), a, bi) } def apacheModelBeanInfo(a: AnyRef): BeanInfo = apacheModelBeanInfo(a.getClass) def apacheModelBeanInfo(clazz: Class[_]): BeanInfo = if(clazz.getName startsWith "org.apache.maven.model") Introspector.getBeanInfo(clazz) else apacheModelBeanInfo(clazz.getSuperclass) /** *

* Use the first letter of the bean class name, lowercased. This value is used * as the local variable name within initializer closures in Scala PMaven code. E.g., *

* *

   *  xyz.prop { l =>  // <-- The name "l"
   *    ...
   *  }
   * 

**/ def shortInstanceName(bi: BeanInfo): String = bi.getBeanDescriptor.getBeanClass.getSimpleName.substring(0, 1).toLowerCase /** * List[-non-primitive and non-String]-typed properties have special Scala-ized * setter functions to use. The listMemberSetterNameMap gives the special * Scala-ized setter to use for the list-typed beans property. **/ val listMemberSetterNameMap: Map[String, String] = Map("dependencies" -> "dependency", "exclusions" -> "exclusion", "repositories" -> "repository", "pluginRepositories" -> "pluginRepository", "contributors" -> "contributor", "developers" -> "developer", "licenses" -> "license", "mailingLists" -> "mailingList", "profiles" -> "profile", "resources" -> "resource", "testResources" -> "testResource", "extensions" -> "extension", "notifiers" -> "notifier", "plugins" -> "plugin", "executions" -> "execution", "reportSets" -> "reportSet" ) def listMemberSetterName(s: String): String = listMemberSetterNameMap(s) /** * Simple-typed properties might need a property name-> Scala-ized setter method * mapping. E.g., "getType/setType" in Java cannot be mapped to the name "type", * since that's keyword in Scala; so instead there is a mapping to "_type". **/ def propertySetterName(s: String): String = s match { case "type" => "_type" case x => x } } class ApacheModelBeanScalaSerializer(parentRelativePropRefName: String, instanceName: String, theBean: AnyRef, beanInfo: BeanInfo) { def serializeTo(writer: IndentingPrintWriter): Unit = { writer.println(parentRelativePropRefName + " { " + instanceName + " =>") serializePropsTo(writer.indentedWriter) writer.println("}") } def serializePropsTo(writer: IndentingPrintWriter): Unit = beanInfo.getPropertyDescriptors foreach { pd => serializePropTo(pd, writer) } def serializePropTo(pd: PropertyDescriptor, writer: IndentingPrintWriter): Unit = { import ApacheModelBeanScalaSerializer._ //...make sure there's a property getter AND setter methods, indicating the property // is actually readable, and it can be set by a build script... val reader = pd.getReadMethod if(pd.getReadMethod != null && pd.getWriteMethod != null) { //...make sure the value is not null. Null values are the default, so do // not need to be serialized in Scala code... val value = reader.invoke(theBean) if(value != null) { if(pd.getPropertyType.equals(classOf[String])) { //...a String-typed property... writer.qe(value) { instanceName + "." + propertySetterName(pd.getName) + " = \"" + _ + "\"" } } else if(pd.getPropertyType.isPrimitive) { //...a Boolean or Int or other primitive-typed property writer.qe(value) { instanceName + "." + propertySetterName(pd.getName) + " = " + _ } } else if(classOf[java.util.List[_]].isAssignableFrom(pd.getPropertyType)) { //...a java.util.List-typed property. Write out each member as a property... val list = value.asInstanceOf[java.util.List[java.lang.Object]] if(list != null) { (list: Buffer[java.lang.Object]) foreach { item: java.lang.Object => if(classOf[String].isInstance(item)) { //...property is a List[String], which is represented as a "+=" call // to the list-typed property... writer.println(instanceName + "." + pd.getName + " += \"" + item.toString + "\"") } else { //...property is a List[Apache Model object type]. To serialize this // we recurse a another level and serialize the value object... ApacheModelBeanScalaSerializer(instanceName + "." + listMemberSetterName(pd.getName), item).serializeTo(writer) } } } } else if(classOf[java.util.Properties].isAssignableFrom(pd.getPropertyType)) { //...a Properties-typed properties.Write out each name/value pair // in a tuple of pairs using a "+=" addition to the property... val map = value.asInstanceOf[java.util.Map[String, java.lang.Object]] if(map != null) { (map: Map[String, java.lang.Object]) foreach { pair => writer.println(instanceName + "." + pd.getName + " += (\"" + pair._1 + "\" -> \"" + pair._2.toString + "\")") } } } else if(pd.getPropertyType.equals(classOf[java.lang.Object])) { //...the "java.lang.Object" property type in Apache Model bean properties // represents DOM Elements, which are used as weakly-typed arbitrary // configuration structures. Just serialize the XML fragment w/o processing // preamble, processing instructions, etc... writer.println(instanceName + "." + pd.getName + " =") writer.serializeXpp3Dom(value.asInstanceOf[org.codehaus.plexus.util.xml.Xpp3Dom]) } else { //...we can assume the property type is another Apache Model Bean... ApacheModelBeanScalaSerializer(instanceName + "." + pd.getName, value).serializeTo(writer) } } } } } ModelScalaWriter.scala000077500000000000000000000076421202174026400375220ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/maven/polyglot/scala/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.scala; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import java.io.{Writer => JWriter, PrintWriter => JPrintWriter} import java.util.{Map => JMap} import org.codehaus.plexus.util.xml.Xpp3Dom import scala.collection.mutable.Buffer /** * Writes a Maven {@link org.apache.maven.model.Model} to a pom.scala. * * @since 0.7 */ @Component(role=classOf[ModelWriter], hint="scala") class ModelScalaWriter extends ModelWriterSupport { @Requirement val logger: Logger = null override def write(rawOutput: JWriter, options: JMap[String, java.lang.Object], model: Model) { ApacheModelBeanScalaSerializer("project", model) serializeTo (new IndentingPrintWriter(None, rawOutput,"")) rawOutput.flush } } /** * Convenience class with overriding println() implementation that adds * the indentation to each printed line. **/ class IndentingPrintWriter(parent: Option[IndentingPrintWriter] = None, target: JWriter, indentStr: String = " ") extends JPrintWriter(target) { def indentedWriter = new IndentingPrintWriter(Some(this), target, " ") def printIndent: Unit = { print(indentStr) parent match { case Some(p) => p.printIndent case None => ; } } def qe(s: String)(body: (String) => String): Unit = if(s != null && s.length > 0) println(body(s)) def qe[T <: AnyRef](t: T)(body: (T) => String): Unit = if(t != null) println(body(t)) def qe_foreach[T](buffer: Buffer[T])(body: (T) => String): Unit = if(buffer != null) { buffer foreach { t => println(body(t)) } } override def println(): Unit = { printIndent super.println() } override def println(b: Boolean): Unit = { printIndent super.println(b) } override def println(c: Char): Unit = { printIndent super.println(c) } override def println(ac: Array[Char]): Unit = { printIndent super.println(ac) } override def println(d: Double): Unit = { printIndent super.println(d) } override def println(f: Float): Unit = { printIndent super.println(f) } override def println(i: Int): Unit = { printIndent super.println(i) } override def println(l: Long): Unit = { printIndent super.println(l) } override def println(o: java.lang.Object): Unit = { printIndent super.println(o) } override def println(s: String): Unit = { printIndent super.println(s) } def serializeXpp3Dom(dom: Xpp3Dom): Unit = { if (dom.getChildCount() == 0) { println("<" + dom.getName() + ">" + escapeScalaXML(dom.getValue) + ""); } else { println("<" + dom.getName() + ">") for(child <- dom.getChildren()) indentedWriter.serializeXpp3Dom(child) println("") } } def escapeScalaXML(s: String): String = { val m = java.util.regex.Pattern.compile("\\$\\{[^}]+}").matcher(s) var t = s while (m.find) { t = t.substring(0, m.start) + "{\"" + m.group + "\"}" + t.substring(m.end) } t } }PMavenScriptCompiler.scala000077500000000000000000000272601202174026400403650ustar00rootroot00000000000000polyglot-maven-0.8~tobrien+git20120905/pmaven-scala/src/main/scala/org/sonatype/maven/polyglot/scala/* * Copyright (C) 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonatype.maven.polyglot.scala import org.sonatype.maven.polyglot.scala.model.Model import scala.tools.nsc.{GenericRunnerSettings, CompileClient, Settings, CompileSocket, Global, Properties} import scala.tools.nsc.reporters.ConsoleReporter import scala.tools.nsc.io.{Directory, File, Path, PlainFile} import scala.tools.nsc.util.{CompoundSourceFile, BatchSourceFile, SourceFile, SourceFileFragment} import scala.tools.nsc.util.ScalaClassLoader import java.io.{InputStream, OutputStream, BufferedReader, FileInputStream, FileOutputStream, FileReader, InputStreamReader, PrintWriter, FileWriter, IOException, Reader, StringWriter, Writer, File => JFile} import java.util.jar.{JarEntry, JarOutputStream} import java.net.URL import org.apache.maven.model.{Model => ApacheModelBaseClass} import org.codehaus.plexus.logging.Logger /** * @since 0.7 */ object PMavenScriptCompiler { /** * Utility method to make sure something happens, even if there's a global * failure of some sort. **/ private def addShutdownHook(body: => Unit) = Runtime.getRuntime addShutdownHook new Thread { override def run { body } } /** * Statically-defined code inserted before PMaven script, which effectively * makesth e script code the bod yof the generateModel method of an object * named ModelGenerator. */ def preambleCode: String = """ | import org.sonatype.maven.polyglot.scala.model._ | | object ModelGenerator { | def generateModel: Model = { """.stripMargin def endCode: String = """ | } | } """.stripMargin def copyStreams(in: InputStream, out: OutputStream) = { val buf = new Array[Byte](10240) def loop: Unit = in.read(buf, 0, buf.length) match { case -1 => in.close() case n => out.write(buf, 0, n) ; loop } loop } def copyReaders(in: Reader, out: Writer) = { val buf = new Array[Char](10240) def loop: Unit = in.read(buf, 0, buf.length) match { case -1 => in.close() case n => out.write(buf, 0, n) ; loop } loop } private def jarFileFor(scriptFile: String): File = { val name = if (scriptFile endsWith ".jar") scriptFile else scriptFile + ".jar" File(name) } private def tryMakeJar(jarFile: File, sourcePath: Directory) = { def addFromDir(jar: JarOutputStream, dir: Directory, prefix: String) { def addFileToJar(entry: File) = { jar putNextEntry new JarEntry(prefix + entry.name) copyStreams(entry.inputStream, jar) jar.closeEntry } dir.list foreach { entry => if (entry.isFile) addFileToJar(entry.toFile) else addFromDir(jar, entry.toDirectory, prefix + entry.name + "/") } } try { val jar = new JarOutputStream(jarFile.outputStream()) addFromDir(jar, sourcePath, "") jar.close } catch { case _: Error => println("jarfile creation error"); jarFile.delete() // XXX what errors to catch? } } /** * Locates a JAR file or directory housing the given Class' classfile. Uses the * location of he class' classfile, and assumes the normal Java JAR file * URL protocol string "jar:<jar location>!/package/ClassName.class", * and extracts the <jar location> part from it. If thats not right, * then looks for the appropriate parent dir to put on a classpath that would correctly * house the classfile. * * @returns File of the JAR file housing the given Class' classfile. **/ def scalaCPFileFor(clazz: java.lang.Class[_]): JFile = { val fileRelativeUri = "/" + clazz.getName.replace('.', '/') + ".class" val urlAppClass = clazz.getResource(fileRelativeUri) urlAppClass.getProtocol match { case "jar" => val bangIndex = urlAppClass.toString indexOf ('!') val fileUrl = new URL(urlAppClass.toString take bangIndex drop ("jar:".length)) new JFile(fileUrl.getFile) case "file" => val uriIndex = urlAppClass.toString indexOf fileRelativeUri val parentFileUrl = new URL(urlAppClass.toString take uriIndex) new JFile(parentFileUrl.getFile) case _ => null } } /** * Compile a script using the fsc compilation deamon. */ private def compileWithDaemon( settings: GenericRunnerSettings, scriptFileIn: String): Boolean = { val scriptFile = CompileClient absFileName scriptFileIn { import settings._ for (setting <- List(classpath, sourcepath, bootclasspath, extdirs, outdir)) { setting.value = CompileClient absFileName setting.value } } val compSettingNames = new Settings(error).allSettings map (_.name) val compSettings = settings.allSettings filter (compSettingNames contains _.name) val coreCompArgs = compSettings flatMap (_.unparse) val compArgs = coreCompArgs ::: List("-Xscript", "ModelGenerator", scriptFile) var compok = true def ManagedResource[T](x: => T) = Some(x) for { socket <- ManagedResource(CompileSocket getOrCreateSocket "") val _ = if (socket == null) return false out <- ManagedResource(new PrintWriter(socket.getOutputStream(), true)) in <- ManagedResource(new BufferedReader(new InputStreamReader(socket.getInputStream()))) } { out println (CompileSocket getPassword socket.getPort) out println (compArgs mkString "\0") for (fromServer <- (Iterator continually in.readLine()) takeWhile (_ != null)) { Console.err println fromServer if (CompileSocket.errorPattern matcher fromServer matches) compok = false } in.close() ; out.close() ; socket.close() } compok } /** * Wrap a script file into a model generator object named * ModelGenerator. */ def wrappedScript( filename: String, getSourceFile: (PlainFile) => BatchSourceFile): SourceFile = { val preamble = new BatchSourceFile("