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.InaccessibleObjectException;
63  import java.lang.reflect.InvocationTargetException;
64  import java.lang.reflect.Method;
65  import java.nio.file.Files;
66  import java.nio.file.Path;
67  import java.nio.file.Paths;
68  import java.util.Collections;
69  
70  import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
71  import org.eclipse.jgit.lib.Constants;
72  import org.eclipse.jgit.lib.IndexDiff;
73  import org.eclipse.jgit.lib.Repository;
74  import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
75  import org.eclipse.jgit.treewalk.FileTreeIterator;
76  import org.eclipse.jgit.treewalk.WorkingTreeIterator;
77  import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
78  import org.eclipse.jgit.util.FS;
79  import org.eclipse.jgit.util.SystemReader;
80  import org.junit.Before;
81  import org.junit.Test;
82  
83  /**
84   * MacOS-only test for dealing with symlinks in IndexDiff. Recreates using cgit
85   * a test repository prepared with git 2.2.1 on MacOS 10.7.5 containing some
86   * symlinks. Examines a symlink pointing to a file named "äéü.txt" (should be
87   * encoded as UTF-8 NFC), changes it through Java, examines it again to verify
88   * it's been changed to UTF-8 NFD, and finally calculates an IndexDiff.
89   */
90  public class IndexDiffWithSymlinkTest extends LocalDiskRepositoryTestCase {
91  
92  	private static final String FILEREPO = "filerepo";
93  
94  	private static final String TESTFOLDER = "testfolder";
95  
96  	private static final String TESTTARGET = "äéü.txt";
97  
98  	private static final String TESTLINK = "aeu.txt";
99  
100 	private static final byte[] NFC = // "äéü.txt" in NFC
101 	{ -61, -92, -61, -87, -61, -68, 46, 116, 120, 116 };
102 
103 	private static final byte[] NFD = // "äéü.txt" in NFD
104 	{ 97, -52, -120, 101, -52, -127, 117, -52, -120, 46, 116, 120, 116 };
105 
106 	private File testRepoDir;
107 
108 	@Override
109 	@Before
110 	public void setUp() throws Exception {
111 		assumeTrue(SystemReader.getInstance().isMacOS()
112 				&& FS.DETECTED.supportsSymlinks());
113 		super.setUp();
114 		File testDir = createTempDirectory(this.getClass().getSimpleName());
115 		try (InputStream in = this.getClass().getClassLoader()
116 				.getResourceAsStream(
117 				this.getClass().getPackage().getName().replace('.', '/') + '/'
118 								+ FILEREPO + ".txt")) {
119 			assertNotNull("Test repo file not found", in);
120 			testRepoDir = restoreGitRepo(in, testDir, FILEREPO);
121 		}
122 	}
123 
124 	private File restoreGitRepo(InputStream in, File testDir, String name)
125 			throws Exception {
126 		File exportedTestRepo = new File(testDir, name + ".txt");
127 		copy(in, exportedTestRepo);
128 		// Use CGit to restore
129 		File restoreScript = new File(testDir, name + ".sh");
130 		try (OutputStream out = new BufferedOutputStream(
131 				new FileOutputStream(restoreScript));
132 				Writer writer = new OutputStreamWriter(out, UTF_8)) {
133 			writer.write("echo `which git` 1>&2\n");
134 			writer.write("echo `git --version` 1>&2\n");
135 			writer.write("git init " + name + " && \\\n");
136 			writer.write("cd ./" + name + " && \\\n");
137 			writer.write("git fast-import < ../" + name + ".txt && \\\n");
138 			writer.write("git checkout -f\n");
139 		}
140 		String[] cmd = { "/bin/sh", "./" + name + ".sh" };
141 		int exitCode;
142 		String stdErr;
143 		ProcessBuilder builder = new ProcessBuilder(cmd);
144 		builder.environment().put("HOME",
145 				FS.DETECTED.userHome().getAbsolutePath());
146 		builder.directory(testDir);
147 		Process process = builder.start();
148 		try (InputStream stdOutStream = process.getInputStream();
149 				InputStream stdErrStream = process.getErrorStream();
150 				OutputStream stdInStream = process.getOutputStream()) {
151 			readStream(stdOutStream);
152 			stdErr = readStream(stdErrStream);
153 			process.waitFor();
154 			exitCode = process.exitValue();
155 		}
156 		if (exitCode != 0) {
157 			fail("cgit repo restore returned " + exitCode + '\n' + stdErr);
158 		}
159 		return new File(new File(testDir, name), Constants.DOT_GIT);
160 	}
161 
162 	private void copy(InputStream from, File to) throws IOException {
163 		try (OutputStream out = new FileOutputStream(to)) {
164 			byte[] buffer = new byte[4096];
165 			int n;
166 			while ((n = from.read(buffer)) > 0) {
167 				out.write(buffer, 0, n);
168 			}
169 		}
170 	}
171 
172 	private String readStream(InputStream stream) throws IOException {
173 		try (BufferedReader in = new BufferedReader(
174 				new InputStreamReader(stream, UTF_8))) {
175 			StringBuilder out = new StringBuilder();
176 			String line;
177 			while ((line = in.readLine()) != null) {
178 				out.append(line).append('\n');
179 			}
180 			return out.toString();
181 		}
182 	}
183 
184 	@Test
185 	public void testSymlinkWithEncodingDifference() throws Exception {
186 		try (Repository testRepo = FileRepositoryBuilder.create(testRepoDir)) {
187 			File workingTree = testRepo.getWorkTree();
188 			File symLink = new File(new File(workingTree, TESTFOLDER),
189 					TESTLINK);
190 			// Read the symlink as it was created by cgit
191 			Path linkTarget = Files.readSymbolicLink(symLink.toPath());
192 			assertEquals("Unexpected link target", TESTTARGET,
193 					linkTarget.toString());
194 			byte[] raw = rawPath(linkTarget);
195 			if (raw != null) {
196 				assertArrayEquals("Expected an NFC link target", NFC, raw);
197 			}
198 			// Now re-create that symlink through Java
199 			assertTrue("Could not delete symlink", symLink.delete());
200 			Files.createSymbolicLink(symLink.toPath(), Paths.get(TESTTARGET));
201 			// Read it again
202 			linkTarget = Files.readSymbolicLink(symLink.toPath());
203 			assertEquals("Unexpected link target", TESTTARGET,
204 					linkTarget.toString());
205 			raw = rawPath(linkTarget);
206 			if (raw != null) {
207 				assertArrayEquals("Expected an NFD link target", NFD, raw);
208 			}
209 			// Do the indexdiff
210 			WorkingTreeIterator iterator = new FileTreeIterator(testRepo);
211 			IndexDiff diff = new IndexDiff(testRepo, Constants.HEAD, iterator);
212 			diff.setFilter(PathFilterGroup.createFromStrings(
213 					Collections.singleton(TESTFOLDER + '/' + TESTLINK)));
214 			diff.diff();
215 			// We're testing that this does NOT throw "EOFException: Short read
216 			// of block." The diff will not report any modified files -- the
217 			// link modification is not visible to JGit, which always works with
218 			// the Java internal NFC encoding. CGit does report the link as an
219 			// unstaged modification here, though.
220 		}
221 	}
222 
223 	private byte[] rawPath(Path p) {
224 		try {
225 			Method method = p.getClass().getDeclaredMethod("asByteArray");
226 			if (method != null) {
227 				method.setAccessible(true);
228 				return (byte[]) method.invoke(p);
229 			}
230 		} catch (NoSuchMethodException | IllegalAccessException
231 				| IllegalArgumentException | InvocationTargetException
232 				| InaccessibleObjectException e) {
233 			// Ignore and fall through.
234 		}
235 		return null;
236 	}
237 }