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

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