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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 org.eclipse.jgit.errors.ConfigInvalidException;
  58. import org.eclipse.jgit.errors.CorruptObjectException;
  59. import org.eclipse.jgit.lib.Config;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.ObjectChecker;
  62. import org.eclipse.jgit.lib.StoredConfig;
  63. import org.eclipse.jgit.storage.file.FileBasedConfig;
  64. import org.eclipse.jgit.util.time.MonotonicClock;
  65. import org.eclipse.jgit.util.time.MonotonicSystemClock;
  66. import org.slf4j.Logger;
  67. import org.slf4j.LoggerFactory;
  68. /**
  69. * Interface to read values from the system.
  70. * <p>
  71. * When writing unit tests, extending this interface with a custom class
  72. * permits to simulate an access to a system variable or property and
  73. * permits to control the user's global configuration.
  74. * </p>
  75. */
  76. public abstract class SystemReader {
  77. private final static Logger LOG = LoggerFactory
  78. .getLogger(SystemReader.class);
  79. private static final SystemReader DEFAULT;
  80. private static Boolean isMacOS;
  81. private static Boolean isWindows;
  82. static {
  83. SystemReader r = new Default();
  84. r.init();
  85. DEFAULT = r;
  86. }
  87. private static class Default extends SystemReader {
  88. private volatile String hostname;
  89. private volatile FileBasedConfig systemConfig;
  90. private volatile FileBasedConfig userConfig;
  91. @Override
  92. public String getenv(String variable) {
  93. return System.getenv(variable);
  94. }
  95. @Override
  96. public String getProperty(String key) {
  97. return System.getProperty(key);
  98. }
  99. @Override
  100. public FileBasedConfig openSystemConfig(Config parent, FS fs) {
  101. if (systemConfig == null) {
  102. systemConfig = createSystemConfig(parent, fs);
  103. }
  104. return systemConfig;
  105. }
  106. protected FileBasedConfig createSystemConfig(Config parent, FS fs) {
  107. if (StringUtils.isEmptyOrNull(getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
  108. File configFile = fs.getGitSystemConfig();
  109. if (configFile != null) {
  110. return new FileBasedConfig(parent, configFile, fs);
  111. }
  112. }
  113. return new FileBasedConfig(null, fs) {
  114. @Override
  115. public void load() {
  116. // empty, do not load
  117. }
  118. @Override
  119. public boolean isOutdated() {
  120. // regular class would bomb here
  121. return false;
  122. }
  123. };
  124. }
  125. @Override
  126. public FileBasedConfig openUserConfig(Config parent, FS fs) {
  127. if (userConfig == null) {
  128. File home = fs.userHome();
  129. userConfig = new FileBasedConfig(parent,
  130. new File(home, ".gitconfig"), fs); //$NON-NLS-1$
  131. }
  132. return userConfig;
  133. }
  134. @Override
  135. public StoredConfig getSystemConfig()
  136. throws IOException, ConfigInvalidException {
  137. if (systemConfig == null) {
  138. systemConfig = createSystemConfig(null, FS.DETECTED);
  139. }
  140. if (systemConfig.isOutdated()) {
  141. LOG.debug("loading system config {}", systemConfig); //$NON-NLS-1$
  142. systemConfig.load();
  143. }
  144. return systemConfig;
  145. }
  146. @Override
  147. public StoredConfig getUserConfig()
  148. throws IOException, ConfigInvalidException {
  149. if (userConfig == null) {
  150. userConfig = openUserConfig(getSystemConfig(), FS.DETECTED);
  151. } else {
  152. getSystemConfig();
  153. }
  154. if (userConfig.isOutdated()) {
  155. LOG.debug("loading user config {}", userConfig); //$NON-NLS-1$
  156. userConfig.load();
  157. }
  158. return userConfig;
  159. }
  160. @Override
  161. public String getHostname() {
  162. if (hostname == null) {
  163. try {
  164. InetAddress localMachine = InetAddress.getLocalHost();
  165. hostname = localMachine.getCanonicalHostName();
  166. } catch (UnknownHostException e) {
  167. // we do nothing
  168. hostname = "localhost"; //$NON-NLS-1$
  169. }
  170. assert hostname != null;
  171. }
  172. return hostname;
  173. }
  174. @Override
  175. public long getCurrentTime() {
  176. return System.currentTimeMillis();
  177. }
  178. @Override
  179. public int getTimezone(long when) {
  180. return getTimeZone().getOffset(when) / (60 * 1000);
  181. }
  182. }
  183. private static volatile SystemReader INSTANCE = DEFAULT;
  184. /**
  185. * Get the current SystemReader instance
  186. *
  187. * @return the current SystemReader instance.
  188. */
  189. public static SystemReader getInstance() {
  190. return INSTANCE;
  191. }
  192. /**
  193. * Set a new SystemReader instance to use when accessing properties.
  194. *
  195. * @param newReader
  196. * the new instance to use when accessing properties, or null for
  197. * the default instance.
  198. */
  199. public static void setInstance(SystemReader newReader) {
  200. isMacOS = null;
  201. isWindows = null;
  202. if (newReader == null)
  203. INSTANCE = DEFAULT;
  204. else {
  205. newReader.init();
  206. INSTANCE = newReader;
  207. }
  208. }
  209. private ObjectChecker platformChecker;
  210. private void init() {
  211. // Creating ObjectChecker must be deferred. Unit tests change
  212. // behavior of is{Windows,MacOS} in constructor of subclass.
  213. if (platformChecker == null)
  214. setPlatformChecker();
  215. }
  216. /**
  217. * Should be used in tests when the platform is explicitly changed.
  218. *
  219. * @since 3.6
  220. */
  221. protected final void setPlatformChecker() {
  222. platformChecker = new ObjectChecker()
  223. .setSafeForWindows(isWindows())
  224. .setSafeForMacOS(isMacOS());
  225. }
  226. /**
  227. * Gets the hostname of the local host. If no hostname can be found, the
  228. * hostname is set to the default value "localhost".
  229. *
  230. * @return the canonical hostname
  231. */
  232. public abstract String getHostname();
  233. /**
  234. * Get value of the system variable
  235. *
  236. * @param variable
  237. * system variable to read
  238. * @return value of the system variable
  239. */
  240. public abstract String getenv(String variable);
  241. /**
  242. * Get value of the system property
  243. *
  244. * @param key
  245. * of the system property to read
  246. * @return value of the system property
  247. */
  248. public abstract String getProperty(String key);
  249. /**
  250. * Open the git configuration found in the user home. Use
  251. * {@link #getUserConfig()} to get the current git configuration in the user
  252. * home since it manages automatic reloading when the gitconfig file was
  253. * modified and avoids unnecessary reloads.
  254. *
  255. * @param parent
  256. * a config with values not found directly in the returned config
  257. * @param fs
  258. * the file system abstraction which will be necessary to perform
  259. * certain file system operations.
  260. * @return the git configuration found in the user home
  261. */
  262. public abstract FileBasedConfig openUserConfig(Config parent, FS fs);
  263. /**
  264. * Open the gitconfig configuration found in the system-wide "etc"
  265. * directory. Use {@link #getSystemConfig()} to get the current system-wide
  266. * git configuration since it manages automatic reloading when the gitconfig
  267. * file was modified and avoids unnecessary reloads.
  268. *
  269. * @param parent
  270. * a config with values not found directly in the returned
  271. * config. Null is a reasonable value here.
  272. * @param fs
  273. * the file system abstraction which will be necessary to perform
  274. * certain file system operations.
  275. * @return the gitconfig configuration found in the system-wide "etc"
  276. * directory
  277. */
  278. public abstract FileBasedConfig openSystemConfig(Config parent, FS fs);
  279. /**
  280. * Get the git configuration found in the user home. The configuration will
  281. * be reloaded automatically if the configuration file was modified. Also
  282. * reloads the system config if the system config file was modified. If the
  283. * configuration file wasn't modified returns the cached configuration.
  284. *
  285. * @return the git configuration found in the user home
  286. * @throws ConfigInvalidException
  287. * if configuration is invalid
  288. * @throws IOException
  289. * if something went wrong when reading files
  290. * @since 5.1.9
  291. */
  292. public abstract StoredConfig getUserConfig()
  293. throws IOException, ConfigInvalidException;
  294. /**
  295. * Get the gitconfig configuration found in the system-wide "etc" directory.
  296. * The configuration will be reloaded automatically if the configuration
  297. * file was modified otherwise returns the cached system level config.
  298. *
  299. * @return the gitconfig configuration found in the system-wide "etc"
  300. * directory
  301. * @throws ConfigInvalidException
  302. * if configuration is invalid
  303. * @throws IOException
  304. * if something went wrong when reading files
  305. * @since 5.1.9
  306. */
  307. public abstract StoredConfig getSystemConfig()
  308. throws IOException, ConfigInvalidException;
  309. /**
  310. * Get the current system time
  311. *
  312. * @return the current system time
  313. */
  314. public abstract long getCurrentTime();
  315. /**
  316. * Get clock instance preferred by this system.
  317. *
  318. * @return clock instance preferred by this system.
  319. * @since 4.6
  320. */
  321. public MonotonicClock getClock() {
  322. return new MonotonicSystemClock();
  323. }
  324. /**
  325. * Get the local time zone
  326. *
  327. * @param when
  328. * a system timestamp
  329. * @return the local time zone
  330. */
  331. public abstract int getTimezone(long when);
  332. /**
  333. * Get system time zone, possibly mocked for testing
  334. *
  335. * @return system time zone, possibly mocked for testing
  336. * @since 1.2
  337. */
  338. public TimeZone getTimeZone() {
  339. return TimeZone.getDefault();
  340. }
  341. /**
  342. * Get the locale to use
  343. *
  344. * @return the locale to use
  345. * @since 1.2
  346. */
  347. public Locale getLocale() {
  348. return Locale.getDefault();
  349. }
  350. /**
  351. * Returns a simple date format instance as specified by the given pattern.
  352. *
  353. * @param pattern
  354. * the pattern as defined in
  355. * {@link java.text.SimpleDateFormat#SimpleDateFormat(String)}
  356. * @return the simple date format
  357. * @since 2.0
  358. */
  359. public SimpleDateFormat getSimpleDateFormat(String pattern) {
  360. return new SimpleDateFormat(pattern);
  361. }
  362. /**
  363. * Returns a simple date format instance as specified by the given pattern.
  364. *
  365. * @param pattern
  366. * the pattern as defined in
  367. * {@link java.text.SimpleDateFormat#SimpleDateFormat(String)}
  368. * @param locale
  369. * locale to be used for the {@code SimpleDateFormat}
  370. * @return the simple date format
  371. * @since 3.2
  372. */
  373. public SimpleDateFormat getSimpleDateFormat(String pattern, Locale locale) {
  374. return new SimpleDateFormat(pattern, locale);
  375. }
  376. /**
  377. * Returns a date/time format instance for the given styles.
  378. *
  379. * @param dateStyle
  380. * the date style as specified in
  381. * {@link java.text.DateFormat#getDateTimeInstance(int, int)}
  382. * @param timeStyle
  383. * the time style as specified in
  384. * {@link java.text.DateFormat#getDateTimeInstance(int, int)}
  385. * @return the date format
  386. * @since 2.0
  387. */
  388. public DateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
  389. return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
  390. }
  391. /**
  392. * Whether we are running on Windows.
  393. *
  394. * @return true if we are running on Windows.
  395. */
  396. public boolean isWindows() {
  397. if (isWindows == null) {
  398. String osDotName = getOsName();
  399. isWindows = Boolean.valueOf(osDotName.startsWith("Windows")); //$NON-NLS-1$
  400. }
  401. return isWindows.booleanValue();
  402. }
  403. /**
  404. * Whether we are running on Mac OS X
  405. *
  406. * @return true if we are running on Mac OS X
  407. */
  408. public boolean isMacOS() {
  409. if (isMacOS == null) {
  410. String osDotName = getOsName();
  411. isMacOS = Boolean.valueOf(
  412. "Mac OS X".equals(osDotName) || "Darwin".equals(osDotName)); //$NON-NLS-1$ //$NON-NLS-2$
  413. }
  414. return isMacOS.booleanValue();
  415. }
  416. private String getOsName() {
  417. return AccessController.doPrivileged(
  418. (PrivilegedAction<String>) () -> getProperty("os.name") //$NON-NLS-1$
  419. );
  420. }
  421. /**
  422. * Check tree path entry for validity.
  423. * <p>
  424. * Scans a multi-directory path string such as {@code "src/main.c"}.
  425. *
  426. * @param path path string to scan.
  427. * @throws org.eclipse.jgit.errors.CorruptObjectException path is invalid.
  428. * @since 3.6
  429. */
  430. public void checkPath(String path) throws CorruptObjectException {
  431. platformChecker.checkPath(path);
  432. }
  433. /**
  434. * Check tree path entry for validity.
  435. * <p>
  436. * Scans a multi-directory path string such as {@code "src/main.c"}.
  437. *
  438. * @param path
  439. * path string to scan.
  440. * @throws org.eclipse.jgit.errors.CorruptObjectException
  441. * path is invalid.
  442. * @since 4.2
  443. */
  444. public void checkPath(byte[] path) throws CorruptObjectException {
  445. platformChecker.checkPath(path, 0, path.length);
  446. }
  447. }