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

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