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

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