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.

SystemReader.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * Copyright (C) 2009, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2009, Yann Simon <yann.simon.fr@gmail.com>
  5. * Copyright (C) 2012, Daniel Megert <daniel_megert@ch.ibm.com>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.util;
  47. import java.io.File;
  48. import java.io.IOException;
  49. import java.net.InetAddress;
  50. import java.net.UnknownHostException;
  51. import java.security.AccessController;
  52. import java.security.PrivilegedAction;
  53. import java.text.DateFormat;
  54. import java.text.SimpleDateFormat;
  55. import java.util.Locale;
  56. import java.util.TimeZone;
  57. import java.util.concurrent.atomic.AtomicReference;
  58. import org.eclipse.jgit.errors.ConfigInvalidException;
  59. import org.eclipse.jgit.errors.CorruptObjectException;
  60. import org.eclipse.jgit.lib.Config;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.ObjectChecker;
  63. import org.eclipse.jgit.lib.StoredConfig;
  64. import org.eclipse.jgit.storage.file.FileBasedConfig;
  65. import org.eclipse.jgit.util.time.MonotonicClock;
  66. import org.eclipse.jgit.util.time.MonotonicSystemClock;
  67. import org.slf4j.Logger;
  68. import org.slf4j.LoggerFactory;
  69. /**
  70. * Interface to read values from the system.
  71. * <p>
  72. * When writing unit tests, extending this interface with a custom class
  73. * permits to simulate an access to a system variable or property and
  74. * permits to control the user's global configuration.
  75. * </p>
  76. */
  77. public abstract class SystemReader {
  78. private final static Logger LOG = LoggerFactory
  79. .getLogger(SystemReader.class);
  80. private static final SystemReader DEFAULT;
  81. private static Boolean isMacOS;
  82. private static Boolean isWindows;
  83. static {
  84. SystemReader r = new Default();
  85. r.init();
  86. DEFAULT = r;
  87. }
  88. private static class Default extends SystemReader {
  89. private volatile String hostname;
  90. @Override
  91. public String getenv(String variable) {
  92. return System.getenv(variable);
  93. }
  94. @Override
  95. public String getProperty(String key) {
  96. return System.getProperty(key);
  97. }
  98. @Override
  99. public FileBasedConfig openSystemConfig(Config parent, FS fs) {
  100. if (StringUtils
  101. .isEmptyOrNull(getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
  102. File configFile = fs.getGitSystemConfig();
  103. if (configFile != null) {
  104. return new FileBasedConfig(parent, configFile, fs);
  105. }
  106. }
  107. return new FileBasedConfig(parent, null, fs) {
  108. @Override
  109. public void load() {
  110. // empty, do not load
  111. }
  112. @Override
  113. public boolean isOutdated() {
  114. // regular class would bomb here
  115. return false;
  116. }
  117. };
  118. }
  119. @Override
  120. public FileBasedConfig openUserConfig(Config parent, FS fs) {
  121. return new FileBasedConfig(parent, new File(fs.userHome(), ".gitconfig"), //$NON-NLS-1$
  122. fs);
  123. }
  124. @Override
  125. public String getHostname() {
  126. if (hostname == null) {
  127. try {
  128. InetAddress localMachine = InetAddress.getLocalHost();
  129. hostname = localMachine.getCanonicalHostName();
  130. } catch (UnknownHostException e) {
  131. // we do nothing
  132. hostname = "localhost"; //$NON-NLS-1$
  133. }
  134. assert hostname != null;
  135. }
  136. return hostname;
  137. }
  138. @Override
  139. public long getCurrentTime() {
  140. return System.currentTimeMillis();
  141. }
  142. @Override
  143. public int getTimezone(long when) {
  144. return getTimeZone().getOffset(when) / (60 * 1000);
  145. }
  146. }
  147. private static volatile SystemReader INSTANCE = DEFAULT;
  148. /**
  149. * Get the current SystemReader instance
  150. *
  151. * @return the current SystemReader instance.
  152. */
  153. public static SystemReader getInstance() {
  154. return INSTANCE;
  155. }
  156. /**
  157. * Set a new SystemReader instance to use when accessing properties.
  158. *
  159. * @param newReader
  160. * the new instance to use when accessing properties, or null for
  161. * the default instance.
  162. */
  163. public static void setInstance(SystemReader newReader) {
  164. isMacOS = null;
  165. isWindows = null;
  166. if (newReader == null)
  167. INSTANCE = DEFAULT;
  168. else {
  169. newReader.init();
  170. INSTANCE = newReader;
  171. }
  172. }
  173. private ObjectChecker platformChecker;
  174. private AtomicReference<FileBasedConfig> systemConfig = new AtomicReference<>();
  175. private AtomicReference<FileBasedConfig> userConfig = new AtomicReference<>();
  176. private void init() {
  177. // Creating ObjectChecker must be deferred. Unit tests change
  178. // behavior of is{Windows,MacOS} in constructor of subclass.
  179. if (platformChecker == null)
  180. setPlatformChecker();
  181. }
  182. /**
  183. * Should be used in tests when the platform is explicitly changed.
  184. *
  185. * @since 3.6
  186. */
  187. protected final void setPlatformChecker() {
  188. platformChecker = new ObjectChecker()
  189. .setSafeForWindows(isWindows())
  190. .setSafeForMacOS(isMacOS());
  191. }
  192. /**
  193. * Gets the hostname of the local host. If no hostname can be found, the
  194. * hostname is set to the default value "localhost".
  195. *
  196. * @return the canonical hostname
  197. */
  198. public abstract String getHostname();
  199. /**
  200. * Get value of the system variable
  201. *
  202. * @param variable
  203. * system variable to read
  204. * @return value of the system variable
  205. */
  206. public abstract String getenv(String variable);
  207. /**
  208. * Get value of the system property
  209. *
  210. * @param key
  211. * of the system property to read
  212. * @return value of the system property
  213. */
  214. public abstract String getProperty(String key);
  215. /**
  216. * Open the git configuration found in the user home. Use
  217. * {@link #getUserConfig()} to get the current git configuration in the user
  218. * home since it manages automatic reloading when the gitconfig file was
  219. * modified and avoids unnecessary reloads.
  220. *
  221. * @param parent
  222. * a config with values not found directly in the returned config
  223. * @param fs
  224. * the file system abstraction which will be necessary to perform
  225. * certain file system operations.
  226. * @return the git configuration found in the user home
  227. */
  228. public abstract FileBasedConfig openUserConfig(Config parent, FS fs);
  229. /**
  230. * Open the gitconfig configuration found in the system-wide "etc"
  231. * directory. Use {@link #getSystemConfig()} to get the current system-wide
  232. * git configuration since it manages automatic reloading when the gitconfig
  233. * file was modified and avoids unnecessary reloads.
  234. *
  235. * @param parent
  236. * a config with values not found directly in the returned
  237. * config. Null is a reasonable value here.
  238. * @param fs
  239. * the file system abstraction which will be necessary to perform
  240. * certain file system operations.
  241. * @return the gitconfig configuration found in the system-wide "etc"
  242. * directory
  243. */
  244. public abstract FileBasedConfig openSystemConfig(Config parent, FS fs);
  245. /**
  246. * Get the git configuration found in the user home. The configuration will
  247. * be reloaded automatically if the configuration file was modified. Also
  248. * reloads the system config if the system config file was modified. If the
  249. * configuration file wasn't modified returns the cached configuration.
  250. *
  251. * @return the git configuration found in the user home
  252. * @throws ConfigInvalidException
  253. * if configuration is invalid
  254. * @throws IOException
  255. * if something went wrong when reading files
  256. * @since 5.1.9
  257. */
  258. public StoredConfig getUserConfig()
  259. throws IOException, ConfigInvalidException {
  260. FileBasedConfig c = userConfig.get();
  261. if (c == null) {
  262. userConfig.compareAndSet(null,
  263. openUserConfig(getSystemConfig(), FS.DETECTED));
  264. c = userConfig.get();
  265. } else {
  266. // Ensure the parent is up to date
  267. getSystemConfig();
  268. }
  269. if (c.isOutdated()) {
  270. LOG.debug("loading user config {}", userConfig); //$NON-NLS-1$
  271. c.load();
  272. }
  273. return c;
  274. }
  275. /**
  276. * Get the gitconfig configuration found in the system-wide "etc" directory.
  277. * The configuration will be reloaded automatically if the configuration
  278. * file was modified otherwise returns the cached system level config.
  279. *
  280. * @return the gitconfig configuration found in the system-wide "etc"
  281. * directory
  282. * @throws ConfigInvalidException
  283. * if configuration is invalid
  284. * @throws IOException
  285. * if something went wrong when reading files
  286. * @since 5.1.9
  287. */
  288. public StoredConfig getSystemConfig()
  289. throws IOException, ConfigInvalidException {
  290. FileBasedConfig c = systemConfig.get();
  291. if (c == null) {
  292. systemConfig.compareAndSet(null,
  293. openSystemConfig(null, FS.DETECTED));
  294. c = systemConfig.get();
  295. }
  296. if (c.isOutdated()) {
  297. LOG.debug("loading system config {}", systemConfig); //$NON-NLS-1$
  298. c.load();
  299. }
  300. return c;
  301. }
  302. /**
  303. * Get the current system time
  304. *
  305. * @return the current system time
  306. */
  307. public abstract long getCurrentTime();
  308. /**
  309. * Get clock instance preferred by this system.
  310. *
  311. * @return clock instance preferred by this system.
  312. * @since 4.6
  313. */
  314. public MonotonicClock getClock() {
  315. return new MonotonicSystemClock();
  316. }
  317. /**
  318. * Get the local time zone
  319. *
  320. * @param when
  321. * a system timestamp
  322. * @return the local time zone
  323. */
  324. public abstract int getTimezone(long when);
  325. /**
  326. * Get system time zone, possibly mocked for testing
  327. *
  328. * @return system time zone, possibly mocked for testing
  329. * @since 1.2
  330. */
  331. public TimeZone getTimeZone() {
  332. return TimeZone.getDefault();
  333. }
  334. /**
  335. * Get the locale to use
  336. *
  337. * @return the locale to use
  338. * @since 1.2
  339. */
  340. public Locale getLocale() {
  341. return Locale.getDefault();
  342. }
  343. /**
  344. * Returns a simple date format instance as specified by the given pattern.
  345. *
  346. * @param pattern
  347. * the pattern as defined in
  348. * {@link java.text.SimpleDateFormat#SimpleDateFormat(String)}
  349. * @return the simple date format
  350. * @since 2.0
  351. */
  352. public SimpleDateFormat getSimpleDateFormat(String pattern) {
  353. return new SimpleDateFormat(pattern);
  354. }
  355. /**
  356. * Returns a simple date format instance as specified by the given pattern.
  357. *
  358. * @param pattern
  359. * the pattern as defined in
  360. * {@link java.text.SimpleDateFormat#SimpleDateFormat(String)}
  361. * @param locale
  362. * locale to be used for the {@code SimpleDateFormat}
  363. * @return the simple date format
  364. * @since 3.2
  365. */
  366. public SimpleDateFormat getSimpleDateFormat(String pattern, Locale locale) {
  367. return new SimpleDateFormat(pattern, locale);
  368. }
  369. /**
  370. * Returns a date/time format instance for the given styles.
  371. *
  372. * @param dateStyle
  373. * the date style as specified in
  374. * {@link java.text.DateFormat#getDateTimeInstance(int, int)}
  375. * @param timeStyle
  376. * the time style as specified in
  377. * {@link java.text.DateFormat#getDateTimeInstance(int, int)}
  378. * @return the date format
  379. * @since 2.0
  380. */
  381. public DateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
  382. return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
  383. }
  384. /**
  385. * Whether we are running on Windows.
  386. *
  387. * @return true if we are running on Windows.
  388. */
  389. public boolean isWindows() {
  390. if (isWindows == null) {
  391. String osDotName = getOsName();
  392. isWindows = Boolean.valueOf(osDotName.startsWith("Windows")); //$NON-NLS-1$
  393. }
  394. return isWindows.booleanValue();
  395. }
  396. /**
  397. * Whether we are running on Mac OS X
  398. *
  399. * @return true if we are running on Mac OS X
  400. */
  401. public boolean isMacOS() {
  402. if (isMacOS == null) {
  403. String osDotName = getOsName();
  404. isMacOS = Boolean.valueOf(
  405. "Mac OS X".equals(osDotName) || "Darwin".equals(osDotName)); //$NON-NLS-1$ //$NON-NLS-2$
  406. }
  407. return isMacOS.booleanValue();
  408. }
  409. private String getOsName() {
  410. return AccessController.doPrivileged(new PrivilegedAction<String>() {
  411. @Override
  412. public String run() {
  413. return getProperty("os.name"); //$NON-NLS-1$
  414. }
  415. });
  416. }
  417. /**
  418. * Check tree path entry for validity.
  419. * <p>
  420. * Scans a multi-directory path string such as {@code "src/main.c"}.
  421. *
  422. * @param path path string to scan.
  423. * @throws org.eclipse.jgit.errors.CorruptObjectException path is invalid.
  424. * @since 3.6
  425. */
  426. public void checkPath(String path) throws CorruptObjectException {
  427. platformChecker.checkPath(path);
  428. }
  429. /**
  430. * Check tree path entry for validity.
  431. * <p>
  432. * Scans a multi-directory path string such as {@code "src/main.c"}.
  433. *
  434. * @param path
  435. * path string to scan.
  436. * @throws org.eclipse.jgit.errors.CorruptObjectException
  437. * path is invalid.
  438. * @since 4.2
  439. */
  440. public void checkPath(byte[] path) throws CorruptObjectException {
  441. platformChecker.checkPath(path, 0, path.length);
  442. }
  443. }