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

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