Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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