View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.scm.provider.git;
20  
21  import java.io.File;
22  import java.io.FileWriter;
23  import java.io.IOException;
24  import java.util.function.Consumer;
25  
26  import org.apache.maven.scm.PlexusJUnit4TestCase;
27  import org.codehaus.plexus.util.FileUtils;
28  import org.codehaus.plexus.util.cli.CommandLineException;
29  import org.junit.Assert;
30  
31  /**
32   * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a>
33   */
34  public final class GitScmTestUtils {
35      /** 'git' command line. */
36      public static final String GIT_COMMAND_LINE = "git";
37  
38      private GitScmTestUtils() {}
39  
40      public static void initRepo(File repository, File workingDirectory, File assertionDirectory) throws IOException {
41          initRepo("src/test/repository/", repository, workingDirectory);
42  
43          FileUtils.deleteDirectory(assertionDirectory);
44  
45          Assert.assertTrue(assertionDirectory.mkdirs());
46      }
47  
48      public static void initRepo(String source, File repository, File workingDirectory) throws IOException {
49          // Copy the repository to target
50          File src = PlexusJUnit4TestCase.getTestFile(source);
51  
52          FileUtils.deleteDirectory(repository);
53  
54          Assert.assertTrue(repository.mkdirs());
55  
56          FileUtils.copyDirectoryStructure(src, repository);
57  
58          File dotGitDirectory = new File(src, "dotgit");
59  
60          if (dotGitDirectory.exists()) {
61              FileUtils.copyDirectoryStructure(dotGitDirectory, new File(repository, ".git"));
62          }
63  
64          FileUtils.deleteDirectory(workingDirectory);
65  
66          Assert.assertTrue(workingDirectory.mkdirs());
67      }
68  
69      public static String getScmUrl(File repositoryRootFile, String provider) throws CommandLineException {
70          return "scm:" + provider + ":"
71                  + repositoryRootFile.toPath().toAbsolutePath().toUri().toASCIIString();
72      }
73  
74      public static void deleteAllDirectories(File startDirectory, String pattern) throws IOException {
75          if (startDirectory.isDirectory()) {
76              File[] childs = startDirectory.listFiles();
77              for (int i = 0; i < childs.length; i++) {
78                  File child = childs[i];
79                  if (child.isDirectory()) {
80                      if (child.getName().equals(pattern)) {
81                          FileUtils.deleteDirectory(child);
82                      } else {
83                          deleteAllDirectories(child, pattern);
84                      }
85                  }
86              }
87          }
88      }
89  
90      public static void setDefaultGitConfig(File repositoryRootFile) throws IOException {
91          setDefaultGitConfig(repositoryRootFile, null);
92      }
93  
94      public static void setDefaultGitConfig(File repositoryRootFile, Consumer<FileWriter> configWriterCustomizer)
95              throws IOException {
96          File gitConfigFile = new File(new File(repositoryRootFile, ".git"), "config");
97  
98          try (FileWriter fw = new FileWriter(gitConfigFile, true)) {
99              fw.append("[user]\n");
100             fw.append("\tname = John Doe\n");
101             fw.append("\temail = john.doe@nowhere.com\n");
102             fw.append("[commit]\n");
103             // disable gpg signing for commits and tags by default
104             fw.append("\tgpgsign = false\n");
105             fw.append("[tag]\n");
106             fw.append("\tgpgsign = false\n");
107             if (configWriterCustomizer != null) {
108                 configWriterCustomizer.accept(fw);
109             }
110         }
111     }
112 
113     /**
114      * Sets up a pre-receive git hook that rejects all commits for the given repository (server-side).
115      * This is useful for testing scenarios where you want to simulate a repository
116      * that doesn't allow any new commits.
117      * This hook is <a href="https://github.com/eclipse-jgit/jgit/issues/192">not supported by JGit</a>.
118      *
119      * @param repositoryRootFile the root directory of the git repository
120      * @throws IOException if there's an error creating or writing the hook file
121      */
122     public static void setupRejectAllCommitsPreReceiveHook(File repositoryRootFile) throws IOException {
123         setupRejectAllCommitsHook(repositoryRootFile, true, "pre-receive");
124     }
125 
126     /**
127      * Sets up a pre-push git hook that rejects all commits for the given repository (client-side).
128      * This is useful for testing scenarios where you want to simulate a repository
129      * that doesn't allow any new commits.
130      *
131      * @param workspaceRoot the root directory of the git working copy
132      * @throws IOException if there's an error creating or writing the hook file
133      */
134     public static void setupRejectAllCommitsPrePushHook(File workspaceRoot) throws IOException {
135         setupRejectAllCommitsHook(workspaceRoot, false, "pre-push");
136     }
137 
138     public static void setupRejectAllCommitsPreCommitHook(File workspaceRoot) throws IOException {
139         setupRejectAllCommitsHook(workspaceRoot, false, "pre-commit");
140     }
141 
142     private static void setupRejectAllCommitsHook(
143             File repositoryOrWorkspaceRootFile, boolean isServerSide, String hookName) throws IOException {
144         File hooksDir;
145         if (!isServerSide) {
146             // For client-side hooks, we use the .git/hooks directory
147             hooksDir = new File(repositoryOrWorkspaceRootFile, ".git/hooks");
148         } else {
149             // For server-side hooks, we use the hooks directory directly
150             hooksDir = new File(repositoryOrWorkspaceRootFile, "hooks");
151         }
152         if (!hooksDir.exists() && !hooksDir.mkdirs()) {
153             throw new IOException("Failed to create hooks directory: " + hooksDir.getAbsolutePath());
154         }
155 
156         File preReceiveHook = new File(hooksDir, hookName);
157         try (FileWriter fw = new FileWriter(preReceiveHook)) {
158             fw.write("#!/bin/sh\n");
159             fw.write("# Pre-receive hook that rejects all commits\n");
160             fw.write("echo \"Error: This repository is configured to reject all commits\"\n");
161             fw.write("exit 1\n");
162         }
163 
164         // Make the hook executable (on Unix-like systems)
165         if (!preReceiveHook.setExecutable(true)) {
166             throw new IOException("Could not make pre-receive hook executable at: " + preReceiveHook.getAbsolutePath());
167         }
168     }
169 }