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

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