You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FS.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.util;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.io.InputStreamReader;
  49. import java.security.AccessController;
  50. import java.security.PrivilegedAction;
  51. import java.util.Arrays;
  52. import java.util.concurrent.atomic.AtomicBoolean;
  53. /** Abstraction to support various file system operations not in Java. */
  54. public abstract class FS {
  55. /** The auto-detected implementation selected for this operating system and JRE. */
  56. public static final FS DETECTED = detect();
  57. /**
  58. * Auto-detect the appropriate file system abstraction.
  59. *
  60. * @return detected file system abstraction
  61. */
  62. public static FS detect() {
  63. return detect(null);
  64. }
  65. /**
  66. * Auto-detect the appropriate file system abstraction, taking into account
  67. * the presence of a Cygwin installation on the system. Using jgit in
  68. * combination with Cygwin requires a more elaborate (and possibly slower)
  69. * resolution of file system paths.
  70. *
  71. * @param cygwinUsed
  72. * <ul>
  73. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  74. * combination with jgit</li>
  75. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  76. * <b>not</b> used with jgit</li>
  77. * <li><code>null</code> to auto-detect whether a Cygwin
  78. * installation is present on the system and in this case assume
  79. * that Cygwin is used</li>
  80. * </ul>
  81. *
  82. * Note: this parameter is only relevant on Windows.
  83. *
  84. * @return detected file system abstraction
  85. */
  86. public static FS detect(Boolean cygwinUsed) {
  87. if (FS_Win32.isWin32()) {
  88. if (cygwinUsed == null)
  89. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  90. if (cygwinUsed.booleanValue())
  91. return new FS_Win32_Cygwin();
  92. else
  93. return new FS_Win32();
  94. } else if (FS_POSIX_Java6.hasExecute())
  95. return new FS_POSIX_Java6();
  96. else
  97. return new FS_POSIX_Java5();
  98. }
  99. private volatile Holder<File> userHome;
  100. private volatile Holder<File> gitPrefix;
  101. /**
  102. * Constructs a file system abstraction.
  103. */
  104. protected FS() {
  105. // Do nothing by default.
  106. }
  107. /**
  108. * Initialize this FS using another's current settings.
  109. *
  110. * @param src
  111. * the source FS to copy from.
  112. */
  113. protected FS(FS src) {
  114. userHome = src.userHome;
  115. gitPrefix = src.gitPrefix;
  116. }
  117. /** @return a new instance of the same type of FS. */
  118. public abstract FS newInstance();
  119. /**
  120. * Does this operating system and JRE support the execute flag on files?
  121. *
  122. * @return true if this implementation can provide reasonably accurate
  123. * executable bit information; false otherwise.
  124. */
  125. public abstract boolean supportsExecute();
  126. /**
  127. * Determine if the file is executable (or not).
  128. * <p>
  129. * Not all platforms and JREs support executable flags on files. If the
  130. * feature is unsupported this method will always return false.
  131. *
  132. * @param f
  133. * abstract path to test.
  134. * @return true if the file is believed to be executable by the user.
  135. */
  136. public abstract boolean canExecute(File f);
  137. /**
  138. * Set a file to be executable by the user.
  139. * <p>
  140. * Not all platforms and JREs support executable flags on files. If the
  141. * feature is unsupported this method will always return false and no
  142. * changes will be made to the file specified.
  143. *
  144. * @param f
  145. * path to modify the executable status of.
  146. * @param canExec
  147. * true to enable execution; false to disable it.
  148. * @return true if the change succeeded; false otherwise.
  149. */
  150. public abstract boolean setExecute(File f, boolean canExec);
  151. /**
  152. * Resolve this file to its actual path name that the JRE can use.
  153. * <p>
  154. * This method can be relatively expensive. Computing a translation may
  155. * require forking an external process per path name translated. Callers
  156. * should try to minimize the number of translations necessary by caching
  157. * the results.
  158. * <p>
  159. * Not all platforms and JREs require path name translation. Currently only
  160. * Cygwin on Win32 require translation for Cygwin based paths.
  161. *
  162. * @param dir
  163. * directory relative to which the path name is.
  164. * @param name
  165. * path name to translate.
  166. * @return the translated path. <code>new File(dir,name)</code> if this
  167. * platform does not require path name translation.
  168. */
  169. public File resolve(final File dir, final String name) {
  170. final File abspn = new File(name);
  171. if (abspn.isAbsolute())
  172. return abspn;
  173. return new File(dir, name);
  174. }
  175. /**
  176. * Determine the user's home directory (location where preferences are).
  177. * <p>
  178. * This method can be expensive on the first invocation if path name
  179. * translation is required. Subsequent invocations return a cached result.
  180. * <p>
  181. * Not all platforms and JREs require path name translation. Currently only
  182. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  183. *
  184. * @return the user's home directory; null if the user does not have one.
  185. */
  186. public File userHome() {
  187. Holder<File> p = userHome;
  188. if (p == null) {
  189. p = new Holder<File>(userHomeImpl());
  190. userHome = p;
  191. }
  192. return p.value;
  193. }
  194. /**
  195. * Set the user's home directory location.
  196. *
  197. * @param path
  198. * the location of the user's preferences; null if there is no
  199. * home directory for the current user.
  200. * @return {@code this}.
  201. */
  202. public FS setUserHome(File path) {
  203. userHome = new Holder<File>(path);
  204. return this;
  205. }
  206. /**
  207. * Does this file system have problems with atomic renames?
  208. *
  209. * @return true if the caller should retry a failed rename of a lock file.
  210. */
  211. public abstract boolean retryFailedLockFileCommit();
  212. /**
  213. * Determine the user's home directory (location where preferences are).
  214. *
  215. * @return the user's home directory; null if the user does not have one.
  216. */
  217. protected File userHomeImpl() {
  218. final String home = AccessController
  219. .doPrivileged(new PrivilegedAction<String>() {
  220. public String run() {
  221. return System.getProperty("user.home");
  222. }
  223. });
  224. if (home == null || home.length() == 0)
  225. return null;
  226. return new File(home).getAbsoluteFile();
  227. }
  228. /**
  229. * Searches the given path to see if it contains one of the given files.
  230. * Returns the first it finds. Returns null if not found or if path is null.
  231. *
  232. * @param path
  233. * List of paths to search separated by File.pathSeparator
  234. * @param lookFor
  235. * Files to search for in the given path
  236. * @return the first match found, or null
  237. **/
  238. static File searchPath(final String path, final String... lookFor) {
  239. if (path == null)
  240. return null;
  241. for (final String p : path.split(File.pathSeparator)) {
  242. for (String command : lookFor) {
  243. final File e = new File(p, command);
  244. if (e.isFile())
  245. return e.getAbsoluteFile();
  246. }
  247. }
  248. return null;
  249. }
  250. /**
  251. * Execute a command and return a single line of output as a String
  252. *
  253. * @param dir
  254. * Working directory for the command
  255. * @param command
  256. * as component array
  257. * @param encoding
  258. * @return the one-line output of the command
  259. */
  260. protected static String readPipe(File dir, String[] command, String encoding) {
  261. final boolean debug = Boolean.parseBoolean(SystemReader.getInstance()
  262. .getProperty("jgit.fs.debug"));
  263. try {
  264. if (debug)
  265. System.err.println("readpipe " + Arrays.asList(command) + ","
  266. + dir);
  267. final Process p = Runtime.getRuntime().exec(command, null, dir);
  268. final BufferedReader lineRead = new BufferedReader(
  269. new InputStreamReader(p.getInputStream(), encoding));
  270. p.getOutputStream().close();
  271. final AtomicBoolean gooblerFail = new AtomicBoolean(false);
  272. Thread gobbler = new Thread() {
  273. public void run() {
  274. InputStream is = p.getErrorStream();
  275. try {
  276. int ch;
  277. if (debug)
  278. while ((ch = is.read()) != -1)
  279. System.err.print((char) ch);
  280. else
  281. while (is.read() != -1) {
  282. // ignore
  283. }
  284. } catch (IOException e) {
  285. // Just print on stderr for debugging
  286. if (debug)
  287. e.printStackTrace(System.err);
  288. gooblerFail.set(true);
  289. }
  290. try {
  291. is.close();
  292. } catch (IOException e) {
  293. // Just print on stderr for debugging
  294. if (debug)
  295. e.printStackTrace(System.err);
  296. gooblerFail.set(true);
  297. }
  298. }
  299. };
  300. gobbler.start();
  301. String r = null;
  302. try {
  303. r = lineRead.readLine();
  304. if (debug) {
  305. System.err.println("readpipe may return '" + r + "'");
  306. System.err.println("(ignoring remaing output:");
  307. }
  308. String l;
  309. while ((l = lineRead.readLine()) != null) {
  310. if (debug)
  311. System.err.println(l);
  312. }
  313. } finally {
  314. p.getErrorStream().close();
  315. lineRead.close();
  316. }
  317. for (;;) {
  318. try {
  319. int rc = p.waitFor();
  320. gobbler.join();
  321. if (rc == 0 && r != null && r.length() > 0
  322. && !gooblerFail.get())
  323. return r;
  324. if (debug)
  325. System.err.println("readpipe rc=" + rc);
  326. break;
  327. } catch (InterruptedException ie) {
  328. // Stop bothering me, I have a zombie to reap.
  329. }
  330. }
  331. } catch (IOException e) {
  332. if (debug)
  333. System.err.println(e);
  334. // Ignore error (but report)
  335. }
  336. if (debug)
  337. System.err.println("readpipe returns null");
  338. return null;
  339. }
  340. /** @return the $prefix directory C Git would use. */
  341. public File gitPrefix() {
  342. Holder<File> p = gitPrefix;
  343. if (p == null) {
  344. String overrideGitPrefix = SystemReader.getInstance().getProperty(
  345. "jgit.gitprefix");
  346. if (overrideGitPrefix != null)
  347. p = new Holder<File>(new File(overrideGitPrefix));
  348. else
  349. p = new Holder<File>(discoverGitPrefix());
  350. gitPrefix = p;
  351. }
  352. return p.value;
  353. }
  354. /** @return the $prefix directory C Git would use. */
  355. protected abstract File discoverGitPrefix();
  356. /**
  357. * Set the $prefix directory C Git uses.
  358. *
  359. * @param path
  360. * the directory. Null if C Git is not installed.
  361. * @return {@code this}
  362. */
  363. public FS setGitPrefix(File path) {
  364. gitPrefix = new Holder<File>(path);
  365. return this;
  366. }
  367. /**
  368. * Initialize a ProcesssBuilder to run a command using the system shell.
  369. *
  370. * @param cmd
  371. * command to execute. This string should originate from the
  372. * end-user, and thus is platform specific.
  373. * @param args
  374. * arguments to pass to command. These should be protected from
  375. * shell evaluation.
  376. * @return a partially completed process builder. Caller should finish
  377. * populating directory, environment, and then start the process.
  378. */
  379. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  380. private static class Holder<V> {
  381. final V value;
  382. Holder(V value) {
  383. this.value = value;
  384. }
  385. }
  386. }