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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  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.HashSet;
  56. import java.util.List;
  57. import java.util.Map;
  58. import java.util.Set;
  59. import java.util.concurrent.ConcurrentHashMap;
  60. import java.util.concurrent.atomic.AtomicReference;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.errors.ConfigInvalidException;
  63. import org.eclipse.jgit.events.ConfigChangedEvent;
  64. import org.eclipse.jgit.events.ConfigChangedListener;
  65. import org.eclipse.jgit.events.ListenerHandle;
  66. import org.eclipse.jgit.events.ListenerList;
  67. import org.eclipse.jgit.util.StringUtils;
  68. /**
  69. * Git style {@code .config}, {@code .gitconfig}, {@code .gitmodules} file.
  70. */
  71. public class Config {
  72. private static final String[] EMPTY_STRING_ARRAY = {};
  73. private static final long KiB = 1024;
  74. private static final long MiB = 1024 * KiB;
  75. private static final long GiB = 1024 * MiB;
  76. /** the change listeners */
  77. private final ListenerList listeners = new ListenerList();
  78. /**
  79. * Immutable current state of the configuration data.
  80. * <p>
  81. * This state is copy-on-write. It should always contain an immutable list
  82. * of the configuration keys/values.
  83. */
  84. private final AtomicReference<State> state;
  85. private final Config baseConfig;
  86. /**
  87. * Magic value indicating a missing entry.
  88. * <p>
  89. * This value is tested for reference equality in some contexts, so we
  90. * must ensure it is a special copy of the empty string. It also must
  91. * be treated like the empty string.
  92. */
  93. private static final String MAGIC_EMPTY_VALUE = new String();
  94. /** Create a configuration with no default fallback. */
  95. public Config() {
  96. this(null);
  97. }
  98. /**
  99. * Create an empty configuration with a fallback for missing keys.
  100. *
  101. * @param defaultConfig
  102. * the base configuration to be consulted when a key is missing
  103. * from this configuration instance.
  104. */
  105. public Config(Config defaultConfig) {
  106. baseConfig = defaultConfig;
  107. state = new AtomicReference<State>(newState());
  108. }
  109. /**
  110. * Escape the value before saving
  111. *
  112. * @param x
  113. * the value to escape
  114. * @return the escaped value
  115. */
  116. private static String escapeValue(final String x) {
  117. boolean inquote = false;
  118. int lineStart = 0;
  119. final StringBuilder r = new StringBuilder(x.length());
  120. for (int k = 0; k < x.length(); k++) {
  121. final char c = x.charAt(k);
  122. switch (c) {
  123. case '\n':
  124. if (inquote) {
  125. r.append('"');
  126. inquote = false;
  127. }
  128. r.append("\\n\\\n");
  129. lineStart = r.length();
  130. break;
  131. case '\t':
  132. r.append("\\t");
  133. break;
  134. case '\b':
  135. r.append("\\b");
  136. break;
  137. case '\\':
  138. r.append("\\\\");
  139. break;
  140. case '"':
  141. r.append("\\\"");
  142. break;
  143. case ';':
  144. case '#':
  145. if (!inquote) {
  146. r.insert(lineStart, '"');
  147. inquote = true;
  148. }
  149. r.append(c);
  150. break;
  151. case ' ':
  152. if (!inquote && r.length() > 0
  153. && r.charAt(r.length() - 1) == ' ') {
  154. r.insert(lineStart, '"');
  155. inquote = true;
  156. }
  157. r.append(' ');
  158. break;
  159. default:
  160. r.append(c);
  161. break;
  162. }
  163. }
  164. if (inquote) {
  165. r.append('"');
  166. }
  167. return r.toString();
  168. }
  169. /**
  170. * Obtain an integer value from the configuration.
  171. *
  172. * @param section
  173. * section the key is grouped within.
  174. * @param name
  175. * name of the key to get.
  176. * @param defaultValue
  177. * default value to return if no value was present.
  178. * @return an integer value from the configuration, or defaultValue.
  179. */
  180. public int getInt(final String section, final String name,
  181. final int defaultValue) {
  182. return getInt(section, null, name, defaultValue);
  183. }
  184. /**
  185. * Obtain an integer value from the configuration.
  186. *
  187. * @param section
  188. * section the key is grouped within.
  189. * @param subsection
  190. * subsection name, such a remote or branch name.
  191. * @param name
  192. * name of the key to get.
  193. * @param defaultValue
  194. * default value to return if no value was present.
  195. * @return an integer value from the configuration, or defaultValue.
  196. */
  197. public int getInt(final String section, String subsection,
  198. final String name, final int defaultValue) {
  199. final long val = getLong(section, subsection, name, defaultValue);
  200. if (Integer.MIN_VALUE <= val && val <= Integer.MAX_VALUE)
  201. return (int) val;
  202. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().integerValueOutOfRange
  203. , section, name));
  204. }
  205. /**
  206. * Obtain an integer value from the configuration.
  207. *
  208. * @param section
  209. * section the key is grouped within.
  210. * @param name
  211. * name of the key to get.
  212. * @param defaultValue
  213. * default value to return if no value was present.
  214. * @return an integer value from the configuration, or defaultValue.
  215. */
  216. public long getLong(String section, String name, long defaultValue) {
  217. return getLong(section, null, name, defaultValue);
  218. }
  219. /**
  220. * Obtain an integer value from the configuration.
  221. *
  222. * @param section
  223. * section the key is grouped within.
  224. * @param subsection
  225. * subsection name, such a remote or branch name.
  226. * @param name
  227. * name of the key to get.
  228. * @param defaultValue
  229. * default value to return if no value was present.
  230. * @return an integer value from the configuration, or defaultValue.
  231. */
  232. public long getLong(final String section, String subsection,
  233. final String name, final long defaultValue) {
  234. final String str = getString(section, subsection, name);
  235. if (str == null)
  236. return defaultValue;
  237. String n = str.trim();
  238. if (n.length() == 0)
  239. return defaultValue;
  240. long mul = 1;
  241. switch (StringUtils.toLowerCase(n.charAt(n.length() - 1))) {
  242. case 'g':
  243. mul = GiB;
  244. break;
  245. case 'm':
  246. mul = MiB;
  247. break;
  248. case 'k':
  249. mul = KiB;
  250. break;
  251. }
  252. if (mul > 1)
  253. n = n.substring(0, n.length() - 1).trim();
  254. if (n.length() == 0)
  255. return defaultValue;
  256. try {
  257. return mul * Long.parseLong(n);
  258. } catch (NumberFormatException nfe) {
  259. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidIntegerValue
  260. , section, name, str));
  261. }
  262. }
  263. /**
  264. * Get a boolean value from the git config
  265. *
  266. * @param section
  267. * section the key is grouped within.
  268. * @param name
  269. * name of the key to get.
  270. * @param defaultValue
  271. * default value to return if no value was present.
  272. * @return true if any value or defaultValue is true, false for missing or
  273. * explicit false
  274. */
  275. public boolean getBoolean(final String section, final String name,
  276. final boolean defaultValue) {
  277. return getBoolean(section, null, name, defaultValue);
  278. }
  279. /**
  280. * Get a boolean value from the git config
  281. *
  282. * @param section
  283. * section the key is grouped within.
  284. * @param subsection
  285. * subsection name, such a remote or branch name.
  286. * @param name
  287. * name of the key to get.
  288. * @param defaultValue
  289. * default value to return if no value was present.
  290. * @return true if any value or defaultValue is true, false for missing or
  291. * explicit false
  292. */
  293. public boolean getBoolean(final String section, String subsection,
  294. final String name, final boolean defaultValue) {
  295. String n = getRawString(section, subsection, name);
  296. if (n == null)
  297. return defaultValue;
  298. if (MAGIC_EMPTY_VALUE == n)
  299. return true;
  300. try {
  301. return StringUtils.toBoolean(n);
  302. } catch (IllegalArgumentException err) {
  303. throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidBooleanValue
  304. , section, name, n));
  305. }
  306. }
  307. /**
  308. * Parse an enumeration from the configuration.
  309. *
  310. * @param <T>
  311. * type of the enumeration object.
  312. * @param section
  313. * section the key is grouped within.
  314. * @param subsection
  315. * subsection name, such a remote or branch name.
  316. * @param name
  317. * name of the key to get.
  318. * @param defaultValue
  319. * default value to return if no value was present.
  320. * @return the selected enumeration value, or {@code defaultValue}.
  321. */
  322. public <T extends Enum<?>> T getEnum(final String section,
  323. final String subsection, final String name, final T defaultValue) {
  324. final T[] all = allValuesOf(defaultValue);
  325. return getEnum(all, section, subsection, name, defaultValue);
  326. }
  327. @SuppressWarnings("unchecked")
  328. private static <T> T[] allValuesOf(final T value) {
  329. try {
  330. return (T[]) value.getClass().getMethod("values").invoke(null);
  331. } catch (Exception err) {
  332. String typeName = value.getClass().getName();
  333. String msg = MessageFormat.format(
  334. JGitText.get().enumValuesNotAvailable, typeName);
  335. throw new IllegalArgumentException(msg, err);
  336. }
  337. }
  338. /**
  339. * Parse an enumeration from the configuration.
  340. *
  341. * @param <T>
  342. * type of the enumeration object.
  343. * @param all
  344. * all possible values in the enumeration which should be
  345. * recognized. Typically {@code EnumType.values()}.
  346. * @param section
  347. * section the key is grouped within.
  348. * @param subsection
  349. * subsection name, such a remote or branch name.
  350. * @param name
  351. * name of the key to get.
  352. * @param defaultValue
  353. * default value to return if no value was present.
  354. * @return the selected enumeration value, or {@code defaultValue}.
  355. */
  356. public <T extends Enum<?>> T getEnum(final T[] all, final String section,
  357. final String subsection, final String name, final T defaultValue) {
  358. String value = getString(section, subsection, name);
  359. if (value == null)
  360. return defaultValue;
  361. String n = value.replace(' ', '_');
  362. T trueState = null;
  363. T falseState = null;
  364. for (T e : all) {
  365. if (StringUtils.equalsIgnoreCase(e.name(), n))
  366. return e;
  367. else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE"))
  368. trueState = e;
  369. else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE"))
  370. falseState = e;
  371. }
  372. // This is an odd little fallback. C Git sometimes allows boolean
  373. // values in a tri-state with other things. If we have both a true
  374. // and a false value in our enumeration, assume its one of those.
  375. //
  376. if (trueState != null && falseState != null) {
  377. try {
  378. return StringUtils.toBoolean(n) ? trueState : falseState;
  379. } catch (IllegalArgumentException err) {
  380. // Fall through and use our custom error below.
  381. }
  382. }
  383. if (subsection != null)
  384. throw new IllegalArgumentException(MessageFormat.format(JGitText
  385. .get().enumValueNotSupported3, section, name, value));
  386. else
  387. throw new IllegalArgumentException(MessageFormat.format(JGitText
  388. .get().enumValueNotSupported2, section, name, value));
  389. }
  390. /**
  391. * Get string value
  392. *
  393. * @param section
  394. * the section
  395. * @param subsection
  396. * the subsection for the value
  397. * @param name
  398. * the key name
  399. * @return a String value from git config.
  400. */
  401. public String getString(final String section, String subsection,
  402. final String name) {
  403. return getRawString(section, subsection, name);
  404. }
  405. /**
  406. * Get a list of string values
  407. * <p>
  408. * If this instance was created with a base, the base's values are returned
  409. * first (if any).
  410. *
  411. * @param section
  412. * the section
  413. * @param subsection
  414. * the subsection for the value
  415. * @param name
  416. * the key name
  417. * @return array of zero or more values from the configuration.
  418. */
  419. public String[] getStringList(final String section, String subsection,
  420. final String name) {
  421. final String[] baseList;
  422. if (baseConfig != null)
  423. baseList = baseConfig.getStringList(section, subsection, name);
  424. else
  425. baseList = EMPTY_STRING_ARRAY;
  426. final List<String> lst = getRawStringList(section, subsection, name);
  427. if (lst != null) {
  428. final String[] res = new String[baseList.length + lst.size()];
  429. int idx = baseList.length;
  430. System.arraycopy(baseList, 0, res, 0, idx);
  431. for (final String val : lst)
  432. res[idx++] = val;
  433. return res;
  434. }
  435. return baseList;
  436. }
  437. /**
  438. * @param section
  439. * section to search for.
  440. * @return set of all subsections of specified section within this
  441. * configuration and its base configuration; may be empty if no
  442. * subsection exists.
  443. */
  444. public Set<String> getSubsections(final String section) {
  445. return get(new SubsectionNames(section));
  446. }
  447. /**
  448. * @return the sections defined in this {@link Config}
  449. */
  450. public Set<String> getSections() {
  451. return get(new SectionNames());
  452. }
  453. /**
  454. * @param section
  455. * the section
  456. * @return the list of names defined for this section
  457. */
  458. public Set<String> getNames(String section) {
  459. return getNames(section, null);
  460. }
  461. /**
  462. * @param section
  463. * the section
  464. * @param subsection
  465. * the subsection
  466. * @return the list of names defined for this subsection
  467. */
  468. public Set<String> getNames(String section, String subsection) {
  469. return get(new NamesInSection(section, subsection));
  470. }
  471. /**
  472. * Obtain a handle to a parsed set of configuration values.
  473. *
  474. * @param <T>
  475. * type of configuration model to return.
  476. * @param parser
  477. * parser which can create the model if it is not already
  478. * available in this configuration file. The parser is also used
  479. * as the key into a cache and must obey the hashCode and equals
  480. * contract in order to reuse a parsed model.
  481. * @return the parsed object instance, which is cached inside this config.
  482. */
  483. @SuppressWarnings("unchecked")
  484. public <T> T get(final SectionParser<T> parser) {
  485. final State myState = getState();
  486. T obj = (T) myState.cache.get(parser);
  487. if (obj == null) {
  488. obj = parser.parse(this);
  489. myState.cache.put(parser, obj);
  490. }
  491. return obj;
  492. }
  493. /**
  494. * Remove a cached configuration object.
  495. * <p>
  496. * If the associated configuration object has not yet been cached, this
  497. * method has no effect.
  498. *
  499. * @param parser
  500. * parser used to obtain the configuration object.
  501. * @see #get(SectionParser)
  502. */
  503. public void uncache(final SectionParser<?> parser) {
  504. state.get().cache.remove(parser);
  505. }
  506. /**
  507. * Adds a listener to be notified about changes.
  508. * <p>
  509. * Clients are supposed to remove the listeners after they are done with
  510. * them using the {@link ListenerHandle#remove()} method
  511. *
  512. * @param listener
  513. * the listener
  514. * @return the handle to the registered listener
  515. */
  516. public ListenerHandle addChangeListener(ConfigChangedListener listener) {
  517. return listeners.addConfigChangedListener(listener);
  518. }
  519. /**
  520. * Determine whether to issue change events for transient changes.
  521. * <p>
  522. * If <code>true</code> is returned (which is the default behavior),
  523. * {@link #fireConfigChangedEvent()} will be called upon each change.
  524. * <p>
  525. * Subclasses that override this to return <code>false</code> are
  526. * responsible for issuing {@link #fireConfigChangedEvent()} calls
  527. * themselves.
  528. *
  529. * @return <code></code>
  530. */
  531. protected boolean notifyUponTransientChanges() {
  532. return true;
  533. }
  534. /**
  535. * Notifies the listeners
  536. */
  537. protected void fireConfigChangedEvent() {
  538. listeners.dispatch(new ConfigChangedEvent());
  539. }
  540. private String getRawString(final String section, final String subsection,
  541. final String name) {
  542. final List<String> lst = getRawStringList(section, subsection, name);
  543. if (lst != null)
  544. return lst.get(0);
  545. else if (baseConfig != null)
  546. return baseConfig.getRawString(section, subsection, name);
  547. else
  548. return null;
  549. }
  550. private List<String> getRawStringList(final String section,
  551. final String subsection, final String name) {
  552. List<String> r = null;
  553. for (final Entry e : state.get().entryList) {
  554. if (e.match(section, subsection, name))
  555. r = add(r, e.value);
  556. }
  557. return r;
  558. }
  559. private static List<String> add(final List<String> curr, final String value) {
  560. if (curr == null)
  561. return Collections.singletonList(value);
  562. if (curr.size() == 1) {
  563. final List<String> r = new ArrayList<String>(2);
  564. r.add(curr.get(0));
  565. r.add(value);
  566. return r;
  567. }
  568. curr.add(value);
  569. return curr;
  570. }
  571. private State getState() {
  572. State cur, upd;
  573. do {
  574. cur = state.get();
  575. final State base = getBaseState();
  576. if (cur.baseState == base)
  577. return cur;
  578. upd = new State(cur.entryList, base);
  579. } while (!state.compareAndSet(cur, upd));
  580. return upd;
  581. }
  582. private State getBaseState() {
  583. return baseConfig != null ? baseConfig.getState() : null;
  584. }
  585. /**
  586. * Add or modify a configuration value. The parameters will result in a
  587. * configuration entry like this.
  588. *
  589. * <pre>
  590. * [section &quot;subsection&quot;]
  591. * name = value
  592. * </pre>
  593. *
  594. * @param section
  595. * section name, e.g "branch"
  596. * @param subsection
  597. * optional subsection value, e.g. a branch name
  598. * @param name
  599. * parameter name, e.g. "filemode"
  600. * @param value
  601. * parameter value
  602. */
  603. public void setInt(final String section, final String subsection,
  604. final String name, final int value) {
  605. setLong(section, subsection, name, value);
  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 setLong(final String section, final String subsection,
  626. final String name, final long value) {
  627. final String s;
  628. if (value >= GiB && (value % GiB) == 0)
  629. s = String.valueOf(value / GiB) + " g";
  630. else if (value >= MiB && (value % MiB) == 0)
  631. s = String.valueOf(value / MiB) + " m";
  632. else if (value >= KiB && (value % KiB) == 0)
  633. s = String.valueOf(value / KiB) + " k";
  634. else
  635. s = String.valueOf(value);
  636. setString(section, subsection, name, s);
  637. }
  638. /**
  639. * Add or modify a configuration value. The parameters will result in a
  640. * configuration entry like this.
  641. *
  642. * <pre>
  643. * [section &quot;subsection&quot;]
  644. * name = value
  645. * </pre>
  646. *
  647. * @param section
  648. * section name, e.g "branch"
  649. * @param subsection
  650. * optional subsection value, e.g. a branch name
  651. * @param name
  652. * parameter name, e.g. "filemode"
  653. * @param value
  654. * parameter value
  655. */
  656. public void setBoolean(final String section, final String subsection,
  657. final String name, final boolean value) {
  658. setString(section, subsection, name, value ? "true" : "false");
  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 <T>
  670. * type of the enumeration object.
  671. * @param section
  672. * section name, e.g "branch"
  673. * @param subsection
  674. * optional subsection value, e.g. a branch name
  675. * @param name
  676. * parameter name, e.g. "filemode"
  677. * @param value
  678. * parameter value
  679. */
  680. public <T extends Enum<?>> void setEnum(final String section,
  681. final String subsection, final String name, final T value) {
  682. String n = value.name().toLowerCase().replace('_', ' ');
  683. setString(section, subsection, name, n);
  684. }
  685. /**
  686. * Add or modify a configuration value. The parameters will result in a
  687. * configuration entry like this.
  688. *
  689. * <pre>
  690. * [section &quot;subsection&quot;]
  691. * name = value
  692. * </pre>
  693. *
  694. * @param section
  695. * section name, e.g "branch"
  696. * @param subsection
  697. * optional subsection value, e.g. a branch name
  698. * @param name
  699. * parameter name, e.g. "filemode"
  700. * @param value
  701. * parameter value, e.g. "true"
  702. */
  703. public void setString(final String section, final String subsection,
  704. final String name, final String value) {
  705. setStringList(section, subsection, name, Collections
  706. .singletonList(value));
  707. }
  708. /**
  709. * Remove a configuration value.
  710. *
  711. * @param section
  712. * section name, e.g "branch"
  713. * @param subsection
  714. * optional subsection value, e.g. a branch name
  715. * @param name
  716. * parameter name, e.g. "filemode"
  717. */
  718. public void unset(final String section, final String subsection,
  719. final String name) {
  720. setStringList(section, subsection, name, Collections
  721. .<String> emptyList());
  722. }
  723. /**
  724. * Remove all configuration values under a single section.
  725. *
  726. * @param section
  727. * section name, e.g "branch"
  728. * @param subsection
  729. * optional subsection value, e.g. a branch name
  730. */
  731. public void unsetSection(String section, String subsection) {
  732. State src, res;
  733. do {
  734. src = state.get();
  735. res = unsetSection(src, section, subsection);
  736. } while (!state.compareAndSet(src, res));
  737. }
  738. private State unsetSection(final State srcState, final String section,
  739. final String subsection) {
  740. final int max = srcState.entryList.size();
  741. final ArrayList<Entry> r = new ArrayList<Entry>(max);
  742. boolean lastWasMatch = false;
  743. for (Entry e : srcState.entryList) {
  744. if (e.match(section, subsection)) {
  745. // Skip this record, it's for the section we are removing.
  746. lastWasMatch = true;
  747. continue;
  748. }
  749. if (lastWasMatch && e.section == null && e.subsection == null)
  750. continue; // skip this padding line in the section.
  751. r.add(e);
  752. }
  753. return newState(r);
  754. }
  755. /**
  756. * Set a configuration value.
  757. *
  758. * <pre>
  759. * [section &quot;subsection&quot;]
  760. * name = value
  761. * </pre>
  762. *
  763. * @param section
  764. * section name, e.g "branch"
  765. * @param subsection
  766. * optional subsection value, e.g. a branch name
  767. * @param name
  768. * parameter name, e.g. "filemode"
  769. * @param values
  770. * list of zero or more values for this key.
  771. */
  772. public void setStringList(final String section, final String subsection,
  773. final String name, final List<String> values) {
  774. State src, res;
  775. do {
  776. src = state.get();
  777. res = replaceStringList(src, section, subsection, name, values);
  778. } while (!state.compareAndSet(src, res));
  779. if (notifyUponTransientChanges())
  780. fireConfigChangedEvent();
  781. }
  782. private State replaceStringList(final State srcState,
  783. final String section, final String subsection, final String name,
  784. final List<String> values) {
  785. final List<Entry> entries = copy(srcState, values);
  786. int entryIndex = 0;
  787. int valueIndex = 0;
  788. int insertPosition = -1;
  789. // Reset the first n Entry objects that match this input name.
  790. //
  791. while (entryIndex < entries.size() && valueIndex < values.size()) {
  792. final Entry e = entries.get(entryIndex);
  793. if (e.match(section, subsection, name)) {
  794. entries.set(entryIndex, e.forValue(values.get(valueIndex++)));
  795. insertPosition = entryIndex + 1;
  796. }
  797. entryIndex++;
  798. }
  799. // Remove any extra Entry objects that we no longer need.
  800. //
  801. if (valueIndex == values.size() && entryIndex < entries.size()) {
  802. while (entryIndex < entries.size()) {
  803. final Entry e = entries.get(entryIndex++);
  804. if (e.match(section, subsection, name))
  805. entries.remove(--entryIndex);
  806. }
  807. }
  808. // Insert new Entry objects for additional/new values.
  809. //
  810. if (valueIndex < values.size() && entryIndex == entries.size()) {
  811. if (insertPosition < 0) {
  812. // We didn't find a matching key above, but maybe there
  813. // is already a section available that matches. Insert
  814. // after the last key of that section.
  815. //
  816. insertPosition = findSectionEnd(entries, section, subsection);
  817. }
  818. if (insertPosition < 0) {
  819. // We didn't find any matching section header for this key,
  820. // so we must create a new section header at the end.
  821. //
  822. final Entry e = new Entry();
  823. e.section = section;
  824. e.subsection = subsection;
  825. entries.add(e);
  826. insertPosition = entries.size();
  827. }
  828. while (valueIndex < values.size()) {
  829. final Entry e = new Entry();
  830. e.section = section;
  831. e.subsection = subsection;
  832. e.name = name;
  833. e.value = values.get(valueIndex++);
  834. entries.add(insertPosition++, e);
  835. }
  836. }
  837. return newState(entries);
  838. }
  839. private static List<Entry> copy(final State src, final List<String> values) {
  840. // At worst we need to insert 1 line for each value, plus 1 line
  841. // for a new section header. Assume that and allocate the space.
  842. //
  843. final int max = src.entryList.size() + values.size() + 1;
  844. final ArrayList<Entry> r = new ArrayList<Entry>(max);
  845. r.addAll(src.entryList);
  846. return r;
  847. }
  848. private static int findSectionEnd(final List<Entry> entries,
  849. final String section, final String subsection) {
  850. for (int i = 0; i < entries.size(); i++) {
  851. Entry e = entries.get(i);
  852. if (e.match(section, subsection, null)) {
  853. i++;
  854. while (i < entries.size()) {
  855. e = entries.get(i);
  856. if (e.match(section, subsection, e.name))
  857. i++;
  858. else
  859. break;
  860. }
  861. return i;
  862. }
  863. }
  864. return -1;
  865. }
  866. /**
  867. * @return this configuration, formatted as a Git style text file.
  868. */
  869. public String toText() {
  870. final StringBuilder out = new StringBuilder();
  871. for (final Entry e : state.get().entryList) {
  872. if (e.prefix != null)
  873. out.append(e.prefix);
  874. if (e.section != null && e.name == null) {
  875. out.append('[');
  876. out.append(e.section);
  877. if (e.subsection != null) {
  878. out.append(' ');
  879. String escaped = escapeValue(e.subsection);
  880. // make sure to avoid double quotes here
  881. boolean quoted = escaped.startsWith("\"")
  882. && escaped.endsWith("\"");
  883. if (!quoted)
  884. out.append('"');
  885. out.append(escaped);
  886. if (!quoted)
  887. out.append('"');
  888. }
  889. out.append(']');
  890. } else if (e.section != null && e.name != null) {
  891. if (e.prefix == null || "".equals(e.prefix))
  892. out.append('\t');
  893. out.append(e.name);
  894. if (MAGIC_EMPTY_VALUE != e.value) {
  895. out.append(" =");
  896. if (e.value != null) {
  897. out.append(' ');
  898. out.append(escapeValue(e.value));
  899. }
  900. }
  901. if (e.suffix != null)
  902. out.append(' ');
  903. }
  904. if (e.suffix != null)
  905. out.append(e.suffix);
  906. out.append('\n');
  907. }
  908. return out.toString();
  909. }
  910. /**
  911. * Clear this configuration and reset to the contents of the parsed string.
  912. *
  913. * @param text
  914. * Git style text file listing configuration properties.
  915. * @throws ConfigInvalidException
  916. * the text supplied is not formatted correctly. No changes were
  917. * made to {@code this}.
  918. */
  919. public void fromText(final String text) throws ConfigInvalidException {
  920. final List<Entry> newEntries = new ArrayList<Entry>();
  921. final StringReader in = new StringReader(text);
  922. Entry last = null;
  923. Entry e = new Entry();
  924. for (;;) {
  925. int input = in.read();
  926. if (-1 == input)
  927. break;
  928. final char c = (char) input;
  929. if ('\n' == c) {
  930. // End of this entry.
  931. newEntries.add(e);
  932. if (e.section != null)
  933. last = e;
  934. e = new Entry();
  935. } else if (e.suffix != null) {
  936. // Everything up until the end-of-line is in the suffix.
  937. e.suffix += c;
  938. } else if (';' == c || '#' == c) {
  939. // The rest of this line is a comment; put into suffix.
  940. e.suffix = String.valueOf(c);
  941. } else if (e.section == null && Character.isWhitespace(c)) {
  942. // Save the leading whitespace (if any).
  943. if (e.prefix == null)
  944. e.prefix = "";
  945. e.prefix += c;
  946. } else if ('[' == c) {
  947. // This is a section header.
  948. e.section = readSectionName(in);
  949. input = in.read();
  950. if ('"' == input) {
  951. e.subsection = readValue(in, true, '"');
  952. input = in.read();
  953. }
  954. if (']' != input)
  955. throw new ConfigInvalidException(JGitText.get().badGroupHeader);
  956. e.suffix = "";
  957. } else if (last != null) {
  958. // Read a value.
  959. e.section = last.section;
  960. e.subsection = last.subsection;
  961. in.reset();
  962. e.name = readKeyName(in);
  963. if (e.name.endsWith("\n")) {
  964. e.name = e.name.substring(0, e.name.length() - 1);
  965. e.value = MAGIC_EMPTY_VALUE;
  966. } else
  967. e.value = readValue(in, false, -1);
  968. } else
  969. throw new ConfigInvalidException(JGitText.get().invalidLineInConfigFile);
  970. }
  971. state.set(newState(newEntries));
  972. }
  973. private State newState() {
  974. return new State(Collections.<Entry> emptyList(), getBaseState());
  975. }
  976. private State newState(final List<Entry> entries) {
  977. return new State(Collections.unmodifiableList(entries), getBaseState());
  978. }
  979. /**
  980. * Clear the configuration file
  981. */
  982. protected void clear() {
  983. state.set(newState());
  984. }
  985. private static String readSectionName(final StringReader in)
  986. throws ConfigInvalidException {
  987. final StringBuilder name = new StringBuilder();
  988. for (;;) {
  989. int c = in.read();
  990. if (c < 0)
  991. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  992. if (']' == c) {
  993. in.reset();
  994. break;
  995. }
  996. if (' ' == c || '\t' == c) {
  997. for (;;) {
  998. c = in.read();
  999. if (c < 0)
  1000. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1001. if ('"' == c) {
  1002. in.reset();
  1003. break;
  1004. }
  1005. if (' ' == c || '\t' == c)
  1006. continue; // Skipped...
  1007. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badSectionEntry, name));
  1008. }
  1009. break;
  1010. }
  1011. if (Character.isLetterOrDigit((char) c) || '.' == c || '-' == c)
  1012. name.append((char) c);
  1013. else
  1014. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badSectionEntry, name));
  1015. }
  1016. return name.toString();
  1017. }
  1018. private static String readKeyName(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. break;
  1027. if (' ' == c || '\t' == c) {
  1028. for (;;) {
  1029. c = in.read();
  1030. if (c < 0)
  1031. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1032. if ('=' == c)
  1033. break;
  1034. if (';' == c || '#' == c || '\n' == c) {
  1035. in.reset();
  1036. break;
  1037. }
  1038. if (' ' == c || '\t' == c)
  1039. continue; // Skipped...
  1040. throw new ConfigInvalidException(JGitText.get().badEntryDelimiter);
  1041. }
  1042. break;
  1043. }
  1044. if (Character.isLetterOrDigit((char) c) || c == '-') {
  1045. // From the git-config man page:
  1046. // The variable names are case-insensitive and only
  1047. // alphanumeric characters and - are allowed.
  1048. name.append((char) c);
  1049. } else if ('\n' == c) {
  1050. in.reset();
  1051. name.append((char) c);
  1052. break;
  1053. } else
  1054. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badEntryName, name));
  1055. }
  1056. return name.toString();
  1057. }
  1058. private static String readValue(final StringReader in, boolean quote,
  1059. final int eol) throws ConfigInvalidException {
  1060. final StringBuilder value = new StringBuilder();
  1061. boolean space = false;
  1062. for (;;) {
  1063. int c = in.read();
  1064. if (c < 0) {
  1065. if (value.length() == 0)
  1066. throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);
  1067. break;
  1068. }
  1069. if ('\n' == c) {
  1070. if (quote)
  1071. throw new ConfigInvalidException(JGitText.get().newlineInQuotesNotAllowed);
  1072. in.reset();
  1073. break;
  1074. }
  1075. if (eol == c)
  1076. break;
  1077. if (!quote) {
  1078. if (Character.isWhitespace((char) c)) {
  1079. space = true;
  1080. continue;
  1081. }
  1082. if (';' == c || '#' == c) {
  1083. in.reset();
  1084. break;
  1085. }
  1086. }
  1087. if (space) {
  1088. if (value.length() > 0)
  1089. value.append(' ');
  1090. space = false;
  1091. }
  1092. if ('\\' == c) {
  1093. c = in.read();
  1094. switch (c) {
  1095. case -1:
  1096. throw new ConfigInvalidException(JGitText.get().endOfFileInEscape);
  1097. case '\n':
  1098. continue;
  1099. case 't':
  1100. value.append('\t');
  1101. continue;
  1102. case 'b':
  1103. value.append('\b');
  1104. continue;
  1105. case 'n':
  1106. value.append('\n');
  1107. continue;
  1108. case '\\':
  1109. value.append('\\');
  1110. continue;
  1111. case '"':
  1112. value.append('"');
  1113. continue;
  1114. default:
  1115. throw new ConfigInvalidException(MessageFormat.format(JGitText.get().badEscape, ((char) c)));
  1116. }
  1117. }
  1118. if ('"' == c) {
  1119. quote = !quote;
  1120. continue;
  1121. }
  1122. value.append((char) c);
  1123. }
  1124. return value.length() > 0 ? value.toString() : null;
  1125. }
  1126. /**
  1127. * Parses a section of the configuration into an application model object.
  1128. * <p>
  1129. * Instances must implement hashCode and equals such that model objects can
  1130. * be cached by using the {@code SectionParser} as a key of a HashMap.
  1131. * <p>
  1132. * As the {@code SectionParser} itself is used as the key of the internal
  1133. * HashMap applications should be careful to ensure the SectionParser key
  1134. * does not retain unnecessary application state which may cause memory to
  1135. * be held longer than expected.
  1136. *
  1137. * @param <T>
  1138. * type of the application model created by the parser.
  1139. */
  1140. public static interface SectionParser<T> {
  1141. /**
  1142. * Create a model object from a configuration.
  1143. *
  1144. * @param cfg
  1145. * the configuration to read values from.
  1146. * @return the application model instance.
  1147. */
  1148. T parse(Config cfg);
  1149. }
  1150. private static class SubsectionNames implements SectionParser<Set<String>> {
  1151. private final String section;
  1152. SubsectionNames(final String sectionName) {
  1153. section = sectionName;
  1154. }
  1155. public int hashCode() {
  1156. return section.hashCode();
  1157. }
  1158. public boolean equals(Object other) {
  1159. if (other instanceof SubsectionNames) {
  1160. return section.equals(((SubsectionNames) other).section);
  1161. }
  1162. return false;
  1163. }
  1164. public Set<String> parse(Config cfg) {
  1165. final Set<String> result = new HashSet<String>();
  1166. while (cfg != null) {
  1167. for (final Entry e : cfg.state.get().entryList) {
  1168. if (e.subsection != null && e.name == null
  1169. && StringUtils.equalsIgnoreCase(section, e.section))
  1170. result.add(e.subsection);
  1171. }
  1172. cfg = cfg.baseConfig;
  1173. }
  1174. return Collections.unmodifiableSet(result);
  1175. }
  1176. }
  1177. private static class NamesInSection implements SectionParser<Set<String>> {
  1178. private final String section;
  1179. private final String subsection;
  1180. NamesInSection(final String sectionName, final String subSectionName) {
  1181. section = sectionName;
  1182. subsection = subSectionName;
  1183. }
  1184. @Override
  1185. public int hashCode() {
  1186. final int prime = 31;
  1187. int result = 1;
  1188. result = prime * result + section.hashCode();
  1189. result = prime * result
  1190. + ((subsection == null) ? 0 : subsection.hashCode());
  1191. return result;
  1192. }
  1193. @Override
  1194. public boolean equals(Object obj) {
  1195. if (this == obj)
  1196. return true;
  1197. if (obj == null)
  1198. return false;
  1199. if (getClass() != obj.getClass())
  1200. return false;
  1201. NamesInSection other = (NamesInSection) obj;
  1202. if (!section.equals(other.section))
  1203. return false;
  1204. if (subsection == null) {
  1205. if (other.subsection != null)
  1206. return false;
  1207. } else if (!subsection.equals(other.subsection))
  1208. return false;
  1209. return true;
  1210. }
  1211. public Set<String> parse(Config cfg) {
  1212. final Set<String> result = new HashSet<String>();
  1213. while (cfg != null) {
  1214. for (final Entry e : cfg.state.get().entryList) {
  1215. if (e.name != null
  1216. && StringUtils.equalsIgnoreCase(e.section, section)) {
  1217. if (subsection == null && e.subsection == null)
  1218. result.add(StringUtils.toLowerCase(e.name));
  1219. else if (e.subsection != null
  1220. && e.subsection.equals(subsection))
  1221. result.add(StringUtils.toLowerCase(e.name));
  1222. }
  1223. }
  1224. cfg = cfg.baseConfig;
  1225. }
  1226. return Collections.unmodifiableSet(result);
  1227. }
  1228. }
  1229. private static class SectionNames implements SectionParser<Set<String>> {
  1230. public Set<String> parse(Config cfg) {
  1231. final Set<String> result = new HashSet<String>();
  1232. while (cfg != null) {
  1233. for (final Entry e : cfg.state.get().entryList) {
  1234. if (e.section != null)
  1235. result.add(StringUtils.toLowerCase(e.section));
  1236. }
  1237. cfg = cfg.baseConfig;
  1238. }
  1239. return Collections.unmodifiableSet(result);
  1240. }
  1241. }
  1242. private static class State {
  1243. final List<Entry> entryList;
  1244. final Map<Object, Object> cache;
  1245. final State baseState;
  1246. State(List<Entry> entries, State base) {
  1247. entryList = entries;
  1248. cache = new ConcurrentHashMap<Object, Object>(16, 0.75f, 1);
  1249. baseState = base;
  1250. }
  1251. }
  1252. /**
  1253. * The configuration file entry
  1254. */
  1255. private static class Entry {
  1256. /**
  1257. * The text content before entry
  1258. */
  1259. String prefix;
  1260. /**
  1261. * The section name for the entry
  1262. */
  1263. String section;
  1264. /**
  1265. * Subsection name
  1266. */
  1267. String subsection;
  1268. /**
  1269. * The key name
  1270. */
  1271. String name;
  1272. /**
  1273. * The value
  1274. */
  1275. String value;
  1276. /**
  1277. * The text content after entry
  1278. */
  1279. String suffix;
  1280. Entry forValue(final String newValue) {
  1281. final Entry e = new Entry();
  1282. e.prefix = prefix;
  1283. e.section = section;
  1284. e.subsection = subsection;
  1285. e.name = name;
  1286. e.value = newValue;
  1287. e.suffix = suffix;
  1288. return e;
  1289. }
  1290. boolean match(final String aSection, final String aSubsection,
  1291. final String aKey) {
  1292. return eqIgnoreCase(section, aSection)
  1293. && eqSameCase(subsection, aSubsection)
  1294. && eqIgnoreCase(name, aKey);
  1295. }
  1296. boolean match(final String aSection, final String aSubsection) {
  1297. return eqIgnoreCase(section, aSection)
  1298. && eqSameCase(subsection, aSubsection);
  1299. }
  1300. private static boolean eqIgnoreCase(final String a, final String b) {
  1301. if (a == null && b == null)
  1302. return true;
  1303. if (a == null || b == null)
  1304. return false;
  1305. return StringUtils.equalsIgnoreCase(a, b);
  1306. }
  1307. private static boolean eqSameCase(final String a, final String b) {
  1308. if (a == null && b == null)
  1309. return true;
  1310. if (a == null || b == null)
  1311. return false;
  1312. return a.equals(b);
  1313. }
  1314. }
  1315. private static class StringReader {
  1316. private final char[] buf;
  1317. private int pos;
  1318. StringReader(final String in) {
  1319. buf = in.toCharArray();
  1320. }
  1321. int read() {
  1322. try {
  1323. return buf[pos++];
  1324. } catch (ArrayIndexOutOfBoundsException e) {
  1325. pos = buf.length;
  1326. return -1;
  1327. }
  1328. }
  1329. void reset() {
  1330. pos--;
  1331. }
  1332. }
  1333. }