Skip to content

The Unified and Autonomous Development Platform

Fix issue #359 - Add RESTful API endpoints to operate git repositories

Robin Shen6367a68c59fb
diff --git a/server-core/src/main/java/io/onedev/server/CoreModule.java b/server-core/src/main/java/io/onedev/server/CoreModule.java
index e90227b1e8..5d73850bda 100644
--- a/server-core/src/main/java/io/onedev/server/CoreModule.java
+++ b/server-core/src/main/java/io/onedev/server/CoreModule.java
@@ -646,7 +646,8 @@ public class CoreModule extends AbstractPluginModule {
@Override
public Collection<Class<? extends Exception>> getExpectedExceptionClasses() {
return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class,
- ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class,
+ ObjectNotFoundException.class, io.onedev.server.git.exception.ObjectNotFoundException.class,
+ StaleStateException.class, UnauthorizedException.class,
ExplicitException.class, ValidationException.class, PageExpiredException.class,
StalePageException.class);
}
diff --git a/server-core/src/main/java/io/onedev/server/git/BlobIdent.java b/server-core/src/main/java/io/onedev/server/git/BlobIdent.java
index c8c52e746b..27f8d29f50 100644
--- a/server-core/src/main/java/io/onedev/server/git/BlobIdent.java
+++ b/server-core/src/main/java/io/onedev/server/git/BlobIdent.java
@@ -11,8 +11,8 @@ import org.eclipse.jgit.lib.FileMode;
import com.google.common.base.MoreObjects;
-import io.onedev.server.git.exception.ObjectNotFoundException;
import io.onedev.server.model.Project;
+import io.onedev.server.util.RevisionAndPath;
public class BlobIdent implements Serializable, Comparable<BlobIdent> {
@@ -45,35 +45,14 @@ public class BlobIdent implements Serializable, Comparable<BlobIdent> {
public BlobIdent() {
}
- public BlobIdent(Project project, List<String> urlSegments) {
- StringBuilder revisionBuilder = new StringBuilder();
- for (int i=0; i<urlSegments.size(); i++) {
- if (i != 0)
- revisionBuilder.append("/");
- revisionBuilder.append(urlSegments.get(i));
- if (project.getObjectId(revisionBuilder.toString(), false) != null) {
- revision = revisionBuilder.toString();
- StringBuilder pathBuilder = new StringBuilder();
- for (int j=i+1; j<urlSegments.size(); j++) {
- if (j != i+1)
- pathBuilder.append("/");
- pathBuilder.append(urlSegments.get(j));
- }
- if (pathBuilder.length() != 0) {
- path = pathBuilder.toString();
- mode = project.getMode(revision, path);
- } else {
- mode = FileMode.TREE.getBits();
- }
- return;
- }
- }
- if (revisionBuilder.length() != 0) {
- throw new ObjectNotFoundException("Revision not found: " + revisionBuilder.toString());
- } else {
- revision = project.getDefaultBranch();
+ public BlobIdent(Project project, List<String> segments) {
+ RevisionAndPath revisionAndPath = RevisionAndPath.parse(project, segments);
+ revision = revisionAndPath.getRevision();
+ path = revisionAndPath.getPath();
+ if (path != null)
+ mode = project.getMode(revision, path);
+ else
mode = FileMode.TREE.getBits();
- }
}
public boolean isTree() {
diff --git a/server-core/src/main/java/io/onedev/server/rest/BuildResource.java b/server-core/src/main/java/io/onedev/server/rest/BuildResource.java
index afeeb7bb28..37e50f71bb 100644
--- a/server-core/src/main/java/io/onedev/server/rest/BuildResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/BuildResource.java
@@ -101,7 +101,7 @@ public class BuildResource {
@QueryParam("count") @Api(example="100") int count) {
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
BuildQuery parsedQuery;
try {
diff --git a/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.java b/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.java
index 065c10c9ed..e9d10017eb 100644
--- a/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.java
@@ -81,7 +81,7 @@ public class CodeCommentResource {
@QueryParam("offset") @Api(example="0") int offset, @QueryParam("count") @Api(example="100") int count) {
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
Project project;
if (projectId != null)
diff --git a/server-core/src/main/java/io/onedev/server/rest/GitResource.java b/server-core/src/main/java/io/onedev/server/rest/GitResource.java
deleted file mode 100644
index f6b52bc0ea..0000000000
--- a/server-core/src/main/java/io/onedev/server/rest/GitResource.java
+++ /dev/null
@@ -1,325 +0,0 @@
-package io.onedev.server.rest;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.validation.constraints.NotNull;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.shiro.authz.UnauthorizedException;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.treewalk.TreeWalk;
-
-import io.onedev.server.entitymanager.ProjectManager;
-import io.onedev.server.git.Blob;
-import io.onedev.server.git.BlobEdits;
-import io.onedev.server.git.BlobContent;
-import io.onedev.server.git.BlobIdent;
-import io.onedev.server.git.GitContribution;
-import io.onedev.server.git.GitContributor;
-import io.onedev.server.git.GitUtils;
-import io.onedev.server.model.Project;
-import io.onedev.server.model.UserAuthorization;
-
-import io.onedev.server.rest.annotation.Api;
-import io.onedev.server.rest.jersey.InvalidParamException;
-import io.onedev.server.security.SecurityUtils;
-
-@Api(order=3450)
-@Path("/git-projects")
-@Consumes(MediaType.APPLICATION_JSON)
-@Produces(MediaType.APPLICATION_JSON)
-@Singleton
-public class GitResource {
-
- private final ProjectManager projectManager;
-
- @Inject
- public GitResource(ProjectManager projectManager) {
- this.projectManager = projectManager;
- }
-
- @Api(order=10, description="Retrieve a specific branch from a repository.")
- @Path("/{projectId}/branches/{branch}")
- @GET
- public RefResponse getBranch(@PathParam("projectId") Long projectId, @PathParam("branch") @Api(example="test-branch") String branchName) {
- Project project = projectManager.load(projectId);
- if (!SecurityUtils.canReadCode(project)) {
- throw new UnauthorizedException();
- }
-
- String refName = GitUtils.branch2ref(branchName);
- ObjectId commitId = project.getObjectId(refName, true);
-
- RefResponse response = new RefResponse();
- response.ref = refName;
- response.revision = commitId.name();
- return response;
- }
-
- public static class RefResponse implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private String ref;
-
- private String revision;
-
- public String getRef() {
- return ref;
- }
-
- public void setRef(String ref) {
- this.ref = ref;
- }
-
- public String getRevision() {
- return revision;
- }
-
- public void setRevision(String revision) {
- this.revision = revision;
- }
-
- }
-
- @Api(order=20, description="Create a new git branch")
- @Path("/{projectId}/branches")
- @POST
- public Response createBranch(@PathParam("projectId") Long projectId, @NotNull CreateBranchSettings branch) {
- Project project = projectManager.load(projectId);
- if (!SecurityUtils.canWriteCode(project)) {
- throw new UnauthorizedException();
- }
-
- if (project.getObjectId(GitUtils.branch2ref(branch.getBranchName()), false) != null) {
- throw new InvalidParamException("Branch '" + branch.getBranchName() + "' already exists");
- } else if (project.getBranchProtection(branch.getBranchName(), SecurityUtils.getUser()).isPreventCreation()) {
- throw new InvalidParamException("Can not create this branch according to branch protection setting");
- } else {
- project.createBranch(branch.getBranchName(), branch.getRevision());
- }
-
- return Response.ok().build();
- }
-
- public static class CreateBranchSettings implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private String branchName;
-
- private String revision;
-
- public String getBranchName() {
- return branchName;
- }
-
- public void setBranchName(String branchName) {
- this.branchName = branchName;
- }
-
- public String getRevision() {
- return revision;
- }
-
- public void setRevision(String revision) {
- this.revision = revision;
- }
-
- }
-
- @Api(order=30, description="Delete a specific branch from a repository.")
- @Path("/{projectId}/branches/{branch}")
- @DELETE
- public Response deleteBranch(@PathParam("projectId") Long projectId, @PathParam("branch") @Api(example="test-branch") String branchName) {
- Project project = projectManager.load(projectId);
- if (!SecurityUtils.canDeleteBranch(project, branchName)) {
- throw new UnauthorizedException();
- }
-
- projectManager.deleteBranch(project, branchName);
-
- return Response.ok().build();
- }
-
- @Api(order=40, description="Gets the metadata and contents of a file in a repository.")
- @Path("/{projectId}/contents/{branch}/{filepath:.*}")
- @GET
- public ContentsResponse getContents(@PathParam("projectId") Long projectId, @PathParam("branch") @Api(example="test-branch") String branchName, @PathParam("filepath") @Api(example="path/to/file") String filepath) {
- Project project = projectManager.load(projectId);
- if (!SecurityUtils.canReadCode(project)) {
- throw new UnauthorizedException();
- }
-
- List<String> revisionAndPathSegments = new ArrayList<>();
- revisionAndPathSegments.add(branchName);
- revisionAndPathSegments.add(filepath);
- BlobIdent blobIdent = new BlobIdent(project, revisionAndPathSegments);
-
- if (!blobIdent.isFile()) {
- throw new InvalidParamException("Blob is not a file");
- }
-
- Blob blob = project.getBlob(blobIdent, true);
-
- ContentsResponse response = new ContentsResponse();
- response.path = filepath;
- response.sha = blob.getBlobId().name();
- response.content = new String(Base64.encodeBase64(blob.getBytes()));
- response.size = blob.getSize();
- response.isPartial = blob.isPartial();
- return response;
- }
-
- public static class ContentsResponse implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private String path;
-
- private String sha;
-
- private String content;
-
- private long size;
-
- private boolean isPartial;
-
- public String getPath() {
- return path;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
-
- public String getSha() {
- return sha;
- }
-
- public void setSha(String sha) {
- this.sha = sha;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public long getSize() {
- return size;
- }
-
- public void setSize(long size) {
- this.size = size;
- }
-
- public boolean isPartial() {
- return isPartial;
- }
-
- public void setPartial(boolean partial) {
- isPartial = partial;
- }
-
- }
-
- @Api(order=50, description="Create or update a file in a repository.")
- @Path("/{projectId}/contents/{branch}/{filepath:.*}")
- @PUT
- public RefResponse createOrUpdateContents(@PathParam("projectId") Long projectId, @PathParam("branch") @Api(example="test-branch") String branchName, @PathParam("filepath") @Api(example="path/to/file") String filepath, ContentsRequest request) {
- Project project = projectManager.load(projectId);
- if (!SecurityUtils.canWriteCode(project)) {
- throw new UnauthorizedException();
- }
-
- String refName = GitUtils.branch2ref(branchName);
- ObjectId prevCommitId = project.getObjectId(refName, true);
-
- Set<String> oldPaths = new HashSet<>();
- RevCommit revCommit = project.getRevCommit(prevCommitId, true);
- try (TreeWalk treeWalk = TreeWalk.forPath(project.getRepository(), filepath, revCommit.getTree())) {
- if (treeWalk != null) {
- oldPaths.add(filepath);
- }
- } catch (IOException e) {
- // ignore
- }
-
- Repository repository = project.getRepository();
-
- Map<String, BlobContent> newBlobs = new HashMap<>();
- newBlobs.put(filepath, new BlobContent.Immutable(
- Base64.decodeBase64(request.getContent()),
- FileMode.REGULAR_FILE
- ));
-
- ObjectId newCommitId = new BlobEdits(oldPaths, newBlobs)
- .commit(
- repository,
- refName,
- prevCommitId,
- prevCommitId,
- SecurityUtils.getUser().asPerson(),
- request.getMessage()
- );
-
- RefResponse response = new RefResponse();
- response.ref = refName;
- response.revision = newCommitId.name();
- return response;
- }
-
- public static class ContentsRequest implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private String message;
-
- private String content;
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- }
-
-}
diff --git a/server-core/src/main/java/io/onedev/server/rest/GroupResource.java b/server-core/src/main/java/io/onedev/server/rest/GroupResource.java
index 4d238a9386..1f951742cd 100644
--- a/server-core/src/main/java/io/onedev/server/rest/GroupResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/GroupResource.java
@@ -81,7 +81,7 @@ public class GroupResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<Group> criteria = EntityCriteria.of(Group.class);
if (name != null)
diff --git a/server-core/src/main/java/io/onedev/server/rest/IssueResource.java b/server-core/src/main/java/io/onedev/server/rest/IssueResource.java
index f318e4a732..d6993ac383 100644
--- a/server-core/src/main/java/io/onedev/server/rest/IssueResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/IssueResource.java
@@ -170,7 +170,7 @@ public class IssueResource {
@QueryParam("count") @Api(example="100") int count) {
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
IssueQuery parsedQuery;
try {
diff --git a/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java b/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java
index 9914d17cba..11f1d7b1b6 100644
--- a/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java
@@ -141,7 +141,7 @@ public class ProjectResource {
@QueryParam("count") @Api(example="100") int count) {
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
ProjectQuery parsedQuery;
try {
@@ -166,7 +166,7 @@ public class ProjectResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<Milestone> criteria = EntityCriteria.of(Milestone.class);
criteria.add(Restrictions.eq(Milestone.PROP_PROJECT, project));
@@ -195,7 +195,7 @@ public class ProjectResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
Day sinceDay = new Day(LocalDate.parse(since));
Day untilDay = new Day(LocalDate.parse(until));
diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.java
index 510e804abc..0dd9265531 100644
--- a/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.java
@@ -183,7 +183,7 @@ public class PullRequestResource {
@QueryParam("count") @Api(example="100") int count) {
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
PullRequestQuery parsedQuery;
try {
diff --git a/server-core/src/main/java/io/onedev/server/rest/RepositoryResource.java b/server-core/src/main/java/io/onedev/server/rest/RepositoryResource.java
new file mode 100644
index 0000000000..565063805c
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/RepositoryResource.java
@@ -0,0 +1,537 @@
+package io.onedev.server.rest;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.validation.constraints.NotNull;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevTree;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.hibernate.validator.constraints.NotEmpty;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+
+import io.onedev.server.entitymanager.ProjectManager;
+import io.onedev.server.git.Blob;
+import io.onedev.server.git.BlobContent;
+import io.onedev.server.git.BlobEdits;
+import io.onedev.server.git.BlobIdent;
+import io.onedev.server.git.GitUtils;
+import io.onedev.server.git.command.RevListCommand;
+import io.onedev.server.git.exception.ObjectNotFoundException;
+import io.onedev.server.model.Project;
+import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.rest.jersey.InvalidParamException;
+import io.onedev.server.rest.support.FileCreateOrUpdateRequest;
+import io.onedev.server.rest.support.FileEditRequest;
+import io.onedev.server.search.commit.CommitQuery;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.util.RevisionAndPath;
+
+@Api(order=1100)
+@Path("/repositories")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+@Singleton
+public class RepositoryResource {
+
+ private static final int MAX_COMMITS = 10000;
+
+ private final ProjectManager projectManager;
+
+ @Inject
+ public RepositoryResource(ProjectManager projectManager) {
+ this.projectManager = projectManager;
+ }
+
+ @Api(order=10, description="List all branches")
+ @Path("/{projectId}/branches")
+ @GET
+ public List<String> getBranches(@PathParam("projectId") Long projectId) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ List<String> branchNames = new ArrayList<>();
+ try {
+ for (Ref ref: project.getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS))
+ branchNames.add(GitUtils.ref2branch(ref.getName()));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return branchNames;
+ }
+
+ @Api(order=20, description="Get specified branch")
+ @Path("/{projectId}/branches/{branch:.*}")
+ @GET
+ public RefResponse getBranch(
+ @PathParam("projectId") Long projectId,
+ @PathParam("branch") @Api(example="test-branch") String branchName) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ Ref ref = project.getBranchRef(branchName);
+ if (ref == null)
+ throw new ObjectNotFoundException("Branch not found: " + branchName);
+
+ RefResponse response = new RefResponse();
+
+ response.refName = ref.getName();
+ response.commitHash = project.getRevCommit(ref.getObjectId(), true).getName();
+
+ return response;
+ }
+
+ @Api(order=30, description="Create a new branch")
+ @Path("/{projectId}/branches")
+ @POST
+ public Response createBranch(@PathParam("projectId") Long projectId, @NotNull CreateBranchRequest request) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canCreateBranch(project, request.getBranchName())) {
+ throw new UnauthorizedException();
+ }
+
+ if (project.getBranchRef(request.getBranchName()) != null) {
+ throw new InvalidParamException("Branch '" + request.getBranchName() + "' already exists");
+ } else {
+ project.createBranch(request.getBranchName(), request.getRevision());
+ }
+
+ return Response.ok().build();
+ }
+
+ @Api(order=40, description="Delete specified branch")
+ @Path("/{projectId}/branches/{branch:.*}")
+ @DELETE
+ public Response deleteBranch(@PathParam("projectId") Long projectId,
+ @PathParam("branch") @Api(example="test-branch") String branchName) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canDeleteBranch(project, branchName)) {
+ throw new UnauthorizedException();
+ }
+
+ projectManager.deleteBranch(project, branchName);
+
+ return Response.ok().build();
+ }
+
+ @Api(order=50, description="List all tags")
+ @Path("/{projectId}/tags")
+ @GET
+ public List<String> getTags(@PathParam("projectId") Long projectId) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ List<String> tagNames = new ArrayList<>();
+ try {
+ for (Ref ref: project.getRepository().getRefDatabase().getRefsByPrefix(Constants.R_TAGS))
+ tagNames.add(GitUtils.ref2tag(ref.getName()));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return tagNames;
+ }
+
+ @Api(order=60, description="Get specified tag")
+ @Path("/{projectId}/tags/{tag:.*}")
+ @GET
+ public RefResponse getTag(
+ @PathParam("projectId") Long projectId,
+ @PathParam("tag") @Api(example="test-tag") String tagName) {
+ Project project = projectManager.load(projectId);
+
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ Ref ref = project.getTagRef(tagName);
+ if (ref == null)
+ throw new ObjectNotFoundException("Tag not found: " + tagName);
+
+ RefResponse response = new RefResponse();
+
+ response.refName = ref.getName();
+ response.commitHash = project.getRevCommit(ref.getObjectId(), true).getName();
+
+ return response;
+ }
+
+ @Api(order=70, description="Create a new tag")
+ @Path("/{projectId}/tags")
+ @POST
+ public Response createTag(@PathParam("projectId") Long projectId, @NotNull CreateTagRequest request) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canCreateTag(project, request.getTagName())) {
+ throw new UnauthorizedException();
+ }
+
+ if (project.getTagRef(request.getTagName()) != null) {
+ throw new InvalidParamException("Tag '" + request.getTagName() + "' already exists");
+ } else {
+ PersonIdent tagger = SecurityUtils.getUser().asPerson();
+ project.createTag(request.getTagName(), request.getRevision(), tagger, request.getTagMessage());
+ }
+
+ return Response.ok().build();
+ }
+
+ @Api(order=80, description="Delete specified tag")
+ @Path("/{projectId}/tags/{tag:.*}")
+ @DELETE
+ public Response deleteTag(
+ @PathParam("projectId") Long projectId,
+ @PathParam("tag") @Api(example="test-tag") String tagName) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canDeleteTag(project, tagName)) {
+ throw new UnauthorizedException();
+ }
+
+ projectManager.deleteTag(project, tagName);
+
+ return Response.ok().build();
+ }
+
+ @Api(order=83, description="Query commits of specified project. Will return list of matching commit hashes")
+ @Path("/{projectId}/commits")
+ @GET
+ public List<String> queryCommits(
+ @PathParam("projectId") Long projectId,
+ @QueryParam("query") @Api(description="Syntax of this query is the same as query box in commits page", example="since tag(v4.0.0) until tag(v4.7.0)") String query,
+ @QueryParam("count") @Api(example="100", description="Number of commits to return") int count) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ if (count > MAX_COMMITS)
+ throw new InvalidParamException("Count should not be greater than " + MAX_COMMITS);
+
+ CommitQuery parsedQuery;
+ try {
+ parsedQuery = CommitQuery.parse(project, query);
+ } catch (Exception e) {
+ throw new InvalidParamException("Error parsing query", e);
+ }
+
+ RevListCommand command = new RevListCommand(project.getGitDir());
+ command.ignoreCase(true);
+
+ command.count(count);
+ parsedQuery.fill(project, command);
+
+ return command.call();
+ }
+
+ @Api(order=86, description="Get specified commit")
+ @Path("/{projectId}/commits/{commitHash}")
+ @GET
+ public CommitResponse getCommit(
+ @PathParam("projectId") Long projectId,
+ @PathParam("commitHash") @Api(example="8cbec3d9eda2050a4ca0676767be3b6bf20251b8") String commitHash) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ RevCommit commit = project.getRevCommit(ObjectId.fromString(commitHash), true);
+ CommitResponse response = new CommitResponse();
+ response.commitHash = commit.name();
+ response.author = commit.getAuthorIdent();
+ response.committer = commit.getCommitterIdent();
+ response.commitMessage = commit.getFullMessage();
+
+ return response;
+ }
+
+ @Api(order=90, description="Get children of specified directory")
+ @Path("/{projectId}/directories/{revisionAndDirectory:.*}")
+ @GET
+ public List<DirectoryChild> getDirectory(
+ @PathParam("projectId") Long projectId,
+ @PathParam("revisionAndDirectory") @NotEmpty @Api(example="some-branch-or-tag/path/to/directory") String revisionAndDirectory) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ List<String> revisionAndPathSegments = Splitter.on('/').splitToList(revisionAndDirectory);
+ BlobIdent blobIdent = new BlobIdent(project, revisionAndPathSegments);
+
+ if (!blobIdent.isTree()) {
+ throw new InvalidParamException("Specified path is not a directory: " + blobIdent.path);
+ }
+
+ ObjectId commitId = project.getRevCommit(blobIdent.revision, true);
+
+ List<DirectoryChild> children = new ArrayList<>();
+
+ Repository repository = project.getRepository();
+ try (RevWalk revWalk = new RevWalk(repository)) {
+ RevTree revTree = revWalk.parseCommit(commitId).getTree();
+ TreeWalk treeWalk;
+ if (blobIdent.path != null) {
+ treeWalk = Preconditions.checkNotNull(TreeWalk.forPath(repository, blobIdent.path, revTree));
+ treeWalk.enterSubtree();
+ } else {
+ treeWalk = new TreeWalk(repository);
+ treeWalk.addTree(revTree);
+ }
+ while (treeWalk.next()) {
+ DirectoryChild child = new DirectoryChild();
+ child.path = treeWalk.getPathString();
+ child.isFile = (FileMode.TYPE_MASK & treeWalk.getRawMode(0)) == FileMode.TYPE_FILE;
+ children.add(child);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ return children;
+ }
+
+ @Api(order=100, description="Get metadata and content of specified file")
+ @Path("/{projectId}/files/{revisionAndFile:.*}")
+ @GET
+ public FileResponse getFile(
+ @PathParam("projectId") Long projectId,
+ @PathParam("revisionAndFile") @NotEmpty @Api(example="some-branch-or-tag/path/to/file") String revisionAndFile) {
+ Project project = projectManager.load(projectId);
+ if (!SecurityUtils.canReadCode(project)) {
+ throw new UnauthorizedException();
+ }
+
+ List<String> revisionAndPathSegments = Splitter.on('/').splitToList(revisionAndFile);
+ BlobIdent blobIdent = new BlobIdent(project, revisionAndPathSegments);
+
+ if (!blobIdent.isFile()) {
+ throw new InvalidParamException("Specified path is not a file: " + blobIdent.path);
+ }
+
+ Blob blob = project.getBlob(blobIdent, true);
+
+ FileResponse response = new FileResponse();
+ response.path = blobIdent.path;
+ response.sha = blob.getBlobId().name();
+ response.base64Content = new String(Base64.encodeBase64(blob.getBytes()));
+ response.size = blob.getSize();
+ response.isPartial = blob.isPartial();
+ return response;
+ }
+
+ @Api(order=110, description="Create, update, or delete specified file. Return hash of resulting commit",
+ example="46c001b04cba0ca41588841f1ca32f50b582ee9b")
+ @Path("/{projectId}/files/{branchAndFile:.*}")
+ @POST
+ public String editFile(
+ @PathParam("projectId") Long projectId,
+ @PathParam("branchAndFile") @NotEmpty @Api(example="test-branch/path/to/file") String branchAndFile,
+ @NotNull FileEditRequest request) {
+ Project project = projectManager.load(projectId);
+
+ List<String> revisionAndPathSegments = Splitter.on('/').splitToList(branchAndFile);
+ RevisionAndPath revisionAndPath = RevisionAndPath.parse(project, revisionAndPathSegments);
+
+ Ref ref = project.getBranchRef(revisionAndPath.getRevision());
+ if (ref == null)
+ throw new InvalidParamException("Not a branch: " + revisionAndPath.getRevision());
+
+ if (!SecurityUtils.canModify(project, revisionAndPath.getRevision(), revisionAndPath.getPath())) {
+ throw new UnauthorizedException();
+ }
+
+ ObjectId oldCommitId = ref.getObjectId();
+
+ Repository repository = project.getRepository();
+
+ Map<String, BlobContent> newBlobs = new HashMap<>();
+
+ Set<String> oldPaths = new HashSet<>();
+ RevCommit revCommit = project.getRevCommit(oldCommitId, true);
+ try (TreeWalk treeWalk = TreeWalk.forPath(project.getRepository(), revisionAndPath.getPath(), revCommit.getTree())) {
+ if (treeWalk != null) {
+ oldPaths.add(revisionAndPath.getPath());
+ }
+ } catch (IOException e) {
+ // ignore
+ }
+
+ if (request instanceof FileCreateOrUpdateRequest) {
+ newBlobs.put(revisionAndPath.getPath(), new BlobContent.Immutable(
+ Base64.decodeBase64(((FileCreateOrUpdateRequest)request).getBase64Content()),
+ FileMode.REGULAR_FILE
+ ));
+ }
+
+ ObjectId newCommitId = new BlobEdits(oldPaths, newBlobs)
+ .commit(
+ repository,
+ ref.getName(),
+ oldCommitId,
+ oldCommitId,
+ SecurityUtils.getUser().asPerson(),
+ request.getCommitMessage()
+ );
+
+ return newCommitId.name();
+ }
+
+ public static class RefResponse implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ String refName;
+
+ @Api(example="46c001b04cba0ca41588841f1ca32f50b582ee9b")
+ String commitHash;
+
+ }
+
+ public static class CreateBranchRequest implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String branchName;
+
+ @Api(example="46c001b04cba0ca41588841f1ca32f50b582ee9b")
+ private String revision;
+
+ @NotEmpty
+ public String getBranchName() {
+ return branchName;
+ }
+
+ public void setBranchName(String branchName) {
+ this.branchName = branchName;
+ }
+
+ @NotEmpty
+ public String getRevision() {
+ return revision;
+ }
+
+ public void setRevision(String revision) {
+ this.revision = revision;
+ }
+
+ }
+
+ public static class CreateTagRequest implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String tagName;
+
+ private String tagMessage;
+
+ @Api(example="46c001b04cba0ca41588841f1ca32f50b582ee9b")
+ private String revision;
+
+ @NotEmpty
+ public String getTagName() {
+ return tagName;
+ }
+
+ public void setTagName(String tagName) {
+ this.tagName = tagName;
+ }
+
+ public String getTagMessage() {
+ return tagMessage;
+ }
+
+ public void setTagMessage(String tagMessage) {
+ this.tagMessage = tagMessage;
+ }
+
+ @NotEmpty
+ public String getRevision() {
+ return revision;
+ }
+
+ public void setRevision(String revision) {
+ this.revision = revision;
+ }
+
+ }
+
+ public static class DirectoryChild implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ String path;
+
+ boolean isFile;
+
+ }
+
+ public static class FileResponse implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ String path;
+
+ @Api(example="46c001b04cba0ca41588841f1ca32f50b582ee9b")
+ String sha;
+
+ @Api(description="Base64 encoding of file content")
+ String base64Content;
+
+ long size;
+
+ @Api(description="True if the content is not fully loaded due to too large. "
+ + "The partial content can still be useful for instance to decide "
+ + "mime type of the file")
+ boolean isPartial;
+
+ }
+
+ public static class CommitResponse implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ String commitHash;
+
+ PersonIdent author;
+
+ PersonIdent committer;
+
+ String commitMessage;
+
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/RoleResource.java b/server-core/src/main/java/io/onedev/server/rest/RoleResource.java
index dc282edf63..2b13c3bd91 100644
--- a/server-core/src/main/java/io/onedev/server/rest/RoleResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/RoleResource.java
@@ -60,7 +60,7 @@ public class RoleResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<Role> criteria = EntityCriteria.of(Role.class);
if (name != null)
diff --git a/server-core/src/main/java/io/onedev/server/rest/UserResource.java b/server-core/src/main/java/io/onedev/server/rest/UserResource.java
index 5e3e4472b3..6dd5488e01 100644
--- a/server-core/src/main/java/io/onedev/server/rest/UserResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/UserResource.java
@@ -269,7 +269,7 @@ public class UserResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamException("Count should be less than " + RestConstants.MAX_PAGE_SIZE);
+ throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<User> criteria = EntityCriteria.of(User.class);
criteria.add(Restrictions.not(Restrictions.eq("id", User.SYSTEM_ID)));
diff --git a/server-core/src/main/java/io/onedev/server/rest/jersey/EntityNotFoundExceptionMapper.java b/server-core/src/main/java/io/onedev/server/rest/jersey/EntityNotFoundExceptionMapper.java
new file mode 100644
index 0000000000..c78d2b0ac3
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/jersey/EntityNotFoundExceptionMapper.java
@@ -0,0 +1,23 @@
+package io.onedev.server.rest.jersey;
+
+import javax.persistence.EntityNotFoundException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+@Provider
+public class EntityNotFoundExceptionMapper implements ExceptionMapper<EntityNotFoundException> {
+
+ @Override
+ public Response toResponse(EntityNotFoundException exception) {
+ ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND);
+ if (exception.getMessage() != null)
+ builder = builder.entity(exception.getMessage()).type("text/plain");
+ else
+ builder = builder.entity("Not found").type("text/plain");
+
+ return builder.build();
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/jersey/GitObjectNotFoundExceptionMapper.java b/server-core/src/main/java/io/onedev/server/rest/jersey/GitObjectNotFoundExceptionMapper.java
new file mode 100644
index 0000000000..75e1996ddc
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/jersey/GitObjectNotFoundExceptionMapper.java
@@ -0,0 +1,24 @@
+package io.onedev.server.rest.jersey;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+import io.onedev.server.git.exception.ObjectNotFoundException;
+
+@Provider
+public class GitObjectNotFoundExceptionMapper implements ExceptionMapper<ObjectNotFoundException> {
+
+ @Override
+ public Response toResponse(ObjectNotFoundException exception) {
+ ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND);
+ if (exception.getMessage() != null)
+ builder = builder.entity(exception.getMessage()).type("text/plain");
+ else
+ builder = builder.entity("Not found").type("text/plain");
+
+ return builder.build();
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/jersey/HibernateObjectNotFoundExceptionMapper.java b/server-core/src/main/java/io/onedev/server/rest/jersey/HibernateObjectNotFoundExceptionMapper.java
new file mode 100644
index 0000000000..abfbe8c04f
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/jersey/HibernateObjectNotFoundExceptionMapper.java
@@ -0,0 +1,24 @@
+package io.onedev.server.rest.jersey;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+import org.hibernate.ObjectNotFoundException;
+
+@Provider
+public class HibernateObjectNotFoundExceptionMapper implements ExceptionMapper<ObjectNotFoundException> {
+
+ @Override
+ public Response toResponse(ObjectNotFoundException exception) {
+ ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND);
+ if (exception.getMessage() != null)
+ builder = builder.entity(exception.getMessage()).type("text/plain");
+ else
+ builder = builder.entity("Not found").type("text/plain");
+
+ return builder.build();
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/support/FileCreateOrUpdateRequest.java b/server-core/src/main/java/io/onedev/server/rest/support/FileCreateOrUpdateRequest.java
new file mode 100644
index 0000000000..1b2b4b7e6d
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/support/FileCreateOrUpdateRequest.java
@@ -0,0 +1,20 @@
+package io.onedev.server.rest.support;
+
+import io.onedev.server.rest.annotation.Api;
+
+public class FileCreateOrUpdateRequest extends FileEditRequest {
+
+ private static final long serialVersionUID = 1L;
+
+ @Api(description="Base64 encoding of created/updated file content")
+ private String base64Content;
+
+ public String getBase64Content() {
+ return base64Content;
+ }
+
+ public void setBase64Content(String base64Content) {
+ this.base64Content = base64Content;
+ }
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/rest/support/FileDeleteRequest.java b/server-core/src/main/java/io/onedev/server/rest/support/FileDeleteRequest.java
new file mode 100644
index 0000000000..1c3a0f1258
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/support/FileDeleteRequest.java
@@ -0,0 +1,7 @@
+package io.onedev.server.rest.support;
+
+public class FileDeleteRequest extends FileEditRequest {
+
+ private static final long serialVersionUID = 1L;
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/rest/support/FileEditRequest.java b/server-core/src/main/java/io/onedev/server/rest/support/FileEditRequest.java
new file mode 100644
index 0000000000..382b975a92
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/support/FileEditRequest.java
@@ -0,0 +1,22 @@
+package io.onedev.server.rest.support;
+
+import java.io.Serializable;
+
+import org.hibernate.validator.constraints.NotEmpty;
+
+public abstract class FileEditRequest implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String commitMessage;
+
+ @NotEmpty
+ public String getCommitMessage() {
+ return commitMessage;
+ }
+
+ public void setCommitMessage(String commitMessage) {
+ this.commitMessage = commitMessage;
+ }
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
index 7df8ca2c98..493756a611 100644
--- a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
+++ b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
@@ -107,6 +107,13 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
return false;
}
+ public static boolean canDeleteTag(Project project, String tagName) {
+ if (canWriteCode(project))
+ return !project.getTagProtection(tagName, getUser()).isPreventDeletion();
+ else
+ return false;
+ }
+
public static boolean canCreateTag(Project project, String tagName) {
if (canWriteCode(project))
return !project.getTagProtection(tagName, getUser()).isPreventCreation();
diff --git a/server-core/src/main/java/io/onedev/server/util/RevisionAndPath.java b/server-core/src/main/java/io/onedev/server/util/RevisionAndPath.java
new file mode 100644
index 0000000000..0fd575f493
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/util/RevisionAndPath.java
@@ -0,0 +1,64 @@
+package io.onedev.server.util;
+
+import java.io.Serializable;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import io.onedev.server.git.exception.ObjectNotFoundException;
+import io.onedev.server.model.Project;
+
+public class RevisionAndPath implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String revision;
+
+ private final String path;
+
+ public RevisionAndPath(String revision, @Nullable String path) {
+ this.revision = revision;
+ this.path = path;
+ }
+
+ public static RevisionAndPath parse(Project project, List<String> segments) {
+ String revision = null;
+ String path = null;
+
+ StringBuilder revisionBuilder = new StringBuilder();
+ for (int i=0; i<segments.size(); i++) {
+ if (i != 0)
+ revisionBuilder.append("/");
+ revisionBuilder.append(segments.get(i));
+ if (project.getObjectId(revisionBuilder.toString(), false) != null) {
+ revision = revisionBuilder.toString();
+ StringBuilder pathBuilder = new StringBuilder();
+ for (int j=i+1; j<segments.size(); j++) {
+ if (j != i+1)
+ pathBuilder.append("/");
+ pathBuilder.append(segments.get(j));
+ }
+ if (pathBuilder.length() != 0) {
+ path = pathBuilder.toString();
+ }
+ return new RevisionAndPath(revision, path);
+ }
+ }
+ if (revisionBuilder.length() != 0) {
+ throw new ObjectNotFoundException("Revision not found: " + revisionBuilder.toString());
+ } else {
+ revision = project.getDefaultBranch();
+ return new RevisionAndPath(revision, path);
+ }
+ }
+
+ public String getRevision() {
+ return revision;
+ }
+
+ @Nullable
+ public String getPath() {
+ return path;
+ }
+
+}