]> source.dussan.org Git - gitblit.git/commitdiff
Draft mechanism to record a push log as a hidden orphan branch
authorJames Moger <james.moger@gitblit.com>
Sat, 5 Jan 2013 15:23:42 +0000 (10:23 -0500)
committerJames Moger <james.moger@gitblit.com>
Sat, 5 Jan 2013 20:04:40 +0000 (15:04 -0500)
13 files changed:
src/com/gitblit/Constants.java
src/com/gitblit/GitServlet.java
src/com/gitblit/models/Activity.java
src/com/gitblit/models/PushLogEntry.java [new file with mode: 0644]
src/com/gitblit/models/RepositoryCommit.java [new file with mode: 0644]
src/com/gitblit/utils/ActivityUtils.java
src/com/gitblit/utils/IssueUtils.java
src/com/gitblit/utils/JGitUtils.java
src/com/gitblit/utils/PushLogUtils.java [new file with mode: 0644]
src/com/gitblit/wicket/panels/ActivityPanel.java
src/com/gitblit/wicket/panels/RefsPanel.java
tests/com/gitblit/tests/GitServletTest.java
tests/com/gitblit/tests/PushLogTest.java [new file with mode: 0644]

index ca3326900a88480c56364e15a703b783c9fd3f2b..4dd1471269a9d7c64664d53e5b82b3e4752fb94c 100644 (file)
@@ -88,6 +88,8 @@ public class Constants {
        \r
        public static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssZ";\r
        \r
+       public static final String R_GITBLIT = "refs/gitblit/";\r
+       \r
        public static String getGitBlitVersion() {\r
                return NAME + " v" + VERSION;\r
        }\r
index 94a51be070fa3f3f6e8a37b2288f34df12a3d34f..05f38b9d798f97ccd8387876b8324e10cf59c9df 100644 (file)
@@ -29,6 +29,7 @@ import java.util.Collection;
 import java.util.Enumeration;\r
 import java.util.LinkedHashSet;\r
 import java.util.List;\r
+import java.util.Map;\r
 import java.util.Set;\r
 \r
 import javax.servlet.ServletConfig;\r
@@ -37,7 +38,9 @@ import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;\r
 \r
 import org.eclipse.jgit.http.server.resolver.DefaultReceivePackFactory;\r
+import org.eclipse.jgit.http.server.resolver.DefaultUploadPackFactory;\r
 import org.eclipse.jgit.lib.PersonIdent;\r
+import org.eclipse.jgit.lib.Ref;\r
 import org.eclipse.jgit.lib.Repository;\r
 import org.eclipse.jgit.revwalk.RevCommit;\r
 import org.eclipse.jgit.transport.PostReceiveHook;\r
@@ -45,6 +48,8 @@ import org.eclipse.jgit.transport.PreReceiveHook;
 import org.eclipse.jgit.transport.ReceiveCommand;\r
 import org.eclipse.jgit.transport.ReceiveCommand.Result;\r
 import org.eclipse.jgit.transport.ReceivePack;\r
+import org.eclipse.jgit.transport.RefFilter;\r
+import org.eclipse.jgit.transport.UploadPack;\r
 import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;\r
 import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException;\r
 import org.slf4j.Logger;\r
@@ -55,7 +60,9 @@ import com.gitblit.models.RepositoryModel;
 import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.ClientLogger;\r
 import com.gitblit.utils.HttpUtils;\r
+import com.gitblit.utils.IssueUtils;\r
 import com.gitblit.utils.JGitUtils;\r
+import com.gitblit.utils.PushLogUtils;\r
 import com.gitblit.utils.StringUtils;\r
 \r
 /**\r
@@ -131,6 +138,35 @@ public class GitServlet extends org.eclipse.jgit.http.server.GitServlet {
                                return rp;\r
                        }\r
                });\r
+               \r
+               // override the default upload pack to exclude gitblit refs\r
+               setUploadPackFactory(new DefaultUploadPackFactory() {\r
+                       @Override\r
+                       public UploadPack create(final HttpServletRequest req, final Repository db)\r
+                                       throws ServiceNotEnabledException, ServiceNotAuthorizedException {\r
+                               UploadPack up = super.create(req, db);\r
+                               RefFilter refFilter = new RefFilter() {\r
+                                       @Override\r
+                                       public Map<String, Ref> filter(Map<String, Ref> refs) {\r
+                                               // admin accounts can access all refs \r
+                                               UserModel user = GitBlit.self().authenticate(req);\r
+                                               if (user == null) {\r
+                                                       user = UserModel.ANONYMOUS;\r
+                                               }\r
+                                               if (user.canAdmin()) {\r
+                                                       return refs;\r
+                                               }\r
+\r
+                                               // normal users can not clone gitblit refs\r
+                                               refs.remove(IssueUtils.GB_ISSUES);\r
+                                               refs.remove(PushLogUtils.GB_PUSHES);\r
+                                               return refs;\r
+                                       }\r
+                               };\r
+                               up.setRefFilter(refFilter);\r
+                               return up;\r
+                       }\r
+               });\r
                super.init(new GitblitServletConfig(config));\r
        }\r
 \r
@@ -264,12 +300,11 @@ public class GitServlet extends org.eclipse.jgit.http.server.GitServlet {
                                logger.info("skipping post-receive hooks, no refs created, updated, or removed");\r
                                return;\r
                        }\r
-                       RepositoryModel repository = GitBlit.self().getRepositoryModel(repositoryName);\r
-                       Set<String> scripts = new LinkedHashSet<String>();\r
-                       scripts.addAll(GitBlit.self().getPostReceiveScriptsInherited(repository));\r
-                       scripts.addAll(repository.postReceiveScripts);\r
+\r
                        UserModel user = getUserModel(rp);\r
-                       runGroovy(repository, user, commands, rp, scripts);\r
+                       RepositoryModel repository = GitBlit.self().getRepositoryModel(repositoryName);\r
+\r
+                       // log ref changes\r
                        for (ReceiveCommand cmd : commands) {\r
                                if (Result.OK.equals(cmd.getResult())) {\r
                                        // add some logging for important ref changes\r
@@ -288,6 +323,16 @@ public class GitServlet extends org.eclipse.jgit.http.server.GitServlet {
                                        }\r
                                }\r
                        }\r
+\r
+                       // update push log\r
+                       PushLogUtils.updatePushLog(user, rp.getRepository(), commands);\r
+                       logger.info(MessageFormat.format("{0} push log updated", repository.name));\r
+                       \r
+                       // run Groovy hook scripts \r
+                       Set<String> scripts = new LinkedHashSet<String>();\r
+                       scripts.addAll(GitBlit.self().getPostReceiveScriptsInherited(repository));\r
+                       scripts.addAll(repository.postReceiveScripts);\r
+                       runGroovy(repository, user, commands, rp, scripts);\r
                        \r
                        // Experimental\r
                        // runNativeScript(rp, "hooks/post-receive", commands);\r
index 7e0cb4b34b7c43c4fb121207e419cbbce5f60cd6..59405c7f469c170ea647f04f9bf8d41ab73eac5b 100644 (file)
@@ -25,7 +25,6 @@ import java.util.List;
 import java.util.Map;\r
 import java.util.Set;\r
 \r
-import org.eclipse.jgit.lib.PersonIdent;\r
 import org.eclipse.jgit.revwalk.RevCommit;\r
 \r
 import com.gitblit.utils.StringUtils;\r
@@ -127,86 +126,4 @@ public class Activity implements Serializable, Comparable<Activity> {
                // reverse chronological order\r
                return o.startDate.compareTo(startDate);\r
        }\r
-\r
-       /**\r
-        * Model class to represent a RevCommit, it's source repository, and the\r
-        * branch. This class is used by the activity page.\r
-        * \r
-        * @author James Moger\r
-        */\r
-       public static class RepositoryCommit implements Serializable, Comparable<RepositoryCommit> {\r
-\r
-               private static final long serialVersionUID = 1L;\r
-\r
-               public final String repository;\r
-\r
-               public final String branch;\r
-\r
-               private final RevCommit commit;\r
-\r
-               private List<RefModel> refs;\r
-\r
-               public RepositoryCommit(String repository, String branch, RevCommit commit) {\r
-                       this.repository = repository;\r
-                       this.branch = branch;\r
-                       this.commit = commit;\r
-               }\r
-\r
-               public void setRefs(List<RefModel> refs) {\r
-                       this.refs = refs;\r
-               }\r
-\r
-               public List<RefModel> getRefs() {\r
-                       return refs;\r
-               }\r
-\r
-               public String getName() {\r
-                       return commit.getName();\r
-               }\r
-\r
-               public String getShortName() {\r
-                       return commit.getName().substring(0, 8);\r
-               }\r
-\r
-               public String getShortMessage() {\r
-                       return commit.getShortMessage();\r
-               }\r
-\r
-               public int getParentCount() {\r
-                       return commit.getParentCount();\r
-               }\r
-\r
-               public PersonIdent getAuthorIdent() {\r
-                       return commit.getAuthorIdent();\r
-               }\r
-\r
-               public PersonIdent getCommitterIdent() {\r
-                       return commit.getCommitterIdent();\r
-               }\r
-\r
-               @Override\r
-               public boolean equals(Object o) {\r
-                       if (o instanceof RepositoryCommit) {\r
-                               RepositoryCommit commit = (RepositoryCommit) o;\r
-                               return repository.equals(commit.repository) && getName().equals(commit.getName());\r
-                       }\r
-                       return false;\r
-               }\r
-               \r
-               @Override\r
-               public int hashCode() {\r
-                       return (repository + commit).hashCode();\r
-               }\r
-\r
-               @Override\r
-               public int compareTo(RepositoryCommit o) {\r
-                       // reverse-chronological order\r
-                       if (commit.getCommitTime() > o.commit.getCommitTime()) {\r
-                               return -1;\r
-                       } else if (commit.getCommitTime() < o.commit.getCommitTime()) {\r
-                               return 1;\r
-                       }\r
-                       return 0;\r
-               }\r
-       }\r
 }\r
diff --git a/src/com/gitblit/models/PushLogEntry.java b/src/com/gitblit/models/PushLogEntry.java
new file mode 100644 (file)
index 0000000..32a7d00
--- /dev/null
@@ -0,0 +1,166 @@
+/*\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
+package com.gitblit.models;\r
+\r
+import java.io.Serializable;\r
+import java.text.MessageFormat;\r
+import java.util.ArrayList;\r
+import java.util.Collections;\r
+import java.util.Date;\r
+import java.util.HashSet;\r
+import java.util.LinkedHashSet;\r
+import java.util.List;\r
+import java.util.Set;\r
+\r
+import org.eclipse.jgit.lib.Constants;\r
+import org.eclipse.jgit.revwalk.RevCommit;\r
+\r
+/**\r
+ * Model class to represent a push into a repository.\r
+ * \r
+ * @author James Moger\r
+ */\r
+public class PushLogEntry implements Serializable, Comparable<PushLogEntry> {\r
+\r
+       private static final long serialVersionUID = 1L;\r
+\r
+       public final String repository;\r
+       \r
+       public final Date date;\r
+       \r
+       public final UserModel user;\r
+\r
+       private final Set<RepositoryCommit> commits;\r
+\r
+       /**\r
+        * Constructor for specified duration of push from start date.\r
+        * \r
+        * @param repository\r
+        *            the repository that received the push\r
+        * @param date\r
+        *            the date of the push\r
+        * @param user\r
+        *            the user who pushed\r
+        */\r
+       public PushLogEntry(String repository, Date date, UserModel user) {\r
+               this.repository = repository;\r
+               this.date = date;\r
+               this.user = user;\r
+               this.commits = new LinkedHashSet<RepositoryCommit>();\r
+       }\r
+\r
+       /**\r
+        * Adds a commit to the push entry object as long as the commit is not a\r
+        * duplicate.\r
+        * \r
+        * @param branch\r
+        * @param commit\r
+        * @return a RepositoryCommit, if one was added. Null if this is duplicate\r
+        *         commit\r
+        */\r
+       public RepositoryCommit addCommit(String branch, RevCommit commit) {\r
+               RepositoryCommit commitModel = new RepositoryCommit(repository, branch, commit);\r
+               if (commits.add(commitModel)) {\r
+                       return commitModel;\r
+               }\r
+               return null;\r
+       }\r
+       \r
+       /**\r
+        * Returns the list of branches changed by the push.\r
+        * \r
+        * @return a list of branches\r
+        */\r
+       public List<String> getChangedBranches() {\r
+               return getChangedRefs(Constants.R_HEADS);\r
+       }\r
+       \r
+       /**\r
+        * Returns the list of tags changed by the push.\r
+        * \r
+        * @return a list of tags\r
+        */\r
+       public List<String> getChangedTags() {\r
+               return getChangedRefs(Constants.R_TAGS);\r
+       }\r
+\r
+       /**\r
+        * Gets the changed refs in the push.\r
+        * \r
+        * @param baseRef\r
+        * @return the changed refs\r
+        */\r
+       protected List<String> getChangedRefs(String baseRef) {\r
+               Set<String> refs = new HashSet<String>();\r
+               for (RepositoryCommit commit : commits) {\r
+                       if (baseRef == null || commit.branch.startsWith(baseRef)) {\r
+                               refs.add(commit.branch);\r
+                       }\r
+               }\r
+               List<String> list = new ArrayList<String>(refs);\r
+               Collections.sort(list);\r
+               return list;\r
+       }\r
+       \r
+       /**\r
+        * The total number of commits in the push.\r
+        * \r
+        * @return the number of commits in the push\r
+        */\r
+       public int getCommitCount() {\r
+               return commits.size();\r
+       }\r
+       \r
+       /**\r
+        * Returns all commits in the push.\r
+        * \r
+        * @return a list of commits\r
+        */\r
+       public List<RepositoryCommit> getCommits() {\r
+               List<RepositoryCommit> list = new ArrayList<RepositoryCommit>(commits);\r
+               Collections.sort(list);\r
+               return list;\r
+       }\r
+       \r
+       /**\r
+        * Returns all commits that belong to a particular ref\r
+        * \r
+        * @param ref\r
+        * @return a list of commits\r
+        */\r
+       public List<RepositoryCommit> getCommits(String ref) {\r
+               List<RepositoryCommit> list = new ArrayList<RepositoryCommit>();\r
+               for (RepositoryCommit commit : commits) {\r
+                       if (commit.branch.equals(ref)) {\r
+                               list.add(commit);\r
+                       }\r
+               }\r
+               Collections.sort(list);\r
+               return list;\r
+       }\r
+\r
+       @Override\r
+       public int compareTo(PushLogEntry o) {\r
+               // reverse chronological order\r
+               return o.date.compareTo(date);\r
+       }\r
+       \r
+       @Override\r
+       public String toString() {\r
+               return MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1} pushed {2,number,0} commit{3} to {4} ",\r
+                               date, user.getDisplayName(), commits.size(), commits.size() == 1 ? "":"s", repository);\r
+       }\r
+}\r
diff --git a/src/com/gitblit/models/RepositoryCommit.java b/src/com/gitblit/models/RepositoryCommit.java
new file mode 100644 (file)
index 0000000..3a98f61
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2011 gitblit.com.
+ *
+ * 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.gitblit.models;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.revwalk.RevCommit;
+
+/**
+ * Model class to represent a RevCommit, it's source repository, and the branch.
+ * This class is used by the activity page.
+ * 
+ * @author James Moger
+ */
+public class RepositoryCommit implements Serializable, Comparable<RepositoryCommit> {
+
+       private static final long serialVersionUID = 1L;
+
+       public final String repository;
+
+       public final String branch;
+
+       private final RevCommit commit;
+
+       private List<RefModel> refs;
+
+       public RepositoryCommit(String repository, String branch, RevCommit commit) {
+               this.repository = repository;
+               this.branch = branch;
+               this.commit = commit;
+       }
+
+       public void setRefs(List<RefModel> refs) {
+               this.refs = refs;
+       }
+
+       public List<RefModel> getRefs() {
+               return refs;
+       }
+
+       public String getName() {
+               return commit.getName();
+       }
+
+       public String getShortName() {
+               return commit.getName().substring(0, 8);
+       }
+
+       public String getShortMessage() {
+               return commit.getShortMessage();
+       }
+
+       public int getParentCount() {
+               return commit.getParentCount();
+       }
+
+       public PersonIdent getAuthorIdent() {
+               return commit.getAuthorIdent();
+       }
+
+       public PersonIdent getCommitterIdent() {
+               return commit.getCommitterIdent();
+       }
+
+       @Override
+       public boolean equals(Object o) {
+               if (o instanceof RepositoryCommit) {
+                       RepositoryCommit commit = (RepositoryCommit) o;
+                       return repository.equals(commit.repository) && getName().equals(commit.getName());
+               }
+               return false;
+       }
+
+       @Override
+       public int hashCode() {
+               return (repository + commit).hashCode();
+       }
+
+       @Override
+       public int compareTo(RepositoryCommit o) {
+               // reverse-chronological order
+               if (commit.getCommitTime() > o.commit.getCommitTime()) {
+                       return -1;
+               } else if (commit.getCommitTime() < o.commit.getCommitTime()) {
+                       return 1;
+               }
+               return 0;
+       }
+}
\ No newline at end of file
index ef3a55e7d71bb04bb3c3dbf45b2a8feba6413779..732fdeb17dc6feeeecbc16fb36a3cd6a0c156f20 100644 (file)
@@ -36,9 +36,9 @@ import org.eclipse.jgit.revwalk.RevCommit;
 \r
 import com.gitblit.GitBlit;\r
 import com.gitblit.models.Activity;\r
-import com.gitblit.models.Activity.RepositoryCommit;\r
 import com.gitblit.models.GravatarProfile;\r
 import com.gitblit.models.RefModel;\r
+import com.gitblit.models.RepositoryCommit;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.google.gson.reflect.TypeToken;\r
 \r
index 7b24ccf7dcb06fb82ce557e8d076f5ab44c4c845..1b90c7d6ad1f517aca101d9a2f85b7bdaab3488e 100644 (file)
@@ -76,9 +76,9 @@ public class IssueUtils {
                public abstract boolean accept(IssueModel issue);\r
        }\r
 \r
-       public static final String GB_ISSUES = "refs/heads/gb-issues";\r
+       public static final String GB_ISSUES = "refs/gitblit/issues";\r
 \r
-       static final Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class);\r
+       static final Logger LOGGER = LoggerFactory.getLogger(IssueUtils.class);\r
 \r
        /**\r
         * Log an error message and exception.\r
@@ -111,7 +111,13 @@ public class IssueUtils {
         * @return a refmodel for the gb-issues branch or null\r
         */\r
        public static RefModel getIssuesBranch(Repository repository) {\r
-               return JGitUtils.getBranch(repository, "gb-issues");\r
+               List<RefModel> refs = JGitUtils.getRefs(repository, com.gitblit.Constants.R_GITBLIT);\r
+               for (RefModel ref : refs) {\r
+                       if (ref.reference.getName().equals(GB_ISSUES)) {\r
+                               return ref;\r
+                       }\r
+               }\r
+               return null;\r
        }\r
 \r
        /**\r
@@ -394,7 +400,7 @@ public class IssueUtils {
        public static IssueModel createIssue(Repository repository, Change change) {\r
                RefModel issuesBranch = getIssuesBranch(repository);\r
                if (issuesBranch == null) {\r
-                       JGitUtils.createOrphanBranch(repository, "gb-issues", null);\r
+                       JGitUtils.createOrphanBranch(repository, GB_ISSUES, null);\r
                }\r
 \r
                if (StringUtils.isEmpty(change.author)) {\r
@@ -471,7 +477,7 @@ public class IssueUtils {
                RefModel issuesBranch = getIssuesBranch(repository);\r
 \r
                if (issuesBranch == null) {\r
-                       throw new RuntimeException("gb-issues branch does not exist!");\r
+                       throw new RuntimeException(GB_ISSUES + " does not exist!");\r
                }\r
 \r
                if (StringUtils.isEmpty(issueId)) {\r
index beaa27da1726ac5c6493cf94966a426fa42a41b8..099036e537deb373fdb1d1335b8a58b568b55c82 100644 (file)
@@ -1457,6 +1457,20 @@ public class JGitUtils {
                        int maxCount) {\r
                return getRefs(repository, Constants.R_NOTES, fullName, maxCount);\r
        }\r
+       \r
+       /**\r
+        * Returns the list of refs in the specified base ref. If repository does \r
+        * not exist or is empty, an empty list is returned.\r
+        * \r
+        * @param repository\r
+        * @param fullName\r
+        *            if true, /refs/yadayadayada is returned. If false,\r
+        *            yadayadayada is returned.\r
+        * @return list of refs\r
+        */\r
+       public static List<RefModel> getRefs(Repository repository, String baseRef) {\r
+               return getRefs(repository, baseRef, true, -1);\r
+       }\r
 \r
        /**\r
         * Returns a list of references in the repository matching "refs". If the\r
diff --git a/src/com/gitblit/utils/PushLogUtils.java b/src/com/gitblit/utils/PushLogUtils.java
new file mode 100644 (file)
index 0000000..a3b1d66
--- /dev/null
@@ -0,0 +1,344 @@
+/*
+ * Copyright 2013 gitblit.com.
+ *
+ * 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.gitblit.utils;
+
+import java.io.IOException;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
+import org.eclipse.jgit.api.errors.JGitInternalException;
+import org.eclipse.jgit.dircache.DirCache;
+import org.eclipse.jgit.dircache.DirCacheBuilder;
+import org.eclipse.jgit.dircache.DirCacheEntry;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.RefUpdate;
+import org.eclipse.jgit.lib.RefUpdate.Result;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.transport.ReceiveCommand;
+import org.eclipse.jgit.treewalk.CanonicalTreeParser;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.gitblit.models.PathModel.PathChangeModel;
+import com.gitblit.models.PushLogEntry;
+import com.gitblit.models.RefModel;
+import com.gitblit.models.UserModel;
+
+/**
+ * Utility class for maintaining a pushlog within a git repository on an
+ * orphan branch.
+ * 
+ * @author James Moger
+ *
+ */
+public class PushLogUtils {
+       
+       public static final String GB_PUSHES = "refs/gitblit/pushes";
+
+       static final Logger LOGGER = LoggerFactory.getLogger(PushLogUtils.class);
+
+       /**
+        * Log an error message and exception.
+        * 
+        * @param t
+        * @param repository
+        *            if repository is not null it MUST be the {0} parameter in the
+        *            pattern.
+        * @param pattern
+        * @param objects
+        */
+       private static void error(Throwable t, Repository repository, String pattern, Object... objects) {
+               List<Object> parameters = new ArrayList<Object>();
+               if (objects != null && objects.length > 0) {
+                       for (Object o : objects) {
+                               parameters.add(o);
+                       }
+               }
+               if (repository != null) {
+                       parameters.add(0, repository.getDirectory().getAbsolutePath());
+               }
+               LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t);
+       }
+
+       /**
+        * Returns a RefModel for the gb-pushes branch in the repository. If the
+        * branch can not be found, null is returned.
+        * 
+        * @param repository
+        * @return a refmodel for the gb-pushes branch or null
+        */
+       public static RefModel getPushLogBranch(Repository repository) {
+               List<RefModel> refs = JGitUtils.getRefs(repository, com.gitblit.Constants.R_GITBLIT);
+               for (RefModel ref : refs) {
+                       if (ref.reference.getName().equals(GB_PUSHES)) {
+                               return ref;
+                       }
+               }
+               return null;
+       }
+       
+       /**
+        * Updates a push log.
+        * 
+        * @param user
+        * @param repository
+        * @param commands
+        * @return true, if the update was successful
+        */
+       public static boolean updatePushLog(UserModel user, Repository repository,
+                       Collection<ReceiveCommand> commands) {
+               RefModel pushlogBranch = getPushLogBranch(repository);
+               if (pushlogBranch == null) {
+                       JGitUtils.createOrphanBranch(repository, GB_PUSHES, null);
+               }
+               
+               boolean success = false;
+               String message = "push";
+               
+               try {
+                       ObjectId headId = repository.resolve(GB_PUSHES + "^{commit}");
+                       ObjectInserter odi = repository.newObjectInserter();
+                       try {
+                               // Create the in-memory index of the push log entry
+                               DirCache index = createIndex(repository, headId, commands);
+                               ObjectId indexTreeId = index.writeTree(odi);
+
+                               PersonIdent ident = new PersonIdent(user.getDisplayName(), 
+                                               user.emailAddress == null ? user.username:user.emailAddress);
+
+                               // Create a commit object
+                               CommitBuilder commit = new CommitBuilder();
+                               commit.setAuthor(ident);
+                               commit.setCommitter(ident);
+                               commit.setEncoding(Constants.CHARACTER_ENCODING);
+                               commit.setMessage(message);
+                               commit.setParentId(headId);
+                               commit.setTreeId(indexTreeId);
+
+                               // Insert the commit into the repository
+                               ObjectId commitId = odi.insert(commit);
+                               odi.flush();
+
+                               RevWalk revWalk = new RevWalk(repository);
+                               try {
+                                       RevCommit revCommit = revWalk.parseCommit(commitId);
+                                       RefUpdate ru = repository.updateRef(GB_PUSHES);
+                                       ru.setNewObjectId(commitId);
+                                       ru.setExpectedOldObjectId(headId);
+                                       ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
+                                       Result rc = ru.forceUpdate();
+                                       switch (rc) {
+                                       case NEW:
+                                       case FORCED:
+                                       case FAST_FORWARD:
+                                               success = true;
+                                               break;
+                                       case REJECTED:
+                                       case LOCK_FAILURE:
+                                               throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
+                                                               ru.getRef(), rc);
+                                       default:
+                                               throw new JGitInternalException(MessageFormat.format(
+                                                               JGitText.get().updatingRefFailed, GB_PUSHES, commitId.toString(),
+                                                               rc));
+                                       }
+                               } finally {
+                                       revWalk.release();
+                               }
+                       } finally {
+                               odi.release();
+                       }
+               } catch (Throwable t) {
+                       error(t, repository, "Failed to commit pushlog entry to {0}");
+               }
+               return success;
+       }
+       
+       /**
+        * Creates an in-memory index of the push log entry.
+        * 
+        * @param repo
+        * @param headId
+        * @param commands
+        * @return an in-memory index
+        * @throws IOException
+        */
+       private static DirCache createIndex(Repository repo, ObjectId headId, 
+                       Collection<ReceiveCommand> commands) throws IOException {
+
+               DirCache inCoreIndex = DirCache.newInCore();
+               DirCacheBuilder dcBuilder = inCoreIndex.builder();
+               ObjectInserter inserter = repo.newObjectInserter();
+
+               long now = System.currentTimeMillis();
+               Set<String> ignorePaths = new TreeSet<String>();
+               try {
+                       // add receive commands to the temporary index
+                       for (ReceiveCommand command : commands) {
+                               // use the ref names as the path names
+                               String path = command.getRefName();
+                               ignorePaths.add(path);
+
+                               StringBuilder change = new StringBuilder();
+                               change.append(command.getType().name()).append(' ');
+                               switch (command.getType()) {
+                               case CREATE:
+                                       change.append(ObjectId.zeroId().getName());
+                                       change.append(' ');
+                                       change.append(command.getNewId().getName());
+                                       break;
+                               case UPDATE:
+                               case UPDATE_NONFASTFORWARD:
+                                       change.append(command.getOldId().getName());
+                                       change.append(' ');
+                                       change.append(command.getNewId().getName());
+                                       break;
+                               case DELETE:
+                                       change = null;
+                                       break;
+                               }
+                               if (change == null) {
+                                       // ref deleted
+                                       continue;
+                               }
+                               String content = change.toString();
+                               
+                               // create an index entry for this attachment
+                               final DirCacheEntry dcEntry = new DirCacheEntry(path);
+                               dcEntry.setLength(content.length());
+                               dcEntry.setLastModified(now);
+                               dcEntry.setFileMode(FileMode.REGULAR_FILE);
+
+                               // insert object
+                               dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, content.getBytes("UTF-8")));
+
+                               // add to temporary in-core index
+                               dcBuilder.add(dcEntry);
+                       }
+
+                       // Traverse HEAD to add all other paths
+                       TreeWalk treeWalk = new TreeWalk(repo);
+                       int hIdx = -1;
+                       if (headId != null)
+                               hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
+                       treeWalk.setRecursive(true);
+
+                       while (treeWalk.next()) {
+                               String path = treeWalk.getPathString();
+                               CanonicalTreeParser hTree = null;
+                               if (hIdx != -1)
+                                       hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
+                               if (!ignorePaths.contains(path)) {
+                                       // add entries from HEAD for all other paths
+                                       if (hTree != null) {
+                                               // create a new DirCacheEntry with data retrieved from
+                                               // HEAD
+                                               final DirCacheEntry dcEntry = new DirCacheEntry(path);
+                                               dcEntry.setObjectId(hTree.getEntryObjectId());
+                                               dcEntry.setFileMode(hTree.getEntryFileMode());
+
+                                               // add to temporary in-core index
+                                               dcBuilder.add(dcEntry);
+                                       }
+                               }
+                       }
+
+                       // release the treewalk
+                       treeWalk.release();
+
+                       // finish temporary in-core index used for this commit
+                       dcBuilder.finish();
+               } finally {
+                       inserter.release();
+               }
+               return inCoreIndex;
+       }
+
+       public static List<PushLogEntry> getPushLog(String repositoryName, Repository repository) {
+               return getPushLog(repositoryName, repository, null, -1);
+       }
+
+       public static List<PushLogEntry> getPushLog(String repositoryName, Repository repository, int maxCount) {
+               return getPushLog(repositoryName, repository, null, maxCount);
+       }
+
+       public static List<PushLogEntry> getPushLog(String repositoryName, Repository repository, Date minimumDate) {
+               return getPushLog(repositoryName, repository, minimumDate, -1);
+       }
+       
+       public static List<PushLogEntry> getPushLog(String repositoryName, Repository repository, Date minimumDate, int maxCount) {
+               List<PushLogEntry> list = new ArrayList<PushLogEntry>();
+               RefModel ref = getPushLogBranch(repository);
+               if (ref == null) {
+                       return list;
+               }
+               List<RevCommit> pushes;
+               if (minimumDate == null) {
+                       pushes = JGitUtils.getRevLog(repository, GB_PUSHES, 0, maxCount);
+               } else {
+                       pushes = JGitUtils.getRevLog(repository, GB_PUSHES, minimumDate);
+               }
+               for (RevCommit push : pushes) {
+                       if (push.getAuthorIdent().getName().equalsIgnoreCase("gitblit")) {
+                               // skip gitblit/internal commits
+                               continue;
+                       }
+                       Date date = push.getAuthorIdent().getWhen();
+                       UserModel user = new UserModel(push.getAuthorIdent().getEmailAddress());
+                       user.displayName = push.getAuthorIdent().getName();
+                       PushLogEntry log = new PushLogEntry(repositoryName, date, user);
+                       list.add(log);
+                       List<PathChangeModel> changedRefs = JGitUtils.getFilesInCommit(repository, push);
+                       for (PathChangeModel change : changedRefs) {
+                               switch (change.changeType) {
+                               case DELETE:
+                                       break;
+                               case ADD:
+                               case MODIFY:
+                                       String content = JGitUtils.getStringContent(repository, push.getTree(), change.path);
+                                       String [] fields = content.split(" ");
+                                       String oldId = fields[1];
+                                       String newId = fields[2];
+                                       List<RevCommit> pushedCommits = JGitUtils.getRevLog(repository, oldId, newId);
+                                       for (RevCommit pushedCommit : pushedCommits) {
+                                               log.addCommit(change.path, pushedCommit);
+                                       }
+                                       break;
+                               default:
+                                       break;
+                               }
+                       }
+               }
+               Collections.sort(list);
+               return list;
+       }
+}
index 6caee3e774d644559075428457902acc0b490103..669c36beb204b39338c50f29fde1d4a735bf7c24 100644 (file)
@@ -27,7 +27,7 @@ import com.gitblit.Constants;
 import com.gitblit.GitBlit;\r
 import com.gitblit.Keys;\r
 import com.gitblit.models.Activity;\r
-import com.gitblit.models.Activity.RepositoryCommit;\r
+import com.gitblit.models.RepositoryCommit;\r
 import com.gitblit.utils.StringUtils;\r
 import com.gitblit.wicket.WicketUtils;\r
 import com.gitblit.wicket.pages.CommitDiffPage;\r
index b4676427d1591c900ae14ee10344fee3b8db5ff9..3ba22c0b9249cc59e45445e5be44a64671041ac3 100644 (file)
@@ -129,8 +129,14 @@ public class RefsPanel extends Panel {
                                        name = name.substring(Constants.R_TAGS.length());\r
                                        cssClass = "tagRef";\r
                                } else if (name.startsWith(Constants.R_NOTES)) {\r
+                                       // codereview refs\r
                                        linkClass = CommitPage.class;\r
                                        cssClass = "otherRef";\r
+                               } else if (name.startsWith(com.gitblit.Constants.R_GITBLIT)) {\r
+                                       // gitblit refs\r
+                                       linkClass = LogPage.class;\r
+                                       cssClass = "otherRef";\r
+                                       name = name.substring(com.gitblit.Constants.R_GITBLIT.length());\r
                                }\r
 \r
                                Component c = new LinkPanel("refName", null, name, linkClass,\r
index 7dce07d8f4abd8624597b41f09c6bef1796fea48..771c4b9a56a1526faa3a45b492c2e584bf490bb6 100644 (file)
@@ -7,9 +7,11 @@ import static org.junit.Assert.assertTrue;
 import java.io.BufferedWriter;\r
 import java.io.File;\r
 import java.io.FileOutputStream;\r
+import java.io.IOException;\r
 import java.io.OutputStreamWriter;\r
 import java.text.MessageFormat;\r
 import java.util.Date;\r
+import java.util.List;\r
 import java.util.concurrent.atomic.AtomicBoolean;\r
 \r
 import org.eclipse.jgit.api.CloneCommand;\r
@@ -18,6 +20,7 @@ import org.eclipse.jgit.api.ResetCommand.ResetType;
 import org.eclipse.jgit.api.errors.GitAPIException;\r
 import org.eclipse.jgit.lib.Constants;\r
 import org.eclipse.jgit.revwalk.RevCommit;\r
+import org.eclipse.jgit.storage.file.FileRepository;\r
 import org.eclipse.jgit.transport.CredentialsProvider;\r
 import org.eclipse.jgit.transport.PushResult;\r
 import org.eclipse.jgit.transport.RefSpec;\r
@@ -34,9 +37,11 @@ import com.gitblit.Constants.AccessRestrictionType;
 import com.gitblit.Constants.AuthorizationControl;\r
 import com.gitblit.GitBlit;\r
 import com.gitblit.Keys;\r
+import com.gitblit.models.PushLogEntry;\r
 import com.gitblit.models.RepositoryModel;\r
 import com.gitblit.models.UserModel;\r
 import com.gitblit.utils.JGitUtils;\r
+import com.gitblit.utils.PushLogUtils;\r
 \r
 public class GitServletTest {\r
 \r
@@ -756,4 +761,14 @@ public class GitServletTest {
                GitBlitSuite.close(git);\r
                GitBlit.self().deleteUser(user.username);\r
        }\r
+       \r
+       @Test\r
+       public void testPushLog() throws IOException {\r
+               String name = "refchecks/ticgit.git";\r
+               File refChecks = new File(GitBlitSuite.REPOSITORIES, name);\r
+               FileRepository repository = new FileRepository(refChecks);\r
+               List<PushLogEntry> pushes = PushLogUtils.getPushLog(name, repository);\r
+               GitBlitSuite.close(repository);\r
+               assertTrue("Repository has an empty push log!", pushes.size() > 0);\r
+       }\r
 }\r
diff --git a/tests/com/gitblit/tests/PushLogTest.java b/tests/com/gitblit/tests/PushLogTest.java
new file mode 100644 (file)
index 0000000..aa4cf41
--- /dev/null
@@ -0,0 +1,37 @@
+/*\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
+package com.gitblit.tests;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.List;\r
+\r
+import org.eclipse.jgit.storage.file.FileRepository;\r
+import org.junit.Test;\r
+\r
+import com.gitblit.models.PushLogEntry;\r
+import com.gitblit.utils.PushLogUtils;\r
+\r
+public class PushLogTest {\r
+\r
+       @Test\r
+       public void testPushLog() throws IOException {\r
+               String name = "~james/helloworld.git";\r
+               FileRepository repository = new FileRepository(new File(GitBlitSuite.REPOSITORIES, name));\r
+               List<PushLogEntry> pushes = PushLogUtils.getPushLog(name, repository);\r
+               GitBlitSuite.close(repository);\r
+       }\r
+}
\ No newline at end of file