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.

Config.java 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  1. /*
  2. * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
  3. * Copyright (C) 2009, Constantine Plotnikov <constantine.plotnikov@gmail.com>
  4. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  5. * Copyright (C) 2008-2010, Google Inc.
  6. * Copyright (C) 2009, Google, Inc.
  7. * Copyright (C) 2009, JetBrains s.r.o.
  8. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  9. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  10. * Copyright (C) 2008, Thad Hughes <thadh@thad.corp.google.com>
  11. * and other copyright owners as documented in the project's IP log.
  12. *
  13. * This program and the accompanying materials are made available
  14. * under the terms of the Eclipse Distribution License v1.0 which
  15. * accompanies this distribution, is reproduced below, and is
  16. * available at http://www.eclipse.org/org/documents/edl-v10.php
  17. *
  18. * All rights reserved.
  19. *
  20. * Redistribution and use in source and binary forms, with or
  21. * without modification, are permitted provided that the following
  22. * conditions are met:
  23. *
  24. * - Redistributions of source code must retain the above copyright
  25. * notice, this list of conditions and the following disclaimer.
  26. *
  27. * - Redistributions in binary form must reproduce the above
  28. * copyright notice, this list of conditions and the following
  29. * disclaimer in the documentation and/or other materials provided
  30. * with the distribution.
  31. *
  32. * - Neither the name of the Eclipse Foundation, Inc. nor the
  33. * names of its contributors may be used to endorse or promote
  34. * products derived from this software without specific prior
  35. * written permission.
  36. *
  37. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  38. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  39. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  40. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  41. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  42. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  43. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  44. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  45. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  46. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  47. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  48. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  49. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  50. */
  51. package org.eclipse.jgit.lib;
  52. import java.text.MessageFormat;
  53. import java.util.ArrayList;
  54. import java.util.Collections;
  55. import java.util.List;
  56. import java.util.Set;
  57. import java.util.concurrent.atomic.AtomicReference;
  58. import org.eclipse.jgit.errors.ConfigInvalidException;
  59. import org.eclipse.jgit.events.ConfigChangedEvent;
  60. import org.eclipse.jgit.events.ConfigChangedListener;
  61. import org.eclipse.jgit.events.ListenerHandle;
  62. import org.eclipse.jgit.events.ListenerList;
  63. import org.eclipse.jgit.internal.JGitText;
  64. import org.eclipse.jgit.util.StringUtils;
  65. /**
  66. * Git style {@code .config}, {@code .gitconfig}, {@code .gitmodules} file.
  67. */
  68. public class Config {
  69. private static final String[] EMPTY_STRING_ARRAY = {};
  70. private static final long KiB = 1024;
  71. private static final long MiB = 1024 * KiB;
  72. private static final long GiB = 1024 * MiB;
  73. /** the change listeners */
  74. private final ListenerList listeners = new ListenerList();
  75. /**
  76. * Immutable current state of the configuration data.
  77. * <p>
  78. * This state is copy-on-write. It should always contain an immutable list
  79. * of the configuration keys/values.
  80. */
  81. private final AtomicReference<ConfigSnapshot> state;
  82. private final Config baseConfig;
  83. /**
  84. * Magic value indicating a missing entry.
  85. * <p>
  86. * This value is tested for reference equality in some contexts, so we
  87. * must ensure it is a special copy of the empty string. It also must
  88. * be treated like the empty string.
  89. */
  90. private static final String MAGIC_EMPTY_VALUE = new String();
  91. /** Create a configuration with no default fallback. */
  92. public Config() {
  93. this(null);
  94. }
  95. /**
  96. * Create an empty configuration with a fallback for missing keys.
  97. *
  98. * @param defaultConfig
  99. * the base configuration to be consulted when a key is missing
  100. * from this configuration instance.
  101. */
  102. public Config(Config defaultConfig) {
  103. baseConfig = defaultConfig;
  104. state = new AtomicReference<ConfigSnapshot>(newState());
  105. }
  106. /**
  107. * Escape the value before saving
  108. *
  109. * @param x
  110. * the value to escape
  111. * @return the escaped value
  112. */
  113. private static String escapeValue(final String x) {
  114. boolean inquote = false;
  115. int lineStart = 0;
  116. final StringBuilder r = new StringBuilder(x.length());
  117. for (int k = 0; k < x.length(); k++) {
  118. final char c = x.charAt(k);
  119. switch (c) {
  120. case '\n':
  121. if (inquote) {
  122. r.append('"');
  123. inquote = false;
  124. }
  125. r.append("\\n\\\n"); //$NON-NLS-1$
  126. lineStart = r.length();
  127. break;
  128. case '\t':
  129. r.append("\\t"); //$NON-NLS-1$
  130. break;
  131. case '\b':
  132. r.append("\\b"); //$NON-NLS-1$
  133. break;
  134. case '\\':
  135. r.append("\\\\"); //$NON-NLS-1$
  136. break;
  137. case '"':
  138. r.append("\\\""); //$NON-NLS-1$
  139. break;
  140. case ';':
  141. case '#':
  142. if (!inquote) {
  143. r.insert(lineStart, '"');
  144. inquote = true;
  145. }
  146. r.append(c);
  147. break;
  148. case ' ':
  149. if (!inquote && r.length() > 0
  150. && r.charAt(r.length() - 1) == ' ') {
  151. r.insert(lineStart, '"');
  152. inquote = true;
  153. }
  154. r.append(' ');
  155. break;
  156. default:
  157. r.append(c);
  158. break;
  159. }
  160. }
  161. if (inquote) {
  162. r.append('"');
  163. }
  164. return r.toString();
  165. }
  166. /**
  167. * Obtain an integer value from the configuration.
  168. *
  169. * @param section
  170. * section the key is grouped within.
  171. * @param name
  172. * name of the key to get.
  173. * @param defaultValue
  174. * default value to return if no value was present.
  175. * @return an integer value from the configuration, or defaultValue.
  176. */
  177. public int getInt(final String section, final String name,
  178. final int defaultValue) {
  179. return getInt(section, null, name, defaultValue);
  180. }
  181. /**
  182. * Obtain an integer value from the configuration.
  183. *
  184. * @param section
  185. * section the key is grouped within.
  186. * @param subsection
  187. * subsection name, such a remote or branch name.
  188. * @param name
  189. * name of the key to get.
  190. * @param defaultValue
  191. * default value to return if no value was present.
  192. * @return an integer value from the configuration, or defaultValue.
  193. */
  194. public int getInt(final String section, String subsection,
  195. final String name, final int defaultValue) {
  196. final long val = getLong(section, subsection, name, defaultValue);
  197. if (Integer.MIN_VALUE <= val && val <= Integer.MAX_VALUE)
  198. return (int) val;
  199. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().integerValueOutOfRange
  200. , section, name));
  201. }
  202. /**
  203. * Obtain an integer value from the configuration.
  204. *
  205. * @param section
  206. * section the key is grouped within.
  207. * @param name
  208. * name of the key to get.
  209. * @param defaultValue
  210. * default value to return if no value was present.
  211. * @return an integer value from the configuration, or defaultValue.
  212. */
  213. public long getLong(String section, String name, long defaultValue) {
  214. return getLong(section, null, name, defaultValue);
  215. }
  216. /**
  217. * Obtain an integer value from the configuration.
  218. *
  219. * @param section
  220. * section the key is grouped within.
  221. * @param subsection
  222. * subsection name, such a remote or branch name.
  223. * @param name
  224. * name of the key to get.
  225. * @param defaultValue
  226. * default value to return if no value was present.
  227. * @return an integer value from the configuration, or defaultValue.
  228. */
  229. public long getLong(final String section, String subsection,
  230. final String name, final long defaultValue) {
  231. final String str = getString(section, subsection, name);
  232. if (str == null)
  233. return defaultValue;
  234. String n = str.trim();
  235. if (n.length() == 0)
  236. return defaultValue;
  237. long mul = 1;
  238. switch (StringUtils.toLowerCase(n.charAt(n.length() - 1))) {
  239. case 'g':
  240. mul = GiB;
  241. break;
  242. case 'm':
  243. mul = MiB;
  244. break;
  245. case 'k':
  246. mul = KiB;
  247. break;
  248. }
  249. if (mul > 1)
  250. n = n.substring(0, n.length() - 1).trim();
  251. if (n.length() == 0)
  252. return defaultValue;
  253. try {
  254. return mul * Long.parseLong(n);
  255. } catch (NumberFormatException nfe) {
  256. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidIntegerValue
  257. , section, name, str));
  258. }
  259. }
  260. /**
  261. * Get a boolean value from the git config
  262. *
  263. * @param section
  264. * section the key is grouped within.
  265. * @param name
  266. * name of the key to get.
  267. * @param defaultValue
  268. * default value to return if no value was present.
  269. * @return true if any value or defaultValue is true, false for missing or
  270. * explicit false
  271. */
  272. public boolean getBoolean(final String section, final String name,
  273. final boolean defaultValue) {
  274. return getBoolean(section, null, name, defaultValue);
  275. }
  276. /**
  277. * Get a boolean value from the git config
  278. *
  279. * @param section
  280. * section the key is grouped within.
  281. * @param subsection
  282. * subsection name, such a remote or branch name.
  283. * @param name
  284. * name of the key to get.
  285. * @param defaultValue
  286. * default value to return if no value was present.
  287. * @return true if any value or defaultValue is true, false for missing or
  288. * explicit false
  289. */
  290. public boolean getBoolean(final String section, String subsection,
  291. final String name, final boolean defaultValue) {
  292. String n = getRawString(section, subsection, name);
  293. if (n == null)
  294. return defaultValue;
  295. if (MAGIC_EMPTY_VALUE == n)
  296. return true;
  297. try {
  298. return StringUtils.toBoolean(n);
  299. } catch (IllegalArgumentException err) {
  300. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidBooleanValue
  301. , section, name, n));
  302. }
  303. }
  304. /**
  305. * Parse an enumeration from the configuration.
  306. *
  307. * @param <T>
  308. * type of the enumeration object.
  309. * @param section
  310. * section the key is grouped within.
  311. * @param subsection
  312. * subsection name, such a remote or branch name.
  313. * @param name
  314. * name of the key to get.
  315. * @param defaultValue
  316. * default value to return if no value was present.
  317. * @return the selected enumeration value, or {@code defaultValue}.
  318. */
  319. public <T extends Enum<?>> T getEnum(final String section,
  320. final String subsection, final String name, final T defaultValue) {
  321. final T[] all = allValuesOf(defaultValue);
  322. return getEnum(all, section, subsection, name, defaultValue);
  323. }
  324. @SuppressWarnings("unchecked")
  325. private static <T> T[] allValuesOf(final T value) {
  326. try {
  327. return (T[]) value.getClass().getMethod("values").invoke(null); //$NON-NLS-1$
  328. } catch (Exception err) {
  329. String typeName = value.getClass().getName();
  330. String msg = MessageFormat.format(
  331. JGitText.get().enumValuesNotAvailable, typeName);
  332. throw new IllegalArgumentException(msg, err);
  333. }
  334. }
  335. /**
  336. * Parse an enumeration from the configuration.
  337. *
  338. * @param <T>
  339. * type of the enumeration object.
  340. * @param all
  341. * all possible values in the enumeration which should be
  342. * recognized. Typically {@code EnumType.values()}.
  343. * @param section
  344. * section the key is grouped within.
  345. * @param subsection
  346. * subsection name, such a remote or branch name.
  347. * @param name
  348. * name of the key to get.
  349. * @param defaultValue
  350. * default value to return if no value was present.
  351. * @return the selected enumeration value, or {@code defaultValue}.
  352. */
  353. public <T extends Enum<?>> T getEnum(final T[] all, final String section,
  354. final String subsection, final String name, final T defaultValue) {
  355. String value = getString(section, subsection, name);
  356. if (value == null)
  357. return defaultValue;
  358. if (all[0] instanceof ConfigEnum) {
  359. for (T t : all) {
  360. if (((ConfigEnum) t).matchConfigValue(value))
  361. return t;
  362. }
  363. }
  364. String n = value.replace(' ', '_');
  365. // Because of c98abc9c0586c73ef7df4172644b7dd21c979e9d being used in
  366. // the real world before its breakage was fully understood, we must
  367. // also accept '-' as though it were ' '.
  368. n = n.replace('-', '_');
  369. T trueState = null;
  370. T falseState = null;
  371. for (T e : all) {
  372. if (StringUtils.equalsIgnoreCase(e.name(), n))
  373. return e;
  374. else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) //$NON-NLS-1$
  375. trueState = e;
  376. else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) //$NON-NLS-1$
  377. falseState = e;
  378. }
  379. // This is an odd little fallback. C Git sometimes allows boolean
  380. // values in a tri-state with other things. If we have both a true
  381. // and a false value in our enumeration, assume its one of those.
  382. //
  383. if (trueState != null && falseState != null) {
  384. try {
  385. return StringUtils.toBoolean(n) ? trueState : falseState;
  386. } catch (IllegalArgumentException err) {
  387. // Fall through and use our custom error below.
  388. }
  389. }
  390. if (subsection != null)
  391. throw new IllegalArgumentException(MessageFormat.format(
  392. JGitText.get().enumValueNotSupported3, section, subsection,
  393. name, value));
  394. else
  395. throw new IllegalArgumentException(
  396. MessageFormat.format(JGitText.get().enumValueNotSupported2,
  397. section, name, value));
  398. }
  399. /**
  400. * Get string value or null if not found.
  401. *
  402. * @param section
  403. * the section
  404. * @param subsection
  405. * the subsection for the value
  406. * @param name
  407. * the key name
  408. * @return a String value from the config, <code>null</code> if not found
  409. */
  410. public String getString(final String section, String subsection,
  411. final String name) {
  412. return getRawString(section, subsection, name);
  413. }
  414. /**
  415. * Get a list of string values
  416. * <p>
  417. * If this instance was created with a base, the base's values are returned
  418. * first (if any).
  419. *
  420. * @param section
  421. * the section
  422. * @param subsection
  423. * the subsection for the value
  424. * @param name
  425. * the key name
  426. * @return array of zero or more values from the configuration.
  427. */
  428. public String[] getStringList(final String section, String subsection,
  429. final String name) {
  430. String[] base;
  431. if (baseConfig != null)
  432. base = baseConfig.getStringList(section, subsection, name);
  433. else
  434. base = EMPTY_STRING_ARRAY;
  435. String[] self = getRawStringList(section, subsection, name);
  436. if (self == null)
  437. return base;
  438. if (base.length == 0)
  439. return self;
  440. String[] res = new String[base.length + self.length];
  441. int n = base.length;
  442. System.arraycopy(base, 0, res, 0, n);
  443. System.arraycopy(self, 0, res, n, self.length);
  444. return res;
  445. }
  446. /**
  447. * @param section
  448. * section to search for.
  449. * @return set of all subsections of specified section within this
  450. * configuration and its base configuration; may be empty if no
  451. * subsection exists. The set's iterator returns sections in the
  452. * order they are declared by the configuration starting from this
  453. * instance and progressing through the base.
  454. */
  455. public Set<String> getSubsections(final String section) {
  456. return getState().getSubsections(section);
  457. }
  458. /**
  459. * @return the sections defined in this {@link Config}. The set's iterator
  460. * returns sections in the order they are declared by the
  461. * configuration starting from this instance and progressing through
  462. * the base.
  463. */
  464. public Set<String> getSections() {
  465. return getState().getSections();
  466. }
  467. /**
  468. * @param section
  469. * the section
  470. * @return the list of names defined for this section
  471. */
  472. public Set<String> getNames(String section) {
  473. return getNames(section, null);
  474. }
  475. /**
  476. * @param section
  477. * the section
  478. * @param subsection
  479. * the subsection
  480. * @return the list of names defined for this subsection
  481. */
  482. public Set<String> getNames(String section, String subsection) {
  483. return getState().getNames(section, subsection);
  484. }
  485. /**
  486. * @param section
  487. * the section
  488. * @param recursive
  489. * if {@code true} recursively adds the names defined in all base
  490. * configurations
  491. * @return the list of names defined for this section
  492. */
  493. public Set<String> getNames(String section, boolean recursive) {
  494. return getState().getNames(section, null, recursive);
  495. }
  496. /**
  497. * @param section
  498. * the section
  499. * @param subsection
  500. * the subsection
  501. * @param recursive
  502. * if {@code true} recursively adds the names defined in all base
  503. * configurations
  504. * @return the list of names defined for this subsection
  505. */
  506. public Set<String> getNames(String section, String subsection,
  507. boolean recursive) {
  508. return getState().getNames(section, subsection, recursive);
  509. }
  510. /**
  511. * Obtain a handle to a parsed set of configuration values.
  512. *
  513. * @param <T>
  514. * type of configuration model to return.
  515. * @param parser
  516. * parser which can create the model if it is not already
  517. * available in this configuration file. The parser is also used
  518. * as the key into a cache and must obey the hashCode and equals
  519. * contract in order to reuse a parsed model.
  520. * @return the parsed object instance, which is cached inside this config.
  521. */
  522. @SuppressWarnings("unchecked")
  523. public <T> T get(final SectionParser<T> parser) {
  524. final ConfigSnapshot myState = getState();
  525. T obj = (T) myState.cache.get(parser);
  526. if (obj == null) {
  527. obj = parser.parse(this);
  528. myState.cache.put(parser, obj);
  529. }
  530. return obj;
  531. }
  532. /**
  533. * Remove a cached configuration object.
  534. * <p>
  535. * If the associated configuration object has not yet been cached, this
  536. * method has no effect.
  537. *
  538. * @param parser
  539. * parser used to obtain the configuration object.
  540. * @see #get(SectionParser)
  541. */
  542. public void uncache(final SectionParser<?> parser) {
  543. state.get().cache.remove(parser);
  544. }
  545. /**
  546. * Adds a listener to be notified about changes.
  547. * <p>
  548. * Clients are supposed to remove the listeners after they are done with
  549. * them using the {@link ListenerHandle#remove()} method
  550. *
  551. * @param listener
  552. * the listener
  553. * @return the handle to the registered listener
  554. */
  555. public ListenerHandle addChangeListener(ConfigChangedListener listener) {
  556. return listeners.addConfigChangedListener(listener);
  557. }
  558. /**
  559. * Determine whether to issue change events for transient changes.
  560. * <p>
  561. * If <code>true</code> is returned (which is the default behavior),
  562. * {@link #fireConfigChangedEvent()} will be called upon each change.
  563. * <p>
  564. * Subclasses that override this to return <code>false</code> are
  565. * responsible for issuing {@link #fireConfigChangedEvent()} calls
  566. * themselves.
  567. *
  568. * @return <code></code>
  569. */
  570. protected boolean notifyUponTransientChanges() {
  571. return true;
  572. }
  573. /**
  574. * Notifies the listeners
  575. */
  576. protected void fireConfigChangedEvent() {
  577. listeners.dispatch(new ConfigChangedEvent());
  578. }
  579. private String getRawString(final String section, final String subsection,
  580. final String name) {
  581. String[] lst = getRawStringList(section, subsection, name);
  582. if (lst != null)
  583. return lst[0];
  584. else if (baseConfig != null)
  585. return baseConfig.getRawString(section, subsection, name);
  586. else
  587. return null;
  588. }
  589. private String[] getRawStringList(String section, String subsection,
  590. String name) {
  591. return state.get().get(section, subsection, name);
  592. }
  593. private ConfigSnapshot getState() {
  594. ConfigSnapshot cur, upd;
  595. do {
  596. cur = state.get();
  597. final ConfigSnapshot base = getBaseState();
  598. if (cur.baseState == base)
  599. return cur;
  600. upd = new ConfigSnapshot(cur.entryList, base);
  601. } while (!state.compareAndSet(cur, upd));
  602. return upd;
  603. }
  604. private ConfigSnapshot getBaseState() {
  605. return baseConfig != null ? baseConfig.getState() : null;
  606. }
  607. /**
  608. * Add or modify a configuration value. The parameters will result in a
  609. * configuration entry like this.
  610. *
  611. * <pre>
  612. * [section &quot;subsection&quot;]
  613. * name = value
  614. * </pre>
  615. *
  616. * @param section
  617. * section name, e.g "branch"
  618. * @param subsection
  619. * optional subsection value, e.g. a branch name
  620. * @param name
  621. * parameter name, e.g. "filemode"
  622. * @param value
  623. * parameter value
  624. */
  625. public void setInt(final String section, final String subsection,
  626. final String name, final int value) {
  627. setLong(section, subsection, name, value);
  628. }
  629. /**
  630. * Add or modify a configuration value. The parameters will result in a
  631. * configuration entry like this.
  632. *
  633. * <pre>
  634. * [section &quot;subsection&quot;]
  635. * name = value
  636. * </pre>
  637. *
  638. * @param section
  639. * section name, e.g "branch"
  640. * @param subsection
  641. * optional subsection value, e.g. a branch name
  642. * @param name
  643. * parameter name, e.g. "filemode"
  644. * @param value
  645. * parameter value
  646. */
  647. public void setLong(final String section, final String subsection,
  648. final String name, final long value) {
  649. final String s;
  650. if (value >= GiB && (value % GiB) == 0)
  651. s = String.valueOf(value / GiB) + " g"; //$NON-NLS-1$
  652. else if (value >= MiB && (value % MiB) == 0)
  653. s = String.valueOf(value / MiB) + " m"; //$NON-NLS-1$
  654. else if (value >= KiB && (value % KiB) == 0)
  655. s = String.valueOf(value / KiB) + " k"; //$NON-NLS-1$
  656. else
  657. s = String.valueOf(value);
  658. setString(section, subsection, name, s);
  659. }
  660. /**
  661. * Add or modify a configuration value. The parameters will result in a
  662. * configuration entry like this.
  663. *
  664. * <pre>
  665. * [section &quot;subsection&quot;]
  666. * name = value
  667. * </pre>
  668. *
  669. * @param section
  670. * section name, e.g "branch"
  671. * @param subsection
  672. * optional subsection value, e.g. a branch name
  673. * @param name
  674. * parameter name, e.g. "filemode"
  675. * @param value
  676. * parameter value
  677. */
  678. public void setBoolean(final String section, final String subsection,
  679. final String name, final boolean value) {
  680. setString(section, subsection, name, value ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
  681. }
  682. /**
  683. * Add or modify a configuration value. The parameters will result in a
  684. * configuration entry like this.
  685. *
  686. * <pre>
  687. * [section &quot;subsection&quot;]
  688. * name = value
  689. * </pre>
  690. *
  691. * @param <T>
  692. * type of the enumeration object.
  693. * @param section
  694. * section name, e.g "branch"
  695. * @param subsection
  696. * optional subsection value, e.g. a branch name
  697. * @param name
  698. * parameter name, e.g. "filemode"
  699. * @param value
  700. * parameter value
  701. */
  702. public <T extends Enum<?>> void setEnum(final String section,
  703. final String subsection, final String name, final T value) {
  704. String n;
  705. if (value instanceof ConfigEnum)
  706. n = ((ConfigEnum) value).toConfigValue();
  707. else
  708. n = value.name().toLowerCase().replace('_', ' ');
  709. setString(section, subsection, name, n);
  710. }
  711. /**
  712. * Add or modify a configuration value. The parameters will result in a
  713. * configuration entry like this.
  714. *
  715. * <pre>
  716. * [section &quot;subsection&quot;]
  717. * name = value
  718. * </pre>
  719. *
  720. * @param section
  721. * section name, e.g "branch"
  722. * @param subsection
  723. * optional subsection value, e.g. a branch name
  724. * @param name
  725. * parameter name, e.g. "filemode"
  726. * @param value
  727. * parameter value, e.g. "true"
  728. */
  729. public void setString(final String section, final String subsection,
  730. final String name, final String value) {
  731. setStringList(section, subsection, name, Collections
  732. .singletonList(value));
  733. }
  734. /**
  735. * Remove a configuration value.
  736. *
  737. * @param section
  738. * section name, e.g "branch"
  739. * @param subsection
  740. * optional subsection value, e.g. a branch name
  741. * @param name
  742. * parameter name, e.g. "filemode"
  743. */
  744. public void unset(final String section, final String subsection,
  745. final String name) {
  746. setStringList(section, subsection, name, Collections
  747. .<String> emptyList());
  748. }
  749. /**
  750. * Remove all configuration values under a single section.
  751. *
  752. * @param section
  753. * section name, e.g "branch"
  754. * @param subsection
  755. * optional subsection value, e.g. a branch name
  756. */
  757. public void unsetSection(String section, String subsection) {
  758. ConfigSnapshot src, res;
  759. do {
  760. src = state.get();
  761. res = unsetSection(src, section, subsection);
  762. } while (!state.compareAndSet(src, res));
  763. }
  764. private ConfigSnapshot unsetSection(final ConfigSnapshot srcState,
  765. final String section,
  766. final String subsection) {
  767. final int max = srcState.entryList.size();
  768. final ArrayList<ConfigLine> r = new ArrayList<ConfigLine>(max);
  769. boolean lastWasMatch = false;
  770. for (ConfigLine e : srcState.entryList) {
  771. if (e.match(section, subsection)) {
  772. // Skip this record, it's for the section we are removing.
  773. lastWasMatch = true;
  774. continue;
  775. }
  776. if (lastWasMatch && e.section == null && e.subsection == null)
  777. continue; // skip this padding line in the section.
  778. r.add(e);
  779. }
  780. return newState(r);
  781. }
  782. /**
  783. * Set a configuration value.
  784. *
  785. * <pre>
  786. * [section &quot;subsection&quot;]
  787. * name = value
  788. * </pre>
  789. *
  790. * @param section
  791. * section name, e.g "branch"
  792. * @param subsection
  793. * optional subsection value, e.g. a branch name
  794. * @param name
  795. * parameter name, e.g. "filemode"
  796. * @param values
  797. * list of zero or more values for this key.
  798. */
  799. public void setStringList(final String section, final String subsection,
  800. final String name, final List<String> values) {
  801. ConfigSnapshot src, res;
  802. do {
  803. src = state.get();
  804. res = replaceStringList(src, section, subsection, name, values);
  805. } while (!state.compareAndSet(src, res));
  806. if (notifyUponTransientChanges())
  807. fireConfigChangedEvent();
  808. }
  809. private ConfigSnapshot replaceStringList(final ConfigSnapshot srcState,
  810. final String section, final String subsection, final String name,
  811. final List<String> values) {
  812. final List<ConfigLine> entries = copy(srcState, values);
  813. int entryIndex = 0;
  814. int valueIndex = 0;
  815. int insertPosition = -1;
  816. // Reset the first n Entry objects that match this input name.
  817. //
  818. while (entryIndex < entries.size() && valueIndex < values.size()) {
  819. final ConfigLine e = entries.get(entryIndex);
  820. if (e.match(section, subsection, name)) {
  821. entries.set(entryIndex, e.forValue(values.get(valueIndex++)));
  822. insertPosition = entryIndex + 1;
  823. }
  824. entryIndex++;
  825. }
  826. // Remove any extra Entry objects that we no longer need.
  827. //
  828. if (valueIndex == values.size() && entryIndex < entries.size()) {
  829. while (entryIndex < entries.size()) {
  830. final ConfigLine e = entries.get(entryIndex++);
  831. if (e.match(section, subsection, name))
  832. entries.remove(--entryIndex);
  833. }
  834. }
  835. // Insert new Entry objects for additional/new values.
  836. //
  837. if (valueIndex < values.size() && entryIndex == entries.size()) {
  838. if (insertPosition < 0) {
  839. // We didn't find a matching key above, but maybe there
  840. // is already a section available that matches. Insert
  841. // after the last key of that section.
  842. //
  843. insertPosition = findSectionEnd(entries, section, subsection);
  844. }
  845. if (insertPosition < 0) {
  846. // We didn't find any matching section header for this key,
  847. // so we must create a new section header at the end.
  848. //
  849. final ConfigLine e = new ConfigLine();
  850. e.section = section;
  851. e.subsection = subsection;
  852. entries.add(e);
  853. insertPosition = entries.size();
  854. }
  855. while (valueIndex < values.size()) {
  856. final ConfigLine e = new ConfigLine();
  857. e.section = section;
  858. e.subsection = subsection;
  859. e.name = name;
  860. e.value = values.get(valueIndex++);
  861. entries.add(insertPosition++, e);
  862. }
  863. }
  864. return newState(entries);
  865. }
  866. private static List<ConfigLine> copy(final ConfigSnapshot src,
  867. final List<String> values) {
  868. // At worst we need to insert 1 line for each value, plus 1 line
  869. // for a new section header. Assume that and allocate the space.
  870. //
  871. final int max = src.entryList.size() + values.size() + 1;
  872. final ArrayList<ConfigLine> r = new ArrayList<ConfigLine>(max);
  873. r.addAll(src.entryList);
  874. return r;
  875. }
  876. private static int findSectionEnd(final List<ConfigLine> entries,
  877. final String section, final String subsection) {
  878. for (int i = 0; i < entries.size(); i++) {
  879. ConfigLine e = entries.get(i);
  880. if (e.match(section, subsection, null)) {
  881. i++;
  882. while (i < entries.size()) {
  883. e = entries.get(i);
  884. if (e.match(section, subsection, e.name))
  885. i++;
  886. else
  887. break;
  888. }
  889. return i;
  890. }
  891. }
  892. return -1;
  893. }
  894. /**
  895. * @return this configuration, formatted as a Git style text file.
  896. */
  897. public String toText() {
  898. final StringBuilder out = new StringBuilder();
  899. for (final ConfigLine e : state.get().entryList) {
  900. if (e.prefix != null)
  901. out.append(e.prefix);
  902. if (e.section != null && e.name == null) {
  903. out.append('[');
  904. out.append(e.section);
  905. if (e.subsection != null) {
  906. out.append(' ');
  907. String escaped = escapeValue(e.subsection);
  908. // make sure to avoid double quotes here
  909. boolean quoted = escaped.startsWith("\"") //$NON-NLS-1$
  910. && escaped.endsWith("\""); //$NON-NLS-1$
  911. if (!quoted)
  912. out.append('"');
  913. out.append(escaped);
  914. if (!quoted)
  915. out.append('"');
  916. }
  917. out.append(']');
  918. } else if (e.section != null && e.name != null) {
  919. if (e.prefix == null || "".equals(e.prefix)) //$NON-NLS-1$
  920. out.append('\t');
  921. out.append(e.name);
  922. if (MAGIC_EMPTY_VALUE != e.value) {
  923. out.append(" ="); //$NON-NLS-1$
  924. if (e.value != null) {
  925. out.append(' ');
  926. out.append(escapeValue(e.value));
  927. }
  928. }
  929. if (e.suffix != null)
  930. out.append(' ');
  931. }
  932. if (e.suffix != null)
  933. out.append(e.suffix);
  934. out.append('\n');
  935. }
  936. return out.toString();
  937. }
  938. /**
  939. * Clear this configuration and reset to the contents of the parsed string.
  940. *
  941. * @param text
  942. * Git style text file listing configuration properties.
  943. * @throws ConfigInvalidException
  944. * the text supplied is not formatted correctly. No changes were
  945. * made to {@code this}.
  946. */
  947. public void fromText(final String text) throws ConfigInvalidException {
  948. final List<ConfigLine> newEntries = new ArrayList<ConfigLine>();
  949. final StringReader in = new StringReader(text);
  950. ConfigLine last = null;
  951. ConfigLine e = new ConfigLine();
  952. for (;;) {
  953. int input = in.read();
  954. if (-1 == input) {
  955. if (e.section != null)
  956. newEntries.add(e);
  957. break;
  958. }
  959. final char c = (char) input;
  960. if ('\n' == c) {
  961. // End of this entry.
  962. newEntries.add(e);
  963. if (e.section != null)
  964. last = e;
  965. e = new ConfigLine();
  966. } else if (e.suffix != null) {
  967. // Everything up until the end-of-line is in the suffix.
  968. e.suffix += c;
  969. } else if (';' == c || '#' == c) {
  970. // The rest of this line is a comment; put into suffix.
  971. e.suffix = String.valueOf(c);
  972. } else if (e.section == null && Character.isWhitespace(c)) {
  973. // Save the leading whitespace (if any).
  974. if (e.prefix == null)
  975. e.prefix = ""; //$NON-NLS-1$
  976. e.prefix += c;
  977. } else if ('[' == c) {
  978. // This is a section header.
  979. e.section = readSectionName(in);
  980. input = in.read();
  981. if ('"' == input) {
  982. e.subsection = readValue(in, true, '"');
  983. input = in.read();
  984. }
  985. if (']' != input)
  986. throw new ConfigInvalidException(JGitText.get().badGroupHeader);
  987. e.suffix = ""; //$NON-NLS-1$
  988. } else if (last != null) {
  989. // Read a value.
  990. e.section = last.section;
  991. e.subsection = last.subsection;
  992. in.reset();
  993. e.name = readKeyName(in);
  994. if (e.name.endsWith("\n")) { //$NON-NLS-1$
  995. e.name = e.name.substring(0, e.name.length() - 1);
  996. e.value = MAGIC_EMPTY_VALUE;
  997. } else
  998. e.value = readValue(in, false, -1);
  999. } else
  1000. throw new ConfigInvalidException(JGitText.get().invalidLineInConfigFile);
  1001. }
  1002. state.set(newState(newEntries));
  1003. }
  1004. private ConfigSnapshot newState() {
  1005. return new ConfigSnapshot(Collections.<ConfigLine> emptyList(),
  1006. getBaseState());
  1007. }
  1008. private ConfigSnapshot newState(final List<ConfigLine> entries) {
  1009. return new ConfigSnapshot(Collections.unmodifiableList(entries),
  1010. getBaseState());
  1011. }
  1012. /**
  1013. * Clear the configuration file
  1014. */
  1015. protected void clear() {
  1016. state.set(newState());
  1017. }
  1018. private static String readSectionName(final StringReader in)
  1019. throws ConfigInvalidException {
  1020. final StringBuilder name = new StringBuilder();
  1021. for (;;) {
  1022. int c = in.read();
  1023. if (c < 0)
  1024. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1025. if (']' == c) {
  1026. in.reset();
  1027. break;
  1028. }
  1029. if (' ' == c || '\t' == c) {
  1030. for (;;) {
  1031. c = in.read();
  1032. if (c < 0)
  1033. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1034. if ('"' == c) {
  1035. in.reset();
  1036. break;
  1037. }
  1038. if (' ' == c || '\t' == c)
  1039. continue; // Skipped...
  1040. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badSectionEntry, name));
  1041. }
  1042. break;
  1043. }
  1044. if (Character.isLetterOrDigit((char) c) || '.' == c || '-' == c)
  1045. name.append((char) c);
  1046. else
  1047. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badSectionEntry, name));
  1048. }
  1049. return name.toString();
  1050. }
  1051. private static String readKeyName(final StringReader in)
  1052. throws ConfigInvalidException {
  1053. final StringBuilder name = new StringBuilder();
  1054. for (;;) {
  1055. int c = in.read();
  1056. if (c < 0)
  1057. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1058. if ('=' == c)
  1059. break;
  1060. if (' ' == c || '\t' == c) {
  1061. for (;;) {
  1062. c = in.read();
  1063. if (c < 0)
  1064. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1065. if ('=' == c)
  1066. break;
  1067. if (';' == c || '#' == c || '\n' == c) {
  1068. in.reset();
  1069. break;
  1070. }
  1071. if (' ' == c || '\t' == c)
  1072. continue; // Skipped...
  1073. throw new ConfigInvalidException(JGitText.get().badEntryDelimiter);
  1074. }
  1075. break;
  1076. }
  1077. if (Character.isLetterOrDigit((char) c) || c == '-') {
  1078. // From the git-config man page:
  1079. // The variable names are case-insensitive and only
  1080. // alphanumeric characters and - are allowed.
  1081. name.append((char) c);
  1082. } else if ('\n' == c) {
  1083. in.reset();
  1084. name.append((char) c);
  1085. break;
  1086. } else
  1087. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badEntryName, name));
  1088. }
  1089. return name.toString();
  1090. }
  1091. private static String readValue(final StringReader in, boolean quote,
  1092. final int eol) throws ConfigInvalidException {
  1093. final StringBuilder value = new StringBuilder();
  1094. boolean space = false;
  1095. for (;;) {
  1096. int c = in.read();
  1097. if (c < 0) {
  1098. if (value.length() == 0)
  1099. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1100. break;
  1101. }
  1102. if ('\n' == c) {
  1103. if (quote)
  1104. throw new ConfigInvalidException(JGitText.get().newlineInQuotesNotAllowed);
  1105. in.reset();
  1106. break;
  1107. }
  1108. if (eol == c)
  1109. break;
  1110. if (!quote) {
  1111. if (Character.isWhitespace((char) c)) {
  1112. space = true;
  1113. continue;
  1114. }
  1115. if (';' == c || '#' == c) {
  1116. in.reset();
  1117. break;
  1118. }
  1119. }
  1120. if (space) {
  1121. if (value.length() > 0)
  1122. value.append(' ');
  1123. space = false;
  1124. }
  1125. if ('\\' == c) {
  1126. c = in.read();
  1127. switch (c) {
  1128. case -1:
  1129. throw new ConfigInvalidException(JGitText.get().endOfFileInEscape);
  1130. case '\n':
  1131. continue;
  1132. case 't':
  1133. value.append('\t');
  1134. continue;
  1135. case 'b':
  1136. value.append('\b');
  1137. continue;
  1138. case 'n':
  1139. value.append('\n');
  1140. continue;
  1141. case '\\':
  1142. value.append('\\');
  1143. continue;
  1144. case '"':
  1145. value.append('"');
  1146. continue;
  1147. default:
  1148. throw new ConfigInvalidException(MessageFormat.format(
  1149. JGitText.get().badEscape,
  1150. Character.valueOf(((char) c))));
  1151. }
  1152. }
  1153. if ('"' == c) {
  1154. quote = !quote;
  1155. continue;
  1156. }
  1157. value.append((char) c);
  1158. }
  1159. return value.length() > 0 ? value.toString() : null;
  1160. }
  1161. /**
  1162. * Parses a section of the configuration into an application model object.
  1163. * <p>
  1164. * Instances must implement hashCode and equals such that model objects can
  1165. * be cached by using the {@code SectionParser} as a key of a HashMap.
  1166. * <p>
  1167. * As the {@code SectionParser} itself is used as the key of the internal
  1168. * HashMap applications should be careful to ensure the SectionParser key
  1169. * does not retain unnecessary application state which may cause memory to
  1170. * be held longer than expected.
  1171. *
  1172. * @param <T>
  1173. * type of the application model created by the parser.
  1174. */
  1175. public static interface SectionParser<T> {
  1176. /**
  1177. * Create a model object from a configuration.
  1178. *
  1179. * @param cfg
  1180. * the configuration to read values from.
  1181. * @return the application model instance.
  1182. */
  1183. T parse(Config cfg);
  1184. }
  1185. private static class StringReader {
  1186. private final char[] buf;
  1187. private int pos;
  1188. StringReader(final String in) {
  1189. buf = in.toCharArray();
  1190. }
  1191. int read() {
  1192. try {
  1193. return buf[pos++];
  1194. } catch (ArrayIndexOutOfBoundsException e) {
  1195. pos = buf.length;
  1196. return -1;
  1197. }
  1198. }
  1199. void reset() {
  1200. pos--;
  1201. }
  1202. }
  1203. /**
  1204. * Converts enumeration values into configuration options and vice-versa,
  1205. * allowing to match a config option with an enum value.
  1206. *
  1207. */
  1208. public static interface ConfigEnum {
  1209. /**
  1210. * Converts enumeration value into a string to be save in config.
  1211. *
  1212. * @return the enum value as config string
  1213. */
  1214. String toConfigValue();
  1215. /**
  1216. * Checks if the given string matches with enum value.
  1217. *
  1218. * @param in
  1219. * the string to match
  1220. * @return true if the given string matches enum value, false otherwise
  1221. */
  1222. boolean matchConfigValue(String in);
  1223. }
  1224. }