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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  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. }
  1286. inLeadingSpace = false;
  1287. if (trailingSpaces != null) {
  1288. value.append(trailingSpaces);
  1289. trailingSpaces.setLength(0);
  1290. }
  1291. if ('\\' == c) {
  1292. c = in.read();
  1293. switch (c) {
  1294. case -1:
  1295. throw new ConfigInvalidException(JGitText.get().endOfFileInEscape);
  1296. case '\n':
  1297. continue;
  1298. case 't':
  1299. value.append('\t');
  1300. continue;
  1301. case 'b':
  1302. value.append('\b');
  1303. continue;
  1304. case 'n':
  1305. value.append('\n');
  1306. continue;
  1307. case '\\':
  1308. value.append('\\');
  1309. continue;
  1310. case '"':
  1311. value.append('"');
  1312. continue;
  1313. case '\r': {
  1314. int next = in.read();
  1315. if (next == '\n') {
  1316. continue; // CR-LF
  1317. } else if (next >= 0) {
  1318. in.reset();
  1319. }
  1320. break;
  1321. }
  1322. default:
  1323. break;
  1324. }
  1325. throw new ConfigInvalidException(
  1326. MessageFormat.format(JGitText.get().badEscape,
  1327. Character.isAlphabetic(c)
  1328. ? Character.valueOf(((char) c))
  1329. : toUnicodeLiteral(c)));
  1330. }
  1331. if ('"' == c) {
  1332. quote = !quote;
  1333. continue;
  1334. }
  1335. value.append(cc);
  1336. }
  1337. return value.length() > 0 ? value.toString() : null;
  1338. }
  1339. private static String toUnicodeLiteral(int c) {
  1340. return String.format("\\u%04x", //$NON-NLS-1$
  1341. Integer.valueOf(c));
  1342. }
  1343. /**
  1344. * Parses a section of the configuration into an application model object.
  1345. * <p>
  1346. * Instances must implement hashCode and equals such that model objects can
  1347. * be cached by using the {@code SectionParser} as a key of a HashMap.
  1348. * <p>
  1349. * As the {@code SectionParser} itself is used as the key of the internal
  1350. * HashMap applications should be careful to ensure the SectionParser key
  1351. * does not retain unnecessary application state which may cause memory to
  1352. * be held longer than expected.
  1353. *
  1354. * @param <T>
  1355. * type of the application model created by the parser.
  1356. */
  1357. public static interface SectionParser<T> {
  1358. /**
  1359. * Create a model object from a configuration.
  1360. *
  1361. * @param cfg
  1362. * the configuration to read values from.
  1363. * @return the application model instance.
  1364. */
  1365. T parse(Config cfg);
  1366. }
  1367. private static class StringReader {
  1368. private final char[] buf;
  1369. private int pos;
  1370. StringReader(String in) {
  1371. buf = in.toCharArray();
  1372. }
  1373. int read() {
  1374. if (pos >= buf.length) {
  1375. return -1;
  1376. }
  1377. return buf[pos++];
  1378. }
  1379. void reset() {
  1380. pos--;
  1381. }
  1382. }
  1383. /**
  1384. * Converts enumeration values into configuration options and vice-versa,
  1385. * allowing to match a config option with an enum value.
  1386. *
  1387. */
  1388. public static interface ConfigEnum {
  1389. /**
  1390. * Converts enumeration value into a string to be save in config.
  1391. *
  1392. * @return the enum value as config string
  1393. */
  1394. String toConfigValue();
  1395. /**
  1396. * Checks if the given string matches with enum value.
  1397. *
  1398. * @param in
  1399. * the string to match
  1400. * @return true if the given string matches enum value, false otherwise
  1401. */
  1402. boolean matchConfigValue(String in);
  1403. }
  1404. }