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 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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");
  126. lineStart = r.length();
  127. break;
  128. case '\t':
  129. r.append("\\t");
  130. break;
  131. case '\b':
  132. r.append("\\b");
  133. break;
  134. case '\\':
  135. r.append("\\\\");
  136. break;
  137. case '"':
  138. r.append("\\\"");
  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);
  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. String n = value.replace(' ', '_');
  359. T trueState = null;
  360. T falseState = null;
  361. for (T e : all) {
  362. if (StringUtils.equalsIgnoreCase(e.name(), n))
  363. return e;
  364. else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE"))
  365. trueState = e;
  366. else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE"))
  367. falseState = e;
  368. }
  369. // This is an odd little fallback. C Git sometimes allows boolean
  370. // values in a tri-state with other things. If we have both a true
  371. // and a false value in our enumeration, assume its one of those.
  372. //
  373. if (trueState != null && falseState != null) {
  374. try {
  375. return StringUtils.toBoolean(n) ? trueState : falseState;
  376. } catch (IllegalArgumentException err) {
  377. // Fall through and use our custom error below.
  378. }
  379. }
  380. if (subsection != null)
  381. throw new IllegalArgumentException(MessageFormat.format(JGitText
  382. .get().enumValueNotSupported3, section, name, value));
  383. else
  384. throw new IllegalArgumentException(MessageFormat.format(JGitText
  385. .get().enumValueNotSupported2, section, name, value));
  386. }
  387. /**
  388. * Get string value
  389. *
  390. * @param section
  391. * the section
  392. * @param subsection
  393. * the subsection for the value
  394. * @param name
  395. * the key name
  396. * @return a String value from git config.
  397. */
  398. public String getString(final String section, String subsection,
  399. final String name) {
  400. return getRawString(section, subsection, name);
  401. }
  402. /**
  403. * Get a list of string values
  404. * <p>
  405. * If this instance was created with a base, the base's values are returned
  406. * first (if any).
  407. *
  408. * @param section
  409. * the section
  410. * @param subsection
  411. * the subsection for the value
  412. * @param name
  413. * the key name
  414. * @return array of zero or more values from the configuration.
  415. */
  416. public String[] getStringList(final String section, String subsection,
  417. final String name) {
  418. String[] base;
  419. if (baseConfig != null)
  420. base = baseConfig.getStringList(section, subsection, name);
  421. else
  422. base = EMPTY_STRING_ARRAY;
  423. String[] self = getRawStringList(section, subsection, name);
  424. if (self == null)
  425. return base;
  426. if (base.length == 0)
  427. return self;
  428. String[] res = new String[base.length + self.length];
  429. int n = base.length;
  430. System.arraycopy(base, 0, res, 0, n);
  431. System.arraycopy(self, 0, res, n, self.length);
  432. return res;
  433. }
  434. /**
  435. * @param section
  436. * section to search for.
  437. * @return set of all subsections of specified section within this
  438. * configuration and its base configuration; may be empty if no
  439. * subsection exists. The set's iterator returns sections in the
  440. * order they are declared by the configuration starting from this
  441. * instance and progressing through the base.
  442. */
  443. public Set<String> getSubsections(final String section) {
  444. return getState().getSubsections(section);
  445. }
  446. /**
  447. * @return the sections defined in this {@link Config}. The set's iterator
  448. * returns sections in the order they are declared by the
  449. * configuration starting from this instance and progressing through
  450. * the base.
  451. */
  452. public Set<String> getSections() {
  453. return getState().getSections();
  454. }
  455. /**
  456. * @param section
  457. * the section
  458. * @return the list of names defined for this section
  459. */
  460. public Set<String> getNames(String section) {
  461. return getNames(section, null);
  462. }
  463. /**
  464. * @param section
  465. * the section
  466. * @param subsection
  467. * the subsection
  468. * @return the list of names defined for this subsection
  469. */
  470. public Set<String> getNames(String section, String subsection) {
  471. return getState().getNames(section, subsection);
  472. }
  473. /**
  474. * Obtain a handle to a parsed set of configuration values.
  475. *
  476. * @param <T>
  477. * type of configuration model to return.
  478. * @param parser
  479. * parser which can create the model if it is not already
  480. * available in this configuration file. The parser is also used
  481. * as the key into a cache and must obey the hashCode and equals
  482. * contract in order to reuse a parsed model.
  483. * @return the parsed object instance, which is cached inside this config.
  484. */
  485. @SuppressWarnings("unchecked")
  486. public <T> T get(final SectionParser<T> parser) {
  487. final ConfigSnapshot myState = getState();
  488. T obj = (T) myState.cache.get(parser);
  489. if (obj == null) {
  490. obj = parser.parse(this);
  491. myState.cache.put(parser, obj);
  492. }
  493. return obj;
  494. }
  495. /**
  496. * Remove a cached configuration object.
  497. * <p>
  498. * If the associated configuration object has not yet been cached, this
  499. * method has no effect.
  500. *
  501. * @param parser
  502. * parser used to obtain the configuration object.
  503. * @see #get(SectionParser)
  504. */
  505. public void uncache(final SectionParser<?> parser) {
  506. state.get().cache.remove(parser);
  507. }
  508. /**
  509. * Adds a listener to be notified about changes.
  510. * <p>
  511. * Clients are supposed to remove the listeners after they are done with
  512. * them using the {@link ListenerHandle#remove()} method
  513. *
  514. * @param listener
  515. * the listener
  516. * @return the handle to the registered listener
  517. */
  518. public ListenerHandle addChangeListener(ConfigChangedListener listener) {
  519. return listeners.addConfigChangedListener(listener);
  520. }
  521. /**
  522. * Determine whether to issue change events for transient changes.
  523. * <p>
  524. * If <code>true</code> is returned (which is the default behavior),
  525. * {@link #fireConfigChangedEvent()} will be called upon each change.
  526. * <p>
  527. * Subclasses that override this to return <code>false</code> are
  528. * responsible for issuing {@link #fireConfigChangedEvent()} calls
  529. * themselves.
  530. *
  531. * @return <code></code>
  532. */
  533. protected boolean notifyUponTransientChanges() {
  534. return true;
  535. }
  536. /**
  537. * Notifies the listeners
  538. */
  539. protected void fireConfigChangedEvent() {
  540. listeners.dispatch(new ConfigChangedEvent());
  541. }
  542. private String getRawString(final String section, final String subsection,
  543. final String name) {
  544. String[] lst = getRawStringList(section, subsection, name);
  545. if (lst != null)
  546. return lst[0];
  547. else if (baseConfig != null)
  548. return baseConfig.getRawString(section, subsection, name);
  549. else
  550. return null;
  551. }
  552. private String[] getRawStringList(String section, String subsection,
  553. String name) {
  554. return state.get().get(section, subsection, name);
  555. }
  556. private ConfigSnapshot getState() {
  557. ConfigSnapshot cur, upd;
  558. do {
  559. cur = state.get();
  560. final ConfigSnapshot base = getBaseState();
  561. if (cur.baseState == base)
  562. return cur;
  563. upd = new ConfigSnapshot(cur.entryList, base);
  564. } while (!state.compareAndSet(cur, upd));
  565. return upd;
  566. }
  567. private ConfigSnapshot getBaseState() {
  568. return baseConfig != null ? baseConfig.getState() : null;
  569. }
  570. /**
  571. * Add or modify a configuration value. The parameters will result in a
  572. * configuration entry like this.
  573. *
  574. * <pre>
  575. * [section &quot;subsection&quot;]
  576. * name = value
  577. * </pre>
  578. *
  579. * @param section
  580. * section name, e.g "branch"
  581. * @param subsection
  582. * optional subsection value, e.g. a branch name
  583. * @param name
  584. * parameter name, e.g. "filemode"
  585. * @param value
  586. * parameter value
  587. */
  588. public void setInt(final String section, final String subsection,
  589. final String name, final int value) {
  590. setLong(section, subsection, name, value);
  591. }
  592. /**
  593. * Add or modify a configuration value. The parameters will result in a
  594. * configuration entry like this.
  595. *
  596. * <pre>
  597. * [section &quot;subsection&quot;]
  598. * name = value
  599. * </pre>
  600. *
  601. * @param section
  602. * section name, e.g "branch"
  603. * @param subsection
  604. * optional subsection value, e.g. a branch name
  605. * @param name
  606. * parameter name, e.g. "filemode"
  607. * @param value
  608. * parameter value
  609. */
  610. public void setLong(final String section, final String subsection,
  611. final String name, final long value) {
  612. final String s;
  613. if (value >= GiB && (value % GiB) == 0)
  614. s = String.valueOf(value / GiB) + " g";
  615. else if (value >= MiB && (value % MiB) == 0)
  616. s = String.valueOf(value / MiB) + " m";
  617. else if (value >= KiB && (value % KiB) == 0)
  618. s = String.valueOf(value / KiB) + " k";
  619. else
  620. s = String.valueOf(value);
  621. setString(section, subsection, name, s);
  622. }
  623. /**
  624. * Add or modify a configuration value. The parameters will result in a
  625. * configuration entry like this.
  626. *
  627. * <pre>
  628. * [section &quot;subsection&quot;]
  629. * name = value
  630. * </pre>
  631. *
  632. * @param section
  633. * section name, e.g "branch"
  634. * @param subsection
  635. * optional subsection value, e.g. a branch name
  636. * @param name
  637. * parameter name, e.g. "filemode"
  638. * @param value
  639. * parameter value
  640. */
  641. public void setBoolean(final String section, final String subsection,
  642. final String name, final boolean value) {
  643. setString(section, subsection, name, value ? "true" : "false");
  644. }
  645. /**
  646. * Add or modify a configuration value. The parameters will result in a
  647. * configuration entry like this.
  648. *
  649. * <pre>
  650. * [section &quot;subsection&quot;]
  651. * name = value
  652. * </pre>
  653. *
  654. * @param <T>
  655. * type of the enumeration object.
  656. * @param section
  657. * section name, e.g "branch"
  658. * @param subsection
  659. * optional subsection value, e.g. a branch name
  660. * @param name
  661. * parameter name, e.g. "filemode"
  662. * @param value
  663. * parameter value
  664. */
  665. public <T extends Enum<?>> void setEnum(final String section,
  666. final String subsection, final String name, final T value) {
  667. String n = value.name().toLowerCase().replace('_', ' ');
  668. setString(section, subsection, name, n);
  669. }
  670. /**
  671. * Add or modify a configuration value. The parameters will result in a
  672. * configuration entry like this.
  673. *
  674. * <pre>
  675. * [section &quot;subsection&quot;]
  676. * name = value
  677. * </pre>
  678. *
  679. * @param section
  680. * section name, e.g "branch"
  681. * @param subsection
  682. * optional subsection value, e.g. a branch name
  683. * @param name
  684. * parameter name, e.g. "filemode"
  685. * @param value
  686. * parameter value, e.g. "true"
  687. */
  688. public void setString(final String section, final String subsection,
  689. final String name, final String value) {
  690. setStringList(section, subsection, name, Collections
  691. .singletonList(value));
  692. }
  693. /**
  694. * Remove a configuration value.
  695. *
  696. * @param section
  697. * section name, e.g "branch"
  698. * @param subsection
  699. * optional subsection value, e.g. a branch name
  700. * @param name
  701. * parameter name, e.g. "filemode"
  702. */
  703. public void unset(final String section, final String subsection,
  704. final String name) {
  705. setStringList(section, subsection, name, Collections
  706. .<String> emptyList());
  707. }
  708. /**
  709. * Remove all configuration values under a single section.
  710. *
  711. * @param section
  712. * section name, e.g "branch"
  713. * @param subsection
  714. * optional subsection value, e.g. a branch name
  715. */
  716. public void unsetSection(String section, String subsection) {
  717. ConfigSnapshot src, res;
  718. do {
  719. src = state.get();
  720. res = unsetSection(src, section, subsection);
  721. } while (!state.compareAndSet(src, res));
  722. }
  723. private ConfigSnapshot unsetSection(final ConfigSnapshot srcState,
  724. final String section,
  725. final String subsection) {
  726. final int max = srcState.entryList.size();
  727. final ArrayList<ConfigLine> r = new ArrayList<ConfigLine>(max);
  728. boolean lastWasMatch = false;
  729. for (ConfigLine e : srcState.entryList) {
  730. if (e.match(section, subsection)) {
  731. // Skip this record, it's for the section we are removing.
  732. lastWasMatch = true;
  733. continue;
  734. }
  735. if (lastWasMatch && e.section == null && e.subsection == null)
  736. continue; // skip this padding line in the section.
  737. r.add(e);
  738. }
  739. return newState(r);
  740. }
  741. /**
  742. * Set a configuration value.
  743. *
  744. * <pre>
  745. * [section &quot;subsection&quot;]
  746. * name = value
  747. * </pre>
  748. *
  749. * @param section
  750. * section name, e.g "branch"
  751. * @param subsection
  752. * optional subsection value, e.g. a branch name
  753. * @param name
  754. * parameter name, e.g. "filemode"
  755. * @param values
  756. * list of zero or more values for this key.
  757. */
  758. public void setStringList(final String section, final String subsection,
  759. final String name, final List<String> values) {
  760. ConfigSnapshot src, res;
  761. do {
  762. src = state.get();
  763. res = replaceStringList(src, section, subsection, name, values);
  764. } while (!state.compareAndSet(src, res));
  765. if (notifyUponTransientChanges())
  766. fireConfigChangedEvent();
  767. }
  768. private ConfigSnapshot replaceStringList(final ConfigSnapshot srcState,
  769. final String section, final String subsection, final String name,
  770. final List<String> values) {
  771. final List<ConfigLine> entries = copy(srcState, values);
  772. int entryIndex = 0;
  773. int valueIndex = 0;
  774. int insertPosition = -1;
  775. // Reset the first n Entry objects that match this input name.
  776. //
  777. while (entryIndex < entries.size() && valueIndex < values.size()) {
  778. final ConfigLine e = entries.get(entryIndex);
  779. if (e.match(section, subsection, name)) {
  780. entries.set(entryIndex, e.forValue(values.get(valueIndex++)));
  781. insertPosition = entryIndex + 1;
  782. }
  783. entryIndex++;
  784. }
  785. // Remove any extra Entry objects that we no longer need.
  786. //
  787. if (valueIndex == values.size() && entryIndex < entries.size()) {
  788. while (entryIndex < entries.size()) {
  789. final ConfigLine e = entries.get(entryIndex++);
  790. if (e.match(section, subsection, name))
  791. entries.remove(--entryIndex);
  792. }
  793. }
  794. // Insert new Entry objects for additional/new values.
  795. //
  796. if (valueIndex < values.size() && entryIndex == entries.size()) {
  797. if (insertPosition < 0) {
  798. // We didn't find a matching key above, but maybe there
  799. // is already a section available that matches. Insert
  800. // after the last key of that section.
  801. //
  802. insertPosition = findSectionEnd(entries, section, subsection);
  803. }
  804. if (insertPosition < 0) {
  805. // We didn't find any matching section header for this key,
  806. // so we must create a new section header at the end.
  807. //
  808. final ConfigLine e = new ConfigLine();
  809. e.section = section;
  810. e.subsection = subsection;
  811. entries.add(e);
  812. insertPosition = entries.size();
  813. }
  814. while (valueIndex < values.size()) {
  815. final ConfigLine e = new ConfigLine();
  816. e.section = section;
  817. e.subsection = subsection;
  818. e.name = name;
  819. e.value = values.get(valueIndex++);
  820. entries.add(insertPosition++, e);
  821. }
  822. }
  823. return newState(entries);
  824. }
  825. private static List<ConfigLine> copy(final ConfigSnapshot src,
  826. final List<String> values) {
  827. // At worst we need to insert 1 line for each value, plus 1 line
  828. // for a new section header. Assume that and allocate the space.
  829. //
  830. final int max = src.entryList.size() + values.size() + 1;
  831. final ArrayList<ConfigLine> r = new ArrayList<ConfigLine>(max);
  832. r.addAll(src.entryList);
  833. return r;
  834. }
  835. private static int findSectionEnd(final List<ConfigLine> entries,
  836. final String section, final String subsection) {
  837. for (int i = 0; i < entries.size(); i++) {
  838. ConfigLine e = entries.get(i);
  839. if (e.match(section, subsection, null)) {
  840. i++;
  841. while (i < entries.size()) {
  842. e = entries.get(i);
  843. if (e.match(section, subsection, e.name))
  844. i++;
  845. else
  846. break;
  847. }
  848. return i;
  849. }
  850. }
  851. return -1;
  852. }
  853. /**
  854. * @return this configuration, formatted as a Git style text file.
  855. */
  856. public String toText() {
  857. final StringBuilder out = new StringBuilder();
  858. for (final ConfigLine e : state.get().entryList) {
  859. if (e.prefix != null)
  860. out.append(e.prefix);
  861. if (e.section != null && e.name == null) {
  862. out.append('[');
  863. out.append(e.section);
  864. if (e.subsection != null) {
  865. out.append(' ');
  866. String escaped = escapeValue(e.subsection);
  867. // make sure to avoid double quotes here
  868. boolean quoted = escaped.startsWith("\"")
  869. && escaped.endsWith("\"");
  870. if (!quoted)
  871. out.append('"');
  872. out.append(escaped);
  873. if (!quoted)
  874. out.append('"');
  875. }
  876. out.append(']');
  877. } else if (e.section != null && e.name != null) {
  878. if (e.prefix == null || "".equals(e.prefix))
  879. out.append('\t');
  880. out.append(e.name);
  881. if (MAGIC_EMPTY_VALUE != e.value) {
  882. out.append(" =");
  883. if (e.value != null) {
  884. out.append(' ');
  885. out.append(escapeValue(e.value));
  886. }
  887. }
  888. if (e.suffix != null)
  889. out.append(' ');
  890. }
  891. if (e.suffix != null)
  892. out.append(e.suffix);
  893. out.append('\n');
  894. }
  895. return out.toString();
  896. }
  897. /**
  898. * Clear this configuration and reset to the contents of the parsed string.
  899. *
  900. * @param text
  901. * Git style text file listing configuration properties.
  902. * @throws ConfigInvalidException
  903. * the text supplied is not formatted correctly. No changes were
  904. * made to {@code this}.
  905. */
  906. public void fromText(final String text) throws ConfigInvalidException {
  907. final List<ConfigLine> newEntries = new ArrayList<ConfigLine>();
  908. final StringReader in = new StringReader(text);
  909. ConfigLine last = null;
  910. ConfigLine e = new ConfigLine();
  911. for (;;) {
  912. int input = in.read();
  913. if (-1 == input)
  914. break;
  915. final char c = (char) input;
  916. if ('\n' == c) {
  917. // End of this entry.
  918. newEntries.add(e);
  919. if (e.section != null)
  920. last = e;
  921. e = new ConfigLine();
  922. } else if (e.suffix != null) {
  923. // Everything up until the end-of-line is in the suffix.
  924. e.suffix += c;
  925. } else if (';' == c || '#' == c) {
  926. // The rest of this line is a comment; put into suffix.
  927. e.suffix = String.valueOf(c);
  928. } else if (e.section == null && Character.isWhitespace(c)) {
  929. // Save the leading whitespace (if any).
  930. if (e.prefix == null)
  931. e.prefix = "";
  932. e.prefix += c;
  933. } else if ('[' == c) {
  934. // This is a section header.
  935. e.section = readSectionName(in);
  936. input = in.read();
  937. if ('"' == input) {
  938. e.subsection = readValue(in, true, '"');
  939. input = in.read();
  940. }
  941. if (']' != input)
  942. throw new ConfigInvalidException(JGitText.get().badGroupHeader);
  943. e.suffix = "";
  944. } else if (last != null) {
  945. // Read a value.
  946. e.section = last.section;
  947. e.subsection = last.subsection;
  948. in.reset();
  949. e.name = readKeyName(in);
  950. if (e.name.endsWith("\n")) {
  951. e.name = e.name.substring(0, e.name.length() - 1);
  952. e.value = MAGIC_EMPTY_VALUE;
  953. } else
  954. e.value = readValue(in, false, -1);
  955. } else
  956. throw new ConfigInvalidException(JGitText.get().invalidLineInConfigFile);
  957. }
  958. state.set(newState(newEntries));
  959. }
  960. private ConfigSnapshot newState() {
  961. return new ConfigSnapshot(Collections.<ConfigLine> emptyList(),
  962. getBaseState());
  963. }
  964. private ConfigSnapshot newState(final List<ConfigLine> entries) {
  965. return new ConfigSnapshot(Collections.unmodifiableList(entries),
  966. getBaseState());
  967. }
  968. /**
  969. * Clear the configuration file
  970. */
  971. protected void clear() {
  972. state.set(newState());
  973. }
  974. private static String readSectionName(final StringReader in)
  975. throws ConfigInvalidException {
  976. final StringBuilder name = new StringBuilder();
  977. for (;;) {
  978. int c = in.read();
  979. if (c < 0)
  980. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  981. if (']' == c) {
  982. in.reset();
  983. break;
  984. }
  985. if (' ' == c || '\t' == c) {
  986. for (;;) {
  987. c = in.read();
  988. if (c < 0)
  989. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  990. if ('"' == c) {
  991. in.reset();
  992. break;
  993. }
  994. if (' ' == c || '\t' == c)
  995. continue; // Skipped...
  996. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badSectionEntry, name));
  997. }
  998. break;
  999. }
  1000. if (Character.isLetterOrDigit((char) c) || '.' == c || '-' == c)
  1001. name.append((char) c);
  1002. else
  1003. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badSectionEntry, name));
  1004. }
  1005. return name.toString();
  1006. }
  1007. private static String readKeyName(final StringReader in)
  1008. throws ConfigInvalidException {
  1009. final StringBuilder name = new StringBuilder();
  1010. for (;;) {
  1011. int c = in.read();
  1012. if (c < 0)
  1013. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1014. if ('=' == c)
  1015. break;
  1016. if (' ' == c || '\t' == c) {
  1017. for (;;) {
  1018. c = in.read();
  1019. if (c < 0)
  1020. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1021. if ('=' == c)
  1022. break;
  1023. if (';' == c || '#' == c || '\n' == c) {
  1024. in.reset();
  1025. break;
  1026. }
  1027. if (' ' == c || '\t' == c)
  1028. continue; // Skipped...
  1029. throw new ConfigInvalidException(JGitText.get().badEntryDelimiter);
  1030. }
  1031. break;
  1032. }
  1033. if (Character.isLetterOrDigit((char) c) || c == '-') {
  1034. // From the git-config man page:
  1035. // The variable names are case-insensitive and only
  1036. // alphanumeric characters and - are allowed.
  1037. name.append((char) c);
  1038. } else if ('\n' == c) {
  1039. in.reset();
  1040. name.append((char) c);
  1041. break;
  1042. } else
  1043. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badEntryName, name));
  1044. }
  1045. return name.toString();
  1046. }
  1047. private static String readValue(final StringReader in, boolean quote,
  1048. final int eol) throws ConfigInvalidException {
  1049. final StringBuilder value = new StringBuilder();
  1050. boolean space = false;
  1051. for (;;) {
  1052. int c = in.read();
  1053. if (c < 0) {
  1054. if (value.length() == 0)
  1055. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1056. break;
  1057. }
  1058. if ('\n' == c) {
  1059. if (quote)
  1060. throw new ConfigInvalidException(JGitText.get().newlineInQuotesNotAllowed);
  1061. in.reset();
  1062. break;
  1063. }
  1064. if (eol == c)
  1065. break;
  1066. if (!quote) {
  1067. if (Character.isWhitespace((char) c)) {
  1068. space = true;
  1069. continue;
  1070. }
  1071. if (';' == c || '#' == c) {
  1072. in.reset();
  1073. break;
  1074. }
  1075. }
  1076. if (space) {
  1077. if (value.length() > 0)
  1078. value.append(' ');
  1079. space = false;
  1080. }
  1081. if ('\\' == c) {
  1082. c = in.read();
  1083. switch (c) {
  1084. case -1:
  1085. throw new ConfigInvalidException(JGitText.get().endOfFileInEscape);
  1086. case '\n':
  1087. continue;
  1088. case 't':
  1089. value.append('\t');
  1090. continue;
  1091. case 'b':
  1092. value.append('\b');
  1093. continue;
  1094. case 'n':
  1095. value.append('\n');
  1096. continue;
  1097. case '\\':
  1098. value.append('\\');
  1099. continue;
  1100. case '"':
  1101. value.append('"');
  1102. continue;
  1103. default:
  1104. throw new ConfigInvalidException(MessageFormat.format(
  1105. JGitText.get().badEscape,
  1106. Character.valueOf(((char) c))));
  1107. }
  1108. }
  1109. if ('"' == c) {
  1110. quote = !quote;
  1111. continue;
  1112. }
  1113. value.append((char) c);
  1114. }
  1115. return value.length() > 0 ? value.toString() : null;
  1116. }
  1117. /**
  1118. * Parses a section of the configuration into an application model object.
  1119. * <p>
  1120. * Instances must implement hashCode and equals such that model objects can
  1121. * be cached by using the {@code SectionParser} as a key of a HashMap.
  1122. * <p>
  1123. * As the {@code SectionParser} itself is used as the key of the internal
  1124. * HashMap applications should be careful to ensure the SectionParser key
  1125. * does not retain unnecessary application state which may cause memory to
  1126. * be held longer than expected.
  1127. *
  1128. * @param <T>
  1129. * type of the application model created by the parser.
  1130. */
  1131. public static interface SectionParser<T> {
  1132. /**
  1133. * Create a model object from a configuration.
  1134. *
  1135. * @param cfg
  1136. * the configuration to read values from.
  1137. * @return the application model instance.
  1138. */
  1139. T parse(Config cfg);
  1140. }
  1141. private static class StringReader {
  1142. private final char[] buf;
  1143. private int pos;
  1144. StringReader(final String in) {
  1145. buf = in.toCharArray();
  1146. }
  1147. int read() {
  1148. try {
  1149. return buf[pos++];
  1150. } catch (ArrayIndexOutOfBoundsException e) {
  1151. pos = buf.length;
  1152. return -1;
  1153. }
  1154. }
  1155. void reset() {
  1156. pos--;
  1157. }
  1158. }
  1159. }