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

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