Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Config.java 43KB

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