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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146
  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 static java.nio.charset.StandardCharsets.UTF_8;
  45. import static java.time.Instant.EPOCH;
  46. import java.io.BufferedReader;
  47. import java.io.ByteArrayInputStream;
  48. import java.io.Closeable;
  49. import java.io.File;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.io.InputStreamReader;
  53. import java.io.OutputStream;
  54. import java.io.OutputStreamWriter;
  55. import java.io.PrintStream;
  56. import java.io.Writer;
  57. import java.nio.charset.Charset;
  58. import java.nio.file.AccessDeniedException;
  59. import java.nio.file.FileStore;
  60. import java.nio.file.Files;
  61. import java.nio.file.Path;
  62. import java.nio.file.attribute.BasicFileAttributes;
  63. import java.nio.file.attribute.FileTime;
  64. import java.security.AccessController;
  65. import java.security.PrivilegedAction;
  66. import java.text.MessageFormat;
  67. import java.time.Duration;
  68. import java.time.Instant;
  69. import java.util.ArrayList;
  70. import java.util.Arrays;
  71. import java.util.HashMap;
  72. import java.util.Map;
  73. import java.util.Objects;
  74. import java.util.Optional;
  75. import java.util.UUID;
  76. import java.util.concurrent.CancellationException;
  77. import java.util.concurrent.CompletableFuture;
  78. import java.util.concurrent.ConcurrentHashMap;
  79. import java.util.concurrent.ExecutionException;
  80. import java.util.concurrent.ExecutorService;
  81. import java.util.concurrent.Executors;
  82. import java.util.concurrent.TimeUnit;
  83. import java.util.concurrent.TimeoutException;
  84. import java.util.concurrent.atomic.AtomicBoolean;
  85. import java.util.concurrent.atomic.AtomicReference;
  86. import java.util.concurrent.locks.Lock;
  87. import java.util.concurrent.locks.ReentrantLock;
  88. import org.eclipse.jgit.annotations.NonNull;
  89. import org.eclipse.jgit.annotations.Nullable;
  90. import org.eclipse.jgit.api.errors.JGitInternalException;
  91. import org.eclipse.jgit.errors.CommandFailedException;
  92. import org.eclipse.jgit.errors.ConfigInvalidException;
  93. import org.eclipse.jgit.errors.LockFailedException;
  94. import org.eclipse.jgit.internal.JGitText;
  95. import org.eclipse.jgit.internal.storage.file.FileSnapshot;
  96. import org.eclipse.jgit.lib.ConfigConstants;
  97. import org.eclipse.jgit.lib.Constants;
  98. import org.eclipse.jgit.lib.Repository;
  99. import org.eclipse.jgit.storage.file.FileBasedConfig;
  100. import org.eclipse.jgit.treewalk.FileTreeIterator.FileEntry;
  101. import org.eclipse.jgit.treewalk.FileTreeIterator.FileModeStrategy;
  102. import org.eclipse.jgit.treewalk.WorkingTreeIterator.Entry;
  103. import org.eclipse.jgit.util.ProcessResult.Status;
  104. import org.slf4j.Logger;
  105. import org.slf4j.LoggerFactory;
  106. /**
  107. * Abstraction to support various file system operations not in Java.
  108. */
  109. public abstract class FS {
  110. private static final Logger LOG = LoggerFactory.getLogger(FS.class);
  111. /**
  112. * An empty array of entries, suitable as a return value for
  113. * {@link #list(File, FileModeStrategy)}.
  114. *
  115. * @since 5.0
  116. */
  117. protected static final Entry[] NO_ENTRIES = {};
  118. /**
  119. * This class creates FS instances. It will be overridden by a Java7 variant
  120. * if such can be detected in {@link #detect(Boolean)}.
  121. *
  122. * @since 3.0
  123. */
  124. public static class FSFactory {
  125. /**
  126. * Constructor
  127. */
  128. protected FSFactory() {
  129. // empty
  130. }
  131. /**
  132. * Detect the file system
  133. *
  134. * @param cygwinUsed
  135. * @return FS instance
  136. */
  137. public FS detect(Boolean cygwinUsed) {
  138. if (SystemReader.getInstance().isWindows()) {
  139. if (cygwinUsed == null)
  140. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  141. if (cygwinUsed.booleanValue())
  142. return new FS_Win32_Cygwin();
  143. else
  144. return new FS_Win32();
  145. } else {
  146. return new FS_POSIX();
  147. }
  148. }
  149. }
  150. /**
  151. * Result of an executed process. The caller is responsible to close the
  152. * contained {@link TemporaryBuffer}s
  153. *
  154. * @since 4.2
  155. */
  156. public static class ExecutionResult {
  157. private TemporaryBuffer stdout;
  158. private TemporaryBuffer stderr;
  159. private int rc;
  160. /**
  161. * @param stdout
  162. * @param stderr
  163. * @param rc
  164. */
  165. public ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,
  166. int rc) {
  167. this.stdout = stdout;
  168. this.stderr = stderr;
  169. this.rc = rc;
  170. }
  171. /**
  172. * @return buffered standard output stream
  173. */
  174. public TemporaryBuffer getStdout() {
  175. return stdout;
  176. }
  177. /**
  178. * @return buffered standard error stream
  179. */
  180. public TemporaryBuffer getStderr() {
  181. return stderr;
  182. }
  183. /**
  184. * @return the return code of the process
  185. */
  186. public int getRc() {
  187. return rc;
  188. }
  189. }
  190. /**
  191. * Attributes of FileStores on this system
  192. *
  193. * @since 5.1.9
  194. */
  195. public final static class FileStoreAttributes {
  196. private static final Duration UNDEFINED_DURATION = Duration
  197. .ofNanos(Long.MAX_VALUE);
  198. /**
  199. * Fallback FileStore attributes used when we can't measure the
  200. * filesystem timestamp resolution. The last modified time granularity
  201. * of FAT filesystems is 2 seconds.
  202. */
  203. public static final FileStoreAttributes FALLBACK_FILESTORE_ATTRIBUTES = new FileStoreAttributes(
  204. Duration.ofMillis(2000));
  205. private static final Map<FileStore, FileStoreAttributes> attributeCache = new ConcurrentHashMap<>();
  206. private static AtomicBoolean background = new AtomicBoolean();
  207. private static Map<FileStore, Lock> locks = new ConcurrentHashMap<>();
  208. private static void setBackground(boolean async) {
  209. background.set(async);
  210. }
  211. private static final String javaVersionPrefix = System
  212. .getProperty("java.vendor") + '|' //$NON-NLS-1$
  213. + System.getProperty("java.version") + '|'; //$NON-NLS-1$
  214. private static final Duration FALLBACK_MIN_RACY_INTERVAL = Duration
  215. .ofMillis(10);
  216. /**
  217. * Get the FileStoreAttributes for the given FileStore
  218. *
  219. * @param path
  220. * file residing in the FileStore to get attributes for
  221. * @return FileStoreAttributes for the given path.
  222. */
  223. public static FileStoreAttributes get(Path path) {
  224. path = path.toAbsolutePath();
  225. Path dir = Files.isDirectory(path) ? path : path.getParent();
  226. return getFileStoreAttributes(dir);
  227. }
  228. private static FileStoreAttributes getFileStoreAttributes(Path dir) {
  229. FileStore s;
  230. try {
  231. if (Files.exists(dir)) {
  232. s = Files.getFileStore(dir);
  233. FileStoreAttributes c = attributeCache.get(s);
  234. if (c != null) {
  235. return c;
  236. }
  237. if (!Files.isWritable(dir)) {
  238. // cannot measure resolution in a read-only directory
  239. LOG.debug(
  240. "{}: cannot measure timestamp resolution in read-only directory {}", //$NON-NLS-1$
  241. Thread.currentThread(), dir);
  242. return FALLBACK_FILESTORE_ATTRIBUTES;
  243. }
  244. } else {
  245. // cannot determine FileStore of an unborn directory
  246. LOG.debug(
  247. "{}: cannot measure timestamp resolution of unborn directory {}", //$NON-NLS-1$
  248. Thread.currentThread(), dir);
  249. return FALLBACK_FILESTORE_ATTRIBUTES;
  250. }
  251. CompletableFuture<Optional<FileStoreAttributes>> f = CompletableFuture
  252. .supplyAsync(() -> {
  253. Lock lock = locks.computeIfAbsent(s,
  254. l -> new ReentrantLock());
  255. if (!lock.tryLock()) {
  256. LOG.debug(
  257. "{}: couldn't get lock to measure timestamp resolution in {}", //$NON-NLS-1$
  258. Thread.currentThread(), dir);
  259. return Optional.empty();
  260. }
  261. Optional<FileStoreAttributes> attributes = Optional
  262. .empty();
  263. try {
  264. // Some earlier future might have set the value
  265. // and removed itself since we checked for the
  266. // value above. Hence check cache again.
  267. FileStoreAttributes c = attributeCache
  268. .get(s);
  269. if (c != null) {
  270. return Optional.of(c);
  271. }
  272. attributes = readFromConfig(s);
  273. if (attributes.isPresent()) {
  274. attributeCache.put(s, attributes.get());
  275. return attributes;
  276. }
  277. Optional<Duration> resolution = measureFsTimestampResolution(
  278. s, dir);
  279. if (resolution.isPresent()) {
  280. c = new FileStoreAttributes(
  281. resolution.get());
  282. attributeCache.put(s, c);
  283. // for high timestamp resolution measure
  284. // minimal racy interval
  285. if (c.fsTimestampResolution
  286. .toNanos() < 100_000_000L) {
  287. c.minimalRacyInterval = measureMinimalRacyInterval(
  288. dir);
  289. }
  290. if (LOG.isDebugEnabled()) {
  291. LOG.debug(c.toString());
  292. }
  293. saveToConfig(s, c);
  294. }
  295. attributes = Optional.of(c);
  296. } finally {
  297. lock.unlock();
  298. locks.remove(s);
  299. }
  300. return attributes;
  301. });
  302. f.exceptionally(e -> {
  303. LOG.error(e.getLocalizedMessage(), e);
  304. return Optional.empty();
  305. });
  306. // even if measuring in background wait a little - if the result
  307. // arrives, it's better than returning the large fallback
  308. Optional<FileStoreAttributes> d = background.get() ? f.get(
  309. 100, TimeUnit.MILLISECONDS) : f.get();
  310. if (d.isPresent()) {
  311. return d.get();
  312. }
  313. // return fallback until measurement is finished
  314. } catch (IOException | InterruptedException
  315. | ExecutionException | CancellationException e) {
  316. LOG.error(e.getMessage(), e);
  317. } catch (TimeoutException | SecurityException e) {
  318. // use fallback
  319. }
  320. LOG.debug("{}: use fallback timestamp resolution for directory {}", //$NON-NLS-1$
  321. Thread.currentThread(), dir);
  322. return FALLBACK_FILESTORE_ATTRIBUTES;
  323. }
  324. @SuppressWarnings("boxing")
  325. private static Duration measureMinimalRacyInterval(Path dir) {
  326. LOG.debug("{}: start measure minimal racy interval in {}", //$NON-NLS-1$
  327. Thread.currentThread(), dir);
  328. int n = 0;
  329. int failures = 0;
  330. long racyNanos = 0;
  331. ArrayList<Long> deltas = new ArrayList<>();
  332. Path probe = dir.resolve(".probe-" + UUID.randomUUID()); //$NON-NLS-1$
  333. Instant end = Instant.now().plusSeconds(3);
  334. try {
  335. Files.createFile(probe);
  336. do {
  337. n++;
  338. write(probe, "a"); //$NON-NLS-1$
  339. FileSnapshot snapshot = FileSnapshot.save(probe.toFile());
  340. read(probe);
  341. write(probe, "b"); //$NON-NLS-1$
  342. if (!snapshot.isModified(probe.toFile())) {
  343. deltas.add(Long.valueOf(snapshot.lastDelta()));
  344. racyNanos = snapshot.lastRacyThreshold();
  345. failures++;
  346. }
  347. } while (Instant.now().compareTo(end) < 0);
  348. } catch (IOException e) {
  349. LOG.error(e.getMessage(), e);
  350. return FALLBACK_MIN_RACY_INTERVAL;
  351. } finally {
  352. deleteProbe(probe);
  353. }
  354. if (failures > 0) {
  355. Stats stats = new Stats();
  356. for (Long d : deltas) {
  357. stats.add(d);
  358. }
  359. LOG.debug(
  360. "delta [ns] since modification FileSnapshot failed to detect\n" //$NON-NLS-1$
  361. + "count, failures, racy limit [ns], delta min [ns]," //$NON-NLS-1$
  362. + " delta max [ns], delta avg [ns]," //$NON-NLS-1$
  363. + " delta stddev [ns]\n" //$NON-NLS-1$
  364. + "{}, {}, {}, {}, {}, {}, {}", //$NON-NLS-1$
  365. n, failures, racyNanos, stats.min(), stats.max(),
  366. stats.avg(), stats.stddev());
  367. return Duration
  368. .ofNanos(Double.valueOf(stats.max()).longValue());
  369. }
  370. // since no failures occurred using the measured filesystem
  371. // timestamp resolution there is no need for minimal racy interval
  372. LOG.debug("{}: no failures when measuring minimal racy interval", //$NON-NLS-1$
  373. Thread.currentThread());
  374. return Duration.ZERO;
  375. }
  376. private static void write(Path p, String body) throws IOException {
  377. FileUtils.mkdirs(p.getParent().toFile(), true);
  378. try (Writer w = new OutputStreamWriter(Files.newOutputStream(p),
  379. UTF_8)) {
  380. w.write(body);
  381. }
  382. }
  383. private static String read(Path p) throws IOException {
  384. final byte[] body = IO.readFully(p.toFile());
  385. return new String(body, 0, body.length, UTF_8);
  386. }
  387. private static Optional<Duration> measureFsTimestampResolution(
  388. FileStore s, Path dir) {
  389. LOG.debug("{}: start measure timestamp resolution {} in {}", //$NON-NLS-1$
  390. Thread.currentThread(), s, dir);
  391. Path probe = dir.resolve(".probe-" + UUID.randomUUID()); //$NON-NLS-1$
  392. try {
  393. Files.createFile(probe);
  394. FileTime t1 = Files.getLastModifiedTime(probe);
  395. FileTime t2 = t1;
  396. Instant t1i = t1.toInstant();
  397. for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 20) {
  398. Files.setLastModifiedTime(probe,
  399. FileTime.from(t1i.plusNanos(i * 1000)));
  400. t2 = Files.getLastModifiedTime(probe);
  401. }
  402. Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant());
  403. Duration clockResolution = measureClockResolution();
  404. fsResolution = fsResolution.plus(clockResolution);
  405. LOG.debug("{}: end measure timestamp resolution {} in {}", //$NON-NLS-1$
  406. Thread.currentThread(), s, dir);
  407. return Optional.of(fsResolution);
  408. } catch (AccessDeniedException e) {
  409. LOG.warn(e.getLocalizedMessage(), e); // see bug 548648
  410. } catch (IOException e) {
  411. LOG.error(e.getLocalizedMessage(), e);
  412. } finally {
  413. deleteProbe(probe);
  414. }
  415. return Optional.empty();
  416. }
  417. private static Duration measureClockResolution() {
  418. Duration clockResolution = Duration.ZERO;
  419. for (int i = 0; i < 10; i++) {
  420. Instant t1 = Instant.now();
  421. Instant t2 = t1;
  422. while (t2.compareTo(t1) <= 0) {
  423. t2 = Instant.now();
  424. }
  425. Duration r = Duration.between(t1, t2);
  426. if (r.compareTo(clockResolution) > 0) {
  427. clockResolution = r;
  428. }
  429. }
  430. return clockResolution;
  431. }
  432. private static void deleteProbe(Path probe) {
  433. try {
  434. FileUtils.delete(probe.toFile(),
  435. FileUtils.SKIP_MISSING | FileUtils.RETRY);
  436. } catch (IOException e) {
  437. LOG.error(e.getMessage(), e);
  438. }
  439. }
  440. private static Optional<FileStoreAttributes> readFromConfig(
  441. FileStore s) {
  442. FileBasedConfig userConfig = SystemReader.getInstance()
  443. .openUserConfig(null, FS.DETECTED);
  444. try {
  445. userConfig.load(false);
  446. } catch (IOException e) {
  447. LOG.error(MessageFormat.format(JGitText.get().readConfigFailed,
  448. userConfig.getFile().getAbsolutePath()), e);
  449. } catch (ConfigInvalidException e) {
  450. LOG.error(MessageFormat.format(
  451. JGitText.get().repositoryConfigFileInvalid,
  452. userConfig.getFile().getAbsolutePath(),
  453. e.getMessage()));
  454. }
  455. String key = getConfigKey(s);
  456. Duration resolution = Duration.ofNanos(userConfig.getTimeUnit(
  457. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  458. ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
  459. UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
  460. if (UNDEFINED_DURATION.equals(resolution)) {
  461. return Optional.empty();
  462. }
  463. Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit(
  464. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  465. ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
  466. UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
  467. FileStoreAttributes c = new FileStoreAttributes(resolution);
  468. if (!UNDEFINED_DURATION.equals(minRacyThreshold)) {
  469. c.minimalRacyInterval = minRacyThreshold;
  470. }
  471. return Optional.of(c);
  472. }
  473. private static void saveToConfig(FileStore s,
  474. FileStoreAttributes c) {
  475. FileBasedConfig userConfig = SystemReader.getInstance()
  476. .openUserConfig(null, FS.DETECTED);
  477. long resolution = c.getFsTimestampResolution().toNanos();
  478. TimeUnit resolutionUnit = getUnit(resolution);
  479. long resolutionValue = resolutionUnit.convert(resolution,
  480. TimeUnit.NANOSECONDS);
  481. long minRacyThreshold = c.getMinimalRacyInterval().toNanos();
  482. TimeUnit minRacyThresholdUnit = getUnit(minRacyThreshold);
  483. long minRacyThresholdValue = minRacyThresholdUnit
  484. .convert(minRacyThreshold, TimeUnit.NANOSECONDS);
  485. final int max_retries = 5;
  486. int retries = 0;
  487. boolean succeeded = false;
  488. String key = getConfigKey(s);
  489. while (!succeeded && retries < max_retries) {
  490. try {
  491. userConfig.load(false);
  492. userConfig.setString(
  493. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  494. ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
  495. String.format("%d %s", //$NON-NLS-1$
  496. Long.valueOf(resolutionValue),
  497. resolutionUnit.name().toLowerCase()));
  498. userConfig.setString(
  499. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  500. ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
  501. String.format("%d %s", //$NON-NLS-1$
  502. Long.valueOf(minRacyThresholdValue),
  503. minRacyThresholdUnit.name().toLowerCase()));
  504. userConfig.save();
  505. succeeded = true;
  506. } catch (LockFailedException e) {
  507. // race with another thread, wait a bit and try again
  508. try {
  509. LOG.warn(MessageFormat.format(JGitText.get().cannotLock,
  510. userConfig.getFile().getAbsolutePath()));
  511. retries++;
  512. Thread.sleep(20);
  513. } catch (InterruptedException e1) {
  514. Thread.interrupted();
  515. }
  516. } catch (IOException e) {
  517. LOG.error(MessageFormat.format(
  518. JGitText.get().cannotSaveConfig,
  519. userConfig.getFile().getAbsolutePath()), e);
  520. } catch (ConfigInvalidException e) {
  521. LOG.error(MessageFormat.format(
  522. JGitText.get().repositoryConfigFileInvalid,
  523. userConfig.getFile().getAbsolutePath(),
  524. e.getMessage()));
  525. }
  526. }
  527. }
  528. private static String getConfigKey(FileStore s) {
  529. final String storeKey;
  530. if (SystemReader.getInstance().isWindows()) {
  531. Object attribute = null;
  532. try {
  533. attribute = s.getAttribute("volume:vsn"); //$NON-NLS-1$
  534. } catch (IOException ignored) {
  535. // ignore
  536. }
  537. if (attribute instanceof Integer) {
  538. storeKey = attribute.toString();
  539. } else {
  540. storeKey = s.name();
  541. }
  542. } else {
  543. storeKey = s.name();
  544. }
  545. return javaVersionPrefix + storeKey;
  546. }
  547. private static TimeUnit getUnit(long nanos) {
  548. TimeUnit unit;
  549. if (nanos < 200_000L) {
  550. unit = TimeUnit.NANOSECONDS;
  551. } else if (nanos < 200_000_000L) {
  552. unit = TimeUnit.MICROSECONDS;
  553. } else {
  554. unit = TimeUnit.MILLISECONDS;
  555. }
  556. return unit;
  557. }
  558. private final @NonNull Duration fsTimestampResolution;
  559. private Duration minimalRacyInterval;
  560. /**
  561. * @return the measured minimal interval after a file has been modified
  562. * in which we cannot rely on lastModified to detect
  563. * modifications
  564. */
  565. public Duration getMinimalRacyInterval() {
  566. return minimalRacyInterval;
  567. }
  568. /**
  569. * @return the measured filesystem timestamp resolution
  570. */
  571. @NonNull
  572. public Duration getFsTimestampResolution() {
  573. return fsTimestampResolution;
  574. }
  575. /**
  576. * Construct a FileStoreAttributeCache entry for the given filesystem
  577. * timestamp resolution
  578. *
  579. * @param fsTimestampResolution
  580. */
  581. public FileStoreAttributes(
  582. @NonNull Duration fsTimestampResolution) {
  583. this.fsTimestampResolution = fsTimestampResolution;
  584. this.minimalRacyInterval = Duration.ZERO;
  585. }
  586. @SuppressWarnings({ "nls", "boxing" })
  587. @Override
  588. public String toString() {
  589. return String.format(
  590. "FileStoreAttributes[fsTimestampResolution=%,d µs, "
  591. + "minimalRacyInterval=%,d µs]",
  592. fsTimestampResolution.toNanos() / 1000,
  593. minimalRacyInterval.toNanos() / 1000);
  594. }
  595. }
  596. /** The auto-detected implementation selected for this operating system and JRE. */
  597. public static final FS DETECTED = detect();
  598. private volatile static FSFactory factory;
  599. /**
  600. * Auto-detect the appropriate file system abstraction.
  601. *
  602. * @return detected file system abstraction
  603. */
  604. public static FS detect() {
  605. return detect(null);
  606. }
  607. /**
  608. * Whether FileStore attributes should be determined asynchronously
  609. *
  610. * @param asynch
  611. * whether FileStore attributes should be determined
  612. * asynchronously. If false access to cached attributes may block
  613. * for some seconds for the first call per FileStore
  614. * @since 5.1.9
  615. */
  616. public static void setAsyncFileStoreAttributes(boolean asynch) {
  617. FileStoreAttributes.setBackground(asynch);
  618. }
  619. /**
  620. * Auto-detect the appropriate file system abstraction, taking into account
  621. * the presence of a Cygwin installation on the system. Using jgit in
  622. * combination with Cygwin requires a more elaborate (and possibly slower)
  623. * resolution of file system paths.
  624. *
  625. * @param cygwinUsed
  626. * <ul>
  627. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  628. * combination with jgit</li>
  629. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  630. * <b>not</b> used with jgit</li>
  631. * <li><code>null</code> to auto-detect whether a Cygwin
  632. * installation is present on the system and in this case assume
  633. * that Cygwin is used</li>
  634. * </ul>
  635. *
  636. * Note: this parameter is only relevant on Windows.
  637. * @return detected file system abstraction
  638. */
  639. public static FS detect(Boolean cygwinUsed) {
  640. if (factory == null) {
  641. factory = new FS.FSFactory();
  642. }
  643. return factory.detect(cygwinUsed);
  644. }
  645. /**
  646. * Get cached FileStore attributes, if not yet available measure them using
  647. * a probe file under the given directory.
  648. *
  649. * @param dir
  650. * the directory under which the probe file will be created to
  651. * measure the timer resolution.
  652. * @return measured filesystem timestamp resolution
  653. * @since 5.1.9
  654. */
  655. public static FileStoreAttributes getFileStoreAttributes(
  656. @NonNull Path dir) {
  657. return FileStoreAttributes.get(dir);
  658. }
  659. private volatile Holder<File> userHome;
  660. private volatile Holder<File> gitSystemConfig;
  661. /**
  662. * Constructs a file system abstraction.
  663. */
  664. protected FS() {
  665. // Do nothing by default.
  666. }
  667. /**
  668. * Initialize this FS using another's current settings.
  669. *
  670. * @param src
  671. * the source FS to copy from.
  672. */
  673. protected FS(FS src) {
  674. userHome = src.userHome;
  675. gitSystemConfig = src.gitSystemConfig;
  676. }
  677. /**
  678. * Create a new instance of the same type of FS.
  679. *
  680. * @return a new instance of the same type of FS.
  681. */
  682. public abstract FS newInstance();
  683. /**
  684. * Does this operating system and JRE support the execute flag on files?
  685. *
  686. * @return true if this implementation can provide reasonably accurate
  687. * executable bit information; false otherwise.
  688. */
  689. public abstract boolean supportsExecute();
  690. /**
  691. * Does this file system support atomic file creation via
  692. * java.io.File#createNewFile()? In certain environments (e.g. on NFS) it is
  693. * not guaranteed that when two file system clients run createNewFile() in
  694. * parallel only one will succeed. In such cases both clients may think they
  695. * created a new file.
  696. *
  697. * @return true if this implementation support atomic creation of new Files
  698. * by {@link java.io.File#createNewFile()}
  699. * @since 4.5
  700. */
  701. public boolean supportsAtomicCreateNewFile() {
  702. return true;
  703. }
  704. /**
  705. * Does this operating system and JRE supports symbolic links. The
  706. * capability to handle symbolic links is detected at runtime.
  707. *
  708. * @return true if symbolic links may be used
  709. * @since 3.0
  710. */
  711. public boolean supportsSymlinks() {
  712. return false;
  713. }
  714. /**
  715. * Is this file system case sensitive
  716. *
  717. * @return true if this implementation is case sensitive
  718. */
  719. public abstract boolean isCaseSensitive();
  720. /**
  721. * Determine if the file is executable (or not).
  722. * <p>
  723. * Not all platforms and JREs support executable flags on files. If the
  724. * feature is unsupported this method will always return false.
  725. * <p>
  726. * <em>If the platform supports symbolic links and <code>f</code> is a symbolic link
  727. * this method returns false, rather than the state of the executable flags
  728. * on the target file.</em>
  729. *
  730. * @param f
  731. * abstract path to test.
  732. * @return true if the file is believed to be executable by the user.
  733. */
  734. public abstract boolean canExecute(File f);
  735. /**
  736. * Set a file to be executable by the user.
  737. * <p>
  738. * Not all platforms and JREs support executable flags on files. If the
  739. * feature is unsupported this method will always return false and no
  740. * changes will be made to the file specified.
  741. *
  742. * @param f
  743. * path to modify the executable status of.
  744. * @param canExec
  745. * true to enable execution; false to disable it.
  746. * @return true if the change succeeded; false otherwise.
  747. */
  748. public abstract boolean setExecute(File f, boolean canExec);
  749. /**
  750. * Get the last modified time of a file system object. If the OS/JRE support
  751. * symbolic links, the modification time of the link is returned, rather
  752. * than that of the link target.
  753. *
  754. * @param f
  755. * a {@link java.io.File} object.
  756. * @return last modified time of f
  757. * @throws java.io.IOException
  758. * @since 3.0
  759. * @deprecated use {@link #lastModifiedInstant(Path)} instead
  760. */
  761. @Deprecated
  762. public long lastModified(File f) throws IOException {
  763. return FileUtils.lastModified(f);
  764. }
  765. /**
  766. * Get the last modified time of a file system object. If the OS/JRE support
  767. * symbolic links, the modification time of the link is returned, rather
  768. * than that of the link target.
  769. *
  770. * @param p
  771. * a {@link Path} object.
  772. * @return last modified time of p
  773. * @since 5.1.9
  774. */
  775. public Instant lastModifiedInstant(Path p) {
  776. return FileUtils.lastModifiedInstant(p);
  777. }
  778. /**
  779. * Get the last modified time of a file system object. If the OS/JRE support
  780. * symbolic links, the modification time of the link is returned, rather
  781. * than that of the link target.
  782. *
  783. * @param f
  784. * a {@link File} object.
  785. * @return last modified time of p
  786. * @since 5.1.9
  787. */
  788. public Instant lastModifiedInstant(File f) {
  789. return FileUtils.lastModifiedInstant(f.toPath());
  790. }
  791. /**
  792. * Set the last modified time of a file system object. If the OS/JRE support
  793. * symbolic links, the link is modified, not the target,
  794. *
  795. * @param f
  796. * a {@link java.io.File} object.
  797. * @param time
  798. * last modified time
  799. * @throws java.io.IOException
  800. * @since 3.0
  801. * @deprecated use {@link #setLastModified(Path, Instant)} instead
  802. */
  803. @Deprecated
  804. public void setLastModified(File f, long time) throws IOException {
  805. FileUtils.setLastModified(f, time);
  806. }
  807. /**
  808. * Set the last modified time of a file system object. If the OS/JRE support
  809. * symbolic links, the link is modified, not the target,
  810. *
  811. * @param p
  812. * a {@link Path} object.
  813. * @param time
  814. * last modified time
  815. * @throws java.io.IOException
  816. * @since 5.1.9
  817. */
  818. public void setLastModified(Path p, Instant time) throws IOException {
  819. FileUtils.setLastModified(p, time);
  820. }
  821. /**
  822. * Get the length of a file or link, If the OS/JRE supports symbolic links
  823. * it's the length of the link, else the length of the target.
  824. *
  825. * @param path
  826. * a {@link java.io.File} object.
  827. * @return length of a file
  828. * @throws java.io.IOException
  829. * @since 3.0
  830. */
  831. public long length(File path) throws IOException {
  832. return FileUtils.getLength(path);
  833. }
  834. /**
  835. * Delete a file. Throws an exception if delete fails.
  836. *
  837. * @param f
  838. * a {@link java.io.File} object.
  839. * @throws java.io.IOException
  840. * this may be a Java7 subclass with detailed information
  841. * @since 3.3
  842. */
  843. public void delete(File f) throws IOException {
  844. FileUtils.delete(f);
  845. }
  846. /**
  847. * Resolve this file to its actual path name that the JRE can use.
  848. * <p>
  849. * This method can be relatively expensive. Computing a translation may
  850. * require forking an external process per path name translated. Callers
  851. * should try to minimize the number of translations necessary by caching
  852. * the results.
  853. * <p>
  854. * Not all platforms and JREs require path name translation. Currently only
  855. * Cygwin on Win32 require translation for Cygwin based paths.
  856. *
  857. * @param dir
  858. * directory relative to which the path name is.
  859. * @param name
  860. * path name to translate.
  861. * @return the translated path. <code>new File(dir,name)</code> if this
  862. * platform does not require path name translation.
  863. */
  864. public File resolve(File dir, String name) {
  865. final File abspn = new File(name);
  866. if (abspn.isAbsolute())
  867. return abspn;
  868. return new File(dir, name);
  869. }
  870. /**
  871. * Determine the user's home directory (location where preferences are).
  872. * <p>
  873. * This method can be expensive on the first invocation if path name
  874. * translation is required. Subsequent invocations return a cached result.
  875. * <p>
  876. * Not all platforms and JREs require path name translation. Currently only
  877. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  878. *
  879. * @return the user's home directory; null if the user does not have one.
  880. */
  881. public File userHome() {
  882. Holder<File> p = userHome;
  883. if (p == null) {
  884. p = new Holder<>(userHomeImpl());
  885. userHome = p;
  886. }
  887. return p.value;
  888. }
  889. /**
  890. * Set the user's home directory location.
  891. *
  892. * @param path
  893. * the location of the user's preferences; null if there is no
  894. * home directory for the current user.
  895. * @return {@code this}.
  896. */
  897. public FS setUserHome(File path) {
  898. userHome = new Holder<>(path);
  899. return this;
  900. }
  901. /**
  902. * Does this file system have problems with atomic renames?
  903. *
  904. * @return true if the caller should retry a failed rename of a lock file.
  905. */
  906. public abstract boolean retryFailedLockFileCommit();
  907. /**
  908. * Return all the attributes of a file, without following symbolic links.
  909. *
  910. * @param file
  911. * @return {@link BasicFileAttributes} of the file
  912. * @throws IOException in case of any I/O errors accessing the file
  913. *
  914. * @since 4.5.6
  915. */
  916. public BasicFileAttributes fileAttributes(File file) throws IOException {
  917. return FileUtils.fileAttributes(file);
  918. }
  919. /**
  920. * Determine the user's home directory (location where preferences are).
  921. *
  922. * @return the user's home directory; null if the user does not have one.
  923. */
  924. protected File userHomeImpl() {
  925. final String home = AccessController
  926. .doPrivileged(new PrivilegedAction<String>() {
  927. @Override
  928. public String run() {
  929. return System.getProperty("user.home"); //$NON-NLS-1$
  930. }
  931. });
  932. if (home == null || home.length() == 0)
  933. return null;
  934. return new File(home).getAbsoluteFile();
  935. }
  936. /**
  937. * Searches the given path to see if it contains one of the given files.
  938. * Returns the first it finds. Returns null if not found or if path is null.
  939. *
  940. * @param path
  941. * List of paths to search separated by File.pathSeparator
  942. * @param lookFor
  943. * Files to search for in the given path
  944. * @return the first match found, or null
  945. * @since 3.0
  946. */
  947. protected static File searchPath(String path, String... lookFor) {
  948. if (path == null)
  949. return null;
  950. for (String p : path.split(File.pathSeparator)) {
  951. for (String command : lookFor) {
  952. final File e = new File(p, command);
  953. if (e.isFile())
  954. return e.getAbsoluteFile();
  955. }
  956. }
  957. return null;
  958. }
  959. /**
  960. * Execute a command and return a single line of output as a String
  961. *
  962. * @param dir
  963. * Working directory for the command
  964. * @param command
  965. * as component array
  966. * @param encoding
  967. * to be used to parse the command's output
  968. * @return the one-line output of the command or {@code null} if there is
  969. * none
  970. * @throws org.eclipse.jgit.errors.CommandFailedException
  971. * thrown when the command failed (return code was non-zero)
  972. */
  973. @Nullable
  974. protected static String readPipe(File dir, String[] command,
  975. String encoding) throws CommandFailedException {
  976. return readPipe(dir, command, encoding, null);
  977. }
  978. /**
  979. * Execute a command and return a single line of output as a String
  980. *
  981. * @param dir
  982. * Working directory for the command
  983. * @param command
  984. * as component array
  985. * @param encoding
  986. * to be used to parse the command's output
  987. * @param env
  988. * Map of environment variables to be merged with those of the
  989. * current process
  990. * @return the one-line output of the command or {@code null} if there is
  991. * none
  992. * @throws org.eclipse.jgit.errors.CommandFailedException
  993. * thrown when the command failed (return code was non-zero)
  994. * @since 4.0
  995. */
  996. @Nullable
  997. protected static String readPipe(File dir, String[] command,
  998. String encoding, Map<String, String> env)
  999. throws CommandFailedException {
  1000. final boolean debug = LOG.isDebugEnabled();
  1001. try {
  1002. if (debug) {
  1003. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  1004. + dir);
  1005. }
  1006. ProcessBuilder pb = new ProcessBuilder(command);
  1007. pb.directory(dir);
  1008. if (env != null) {
  1009. pb.environment().putAll(env);
  1010. }
  1011. Process p;
  1012. try {
  1013. p = pb.start();
  1014. } catch (IOException e) {
  1015. // Process failed to start
  1016. throw new CommandFailedException(-1, e.getMessage(), e);
  1017. }
  1018. p.getOutputStream().close();
  1019. GobblerThread gobbler = new GobblerThread(p, command, dir);
  1020. gobbler.start();
  1021. String r = null;
  1022. try (BufferedReader lineRead = new BufferedReader(
  1023. new InputStreamReader(p.getInputStream(), encoding))) {
  1024. r = lineRead.readLine();
  1025. if (debug) {
  1026. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  1027. LOG.debug("remaining output:\n"); //$NON-NLS-1$
  1028. String l;
  1029. while ((l = lineRead.readLine()) != null) {
  1030. LOG.debug(l);
  1031. }
  1032. }
  1033. }
  1034. for (;;) {
  1035. try {
  1036. int rc = p.waitFor();
  1037. gobbler.join();
  1038. if (rc == 0 && !gobbler.fail.get()) {
  1039. return r;
  1040. } else {
  1041. if (debug) {
  1042. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  1043. }
  1044. throw new CommandFailedException(rc,
  1045. gobbler.errorMessage.get(),
  1046. gobbler.exception.get());
  1047. }
  1048. } catch (InterruptedException ie) {
  1049. // Stop bothering me, I have a zombie to reap.
  1050. }
  1051. }
  1052. } catch (IOException e) {
  1053. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  1054. }
  1055. if (debug) {
  1056. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  1057. }
  1058. return null;
  1059. }
  1060. private static class GobblerThread extends Thread {
  1061. /* The process has 5 seconds to exit after closing stderr */
  1062. private static final int PROCESS_EXIT_TIMEOUT = 5;
  1063. private final Process p;
  1064. private final String desc;
  1065. private final String dir;
  1066. final AtomicBoolean fail = new AtomicBoolean();
  1067. final AtomicReference<String> errorMessage = new AtomicReference<>();
  1068. final AtomicReference<Throwable> exception = new AtomicReference<>();
  1069. GobblerThread(Process p, String[] command, File dir) {
  1070. this.p = p;
  1071. this.desc = Arrays.toString(command);
  1072. this.dir = Objects.toString(dir);
  1073. }
  1074. @Override
  1075. public void run() {
  1076. StringBuilder err = new StringBuilder();
  1077. try (InputStream is = p.getErrorStream()) {
  1078. int ch;
  1079. while ((ch = is.read()) != -1) {
  1080. err.append((char) ch);
  1081. }
  1082. } catch (IOException e) {
  1083. if (waitForProcessCompletion(e) && p.exitValue() != 0) {
  1084. setError(e, e.getMessage(), p.exitValue());
  1085. fail.set(true);
  1086. } else {
  1087. // ignore. command terminated faster and stream was just closed
  1088. // or the process didn't terminate within timeout
  1089. }
  1090. } finally {
  1091. if (waitForProcessCompletion(null) && err.length() > 0) {
  1092. setError(null, err.toString(), p.exitValue());
  1093. if (p.exitValue() != 0) {
  1094. fail.set(true);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. @SuppressWarnings("boxing")
  1100. private boolean waitForProcessCompletion(IOException originalError) {
  1101. try {
  1102. if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) {
  1103. setError(originalError, MessageFormat.format(
  1104. JGitText.get().commandClosedStderrButDidntExit,
  1105. desc, PROCESS_EXIT_TIMEOUT), -1);
  1106. fail.set(true);
  1107. return false;
  1108. }
  1109. } catch (InterruptedException e) {
  1110. setError(originalError, MessageFormat.format(
  1111. JGitText.get().threadInterruptedWhileRunning, desc), -1);
  1112. fail.set(true);
  1113. return false;
  1114. }
  1115. return true;
  1116. }
  1117. private void setError(IOException e, String message, int exitCode) {
  1118. exception.set(e);
  1119. errorMessage.set(MessageFormat.format(
  1120. JGitText.get().exceptionCaughtDuringExecutionOfCommand,
  1121. desc, dir, Integer.valueOf(exitCode), message));
  1122. }
  1123. }
  1124. /**
  1125. * Discover the path to the Git executable.
  1126. *
  1127. * @return the path to the Git executable or {@code null} if it cannot be
  1128. * determined.
  1129. * @since 4.0
  1130. */
  1131. protected abstract File discoverGitExe();
  1132. /**
  1133. * Discover the path to the system-wide Git configuration file
  1134. *
  1135. * @return the path to the system-wide Git configuration file or
  1136. * {@code null} if it cannot be determined.
  1137. * @since 4.0
  1138. */
  1139. protected File discoverGitSystemConfig() {
  1140. File gitExe = discoverGitExe();
  1141. if (gitExe == null) {
  1142. return null;
  1143. }
  1144. // Bug 480782: Check if the discovered git executable is JGit CLI
  1145. String v;
  1146. try {
  1147. v = readPipe(gitExe.getParentFile(),
  1148. new String[] { "git", "--version" }, //$NON-NLS-1$ //$NON-NLS-2$
  1149. Charset.defaultCharset().name());
  1150. } catch (CommandFailedException e) {
  1151. LOG.warn(e.getMessage());
  1152. return null;
  1153. }
  1154. if (StringUtils.isEmptyOrNull(v)
  1155. || (v != null && v.startsWith("jgit"))) { //$NON-NLS-1$
  1156. return null;
  1157. }
  1158. // Trick Git into printing the path to the config file by using "echo"
  1159. // as the editor.
  1160. Map<String, String> env = new HashMap<>();
  1161. env.put("GIT_EDITOR", "echo"); //$NON-NLS-1$ //$NON-NLS-2$
  1162. String w;
  1163. try {
  1164. w = readPipe(gitExe.getParentFile(),
  1165. new String[] { "git", "config", "--system", "--edit" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  1166. Charset.defaultCharset().name(), env);
  1167. } catch (CommandFailedException e) {
  1168. LOG.warn(e.getMessage());
  1169. return null;
  1170. }
  1171. if (StringUtils.isEmptyOrNull(w)) {
  1172. return null;
  1173. }
  1174. return new File(w);
  1175. }
  1176. /**
  1177. * Get the currently used path to the system-wide Git configuration file.
  1178. *
  1179. * @return the currently used path to the system-wide Git configuration file
  1180. * or {@code null} if none has been set.
  1181. * @since 4.0
  1182. */
  1183. public File getGitSystemConfig() {
  1184. if (gitSystemConfig == null) {
  1185. gitSystemConfig = new Holder<>(discoverGitSystemConfig());
  1186. }
  1187. return gitSystemConfig.value;
  1188. }
  1189. /**
  1190. * Set the path to the system-wide Git configuration file to use.
  1191. *
  1192. * @param configFile
  1193. * the path to the config file.
  1194. * @return {@code this}
  1195. * @since 4.0
  1196. */
  1197. public FS setGitSystemConfig(File configFile) {
  1198. gitSystemConfig = new Holder<>(configFile);
  1199. return this;
  1200. }
  1201. /**
  1202. * Get the parent directory of this file's parent directory
  1203. *
  1204. * @param grandchild
  1205. * a {@link java.io.File} object.
  1206. * @return the parent directory of this file's parent directory or
  1207. * {@code null} in case there's no grandparent directory
  1208. * @since 4.0
  1209. */
  1210. protected static File resolveGrandparentFile(File grandchild) {
  1211. if (grandchild != null) {
  1212. File parent = grandchild.getParentFile();
  1213. if (parent != null)
  1214. return parent.getParentFile();
  1215. }
  1216. return null;
  1217. }
  1218. /**
  1219. * Check if a file is a symbolic link and read it
  1220. *
  1221. * @param path
  1222. * a {@link java.io.File} object.
  1223. * @return target of link or null
  1224. * @throws java.io.IOException
  1225. * @since 3.0
  1226. */
  1227. public String readSymLink(File path) throws IOException {
  1228. return FileUtils.readSymLink(path);
  1229. }
  1230. /**
  1231. * Whether the path is a symbolic link (and we support these).
  1232. *
  1233. * @param path
  1234. * a {@link java.io.File} object.
  1235. * @return true if the path is a symbolic link (and we support these)
  1236. * @throws java.io.IOException
  1237. * @since 3.0
  1238. */
  1239. public boolean isSymLink(File path) throws IOException {
  1240. return FileUtils.isSymlink(path);
  1241. }
  1242. /**
  1243. * Tests if the path exists, in case of a symbolic link, true even if the
  1244. * target does not exist
  1245. *
  1246. * @param path
  1247. * a {@link java.io.File} object.
  1248. * @return true if path exists
  1249. * @since 3.0
  1250. */
  1251. public boolean exists(File path) {
  1252. return FileUtils.exists(path);
  1253. }
  1254. /**
  1255. * Check if path is a directory. If the OS/JRE supports symbolic links and
  1256. * path is a symbolic link to a directory, this method returns false.
  1257. *
  1258. * @param path
  1259. * a {@link java.io.File} object.
  1260. * @return true if file is a directory,
  1261. * @since 3.0
  1262. */
  1263. public boolean isDirectory(File path) {
  1264. return FileUtils.isDirectory(path);
  1265. }
  1266. /**
  1267. * Examine if path represents a regular file. If the OS/JRE supports
  1268. * symbolic links the test returns false if path represents a symbolic link.
  1269. *
  1270. * @param path
  1271. * a {@link java.io.File} object.
  1272. * @return true if path represents a regular file
  1273. * @since 3.0
  1274. */
  1275. public boolean isFile(File path) {
  1276. return FileUtils.isFile(path);
  1277. }
  1278. /**
  1279. * Whether path is hidden, either starts with . on unix or has the hidden
  1280. * attribute in windows
  1281. *
  1282. * @param path
  1283. * a {@link java.io.File} object.
  1284. * @return true if path is hidden, either starts with . on unix or has the
  1285. * hidden attribute in windows
  1286. * @throws java.io.IOException
  1287. * @since 3.0
  1288. */
  1289. public boolean isHidden(File path) throws IOException {
  1290. return FileUtils.isHidden(path);
  1291. }
  1292. /**
  1293. * Set the hidden attribute for file whose name starts with a period.
  1294. *
  1295. * @param path
  1296. * a {@link java.io.File} object.
  1297. * @param hidden
  1298. * whether to set the file hidden
  1299. * @throws java.io.IOException
  1300. * @since 3.0
  1301. */
  1302. public void setHidden(File path, boolean hidden) throws IOException {
  1303. FileUtils.setHidden(path, hidden);
  1304. }
  1305. /**
  1306. * Create a symbolic link
  1307. *
  1308. * @param path
  1309. * a {@link java.io.File} object.
  1310. * @param target
  1311. * target path of the symlink
  1312. * @throws java.io.IOException
  1313. * @since 3.0
  1314. */
  1315. public void createSymLink(File path, String target) throws IOException {
  1316. FileUtils.createSymLink(path, target);
  1317. }
  1318. /**
  1319. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  1320. * of this class may take care to provide a safe implementation for this
  1321. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  1322. *
  1323. * @param path
  1324. * the file to be created
  1325. * @return <code>true</code> if the file was created, <code>false</code> if
  1326. * the file already existed
  1327. * @throws java.io.IOException
  1328. * @deprecated use {@link #createNewFileAtomic(File)} instead
  1329. * @since 4.5
  1330. */
  1331. @Deprecated
  1332. public boolean createNewFile(File path) throws IOException {
  1333. return path.createNewFile();
  1334. }
  1335. /**
  1336. * A token representing a file created by
  1337. * {@link #createNewFileAtomic(File)}. The token must be retained until the
  1338. * file has been deleted in order to guarantee that the unique file was
  1339. * created atomically. As soon as the file is no longer needed the lock
  1340. * token must be closed.
  1341. *
  1342. * @since 4.7
  1343. */
  1344. public static class LockToken implements Closeable {
  1345. private boolean isCreated;
  1346. private Optional<Path> link;
  1347. LockToken(boolean isCreated, Optional<Path> link) {
  1348. this.isCreated = isCreated;
  1349. this.link = link;
  1350. }
  1351. /**
  1352. * @return {@code true} if the file was created successfully
  1353. */
  1354. public boolean isCreated() {
  1355. return isCreated;
  1356. }
  1357. @Override
  1358. public void close() {
  1359. if (!link.isPresent()) {
  1360. return;
  1361. }
  1362. Path p = link.get();
  1363. if (!Files.exists(p)) {
  1364. return;
  1365. }
  1366. try {
  1367. Files.delete(p);
  1368. } catch (IOException e) {
  1369. LOG.error(MessageFormat
  1370. .format(JGitText.get().closeLockTokenFailed, this), e);
  1371. }
  1372. }
  1373. @Override
  1374. public String toString() {
  1375. return "LockToken [lockCreated=" + isCreated + //$NON-NLS-1$
  1376. ", link=" //$NON-NLS-1$
  1377. + (link.isPresent() ? link.get().getFileName() + "]" //$NON-NLS-1$
  1378. : "<null>]"); //$NON-NLS-1$
  1379. }
  1380. }
  1381. /**
  1382. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  1383. * of this class may take care to provide a safe implementation for this
  1384. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  1385. *
  1386. * @param path
  1387. * the file to be created
  1388. * @return LockToken this token must be closed after the created file was
  1389. * deleted
  1390. * @throws IOException
  1391. * @since 4.7
  1392. */
  1393. public LockToken createNewFileAtomic(File path) throws IOException {
  1394. return new LockToken(path.createNewFile(), Optional.empty());
  1395. }
  1396. /**
  1397. * See
  1398. * {@link org.eclipse.jgit.util.FileUtils#relativizePath(String, String, String, boolean)}.
  1399. *
  1400. * @param base
  1401. * The path against which <code>other</code> should be
  1402. * relativized.
  1403. * @param other
  1404. * The path that will be made relative to <code>base</code>.
  1405. * @return A relative path that, when resolved against <code>base</code>,
  1406. * will yield the original <code>other</code>.
  1407. * @see FileUtils#relativizePath(String, String, String, boolean)
  1408. * @since 3.7
  1409. */
  1410. public String relativize(String base, String other) {
  1411. return FileUtils.relativizePath(base, other, File.separator, this.isCaseSensitive());
  1412. }
  1413. /**
  1414. * Enumerates children of a directory.
  1415. *
  1416. * @param directory
  1417. * to get the children of
  1418. * @param fileModeStrategy
  1419. * to use to calculate the git mode of a child
  1420. * @return an array of entries for the children
  1421. *
  1422. * @since 5.0
  1423. */
  1424. public Entry[] list(File directory, FileModeStrategy fileModeStrategy) {
  1425. final File[] all = directory.listFiles();
  1426. if (all == null) {
  1427. return NO_ENTRIES;
  1428. }
  1429. final Entry[] result = new Entry[all.length];
  1430. for (int i = 0; i < result.length; i++) {
  1431. result[i] = new FileEntry(all[i], this, fileModeStrategy);
  1432. }
  1433. return result;
  1434. }
  1435. /**
  1436. * Checks whether the given hook is defined for the given repository, then
  1437. * runs it with the given arguments.
  1438. * <p>
  1439. * The hook's standard output and error streams will be redirected to
  1440. * <code>System.out</code> and <code>System.err</code> respectively. The
  1441. * hook will have no stdin.
  1442. * </p>
  1443. *
  1444. * @param repository
  1445. * The repository for which a hook should be run.
  1446. * @param hookName
  1447. * The name of the hook to be executed.
  1448. * @param args
  1449. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1450. * but can be an empty array.
  1451. * @return The ProcessResult describing this hook's execution.
  1452. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1453. * if we fail to run the hook somehow. Causes may include an
  1454. * interrupted process or I/O errors.
  1455. * @since 4.0
  1456. */
  1457. public ProcessResult runHookIfPresent(Repository repository,
  1458. final String hookName,
  1459. String[] args) throws JGitInternalException {
  1460. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  1461. null);
  1462. }
  1463. /**
  1464. * Checks whether the given hook is defined for the given repository, then
  1465. * runs it with the given arguments.
  1466. *
  1467. * @param repository
  1468. * The repository for which a hook should be run.
  1469. * @param hookName
  1470. * The name of the hook to be executed.
  1471. * @param args
  1472. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1473. * but can be an empty array.
  1474. * @param outRedirect
  1475. * A print stream on which to redirect the hook's stdout. Can be
  1476. * <code>null</code>, in which case the hook's standard output
  1477. * will be lost.
  1478. * @param errRedirect
  1479. * A print stream on which to redirect the hook's stderr. Can be
  1480. * <code>null</code>, in which case the hook's standard error
  1481. * will be lost.
  1482. * @param stdinArgs
  1483. * A string to pass on to the standard input of the hook. May be
  1484. * <code>null</code>.
  1485. * @return The ProcessResult describing this hook's execution.
  1486. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1487. * if we fail to run the hook somehow. Causes may include an
  1488. * interrupted process or I/O errors.
  1489. * @since 4.0
  1490. */
  1491. public ProcessResult runHookIfPresent(Repository repository,
  1492. final String hookName,
  1493. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  1494. String stdinArgs) throws JGitInternalException {
  1495. return new ProcessResult(Status.NOT_SUPPORTED);
  1496. }
  1497. /**
  1498. * See
  1499. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  1500. * . Should only be called by FS supporting shell scripts execution.
  1501. *
  1502. * @param repository
  1503. * The repository for which a hook should be run.
  1504. * @param hookName
  1505. * The name of the hook to be executed.
  1506. * @param args
  1507. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1508. * but can be an empty array.
  1509. * @param outRedirect
  1510. * A print stream on which to redirect the hook's stdout. Can be
  1511. * <code>null</code>, in which case the hook's standard output
  1512. * will be lost.
  1513. * @param errRedirect
  1514. * A print stream on which to redirect the hook's stderr. Can be
  1515. * <code>null</code>, in which case the hook's standard error
  1516. * will be lost.
  1517. * @param stdinArgs
  1518. * A string to pass on to the standard input of the hook. May be
  1519. * <code>null</code>.
  1520. * @return The ProcessResult describing this hook's execution.
  1521. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1522. * if we fail to run the hook somehow. Causes may include an
  1523. * interrupted process or I/O errors.
  1524. * @since 4.0
  1525. */
  1526. protected ProcessResult internalRunHookIfPresent(Repository repository,
  1527. final String hookName, String[] args, PrintStream outRedirect,
  1528. PrintStream errRedirect, String stdinArgs)
  1529. throws JGitInternalException {
  1530. final File hookFile = findHook(repository, hookName);
  1531. if (hookFile == null)
  1532. return new ProcessResult(Status.NOT_PRESENT);
  1533. final String hookPath = hookFile.getAbsolutePath();
  1534. final File runDirectory;
  1535. if (repository.isBare())
  1536. runDirectory = repository.getDirectory();
  1537. else
  1538. runDirectory = repository.getWorkTree();
  1539. final String cmd = relativize(runDirectory.getAbsolutePath(),
  1540. hookPath);
  1541. ProcessBuilder hookProcess = runInShell(cmd, args);
  1542. hookProcess.directory(runDirectory);
  1543. try {
  1544. return new ProcessResult(runProcess(hookProcess, outRedirect,
  1545. errRedirect, stdinArgs), Status.OK);
  1546. } catch (IOException e) {
  1547. throw new JGitInternalException(MessageFormat.format(
  1548. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  1549. hookName), e);
  1550. } catch (InterruptedException e) {
  1551. throw new JGitInternalException(MessageFormat.format(
  1552. JGitText.get().exceptionHookExecutionInterrupted,
  1553. hookName), e);
  1554. }
  1555. }
  1556. /**
  1557. * Tries to find a hook matching the given one in the given repository.
  1558. *
  1559. * @param repository
  1560. * The repository within which to find a hook.
  1561. * @param hookName
  1562. * The name of the hook we're trying to find.
  1563. * @return The {@link java.io.File} containing this particular hook if it
  1564. * exists in the given repository, <code>null</code> otherwise.
  1565. * @since 4.0
  1566. */
  1567. public File findHook(Repository repository, String hookName) {
  1568. File gitDir = repository.getDirectory();
  1569. if (gitDir == null)
  1570. return null;
  1571. final File hookFile = new File(new File(gitDir,
  1572. Constants.HOOKS), hookName);
  1573. return hookFile.isFile() ? hookFile : null;
  1574. }
  1575. /**
  1576. * Runs the given process until termination, clearing its stdout and stderr
  1577. * streams on-the-fly.
  1578. *
  1579. * @param processBuilder
  1580. * The process builder configured for this process.
  1581. * @param outRedirect
  1582. * A OutputStream on which to redirect the processes stdout. Can
  1583. * be <code>null</code>, in which case the processes standard
  1584. * output will be lost.
  1585. * @param errRedirect
  1586. * A OutputStream on which to redirect the processes stderr. Can
  1587. * be <code>null</code>, in which case the processes standard
  1588. * error will be lost.
  1589. * @param stdinArgs
  1590. * A string to pass on to the standard input of the hook. Can be
  1591. * <code>null</code>.
  1592. * @return the exit value of this process.
  1593. * @throws java.io.IOException
  1594. * if an I/O error occurs while executing this process.
  1595. * @throws java.lang.InterruptedException
  1596. * if the current thread is interrupted while waiting for the
  1597. * process to end.
  1598. * @since 4.2
  1599. */
  1600. public int runProcess(ProcessBuilder processBuilder,
  1601. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  1602. throws IOException, InterruptedException {
  1603. InputStream in = (stdinArgs == null) ? null : new ByteArrayInputStream(
  1604. stdinArgs.getBytes(UTF_8));
  1605. return runProcess(processBuilder, outRedirect, errRedirect, in);
  1606. }
  1607. /**
  1608. * Runs the given process until termination, clearing its stdout and stderr
  1609. * streams on-the-fly.
  1610. *
  1611. * @param processBuilder
  1612. * The process builder configured for this process.
  1613. * @param outRedirect
  1614. * An OutputStream on which to redirect the processes stdout. Can
  1615. * be <code>null</code>, in which case the processes standard
  1616. * output will be lost.
  1617. * @param errRedirect
  1618. * An OutputStream on which to redirect the processes stderr. Can
  1619. * be <code>null</code>, in which case the processes standard
  1620. * error will be lost.
  1621. * @param inRedirect
  1622. * An InputStream from which to redirect the processes stdin. Can
  1623. * be <code>null</code>, in which case the process doesn't get
  1624. * any data over stdin. It is assumed that the whole InputStream
  1625. * will be consumed by the process. The method will close the
  1626. * inputstream after all bytes are read.
  1627. * @return the return code of this process.
  1628. * @throws java.io.IOException
  1629. * if an I/O error occurs while executing this process.
  1630. * @throws java.lang.InterruptedException
  1631. * if the current thread is interrupted while waiting for the
  1632. * process to end.
  1633. * @since 4.2
  1634. */
  1635. public int runProcess(ProcessBuilder processBuilder,
  1636. OutputStream outRedirect, OutputStream errRedirect,
  1637. InputStream inRedirect) throws IOException,
  1638. InterruptedException {
  1639. final ExecutorService executor = Executors.newFixedThreadPool(2);
  1640. Process process = null;
  1641. // We'll record the first I/O exception that occurs, but keep on trying
  1642. // to dispose of our open streams and file handles
  1643. IOException ioException = null;
  1644. try {
  1645. process = processBuilder.start();
  1646. executor.execute(
  1647. new StreamGobbler(process.getErrorStream(), errRedirect));
  1648. executor.execute(
  1649. new StreamGobbler(process.getInputStream(), outRedirect));
  1650. @SuppressWarnings("resource") // Closed in the finally block
  1651. OutputStream outputStream = process.getOutputStream();
  1652. try {
  1653. if (inRedirect != null) {
  1654. new StreamGobbler(inRedirect, outputStream).copy();
  1655. }
  1656. } finally {
  1657. try {
  1658. outputStream.close();
  1659. } catch (IOException e) {
  1660. // When the process exits before consuming the input, the OutputStream
  1661. // is replaced with the null output stream. This null output stream
  1662. // throws IOException for all write calls. When StreamGobbler fails to
  1663. // flush the buffer because of this, this close call tries to flush it
  1664. // again. This causes another IOException. Since we ignore the
  1665. // IOException in StreamGobbler, we also ignore the exception here.
  1666. }
  1667. }
  1668. return process.waitFor();
  1669. } catch (IOException e) {
  1670. ioException = e;
  1671. } finally {
  1672. shutdownAndAwaitTermination(executor);
  1673. if (process != null) {
  1674. try {
  1675. process.waitFor();
  1676. } catch (InterruptedException e) {
  1677. // Thrown by the outer try.
  1678. // Swallow this one to carry on our cleanup, and clear the
  1679. // interrupted flag (processes throw the exception without
  1680. // clearing the flag).
  1681. Thread.interrupted();
  1682. }
  1683. // A process doesn't clean its own resources even when destroyed
  1684. // Explicitly try and close all three streams, preserving the
  1685. // outer I/O exception if any.
  1686. if (inRedirect != null) {
  1687. inRedirect.close();
  1688. }
  1689. try {
  1690. process.getErrorStream().close();
  1691. } catch (IOException e) {
  1692. ioException = ioException != null ? ioException : e;
  1693. }
  1694. try {
  1695. process.getInputStream().close();
  1696. } catch (IOException e) {
  1697. ioException = ioException != null ? ioException : e;
  1698. }
  1699. try {
  1700. process.getOutputStream().close();
  1701. } catch (IOException e) {
  1702. ioException = ioException != null ? ioException : e;
  1703. }
  1704. process.destroy();
  1705. }
  1706. }
  1707. // We can only be here if the outer try threw an IOException.
  1708. throw ioException;
  1709. }
  1710. /**
  1711. * Shuts down an {@link ExecutorService} in two phases, first by calling
  1712. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  1713. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  1714. * necessary, to cancel any lingering tasks. Returns true if the pool has
  1715. * been properly shutdown, false otherwise.
  1716. * <p>
  1717. *
  1718. * @param pool
  1719. * the pool to shutdown
  1720. * @return <code>true</code> if the pool has been properly shutdown,
  1721. * <code>false</code> otherwise.
  1722. */
  1723. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  1724. boolean hasShutdown = true;
  1725. pool.shutdown(); // Disable new tasks from being submitted
  1726. try {
  1727. // Wait a while for existing tasks to terminate
  1728. if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
  1729. pool.shutdownNow(); // Cancel currently executing tasks
  1730. // Wait a while for tasks to respond to being canceled
  1731. if (!pool.awaitTermination(60, TimeUnit.SECONDS))
  1732. hasShutdown = false;
  1733. }
  1734. } catch (InterruptedException ie) {
  1735. // (Re-)Cancel if current thread also interrupted
  1736. pool.shutdownNow();
  1737. // Preserve interrupt status
  1738. Thread.currentThread().interrupt();
  1739. hasShutdown = false;
  1740. }
  1741. return hasShutdown;
  1742. }
  1743. /**
  1744. * Initialize a ProcessBuilder to run a command using the system shell.
  1745. *
  1746. * @param cmd
  1747. * command to execute. This string should originate from the
  1748. * end-user, and thus is platform specific.
  1749. * @param args
  1750. * arguments to pass to command. These should be protected from
  1751. * shell evaluation.
  1752. * @return a partially completed process builder. Caller should finish
  1753. * populating directory, environment, and then start the process.
  1754. */
  1755. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  1756. /**
  1757. * Execute a command defined by a {@link java.lang.ProcessBuilder}.
  1758. *
  1759. * @param pb
  1760. * The command to be executed
  1761. * @param in
  1762. * The standard input stream passed to the process
  1763. * @return The result of the executed command
  1764. * @throws java.lang.InterruptedException
  1765. * @throws java.io.IOException
  1766. * @since 4.2
  1767. */
  1768. public ExecutionResult execute(ProcessBuilder pb, InputStream in)
  1769. throws IOException, InterruptedException {
  1770. try (TemporaryBuffer stdout = new TemporaryBuffer.LocalFile(null);
  1771. TemporaryBuffer stderr = new TemporaryBuffer.Heap(1024,
  1772. 1024 * 1024)) {
  1773. int rc = runProcess(pb, stdout, stderr, in);
  1774. return new ExecutionResult(stdout, stderr, rc);
  1775. }
  1776. }
  1777. private static class Holder<V> {
  1778. final V value;
  1779. Holder(V value) {
  1780. this.value = value;
  1781. }
  1782. }
  1783. /**
  1784. * File attributes we typically care for.
  1785. *
  1786. * @since 3.3
  1787. */
  1788. public static class Attributes {
  1789. /**
  1790. * @return true if this are the attributes of a directory
  1791. */
  1792. public boolean isDirectory() {
  1793. return isDirectory;
  1794. }
  1795. /**
  1796. * @return true if this are the attributes of an executable file
  1797. */
  1798. public boolean isExecutable() {
  1799. return isExecutable;
  1800. }
  1801. /**
  1802. * @return true if this are the attributes of a symbolic link
  1803. */
  1804. public boolean isSymbolicLink() {
  1805. return isSymbolicLink;
  1806. }
  1807. /**
  1808. * @return true if this are the attributes of a regular file
  1809. */
  1810. public boolean isRegularFile() {
  1811. return isRegularFile;
  1812. }
  1813. /**
  1814. * @return the time when the file was created
  1815. */
  1816. public long getCreationTime() {
  1817. return creationTime;
  1818. }
  1819. /**
  1820. * @return the time (milliseconds since 1970-01-01) when this object was
  1821. * last modified
  1822. * @deprecated use getLastModifiedInstant instead
  1823. */
  1824. @Deprecated
  1825. public long getLastModifiedTime() {
  1826. return lastModifiedInstant.toEpochMilli();
  1827. }
  1828. /**
  1829. * @return the time when this object was last modified
  1830. * @since 5.1.9
  1831. */
  1832. public Instant getLastModifiedInstant() {
  1833. return lastModifiedInstant;
  1834. }
  1835. private final boolean isDirectory;
  1836. private final boolean isSymbolicLink;
  1837. private final boolean isRegularFile;
  1838. private final long creationTime;
  1839. private final Instant lastModifiedInstant;
  1840. private final boolean isExecutable;
  1841. private final File file;
  1842. private final boolean exists;
  1843. /**
  1844. * file length
  1845. */
  1846. protected long length = -1;
  1847. final FS fs;
  1848. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  1849. boolean isExecutable, boolean isSymbolicLink,
  1850. boolean isRegularFile, long creationTime,
  1851. Instant lastModifiedInstant, long length) {
  1852. this.fs = fs;
  1853. this.file = file;
  1854. this.exists = exists;
  1855. this.isDirectory = isDirectory;
  1856. this.isExecutable = isExecutable;
  1857. this.isSymbolicLink = isSymbolicLink;
  1858. this.isRegularFile = isRegularFile;
  1859. this.creationTime = creationTime;
  1860. this.lastModifiedInstant = lastModifiedInstant;
  1861. this.length = length;
  1862. }
  1863. /**
  1864. * Constructor when there are issues with reading. All attributes except
  1865. * given will be set to the default values.
  1866. *
  1867. * @param fs
  1868. * @param path
  1869. */
  1870. public Attributes(File path, FS fs) {
  1871. this(fs, path, false, false, false, false, false, 0L, EPOCH, 0L);
  1872. }
  1873. /**
  1874. * @return length of this file object
  1875. */
  1876. public long getLength() {
  1877. if (length == -1)
  1878. return length = file.length();
  1879. return length;
  1880. }
  1881. /**
  1882. * @return the filename
  1883. */
  1884. public String getName() {
  1885. return file.getName();
  1886. }
  1887. /**
  1888. * @return the file the attributes apply to
  1889. */
  1890. public File getFile() {
  1891. return file;
  1892. }
  1893. boolean exists() {
  1894. return exists;
  1895. }
  1896. }
  1897. /**
  1898. * Get the file attributes we care for.
  1899. *
  1900. * @param path
  1901. * a {@link java.io.File} object.
  1902. * @return the file attributes we care for.
  1903. * @since 3.3
  1904. */
  1905. public Attributes getAttributes(File path) {
  1906. boolean isDirectory = isDirectory(path);
  1907. boolean isFile = !isDirectory && path.isFile();
  1908. assert path.exists() == isDirectory || isFile;
  1909. boolean exists = isDirectory || isFile;
  1910. boolean canExecute = exists && !isDirectory && canExecute(path);
  1911. boolean isSymlink = false;
  1912. Instant lastModified = exists ? lastModifiedInstant(path) : EPOCH;
  1913. long createTime = 0L;
  1914. return new Attributes(this, path, exists, isDirectory, canExecute,
  1915. isSymlink, isFile, createTime, lastModified, -1);
  1916. }
  1917. /**
  1918. * Normalize the unicode path to composed form.
  1919. *
  1920. * @param file
  1921. * a {@link java.io.File} object.
  1922. * @return NFC-format File
  1923. * @since 3.3
  1924. */
  1925. public File normalize(File file) {
  1926. return file;
  1927. }
  1928. /**
  1929. * Normalize the unicode path to composed form.
  1930. *
  1931. * @param name
  1932. * path name
  1933. * @return NFC-format string
  1934. * @since 3.3
  1935. */
  1936. public String normalize(String name) {
  1937. return name;
  1938. }
  1939. /**
  1940. * This runnable will consume an input stream's content into an output
  1941. * stream as soon as it gets available.
  1942. * <p>
  1943. * Typically used to empty processes' standard output and error, preventing
  1944. * them to choke.
  1945. * </p>
  1946. * <p>
  1947. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1948. * streams.
  1949. * </p>
  1950. */
  1951. private static class StreamGobbler implements Runnable {
  1952. private InputStream in;
  1953. private OutputStream out;
  1954. public StreamGobbler(InputStream stream, OutputStream output) {
  1955. this.in = stream;
  1956. this.out = output;
  1957. }
  1958. @Override
  1959. public void run() {
  1960. try {
  1961. copy();
  1962. } catch (IOException e) {
  1963. // Do nothing on read failure; leave streams open.
  1964. }
  1965. }
  1966. void copy() throws IOException {
  1967. boolean writeFailure = false;
  1968. byte buffer[] = new byte[4096];
  1969. int readBytes;
  1970. while ((readBytes = in.read(buffer)) != -1) {
  1971. // Do not try to write again after a failure, but keep
  1972. // reading as long as possible to prevent the input stream
  1973. // from choking.
  1974. if (!writeFailure && out != null) {
  1975. try {
  1976. out.write(buffer, 0, readBytes);
  1977. out.flush();
  1978. } catch (IOException e) {
  1979. writeFailure = true;
  1980. }
  1981. }
  1982. }
  1983. }
  1984. }
  1985. }