Initial implementation of hooks plugin using event listeners Change-Id: I96cacc61df7fd0ed31665357e89a965b1047ce75
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea5889f --- /dev/null +++ b/.gitignore
@@ -0,0 +1,5 @@ +/.classpath +/.project +/.buckd +/buck-cache +/buck-out
diff --git a/BUCK b/BUCK new file mode 100644 index 0000000..d77534a --- /dev/null +++ b/BUCK
@@ -0,0 +1,9 @@ +gerrit_plugin( + name = 'hooks', + srcs = glob(['src/main/java/**/*.java']), + resources = glob(['src/main/resources/**/*']), + manifest_entries = [ + 'Gerrit-PluginName: hooks', + 'Gerrit-Module: com.googlesource.gerrit.plugins.hooks.Module' + ] +)
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..11069ed --- /dev/null +++ b/LICENSE
@@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +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.
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/AgreementSignup.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/AgreementSignup.java new file mode 100644 index 0000000..3953bf6 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/AgreementSignup.java
@@ -0,0 +1,46 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.AccountInfo; +import com.google.gerrit.extensions.events.AgreementSignupListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class AgreementSignup implements AgreementSignupListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + AgreementSignup(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("claSignedHook", "cla-signed"); + this.hookFactory = hookFactory; + } + + @Override + public void onAgreementSignup(AgreementSignupListener.Event event) { + AccountInfo submitter = event.getAccount(); + if (submitter != null) { + HookArgs args = hookFactory.createArgs(); + + args.add("--submitter", submitter); + args.add("--user-id", submitter._accountId); + args.add("--cla-name", event.getAgreementName()); + + hook.submit(args); + } + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/AsynchronousHook.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/AsynchronousHook.java new file mode 100644 index 0000000..c581642 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/AsynchronousHook.java
@@ -0,0 +1,34 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import java.nio.file.Path; + +public class AsynchronousHook extends Hook { + private final HookQueue queue; + + AsynchronousHook(HookQueue queue, Path path) { + super(path); + this.queue = queue; + } + + void submit(HookArgs args) { + queue.submit(path, args); + } + + void submit(String projectName, HookArgs args) { + queue.submit(projectName, path, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeAbandoned.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeAbandoned.java new file mode 100644 index 0000000..03a9f0b --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeAbandoned.java
@@ -0,0 +1,50 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.ChangeAbandonedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class ChangeAbandoned implements ChangeAbandonedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + ChangeAbandoned(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("changeAbandonedHook", "change-abandoned"); + this.hookFactory = hookFactory; + } + + @Override + public void onChangeAbandoned(ChangeAbandonedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--topic", c.topic); + args.add("--abandoner", event.getAbandoner()); + args.add("--commit", c.currentRevision); + args.add("--reason", event.getReason()); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeMerged.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeMerged.java new file mode 100644 index 0000000..a31ba97 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeMerged.java
@@ -0,0 +1,50 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.ChangeMergedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class ChangeMerged implements ChangeMergedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + ChangeMerged(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("changeMergedHook", "change-merged"); + this.hookFactory = hookFactory; + } + + @Override + public void onChangeMerged(ChangeMergedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--topic", c.topic); + args.add("--submitter", event.getMerger()); + args.add("--commit", c.currentRevision); + args.add("--newrev", event.getNewRevisionId()); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeRestored.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeRestored.java new file mode 100644 index 0000000..3b717cb --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/ChangeRestored.java
@@ -0,0 +1,50 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.ChangeRestoredListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class ChangeRestored implements ChangeRestoredListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + ChangeRestored(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("changeRestoredHook", "change-restored"); + this.hookFactory = hookFactory; + } + + @Override + public void onChangeRestored(ChangeRestoredListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--topic", c.topic); + args.add("--restorer", event.getRestorer()); + args.add("--commit", c.currentRevision); + args.add("--reason", event.getReason()); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/CommentAdded.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/CommentAdded.java new file mode 100644 index 0000000..9e1e6ed --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/CommentAdded.java
@@ -0,0 +1,52 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.CommentAddedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class CommentAdded implements CommentAddedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + CommentAdded(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("commentAddedHook", "comment-added"); + this.hookFactory = hookFactory; + } + + @Override + public void onCommentAdded(CommentAddedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.add("--is-draft", event.getRevision().draft); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--topic", c.topic); + args.add("--author", event.getAuthor()); + args.add("--commit", event.getRevision().commit.commit); + args.add("--comment", event.getComment()); + args.addApprovals(event.getApprovals(), event.getOldApprovals()); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/CommitReceived.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/CommitReceived.java new file mode 100644 index 0000000..8f8ea57 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/CommitReceived.java
@@ -0,0 +1,79 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import static com.google.gerrit.reviewdb.client.RefNames.REFS_CHANGES; +import static org.eclipse.jgit.lib.Constants.R_HEADS; + +import com.google.gerrit.server.IdentifiedUser; +import com.google.gerrit.server.events.CommitReceivedEvent; +import com.google.gerrit.server.git.validators.CommitValidationException; +import com.google.gerrit.server.git.validators.CommitValidationListener; +import com.google.gerrit.server.git.validators.CommitValidationMessage; +import com.google.inject.Inject; + +import org.eclipse.jgit.lib.ObjectId; + +import java.util.Collections; +import java.util.List; + +public class CommitReceived implements CommitValidationListener { + private final SynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + CommitReceived(HookFactory hookFactory) { + this.hook = hookFactory.createSync("refUpdateHook", "ref-update"); + this.hookFactory = hookFactory; + } + + @Override + public List<CommitValidationMessage> onCommitReceived( + CommitReceivedEvent receiveEvent) throws CommitValidationException { + IdentifiedUser user = receiveEvent.user; + String refname = receiveEvent.refName; + ObjectId old = ObjectId.zeroId(); + if (receiveEvent.commit.getParentCount() > 0) { + old = receiveEvent.commit.getParent(0); + } + + if (receiveEvent.command.getRefName().startsWith(REFS_CHANGES)) { + /* + * If the ref-update hook tries to distinguish behavior between pushes to + * refs/heads/... and refs/for/..., make sure we send it the correct + * refname. + * Also, if this is targetting refs/for/, make sure we behave the same as + * what a push to refs/for/ would behave; in particular, setting oldrev + * to 0000000000000000000000000000000000000000. + */ + refname = refname.replace(R_HEADS, "refs/for/refs/heads/"); + old = ObjectId.zeroId(); + } + + HookArgs args = hookFactory.createArgs(); + args.add("--project", receiveEvent.project.getName()); + args.add("--refname", refname); + args.add("--uploader", user.getNameEmail()); + args.add("--oldrev", old.name()); + args.add("--newrev", receiveEvent.commit.name()); + + HookResult result = hook.run(args); + if (result != null && result.getExitValue() != 0) { + throw new CommitValidationException(result.toString().trim()); + } + + return Collections.emptyList(); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/DraftPublished.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/DraftPublished.java new file mode 100644 index 0000000..f948dcc --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/DraftPublished.java
@@ -0,0 +1,50 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.DraftPublishedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class DraftPublished implements DraftPublishedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + DraftPublished(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("draftPublishedHook", "draft-published"); + this.hookFactory = hookFactory; + } + + @Override + public void onDraftPublished(DraftPublishedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--topic", c.topic); + args.add("--uploader", event.getPublisher()); + args.add("--commit", event.getRevision().commit.commit); + args.add("--patchset", event.getRevision()._number); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/GitReferenceUpdated.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/GitReferenceUpdated.java new file mode 100644 index 0000000..cf1a10d --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/GitReferenceUpdated.java
@@ -0,0 +1,44 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class GitReferenceUpdated implements GitReferenceUpdatedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + GitReferenceUpdated(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("refUpdatedHook", "ref-updated"); + this.hookFactory = hookFactory; + } + + @Override + public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + args.add("--oldrev", event.getOldObjectId()); + args.add("--newrev", event.getNewObjectId()); + args.add("--refname", event.getRefName()); + args.add("--project", event.getProjectName()); + args.add("--submitter", event.getUpdater()); + + hook.submit(event.getProjectName(), args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HashtagsEdited.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HashtagsEdited.java new file mode 100644 index 0000000..401c5d6 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HashtagsEdited.java
@@ -0,0 +1,57 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.HashtagsEditedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +import java.util.Collection; + +@Singleton +class HashtagsEdited implements HashtagsEditedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + HashtagsEdited(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("hashtagsChanged", "hashtags-changed"); + this.hookFactory = hookFactory; + } + + @Override + public void onHashtagsEdited(HashtagsEditedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--editor", event.getEditor()); + add(args, "--hashtag", event.getHashtags()); + add(args, "--added", event.getAddedHashtags()); + add(args, "--removed", event.getRemovedHashtags()); + + hook.submit(c.project, args); + } + + private void add(HookArgs args, String name, Collection<String> hashtags) { + for (String hashtag : hashtags) { + args.add(name, hashtag); + } + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/Hook.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/Hook.java new file mode 100644 index 0000000..87fb4f4 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/Hook.java
@@ -0,0 +1,25 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import java.nio.file.Path; + +public class Hook { + protected final Path path; + + Hook(Path path) { + this.path = path; + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HookArgs.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookArgs.java new file mode 100644 index 0000000..fe9bf20 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookArgs.java
@@ -0,0 +1,109 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import static com.google.common.base.MoreObjects.firstNonNull; + +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.gerrit.extensions.common.AccountInfo; +import com.google.gerrit.extensions.common.ApprovalInfo; +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.inject.Provider; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +class HookArgs { + private final String anonymousCowardName; + private final Provider<String> urlProvider; + private final List<String> args; + + HookArgs(String anonymousCowardName, Provider<String> urlProvider) { + this.anonymousCowardName = anonymousCowardName; + this.urlProvider = urlProvider; + this.args = new ArrayList<>(); + } + + public ImmutableList<String> get() { + return ImmutableList.copyOf(args); + } + + public void add(String name, String value) { + args.add(name); + args.add(Strings.nullToEmpty(value)); + } + + public void add(String name, int value) { + args.add(name); + args.add(String.valueOf(value)); + } + + public void add(String name, Integer value) { + args.add(name); + args.add(value.toString()); + } + + public void add(String name, Boolean value) { + args.add(name); + args.add(firstNonNull(value, false).toString()); + } + + public void add(String name, AccountInfo account) { + if (account != null) { + args.add(name); + args.add(format(account)); + } + } + + public void addUrl(ChangeInfo change) { + args.add("--change-url"); + String url = urlProvider.get(); + if (change != null && url != null) { + args.add(url + change.changeId); + } else { + args.add(""); + } + } + + public void addApprovals(Map<String, ApprovalInfo> approvals, + Map<String, ApprovalInfo> oldApprovals) { + for (Map.Entry<String, ApprovalInfo> approval : approvals.entrySet()) { + if (approval.getValue() != null) { + args.add("--" + approval.getKey()); + args.add(approval.getValue().value.toString()); + if (oldApprovals != null && !oldApprovals.isEmpty()) { + ApprovalInfo oldValue = oldApprovals.get(approval.getKey()); + if (oldValue != null && oldValue.value != null) { + args.add("--" + approval.getKey() + "-oldValue"); + args.add(oldValue.value.toString()); + } + } + } + } + } + + private String format(AccountInfo account) { + StringBuilder who = new StringBuilder( + firstNonNull(account.name, anonymousCowardName)); + if (account.email != null) { + who.append(" (") + .append(account.email) + .append(")"); + } + return who.toString(); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HookExecutor.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookExecutor.java new file mode 100644 index 0000000..ba5ee70 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookExecutor.java
@@ -0,0 +1,100 @@ +package com.googlesource.gerrit.plugins.hooks; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.google.gerrit.extensions.events.LifecycleListener; +import com.google.gerrit.server.config.GerritServerConfig; +import com.google.gerrit.server.config.SitePaths; +import com.google.gerrit.server.git.GitRepositoryManager; +import com.google.inject.Inject; + +import org.eclipse.jgit.lib.Config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class HookExecutor implements LifecycleListener { + private static final Logger log = + LoggerFactory.getLogger(HookExecutor.class); + private static final UncaughtExceptionHandler LOG_UNCAUGHT_EXCEPTION = + new UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + log.error("HookExecutor thread " + t.getName() + + " threw exception", e); + } + }; + + private final SitePaths sitePaths; + private final GitRepositoryManager gitManager; + private final ExecutorService threadPool; + private final int timeout; + + @Inject + HookExecutor(@GerritServerConfig Config config, + SitePaths sitePaths, + GitRepositoryManager gitManager) { + this.sitePaths = sitePaths; + this.gitManager = gitManager; + + this.timeout = config.getInt("hooks", "syncHookTimeout", 30); + this.threadPool = Executors.newCachedThreadPool( + new ThreadFactoryBuilder() + .setNameFormat("SyncHook-%d") + .setUncaughtExceptionHandler(LOG_UNCAUGHT_EXCEPTION) + .build()); + } + + HookResult submit(Path hook, HookArgs args) { + return submit(null, hook, args); + } + + HookResult submit(String projectName, Path hook, HookArgs args) { + if (!Files.exists(hook)) { + return null; + } + HookTask.Sync hookTask = new HookTask.Sync( + gitManager, sitePaths.site_path, projectName, hook, args); + FutureTask<HookResult> task = new FutureTask<>(hookTask); + threadPool.execute(task); + String message; + + try { + return task.get(timeout, TimeUnit.SECONDS); + } catch (TimeoutException e) { + message = "Synchronous hook timed out " + hook.toAbsolutePath(); + log.error(message); + } catch (Exception e) { + message = "Error running hook " + hook.toAbsolutePath(); + log.error(message, e); + } + task.cancel(true); + hookTask.cancel(); + + return new HookResult(hookTask.getOutput(), message); + } + + @Override + public void start() { + } + + @Override + public void stop() { + threadPool.shutdown(); + boolean isTerminated; + do { + try { + isTerminated = threadPool.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + isTerminated = false; + } + } while (!isTerminated); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HookFactory.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookFactory.java new file mode 100644 index 0000000..3ec1d8c --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookFactory.java
@@ -0,0 +1,80 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import static com.google.common.base.MoreObjects.firstNonNull; + +import com.google.gerrit.common.Nullable; +import com.google.gerrit.server.config.AnonymousCowardName; +import com.google.gerrit.server.config.CanonicalWebUrl; +import com.google.gerrit.server.config.GerritServerConfig; +import com.google.gerrit.server.config.SitePaths; +import com.google.inject.Inject; +import com.google.inject.Provider; +import com.google.inject.Singleton; + +import org.eclipse.jgit.lib.Config; + +import java.nio.file.Path; +import java.nio.file.Paths; + +@Singleton +public class HookFactory { + private final HookQueue queue; + private final HookExecutor syncHookExecutor; + private final Config config; + private final String anonymousCowardName; + private final Provider<String> urlProvider; + private final Path hooksPath; + + @Inject + HookFactory(HookQueue queue, + HookExecutor syncHookExecutor, + @GerritServerConfig Config config, + @AnonymousCowardName String anonymousCowardName, + @CanonicalWebUrl @Nullable Provider<String> urlProvider, + SitePaths sitePaths) { + this.queue = queue; + this.syncHookExecutor = syncHookExecutor; + this.config = config; + this.anonymousCowardName = anonymousCowardName; + this.urlProvider = urlProvider; + + String v = config.getString("hooks", null, "path"); + if (v != null) { + this.hooksPath = Paths.get(v); + } else { + this.hooksPath = sitePaths.hooks_dir; + } + } + + private Path getHookPath(String configName, String defaultName) { + String v = config.getString("hooks", null, configName); + return hooksPath.resolve(firstNonNull(v, defaultName)); + } + + public AsynchronousHook createAsync(String configName, String defaultName) { + return new AsynchronousHook(queue, getHookPath(configName, defaultName)); + } + + public SynchronousHook createSync(String configName, String defaultName) { + return new SynchronousHook( + syncHookExecutor, getHookPath(configName, defaultName)); + } + + public HookArgs createArgs() { + return new HookArgs(anonymousCowardName, urlProvider); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HookQueue.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookQueue.java new file mode 100644 index 0000000..0b9c387 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookQueue.java
@@ -0,0 +1,70 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.events.LifecycleListener; +import com.google.gerrit.server.config.SitePaths; +import com.google.gerrit.server.git.GitRepositoryManager; +import com.google.gerrit.server.git.WorkQueue; +import com.google.inject.Inject; + +import java.nio.file.Files; +import java.nio.file.Path; + +class HookQueue implements LifecycleListener { + private final GitRepositoryManager gitManager; + private final WorkQueue workQueue; + private final SitePaths sitePaths; + + private WorkQueue.Executor queue; + + @Inject + HookQueue(GitRepositoryManager m, + WorkQueue q, + SitePaths s) { + gitManager = m; + workQueue = q; + sitePaths = s; + } + + void submit(Path hook, HookArgs args) { + submit(null, hook, args); + } + + void submit(String projectName, Path hook, HookArgs args) { + if (Files.exists(hook)) { + queue.submit(new HookTask.Async( + gitManager, + sitePaths.site_path, + projectName, + hook, + args)); + } + } + + @Override + public void start() { + queue = workQueue.createQueue(1, "HookQueue"); + } + + @Override + public void stop() { + if (queue != null) { + queue.unregisterWorkQueue(); + queue.shutdownNow(); + queue = null; + } + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HookResult.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookResult.java new file mode 100644 index 0000000..c9711db --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookResult.java
@@ -0,0 +1,62 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.common.base.Strings; + +public class HookResult { + private final int exitValue; + private final String output; + private final String executionError; + + HookResult(int exitValue, String output) { + this.exitValue = exitValue; + this.output = output; + this.executionError = null; + } + + HookResult(String output, String executionError) { + this.exitValue = -1; + this.output = output; + this.executionError = executionError; + } + + public int getExitValue() { + return exitValue; + } + + public String getOutput() { + return output; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + if (!Strings.isNullOrEmpty(output)) { + sb.append(output); + + if (executionError != null) { + sb.append(" - "); + } + } + + if (executionError != null) { + sb.append(executionError); + } + + return sb.toString(); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/HookTask.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookTask.java new file mode 100644 index 0000000..f722034 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/HookTask.java
@@ -0,0 +1,157 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.common.io.ByteStreams; +import com.google.gerrit.reviewdb.client.Project; +import com.google.gerrit.server.git.GitRepositoryManager; + +import org.eclipse.jgit.lib.Repository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +class HookTask { + private static final Logger log = LoggerFactory.getLogger(HookTask.class); + + private final GitRepositoryManager gitManager; + private final Path sitePath; + private final String projectName; + private final Path hook; + private final List<String> args; + private StringWriter output; + private Process ps; + + public static class Async extends HookTask implements Runnable { + Async(GitRepositoryManager gitManager, Path sitePath, String projectName, + Path hook, HookArgs args) { + super(gitManager, sitePath, projectName, hook, args); + } + + @Override + public void run() { + super.runHook(); + } + } + + public static class Sync extends HookTask implements Callable<HookResult> { + Sync(GitRepositoryManager gitManager, Path sitePath, String projectName, + Path hook, HookArgs args) { + super(gitManager, sitePath, projectName, hook, args); + } + + @Override + public HookResult call() throws Exception { + return super.runHook(); + } + } + + HookTask(GitRepositoryManager gitManager, + Path sitePath, + String projectName, + Path hook, + HookArgs args) { + this.gitManager = gitManager; + this.sitePath = sitePath; + this.projectName = projectName; + this.hook = hook; + this.args = args.get(); + } + + public void cancel() { + ps.destroy(); + } + + protected String getName() { + return hook.getFileName().toString(); + } + + public String getOutput() { + return output != null ? output.toString() : null; + } + + public HookResult runHook() { + HookResult result = null; + try { + List<String> argv = new ArrayList<>(1 + args.size()); + argv.add(hook.toAbsolutePath().toString()); + argv.addAll(args); + + ProcessBuilder pb = new ProcessBuilder(argv); + pb.redirectErrorStream(true); + + Map<String, String> env = pb.environment(); + env.put("GERRIT_SITE", sitePath.toAbsolutePath().toString()); + + if (projectName != null) { + try (Repository git = gitManager.openRepository( + new Project.NameKey(projectName))) { + pb.directory(git.getDirectory()); + env.put("GIT_DIR", git.getDirectory().getAbsolutePath()); + } + } + + ps = pb.start(); + ps.getOutputStream().close(); + String output = + new String(ByteStreams.toByteArray(ps.getInputStream()), UTF_8); + ps.waitFor(); + result = new HookResult(ps.exitValue(), output); + } catch (InterruptedException iex) { + // InterruptedException - timeout or cancel + } catch (Throwable err) { + log.error("Error running hook " + hook.toAbsolutePath(), err); + } + + if (result != null) { + int exitValue = result.getExitValue(); + if (exitValue == 0) { + log.debug("hook[" + getName() + "] exitValue:" + exitValue); + } else { + log.info("hook[" + getName() + "] exitValue:" + exitValue); + } + + BufferedReader br = + new BufferedReader(new StringReader(result.getOutput())); + try { + String line; + while ((line = br.readLine()) != null) { + log.info("hook[" + getName() + "] output: " + line); + } + } catch (IOException iox) { + log.error("Error writing hook output", iox); + } + } + + return result; + } + + @Override + public String toString() { + return "hook " + hook.getFileName(); + } +} +
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/Module.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/Module.java new file mode 100644 index 0000000..b75fc34 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/Module.java
@@ -0,0 +1,79 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.events.AgreementSignupListener; +import com.google.gerrit.extensions.events.ChangeAbandonedListener; +import com.google.gerrit.extensions.events.ChangeMergedListener; +import com.google.gerrit.extensions.events.ChangeRestoredListener; +import com.google.gerrit.extensions.events.CommentAddedListener; +import com.google.gerrit.extensions.events.DraftPublishedListener; +import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; +import com.google.gerrit.extensions.events.HashtagsEditedListener; +import com.google.gerrit.extensions.events.LifecycleListener; +import com.google.gerrit.extensions.events.NewProjectCreatedListener; +import com.google.gerrit.extensions.events.ReviewerAddedListener; +import com.google.gerrit.extensions.events.ReviewerDeletedListener; +import com.google.gerrit.extensions.events.RevisionCreatedListener; +import com.google.gerrit.extensions.events.TopicEditedListener; +import com.google.gerrit.extensions.registration.DynamicSet; +import com.google.gerrit.server.git.validators.CommitValidationListener; +import com.google.inject.AbstractModule; +import com.google.inject.Scopes; +import com.google.inject.internal.UniqueAnnotations; + +class Module extends AbstractModule { + @Override + protected void configure() { + bind(HookQueue.class).in(Scopes.SINGLETON); + bind(LifecycleListener.class) + .annotatedWith(UniqueAnnotations.create()) + .to(HookQueue.class); + bind(HookExecutor.class).in(Scopes.SINGLETON); + bind(LifecycleListener.class) + .annotatedWith(UniqueAnnotations.create()) + .to(HookExecutor.class); + + DynamicSet.bind(binder(), AgreementSignupListener.class) + .to(AgreementSignup.class); + DynamicSet.bind(binder(), ChangeAbandonedListener.class) + .to(ChangeAbandoned.class); + DynamicSet.bind(binder(), ChangeMergedListener.class) + .to(ChangeMerged.class); + DynamicSet.bind(binder(), ChangeRestoredListener.class) + .to(ChangeRestored.class); + DynamicSet.bind(binder(), CommentAddedListener.class) + .to(CommentAdded.class); + DynamicSet.bind(binder(), DraftPublishedListener.class) + .to(DraftPublished.class); + DynamicSet.bind(binder(), GitReferenceUpdatedListener.class) + .to(GitReferenceUpdated.class); + DynamicSet.bind(binder(), HashtagsEditedListener.class) + .to(HashtagsEdited.class); + DynamicSet.bind(binder(), NewProjectCreatedListener.class) + .to(NewProjectCreated.class); + DynamicSet.bind(binder(), ReviewerAddedListener.class) + .to(ReviewerAdded.class); + DynamicSet.bind(binder(), ReviewerDeletedListener.class) + .to(ReviewerDeleted.class); + DynamicSet.bind(binder(), RevisionCreatedListener.class) + .to(RevisionCreated.class); + DynamicSet.bind(binder(), TopicEditedListener.class) + .to(TopicEdited.class); + + DynamicSet.bind(binder(), CommitValidationListener.class) + .to(CommitReceived.class); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/NewProjectCreated.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/NewProjectCreated.java new file mode 100644 index 0000000..eb566f8 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/NewProjectCreated.java
@@ -0,0 +1,39 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.events.NewProjectCreatedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class NewProjectCreated implements NewProjectCreatedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + NewProjectCreated(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("projectCreated", "project-created"); + this.hookFactory = hookFactory; + } + + @Override + public void onNewProjectCreated(NewProjectCreatedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + args.add("--project", event.getProjectName()); + args.add("--head", event.getHeadName()); + hook.submit(event.getProjectName(), args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/ReviewerAdded.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/ReviewerAdded.java new file mode 100644 index 0000000..8575a45 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/ReviewerAdded.java
@@ -0,0 +1,47 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.ReviewerAddedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class ReviewerAdded implements ReviewerAddedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + ReviewerAdded(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("reviewerAdded", "reviewer-added"); + this.hookFactory = hookFactory; + } + + @Override + public void onReviewerAdded(ReviewerAddedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--reviewer", event.getReviewer()); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/ReviewerDeleted.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/ReviewerDeleted.java new file mode 100644 index 0000000..5830e56 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/ReviewerDeleted.java
@@ -0,0 +1,48 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.ReviewerDeletedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class ReviewerDeleted implements ReviewerDeletedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + ReviewerDeleted(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("reviewerDeleted", "reviewer-deleted"); + this.hookFactory = hookFactory; + } + + @Override + public void onReviewerDeleted(ReviewerDeletedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--reviewer", event.getReviewer()); + args.addApprovals(event.getNewApprovals(), event.getOldApprovals()); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/RevisionCreated.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/RevisionCreated.java new file mode 100644 index 0000000..ea772ae --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/RevisionCreated.java
@@ -0,0 +1,52 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.RevisionCreatedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +public class RevisionCreated implements RevisionCreatedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + RevisionCreated(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("patchsetCreated", "patchset-created"); + this.hookFactory = hookFactory; + } + + @Override + public void onRevisionCreated(Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.add("--is-draft", event.getRevision().draft); + args.add("--kind", String.valueOf(event.getRevision().kind)); + args.addUrl(c); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--topic", c.topic); + args.add("--uploader", event.getUploader()); + args.add("--commit", event.getRevision().commit.commit); + args.add("--patchset", event.getRevision()._number); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/SynchronousHook.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/SynchronousHook.java new file mode 100644 index 0000000..03cbc40 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/SynchronousHook.java
@@ -0,0 +1,34 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import java.nio.file.Path; + +class SynchronousHook extends Hook { + private final HookExecutor executor; + + SynchronousHook(HookExecutor executor, Path path) { + super(path); + this.executor = executor; + } + + HookResult run(HookArgs args) { + return executor.submit(path, args); + } + + HookResult run(String projectName, HookArgs args) { + return executor.submit(projectName, path, args); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/hooks/TopicEdited.java b/src/main/java/com/googlesource/gerrit/plugins/hooks/TopicEdited.java new file mode 100644 index 0000000..7fbe6a4 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/hooks/TopicEdited.java
@@ -0,0 +1,48 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// 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 com.googlesource.gerrit.plugins.hooks; + +import com.google.gerrit.extensions.common.ChangeInfo; +import com.google.gerrit.extensions.events.TopicEditedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +class TopicEdited implements TopicEditedListener { + private final AsynchronousHook hook; + private final HookFactory hookFactory; + + @Inject + TopicEdited(HookFactory hookFactory) { + this.hook = hookFactory.createAsync("topicChanged", "topic-changed"); + this.hookFactory = hookFactory; + } + + @Override + public void onTopicEdited(TopicEditedListener.Event event) { + HookArgs args = hookFactory.createArgs(); + + ChangeInfo c = event.getChange(); + args.add("--change", c.id); + args.add("--change-owner", c.owner); + args.add("--project", c.project); + args.add("--branch", c.branch); + args.add("--changer", event.getEditor()); + args.add("--old-topic", event.getOldTopic()); + args.add("--new-topic", event.getChange().topic); + + hook.submit(c.project, args); + } +}
diff --git a/src/main/resources/Documentation/about.md b/src/main/resources/Documentation/about.md new file mode 100644 index 0000000..17c7998 --- /dev/null +++ b/src/main/resources/Documentation/about.md
@@ -0,0 +1,2 @@ +Gerrit does not run any of the standard git hooks in the repositories +it works with, but this plugin implements its own hook mechanism.
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md new file mode 100644 index 0000000..ccd1aa6 --- /dev/null +++ b/src/main/resources/Documentation/config.md
@@ -0,0 +1,83 @@ +Configuration +============= + +Environment +----------- + +When a project is given to a hook, the environment will have `GIT_DIR` set to +the full path of the affected git repository so that git commands can be easily +run. + +Make sure your hook scripts are executable if running on *nix. + +With the exception of the `ref-update` hook, hooks are run in the background +after the relevant change has taken place so are unable to affect the outcome +of any given change. Because of the fact the hooks are run in the background +after the activity, a hook might not be notified about an event if +the server is shutdown before the hook can be invoked. + +Configuration +------------- + +It is possible to change where this plugin looks for hooks, and what +filenames it looks for by adding a `[hooks]` section to `gerrit.config`. + +hooks.path +: Location of hook executables. If not set, defaults to `$site_path/hooks` + +hooks.syncHookTimeout +: Timeout value in seconds for synchronous hooks. If not set, defaults +to 30 seconds. + +hooks.changeAbandonedHook +: Filename for the change abandoned hook. If not set, defaults to `change-abandoned`. + +hooks.changeMergedHook +: Filename for the change merged hook. If not set, defaults to `change-merged`. + +hooks.changeRestoredHook +: Filename for the change restored hook. If not set, defaults to `change-restored`. + +hooks.claSignedHook +: Filename for the CLA signed hook. If not set, defaults to `cla-signed`. + +hooks.commentAddedHook +: Filename for the comment added hook. If not set, defaults to `comment-added`. + +hooks.draftPublishedHook +: Filename for the draft published hook. If not set, defaults to `draft-published`. + +hooks.hashtagsChangedHook +: Filename for the hashtags changed hook. If not set, defaults to `hashtags-changed`. + +hooks.patchsetCreatedHook +: Filename for the patchset created hook. If not set, defaults to `patchset-created`. + +hooks.projectCreatedHook +: Filename for the project created hook. If not set, defaults to `project-created`. + +hooks.refUpdate +: Filename for the ref update hook. If not set, defaults to `ref-update`. + +hooks.refUpdatedHook +: Filename for the ref updated hook. If not set, defaults to `ref-updated`. + +hooks.reviewerAddedHook +: Filename for the reviewer added hook. If not set, defaults to `reviewer-added`. + +hooks.reviewerDeletedHook +: Filename for the reviewer update hook. If not set, defaults to `reviewer-deleted`. + +hooks.topicChangedHook +: Filename for the topic changed hook. If not set, defaults to `topic-changed`. + + +Missing Change URLs +------------------- + +If [gerrit.canonicalWebUrl][1] is not set in `gerrit.config` the +`--change-url` flag may not be passed to all hooks. Hooks started out +of an SSH context (for example the patchset-created hook) don't know +the server's web URL, unless this variable is configured. + +[1]: ../../../Documentation/config-gerrit.html#gerrit.canonicalWebUrl
diff --git a/src/main/resources/Documentation/hooks.md b/src/main/resources/Documentation/hooks.md new file mode 100644 index 0000000..6b0e0ea --- /dev/null +++ b/src/main/resources/Documentation/hooks.md
@@ -0,0 +1,152 @@ +Supported Hooks +=============== + +ref-update +---------- + +This is called when a push request is received by Gerrit. It allows a push to be +rejected before it is committed to the Gerrit repository. If the script exits +with non-zero return code the push will be rejected. Any output from the script +will be returned to the user, regardless of the return code. + +This hook is called synchronously so it is recommended that it not block. A +default timeout on the hook is set to 30 seconds to avoid "runaway" hooks using +up server threads. See [`hooks.syncHookTimeout`][1] for configuration details. + +``` + ref-update --project <project name> --refname <refname> --uploader <uploader> --oldrev <sha1> --newrev <sha1> +``` + +patchset-created +---------------- + +Called whenever a patchset is created (this includes new changes and drafts). + +``` + patchset-created --change <change id> --is-draft <boolean> --kind <change kind> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --topic <topic> --uploader <uploader> --commit <sha1> --patchset <patchset id> +``` + +The `--kind` parameter represents the kind of change uploaded. See documentation +of [`patchSet`][2] for details. + +draft-published +--------------- + +Called whenever a draft change is published. + +``` + draft-published --change <change id> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --topic <topic> --uploader <uploader> --commit <sha1> --patchset <patchset id> +``` + +comment-added +------------- + +Called whenever a comment is added to a change. + +``` + comment-added --change <change id> --is-draft <boolean> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --topic <topic> --author <comment author> --commit <commit> --comment <comment> [--<approval category id> <score> --<approval category id> <score> --<approval category id>-oldValue <score> ...] +``` + +change-merged +------------- + +Called whenever a change has been merged. + +``` + change-merged --change <change id> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --topic <topic> --submitter <submitter> --commit <sha1> --newrev <sha1> +``` + +change-abandoned +---------------- + +Called whenever a change has been abandoned. + +``` + change-abandoned --change <change id> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --topic <topic> --abandoner <abandoner> --commit <sha1> --reason <reason> +``` + +change-restored +--------------- + +Called whenever a change has been restored. + +``` + change-restored --change <change id> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --topic <topic> --restorer <restorer> --commit <sha1> --reason <reason> +``` + +ref-updated +----------- + +Called whenever a ref has been updated. + +``` + ref-updated --oldrev <old rev> --newrev <new rev> --refname <ref name> --project <project name> --submitter <submitter> +``` + +project-created +--------------- + +Called whenever a project has been created. + +``` + project-created --project <project name> --head <head name> +``` + +reviewer-added +-------------- + +Called whenever a reviewer is added to a change. + +``` + reviewer-added --change <change id> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --reviewer <reviewer> +``` + +reviewer-deleted +---------------- + +Called whenever a reviewer (with a vote) is removed from a change. + +``` + reviewer-deleted --change <change id> --change-url <change url> --change-owner <change owner> --project <project name> --branch <branch> --reviewer <reviewer> [--<approval category id> <score> --<approval category id> <score> ...] +``` + +topic-changed +------------- + +Called whenever a change's topic is changed from the Web UI or via the REST API. + +``` + topic-changed --change <change id> --change-owner <change owner> --project <project name> --branch <branch> --changer <changer> --old-topic <old topic> --new-topic <new topic> +``` + +hashtags-changed +---------------- + +Called whenever hashtags are added to or removed from a change from the Web UI +or via the REST API. + +``` + hashtags-changed --change <change id> --change-owner <change owner> --project <project name> --branch <branch> --editor <editor> --added <hashtag> --removed <hashtag> --hashtag <hashtag> +``` + +The `--added` parameter may be passed multiple times, once for each +hashtag that was added to the change. + +The `--removed` parameter may be passed multiple times, once for each +hashtag that was removed from the change. + +The `--hashtag` parameter may be passed multiple times, once for each +hashtag remaining on the change after the add or remove operation has +been performed. + +cla-signed +---------- + +Called whenever a user signs a contributor license agreement. + +``` + cla-signed --submitter <submitter> --user-id <user_id> --cla-id <cla_id> +``` + +[1]: config.html#hooks.syncHookTimeout +[2]: ../../../Documentation/json.html#patchSet