View Javadoc
1   /*
2    * Copyright (C) 2015 Thomas Wolf <thomas.wolf@paranor.ch>
3    *
4    * This program and the accompanying materials are made available
5    * under the terms of the Eclipse Distribution License v1.0 which
6    * accompanies this distribution, is reproduced below, and is
7    * available at http://www.eclipse.org/org/documents/edl-v10.php
8    *
9    * All rights reserved.
10   *
11   * Redistribution and use in source and binary forms, with or
12   * without modification, are permitted provided that the following
13   * conditions are met:
14   *
15   * - Redistributions of source code must retain the above copyright
16   *   notice, this list of conditions and the following disclaimer.
17   *
18   * - Redistributions in binary form must reproduce the above
19   *   copyright notice, this list of conditions and the following
20   *   disclaimer in the documentation and/or other materials provided
21   *   with the distribution.
22   *
23   * - Neither the name of the Eclipse Foundation, Inc. nor the
24   *   names of its contributors may be used to endorse or promote
25   *   products derived from this software without specific prior
26   *   written permission.
27   *
28   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
30   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
33   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
36   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
37   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
40   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41   */
42  package org.eclipse.jgit.indexdiff;
43  
44  import static java.nio.charset.StandardCharsets.UTF_8;
45  import static org.junit.Assert.assertArrayEquals;
46  import static org.junit.Assert.assertEquals;
47  import static org.junit.Assert.assertNotNull;
48  import static org.junit.Assert.assertTrue;
49  import static org.junit.Assert.fail;
50  import static org.junit.Assume.assumeTrue;
51  
52  import java.io.BufferedOutputStream;
53  import java.io.BufferedReader;
54  import java.io.File;
55  import java.io.FileOutputStream;
56  import java.io.IOException;
57  import java.io.InputStream;
58  import java.io.InputStreamReader;
59  import java.io.OutputStream;
60  import java.io.OutputStreamWriter;
61  import java.io.Writer;
62  import java.lang.reflect.InvocationTargetException;
63  import java.lang.reflect.Method;
64  import java.nio.file.Files;
65  import java.nio.file.Path;
66  import java.nio.file.Paths;
67  import java.util.Collections;
68  
69  import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
70  import org.eclipse.jgit.lib.Constants;
71  import org.eclipse.jgit.lib.IndexDiff;
72  import org.eclipse.jgit.lib.Repository;
73  import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
74  import org.eclipse.jgit.treewalk.FileTreeIterator;
75  import org.eclipse.jgit.treewalk.WorkingTreeIterator;
76  import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
77  import org.eclipse.jgit.util.FS;
78  import org.eclipse.jgit.util.SystemReader;
79  import org.junit.Before;
80  import org.junit.Test;
81  
82  /**
83   * MacOS-only test for dealing with symlinks in IndexDiff. Recreates using cgit
84   * a test repository prepared with git 2.2.1 on MacOS 10.7.5 containing some
85   * symlinks. Examines a symlink pointing to a file named "äéü.txt" (should be
86   * encoded as UTF-8 NFC), changes it through Java, examines it again to verify
87   * it's been changed to UTF-8 NFD, and finally calculates an IndexDiff.
88   */
89  public class IndexDiffWithSymlinkTest extends LocalDiskRepositoryTestCase {
90  
91  	private static final String FILEREPO = "filerepo";
92  
93  	private static final String TESTFOLDER = "testfolder";
94  
95  	private static final String TESTTARGET = "äéü.txt";
96  
97  	private static final String TESTLINK = "aeu.txt";
98  
99  	private static final byte[] NFC = // "äéü.txt" in NFC
100 	{ -61, -92, -61, -87, -61, -68, 46, 116, 120, 116 };
101 
102 	private static final byte[] NFD = // "äéü.txt" in NFD
103 	{ 97, -52, -120, 101, -52, -127, 117, -52, -120, 46, 116, 120, 116 };
104 
105 	private File testRepoDir;
106 
107 	@Override
108 	@Before
109 	public void setUp() throws Exception {
110 		assumeTrue(SystemReader.getInstance().isMacOS()
111 				&& FS.DETECTED.supportsSymlinks());
112 		super.setUp();
113 		File testDir = createTempDirectory(this.getClass().getSimpleName());
114 		try (InputStream in = this.getClass().getClassLoader()
115 				.getResourceAsStream(
116 				this.getClass().getPackage().getName().replace('.', '/') + '/'
117 								+ FILEREPO + ".txt")) {
118 			assertNotNull("Test repo file not found", in);
119 			testRepoDir = restoreGitRepo(in, testDir, FILEREPO);
120 		}
121 	}
122 
123 	private File restoreGitRepo(InputStream in, File testDir, String name)
124 			throws Exception {
125 		File exportedTestRepo = new File(testDir, name + ".txt");
126 		copy(in, exportedTestRepo);
127 		// Use CGit to restore
128 		File restoreScript = new File(testDir, name + ".sh");
129 		try (OutputStream out = new BufferedOutputStream(
130 				new FileOutputStream(restoreScript));
131 				Writer writer = new OutputStreamWriter(out, UTF_8)) {
132 			writer.write("echo `which git` 1>&2\n");
133 			writer.write("echo `git --version` 1>&2\n");
134 			writer.write("git init " + name + " && \\\n");
135 			writer.write("cd ./" + name + " && \\\n");
136 			writer.write("git fast-import < ../" + name + ".txt && \\\n");
137 			writer.write("git checkout -f\n");
138 		}
139 		String[] cmd = { "/bin/sh", "./" + name + ".sh" };
140 		int exitCode;
141 		String stdErr;
142 		ProcessBuilder builder = new ProcessBuilder(cmd);
143 		builder.environment().put("HOME",
144 				FS.DETECTED.userHome().getAbsolutePath());
145 		builder.directory(testDir);
146 		Process process = builder.start();
147 		try (InputStream stdOutStream = process.getInputStream();
148 				InputStream stdErrStream = process.getErrorStream();
149 				OutputStream stdInStream = process.getOutputStream()) {
150 			readStream(stdOutStream);
151 			stdErr = readStream(stdErrStream);
152 			process.waitFor();
153 			exitCode = process.exitValue();
154 		}
155 		if (exitCode != 0) {
156 			fail("cgit repo restore returned " + exitCode + '\n' + stdErr);
157 		}
158 		return new File(new File(testDir, name), Constants.DOT_GIT);
159 	}
160 
161 	private void copy(InputStream from, File to) throws IOException {
162 		try (OutputStream out = new FileOutputStream(to)) {
163 			byte[] buffer = new byte[4096];
164 			int n;
165 			while ((n = from.read(buffer)) > 0) {
166 				out.write(buffer, 0, n);
167 			}
168 		}
169 	}
170 
171 	private String readStream(InputStream stream) throws IOException {
172 		try (BufferedReader in = new BufferedReader(
173 				new InputStreamReader(stream, UTF_8))) {
174 			StringBuilder out = new StringBuilder();
175 			String line;
176 			while ((line = in.readLine()) != null) {
177 				out.append(line).append('\n');
178 			}
179 			return out.toString();
180 		}
181 	}
182 
183 	@Test
184 	public void testSymlinkWithEncodingDifference() throws Exception {
185 		try (Repository testRepo = FileRepositoryBuilder.create(testRepoDir)) {
186 			File workingTree = testRepo.getWorkTree();
187 			File symLink = new File(new File(workingTree, TESTFOLDER),
188 					TESTLINK);
189 			// Read the symlink as it was created by cgit
190 			Path linkTarget = Files.readSymbolicLink(symLink.toPath());
191 			assertEquals("Unexpected link target", TESTTARGET,
192 					linkTarget.toString());
193 			byte[] raw = rawPath(linkTarget);
194 			if (raw != null) {
195 				assertArrayEquals("Expected an NFC link target", NFC, raw);
196 			}
197 			// Now re-create that symlink through Java
198 			assertTrue("Could not delete symlink", symLink.delete());
199 			Files.createSymbolicLink(symLink.toPath(), Paths.get(TESTTARGET));
200 			// Read it again
201 			linkTarget = Files.readSymbolicLink(symLink.toPath());
202 			assertEquals("Unexpected link target", TESTTARGET,
203 					linkTarget.toString());
204 			raw = rawPath(linkTarget);
205 			if (raw != null) {
206 				assertArrayEquals("Expected an NFD link target", NFD, raw);
207 			}
208 			// Do the indexdiff
209 			WorkingTreeIterator iterator = new FileTreeIterator(testRepo);
210 			IndexDiff diff = new IndexDiff(testRepo, Constants.HEAD, iterator);
211 			diff.setFilter(PathFilterGroup.createFromStrings(
212 					Collections.singleton(TESTFOLDER + '/' + TESTLINK)));
213 			diff.diff();
214 			// We're testing that this does NOT throw "EOFException: Short read
215 			// of block." The diff will not report any modified files -- the
216 			// link modification is not visible to JGit, which always works with
217 			// the Java internal NFC encoding. CGit does report the link as an
218 			// unstaged modification here, though.
219 		}
220 	}
221 
222 	private byte[] rawPath(Path p) {
223 		try {
224 			Method method = p.getClass().getDeclaredMethod("asByteArray");
225 			if (method != null) {
226 				method.setAccessible(true);
227 				return (byte[]) method.invoke(p);
228 			}
229 		} catch (NoSuchMethodException | IllegalAccessException
230 				| IllegalArgumentException | InvocationTargetException e) {
231 			// Ignore and fall through.
232 		}
233 		return null;
234 	}
235 }