]> source.dussan.org Git - gitblit.git/commitdiff
Added Fogbugz post-receive groovy script
authorRyan Schneider <rschneider@salsalabs.com>
Mon, 21 Jan 2013 19:41:22 +0000 (14:41 -0500)
committerRyan Schneider <rschneider@salsalabs.com>
Mon, 21 Jan 2013 19:41:22 +0000 (14:41 -0500)
distrib/groovy/fogbugz.groovy [new file with mode: 0644]
tests/com/gitblit/tests/GroovyScriptTest.java

diff --git a/distrib/groovy/fogbugz.groovy b/distrib/groovy/fogbugz.groovy
new file mode 100644 (file)
index 0000000..593feef
--- /dev/null
@@ -0,0 +1,167 @@
+import org.eclipse.jgit.revwalk.RevCommit;\r
+\r
+/*\r
+ * Copyright 2013 gitblit.com.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *     http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+import com.gitblit.GitBlit\r
+import com.gitblit.Keys\r
+import com.gitblit.models.RepositoryModel\r
+import com.gitblit.models.TeamModel\r
+import com.gitblit.models.UserModel\r
+import com.gitblit.utils.JGitUtils\r
+import com.sun.org.apache.xalan.internal.xsltc.compiler.Import;\r
+\r
+import java.text.SimpleDateFormat\r
+import org.eclipse.jgit.lib.Repository\r
+import org.eclipse.jgit.lib.Config\r
+import org.eclipse.jgit.revwalk.RevCommit\r
+import org.eclipse.jgit.transport.ReceiveCommand\r
+import org.eclipse.jgit.transport.ReceiveCommand.Result\r
+import org.slf4j.Logger\r
+\r
+import org.eclipse.jgit.api.Status;\r
+import org.eclipse.jgit.api.errors.JGitInternalException;\r
+import org.eclipse.jgit.diff.DiffEntry;\r
+import org.eclipse.jgit.diff.DiffFormatter;\r
+import org.eclipse.jgit.diff.RawTextComparator;\r
+import org.eclipse.jgit.lib.Constants;\r
+import org.eclipse.jgit.lib.IndexDiff;\r
+import org.eclipse.jgit.lib.ObjectId;\r
+import org.eclipse.jgit.patch.FileHeader;\r
+import org.eclipse.jgit.revwalk.RevWalk;\r
+import org.eclipse.jgit.treewalk.FileTreeIterator;\r
+import org.eclipse.jgit.treewalk.EmptyTreeIterator;\r
+import org.eclipse.jgit.treewalk.CanonicalTreeParser;\r
+import org.eclipse.jgit.util.io.DisabledOutputStream;\r
+\r
+import java.util.Set;\r
+import java.util.HashSet;\r
+\r
+/**\r
+ * Sample Gitblit Post-Receive Hook: fogbugz\r
+ *\r
+ * The purpose of this script is to invoke the Fogbugz API and update a case when\r
+ * push is received based.\r
+ * \r
+ * Example URL - http://bugs.salsalabs.com/fogbugz/cvsSubmit.asp?ixBug=bugID&sFile=file&sPrev=x&sNew=y&ixRepository=206\r
+ * \r
+ * The Post-Receive hook is executed AFTER the pushed commits have been applied\r
+ * to the Git repository.  This is the appropriate point to trigger an\r
+ * integration build or to send a notification.\r
+ * \r
+ * This script is only executed when pushing to *Gitblit*, not to other Git\r
+ * tooling you may be using.\r
+ * \r
+ * If this script is specified in *groovy.postReceiveScripts* of gitblit.properties\r
+ * or web.xml then it will be executed by any repository when it receives a\r
+ * push.  If you choose to share your script then you may have to consider\r
+ * tailoring control-flow based on repository access restrictions.\r
+ *\r
+ * Scripts may also be specified per-repository in the repository settings page.\r
+ * Shared scripts will be excluded from this list of available scripts.\r
+ * \r
+ * This script is dynamically reloaded and it is executed within it's own\r
+ * exception handler so it will not crash another script nor crash Gitblit.\r
+ *\r
+ * If you want this hook script to fail and abort all subsequent scripts in the\r
+ * chain, "return false" at the appropriate failure points.\r
+ * \r
+ * Bound Variables:\r
+ *  gitblit                    Gitblit Server                          com.gitblit.GitBlit\r
+ *  repository         Gitblit Repository                      com.gitblit.models.RepositoryModel\r
+ *  receivePack                JGit Receive Pack                       org.eclipse.jgit.transport.ReceivePack\r
+ *  user                       Gitblit User                            com.gitblit.models.UserModel\r
+ *  commands           JGit commands                           Collection<org.eclipse.jgit.transport.ReceiveCommand>\r
+ *     url                             Base url for Gitblit            String\r
+ *  logger                     Logs messages to Gitblit        org.slf4j.Logger\r
+ *  clientLogger       Logs messages to Git client     com.gitblit.utils.ClientLogger\r
+ *\r
+ * Accessing Gitblit Custom Fields:\r
+ *   def myCustomField = repository.customFields.myCustomField\r
+ * \r
+ * Cusom Fileds Used by This script\r
+ *   fogbugzUrl - base URL to Fogbugz (ie. https://bugs.salsalabs.com/fogbugz/)\r
+ *   fogbugzRepositoryId - (ixRepository value from Fogbugz Source Control configuration screen)\r
+ *   fogbugzCommitMessageRegex - regex pattern used to match on bug id\r
+ */\r
+\r
+// Indicate we have started the script\r
+logger.info("fogbugz hook triggered by ${user.username} for ${repository.name}")\r
+\r
+/*\r
+ * Primitive email notification.\r
+ * This requires the mail settings to be properly configured in Gitblit.\r
+ */\r
+\r
+Repository r = gitblit.getRepository(repository.name)\r
+\r
+// pull custom fields from repository specific values\r
+// groovy.customFields = "fogbugzUrl=Fogbugz Base URL" "fogbugzRepositoryId=Fogbugz Repository ID" "fogbugzCommitMessageRegex="Fogbugz Commit Message Regular Expression"\r
+def fogbugzUrl = repository.customFields.fogbugzUrl\r
+def fogbugzRepositoryId = repository.customFields.fogbugzRepositoryId\r
+def bugIdRegex = repository.customFields.fogbugzCommitMessageRegex\r
+\r
+for (command in commands) {\r
+\r
+       for( commit in JGitUtils.getRevLog(r, command.oldId.name, command.newId.name).reverse() ) {\r
+               // Example URL - http://bugs.salsalabs.com/fogbugz/cvsSubmit.asp?ixBug=bugID&sFile=file&sPrev=x&sNew=y&ixRepository=206\r
+               def bugIds = [];\r
+               // Grab the second matcher and then filter out each numeric ID and add it to array\r
+        (commit.getFullMessage() =~ bugIdRegex).each{ (it[1] =~ "\\d+").each {bugIds.add(it)} }\r
+               \r
+               for( file in getFiles(r, commit) ) {\r
+                       for( bugId in bugIds ) {\r
+                               def url = "${fogbugzUrl}/cvsSubmit.asp?ixBug=${bugId}&sFile=${file}&sPrev=${command.oldId.name}&sNew=${command.newId.name}&ixRepository=${fogbugzRepositoryId}"\r
+                               logger.info( url );\r
+                               // Hit the page and make sure we get an "OK" response\r
+                               def responseString = new URL(url).getText()\r
+                               if( !"OK".equals(responseString) ) {\r
+                                       throw new Exception( "Problem posting ${url} - ${responseString}" );\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+}\r
+// close the repository reference\r
+r.close()\r
+\r
+/**\r
+ * For a given commit, find all files part of it.\r
+ */\r
+def Set<String> getFiles(Repository r, RevCommit commit) {\r
+       DiffFormatter formatter = new DiffFormatter(DisabledOutputStream.INSTANCE)\r
+       formatter.setRepository(r)\r
+       formatter.setDetectRenames(true)\r
+       formatter.setDiffComparator(RawTextComparator.DEFAULT);\r
+\r
+       def diffs\r
+       RevWalk rw = new RevWalk(r)\r
+       if (commit.parentCount > 0) {\r
+               RevCommit parent = rw.parseCommit(commit.parents[0].id)\r
+               diffs = formatter.scan(parent.tree, commit.tree)\r
+       } else {\r
+               diffs = formatter.scan(new EmptyTreeIterator(),\r
+                                                          new CanonicalTreeParser(null, rw.objectReader, commit.tree))\r
+       }\r
+       rw.dispose()\r
+       \r
+       // Grab each filepath\r
+       Set<String> fileNameSet = new HashSet<String>( diffs.size() );\r
+       for (DiffEntry entry in diffs) {\r
+               FileHeader header = formatter.toFileHeader(entry)\r
+               fileNameSet.add( header.newPath )\r
+       }\r
+       return fileNameSet;\r
+}
\ No newline at end of file
index 47d20a4cadd28730ec66f476494fcbaae560c559..2954fa1dbfcad53fbaf24c540e0c11715ea070c5 100644 (file)
@@ -30,6 +30,7 @@ import java.util.ArrayList;
 import java.util.Arrays;\r
 import java.util.Collection;\r
 import java.util.Date;\r
+import java.util.HashMap;\r
 import java.util.List;\r
 import java.util.concurrent.atomic.AtomicBoolean;\r
 \r
@@ -69,6 +70,28 @@ public class GroovyScriptTest {
                }\r
        }\r
 \r
+       @Test\r
+       public void testFogbugz() throws Exception {\r
+               MockGitblit gitblit = new MockGitblit();\r
+               MockLogger logger = new MockLogger();\r
+               MockClientLogger clientLogger = new MockClientLogger();\r
+               List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();\r
+               commands.add(new ReceiveCommand(ObjectId\r
+                               .fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"), ObjectId\r
+                               .fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master"));\r
+               commands.add(new ReceiveCommand(ObjectId\r
+                               .fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"), ObjectId\r
+                               .fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master2"));\r
+\r
+               RepositoryModel repository = GitBlit.self().getRepositoryModel("helloworld.git");\r
+               repository.customFields = new HashMap<String,String>();\r
+               repository.customFields.put( "fogbugzUrl", "http://bugs.test.com" );\r
+               repository.customFields.put( "fogbugzRepositoryId", "1" );\r
+               repository.customFields.put( "fogbugzCommitMessageRegex", "\\s*[Bb][Uu][Gg][(Zz)(Ss)]*\\s*[(IDs)]*\\s*[#:; ]+((\\d+[ ,:;#]*)+)" );\r
+\r
+               test("fogbugz.groovy", gitblit, logger, clientLogger, commands, repository);\r
+       }\r
+\r
        @Test\r
        public void testSendHtmlMail() throws Exception {\r
                MockGitblit gitblit = new MockGitblit();\r