Redirect gitiles url using Repo's branch redirect config when format type is default (not provided in gitiles url). PiperOrigin-RevId: 355896835 Change-Id: Ia6d0bb48ba1f5b3ff7176de5b1c0dab0b662562d
diff --git a/java/com/google/gitiles/BranchRedirectFilter.java b/java/com/google/gitiles/BranchRedirectFilter.java index 48ff35b..12dc2b4 100644 --- a/java/com/google/gitiles/BranchRedirectFilter.java +++ b/java/com/google/gitiles/BranchRedirectFilter.java
@@ -107,6 +107,15 @@ } private static boolean isForAutomation(HttpServletRequest req) { - return !FormatType.getFormatType(req).orElse(HTML).equals(HTML); + FormatType formatType = FormatType.getFormatType(req).orElse(HTML); + switch (formatType) { + case HTML: + case DEFAULT: + return false; + case JSON: + case TEXT: + default: + return true; + } } }
diff --git a/javatests/com/google/gitiles/BranchRedirectFilterTest.java b/javatests/com/google/gitiles/BranchRedirectFilterTest.java index c994038..fbf0ff4 100644 --- a/javatests/com/google/gitiles/BranchRedirectFilterTest.java +++ b/javatests/com/google/gitiles/BranchRedirectFilterTest.java
@@ -19,8 +19,10 @@ import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY; import static javax.servlet.http.HttpServletResponse.SC_OK; +import com.google.common.base.Strings; import com.google.common.net.HttpHeaders; import java.util.Optional; +import javax.annotation.Nullable; import org.eclipse.jgit.internal.storage.dfs.DfsRepository; import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription; import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository; @@ -94,6 +96,19 @@ } @Test + public void show_withRedirect_onDefaultFormatType() throws Exception { + repo.branch(MASTER).commit().add("foo", "contents").create(); + + String path = "/repo/+/refs/heads/master/foo"; + FakeHttpServletRequest req = newHttpRequest(path, ORIGIN, null); + FakeHttpServletResponse res = new FakeHttpServletResponse(); + + servlet.service(req, res); + assertThat(res.getStatus()).isEqualTo(SC_MOVED_PERMANENTLY); + assertThat(res.getHeader(HttpHeaders.LOCATION)).isEqualTo("/b/repo/+/refs/heads/main/foo"); + } + + @Test public void show_onAutomationRequest() throws Exception { repo.branch(MASTER).commit().add("foo", "contents").create(); @@ -235,11 +250,13 @@ } private static FakeHttpServletRequest newHttpRequest( - String path, String origin, String queryString) { + String path, String origin, @Nullable String queryString) { FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setHeader(HttpHeaders.ORIGIN, origin); req.setPathInfo(path); - req.setQueryString(queryString); + if (!Strings.isNullOrEmpty(queryString)) { + req.setQueryString(queryString); + } return req; } }