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.

ConfigTest.java 56KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2009-2010, Google Inc.
  4. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  5. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  6. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  7. * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com>
  8. * and other copyright owners as documented in the project's IP log.
  9. *
  10. * This program and the accompanying materials are made available
  11. * under the terms of the Eclipse Distribution License v1.0 which
  12. * accompanies this distribution, is reproduced below, and is
  13. * available at http://www.eclipse.org/org/documents/edl-v10.php
  14. *
  15. * All rights reserved.
  16. *
  17. * Redistribution and use in source and binary forms, with or
  18. * without modification, are permitted provided that the following
  19. * conditions are met:
  20. *
  21. * - Redistributions of source code must retain the above copyright
  22. * notice, this list of conditions and the following disclaimer.
  23. *
  24. * - Redistributions in binary form must reproduce the above
  25. * copyright notice, this list of conditions and the following
  26. * disclaimer in the documentation and/or other materials provided
  27. * with the distribution.
  28. *
  29. * - Neither the name of the Eclipse Foundation, Inc. nor the
  30. * names of its contributors may be used to endorse or promote
  31. * products derived from this software without specific prior
  32. * written permission.
  33. *
  34. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  35. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  36. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  38. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  39. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  43. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  46. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. */
  48. package org.eclipse.jgit.lib;
  49. import static java.nio.charset.StandardCharsets.UTF_8;
  50. import static java.util.concurrent.TimeUnit.DAYS;
  51. import static java.util.concurrent.TimeUnit.HOURS;
  52. import static java.util.concurrent.TimeUnit.MICROSECONDS;
  53. import static java.util.concurrent.TimeUnit.MILLISECONDS;
  54. import static java.util.concurrent.TimeUnit.MINUTES;
  55. import static java.util.concurrent.TimeUnit.NANOSECONDS;
  56. import static java.util.concurrent.TimeUnit.SECONDS;
  57. import static org.eclipse.jgit.util.FileUtils.pathToString;
  58. import static org.junit.Assert.assertArrayEquals;
  59. import static org.junit.Assert.assertEquals;
  60. import static org.junit.Assert.assertFalse;
  61. import static org.junit.Assert.assertNull;
  62. import static org.junit.Assert.assertSame;
  63. import static org.junit.Assert.assertTrue;
  64. import static org.junit.Assert.fail;
  65. import java.io.File;
  66. import java.io.IOException;
  67. import java.nio.file.Files;
  68. import java.text.MessageFormat;
  69. import java.util.ArrayList;
  70. import java.util.Arrays;
  71. import java.util.Collections;
  72. import java.util.Iterator;
  73. import java.util.LinkedList;
  74. import java.util.List;
  75. import java.util.Set;
  76. import java.util.concurrent.TimeUnit;
  77. import java.util.function.Consumer;
  78. import org.eclipse.jgit.api.MergeCommand.FastForwardMode;
  79. import org.eclipse.jgit.errors.ConfigInvalidException;
  80. import org.eclipse.jgit.internal.JGitText;
  81. import org.eclipse.jgit.junit.MockSystemReader;
  82. import org.eclipse.jgit.merge.MergeConfig;
  83. import org.eclipse.jgit.storage.file.FileBasedConfig;
  84. import org.eclipse.jgit.transport.RefSpec;
  85. import org.eclipse.jgit.util.FS;
  86. import org.eclipse.jgit.util.SystemReader;
  87. import org.junit.After;
  88. import org.junit.Rule;
  89. import org.junit.Test;
  90. import org.junit.rules.ExpectedException;
  91. import org.junit.rules.TemporaryFolder;
  92. /**
  93. * Test reading of git config
  94. */
  95. @SuppressWarnings("boxing")
  96. public class ConfigTest {
  97. // A non-ASCII whitespace character: U+2002 EN QUAD.
  98. private static final char WS = '\u2002';
  99. private static final String REFS_ORIGIN = "+refs/heads/*:refs/remotes/origin/*";
  100. private static final String REFS_UPSTREAM = "+refs/heads/*:refs/remotes/upstream/*";
  101. private static final String REFS_BACKUP = "+refs/heads/*:refs/remotes/backup/*";
  102. @Rule
  103. public ExpectedException expectedEx = ExpectedException.none();
  104. @Rule
  105. public TemporaryFolder tmp = new TemporaryFolder();
  106. @After
  107. public void tearDown() {
  108. SystemReader.setInstance(null);
  109. }
  110. @Test
  111. public void test001_ReadBareKey() throws ConfigInvalidException {
  112. final Config c = parse("[foo]\nbar\n");
  113. assertTrue(c.getBoolean("foo", null, "bar", false));
  114. assertEquals("", c.getString("foo", null, "bar"));
  115. }
  116. @Test
  117. public void test002_ReadWithSubsection() throws ConfigInvalidException {
  118. final Config c = parse("[foo \"zip\"]\nbar\n[foo \"zap\"]\nbar=false\nn=3\n");
  119. assertTrue(c.getBoolean("foo", "zip", "bar", false));
  120. assertEquals("", c.getString("foo","zip", "bar"));
  121. assertFalse(c.getBoolean("foo", "zap", "bar", true));
  122. assertEquals("false", c.getString("foo", "zap", "bar"));
  123. assertEquals(3, c.getInt("foo", "zap", "n", 4));
  124. assertEquals(4, c.getInt("foo", "zap","m", 4));
  125. }
  126. @Test
  127. public void test003_PutRemote() {
  128. final Config c = new Config();
  129. c.setString("sec", "ext", "name", "value");
  130. c.setString("sec", "ext", "name2", "value2");
  131. final String expText = "[sec \"ext\"]\n\tname = value\n\tname2 = value2\n";
  132. assertEquals(expText, c.toText());
  133. }
  134. @Test
  135. public void test004_PutGetSimple() {
  136. Config c = new Config();
  137. c.setString("my", null, "somename", "false");
  138. assertEquals("false", c.getString("my", null, "somename"));
  139. assertEquals("[my]\n\tsomename = false\n", c.toText());
  140. }
  141. @Test
  142. public void test005_PutGetStringList() {
  143. Config c = new Config();
  144. final LinkedList<String> values = new LinkedList<>();
  145. values.add("value1");
  146. values.add("value2");
  147. c.setStringList("my", null, "somename", values);
  148. final Object[] expArr = values.toArray();
  149. final String[] actArr = c.getStringList("my", null, "somename");
  150. assertArrayEquals(expArr, actArr);
  151. final String expText = "[my]\n\tsomename = value1\n\tsomename = value2\n";
  152. assertEquals(expText, c.toText());
  153. }
  154. @Test
  155. public void test006_readCaseInsensitive() throws ConfigInvalidException {
  156. final Config c = parse("[Foo]\nBar\n");
  157. assertTrue(c.getBoolean("foo", null, "bar", false));
  158. assertEquals("", c.getString("foo", null, "bar"));
  159. }
  160. @Test
  161. public void test007_readUserConfig() {
  162. final MockSystemReader mockSystemReader = new MockSystemReader();
  163. SystemReader.setInstance(mockSystemReader);
  164. final String hostname = mockSystemReader.getHostname();
  165. final Config userGitConfig = mockSystemReader.openUserConfig(null,
  166. FS.DETECTED);
  167. final Config localConfig = new Config(userGitConfig);
  168. mockSystemReader.clearProperties();
  169. String authorName;
  170. String authorEmail;
  171. // no values defined nowhere
  172. authorName = localConfig.get(UserConfig.KEY).getAuthorName();
  173. authorEmail = localConfig.get(UserConfig.KEY).getAuthorEmail();
  174. assertEquals(Constants.UNKNOWN_USER_DEFAULT, authorName);
  175. assertEquals(Constants.UNKNOWN_USER_DEFAULT + "@" + hostname, authorEmail);
  176. assertTrue(localConfig.get(UserConfig.KEY).isAuthorNameImplicit());
  177. assertTrue(localConfig.get(UserConfig.KEY).isAuthorEmailImplicit());
  178. // the system user name is defined
  179. mockSystemReader.setProperty(Constants.OS_USER_NAME_KEY, "os user name");
  180. localConfig.uncache(UserConfig.KEY);
  181. authorName = localConfig.get(UserConfig.KEY).getAuthorName();
  182. assertEquals("os user name", authorName);
  183. assertTrue(localConfig.get(UserConfig.KEY).isAuthorNameImplicit());
  184. if (hostname != null && hostname.length() != 0) {
  185. authorEmail = localConfig.get(UserConfig.KEY).getAuthorEmail();
  186. assertEquals("os user name@" + hostname, authorEmail);
  187. }
  188. assertTrue(localConfig.get(UserConfig.KEY).isAuthorEmailImplicit());
  189. // the git environment variables are defined
  190. mockSystemReader.setProperty(Constants.GIT_AUTHOR_NAME_KEY, "git author name");
  191. mockSystemReader.setProperty(Constants.GIT_AUTHOR_EMAIL_KEY, "author@email");
  192. localConfig.uncache(UserConfig.KEY);
  193. authorName = localConfig.get(UserConfig.KEY).getAuthorName();
  194. authorEmail = localConfig.get(UserConfig.KEY).getAuthorEmail();
  195. assertEquals("git author name", authorName);
  196. assertEquals("author@email", authorEmail);
  197. assertFalse(localConfig.get(UserConfig.KEY).isAuthorNameImplicit());
  198. assertFalse(localConfig.get(UserConfig.KEY).isAuthorEmailImplicit());
  199. // the values are defined in the global configuration
  200. // first clear environment variables since they would override
  201. // configuration files
  202. mockSystemReader.clearProperties();
  203. userGitConfig.setString("user", null, "name", "global username");
  204. userGitConfig.setString("user", null, "email", "author@globalemail");
  205. authorName = localConfig.get(UserConfig.KEY).getAuthorName();
  206. authorEmail = localConfig.get(UserConfig.KEY).getAuthorEmail();
  207. assertEquals("global username", authorName);
  208. assertEquals("author@globalemail", authorEmail);
  209. assertFalse(localConfig.get(UserConfig.KEY).isAuthorNameImplicit());
  210. assertFalse(localConfig.get(UserConfig.KEY).isAuthorEmailImplicit());
  211. // the values are defined in the local configuration
  212. localConfig.setString("user", null, "name", "local username");
  213. localConfig.setString("user", null, "email", "author@localemail");
  214. authorName = localConfig.get(UserConfig.KEY).getAuthorName();
  215. authorEmail = localConfig.get(UserConfig.KEY).getAuthorEmail();
  216. assertEquals("local username", authorName);
  217. assertEquals("author@localemail", authorEmail);
  218. assertFalse(localConfig.get(UserConfig.KEY).isAuthorNameImplicit());
  219. assertFalse(localConfig.get(UserConfig.KEY).isAuthorEmailImplicit());
  220. authorName = localConfig.get(UserConfig.KEY).getCommitterName();
  221. authorEmail = localConfig.get(UserConfig.KEY).getCommitterEmail();
  222. assertEquals("local username", authorName);
  223. assertEquals("author@localemail", authorEmail);
  224. assertFalse(localConfig.get(UserConfig.KEY).isCommitterNameImplicit());
  225. assertFalse(localConfig.get(UserConfig.KEY).isCommitterEmailImplicit());
  226. // also git environment variables are defined
  227. mockSystemReader.setProperty(Constants.GIT_AUTHOR_NAME_KEY,
  228. "git author name");
  229. mockSystemReader.setProperty(Constants.GIT_AUTHOR_EMAIL_KEY,
  230. "author@email");
  231. localConfig.setString("user", null, "name", "local username");
  232. localConfig.setString("user", null, "email", "author@localemail");
  233. authorName = localConfig.get(UserConfig.KEY).getAuthorName();
  234. authorEmail = localConfig.get(UserConfig.KEY).getAuthorEmail();
  235. assertEquals("git author name", authorName);
  236. assertEquals("author@email", authorEmail);
  237. assertFalse(localConfig.get(UserConfig.KEY).isAuthorNameImplicit());
  238. assertFalse(localConfig.get(UserConfig.KEY).isAuthorEmailImplicit());
  239. }
  240. @Test
  241. public void testReadUserConfigWithInvalidCharactersStripped() {
  242. final MockSystemReader mockSystemReader = new MockSystemReader();
  243. final Config localConfig = new Config(mockSystemReader.openUserConfig(
  244. null, FS.DETECTED));
  245. localConfig.setString("user", null, "name", "foo<bar");
  246. localConfig.setString("user", null, "email", "baz>\nqux@example.com");
  247. UserConfig userConfig = localConfig.get(UserConfig.KEY);
  248. assertEquals("foobar", userConfig.getAuthorName());
  249. assertEquals("bazqux@example.com", userConfig.getAuthorEmail());
  250. }
  251. @Test
  252. public void testReadBoolean_TrueFalse1() throws ConfigInvalidException {
  253. final Config c = parse("[s]\na = true\nb = false\n");
  254. assertEquals("true", c.getString("s", null, "a"));
  255. assertEquals("false", c.getString("s", null, "b"));
  256. assertTrue(c.getBoolean("s", "a", false));
  257. assertFalse(c.getBoolean("s", "b", true));
  258. }
  259. @Test
  260. public void testReadBoolean_TrueFalse2() throws ConfigInvalidException {
  261. final Config c = parse("[s]\na = TrUe\nb = fAlSe\n");
  262. assertEquals("TrUe", c.getString("s", null, "a"));
  263. assertEquals("fAlSe", c.getString("s", null, "b"));
  264. assertTrue(c.getBoolean("s", "a", false));
  265. assertFalse(c.getBoolean("s", "b", true));
  266. }
  267. @Test
  268. public void testReadBoolean_YesNo1() throws ConfigInvalidException {
  269. final Config c = parse("[s]\na = yes\nb = no\n");
  270. assertEquals("yes", c.getString("s", null, "a"));
  271. assertEquals("no", c.getString("s", null, "b"));
  272. assertTrue(c.getBoolean("s", "a", false));
  273. assertFalse(c.getBoolean("s", "b", true));
  274. }
  275. @Test
  276. public void testReadBoolean_YesNo2() throws ConfigInvalidException {
  277. final Config c = parse("[s]\na = yEs\nb = NO\n");
  278. assertEquals("yEs", c.getString("s", null, "a"));
  279. assertEquals("NO", c.getString("s", null, "b"));
  280. assertTrue(c.getBoolean("s", "a", false));
  281. assertFalse(c.getBoolean("s", "b", true));
  282. }
  283. @Test
  284. public void testReadBoolean_OnOff1() throws ConfigInvalidException {
  285. final Config c = parse("[s]\na = on\nb = off\n");
  286. assertEquals("on", c.getString("s", null, "a"));
  287. assertEquals("off", c.getString("s", null, "b"));
  288. assertTrue(c.getBoolean("s", "a", false));
  289. assertFalse(c.getBoolean("s", "b", true));
  290. }
  291. @Test
  292. public void testReadBoolean_OnOff2() throws ConfigInvalidException {
  293. final Config c = parse("[s]\na = ON\nb = OFF\n");
  294. assertEquals("ON", c.getString("s", null, "a"));
  295. assertEquals("OFF", c.getString("s", null, "b"));
  296. assertTrue(c.getBoolean("s", "a", false));
  297. assertFalse(c.getBoolean("s", "b", true));
  298. }
  299. static enum TestEnum {
  300. ONE_TWO;
  301. }
  302. @Test
  303. public void testGetEnum() throws ConfigInvalidException {
  304. Config c = parse("[s]\na = ON\nb = input\nc = true\nd = off\n");
  305. assertSame(CoreConfig.AutoCRLF.TRUE, c.getEnum("s", null, "a",
  306. CoreConfig.AutoCRLF.FALSE));
  307. assertSame(CoreConfig.AutoCRLF.INPUT, c.getEnum("s", null, "b",
  308. CoreConfig.AutoCRLF.FALSE));
  309. assertSame(CoreConfig.AutoCRLF.TRUE, c.getEnum("s", null, "c",
  310. CoreConfig.AutoCRLF.FALSE));
  311. assertSame(CoreConfig.AutoCRLF.FALSE, c.getEnum("s", null, "d",
  312. CoreConfig.AutoCRLF.TRUE));
  313. c = new Config();
  314. assertSame(CoreConfig.AutoCRLF.FALSE, c.getEnum("s", null, "d",
  315. CoreConfig.AutoCRLF.FALSE));
  316. c = parse("[s \"b\"]\n\tc = one two\n");
  317. assertSame(TestEnum.ONE_TWO, c.getEnum("s", "b", "c", TestEnum.ONE_TWO));
  318. c = parse("[s \"b\"]\n\tc = one-two\n");
  319. assertSame(TestEnum.ONE_TWO, c.getEnum("s", "b", "c", TestEnum.ONE_TWO));
  320. }
  321. @Test
  322. public void testGetInvalidEnum() throws ConfigInvalidException {
  323. Config c = parse("[a]\n\tb = invalid\n");
  324. try {
  325. c.getEnum("a", null, "b", TestEnum.ONE_TWO);
  326. fail();
  327. } catch (IllegalArgumentException e) {
  328. assertEquals("Invalid value: a.b=invalid", e.getMessage());
  329. }
  330. c = parse("[a \"b\"]\n\tc = invalid\n");
  331. try {
  332. c.getEnum("a", "b", "c", TestEnum.ONE_TWO);
  333. fail();
  334. } catch (IllegalArgumentException e) {
  335. assertEquals("Invalid value: a.b.c=invalid", e.getMessage());
  336. }
  337. }
  338. @Test
  339. public void testSetEnum() {
  340. final Config c = new Config();
  341. c.setEnum("s", "b", "c", TestEnum.ONE_TWO);
  342. assertEquals("[s \"b\"]\n\tc = one two\n", c.toText());
  343. }
  344. @Test
  345. public void testGetFastForwardMergeoptions() throws ConfigInvalidException {
  346. Config c = new Config(null); // not set
  347. assertSame(FastForwardMode.FF, c.getEnum(
  348. ConfigConstants.CONFIG_BRANCH_SECTION, "side",
  349. ConfigConstants.CONFIG_KEY_MERGEOPTIONS, FastForwardMode.FF));
  350. MergeConfig mergeConfig = c.get(MergeConfig.getParser("side"));
  351. assertSame(FastForwardMode.FF, mergeConfig.getFastForwardMode());
  352. c = parse("[branch \"side\"]\n\tmergeoptions = --ff-only\n");
  353. assertSame(FastForwardMode.FF_ONLY, c.getEnum(
  354. ConfigConstants.CONFIG_BRANCH_SECTION, "side",
  355. ConfigConstants.CONFIG_KEY_MERGEOPTIONS,
  356. FastForwardMode.FF_ONLY));
  357. mergeConfig = c.get(MergeConfig.getParser("side"));
  358. assertSame(FastForwardMode.FF_ONLY, mergeConfig.getFastForwardMode());
  359. c = parse("[branch \"side\"]\n\tmergeoptions = --ff\n");
  360. assertSame(FastForwardMode.FF, c.getEnum(
  361. ConfigConstants.CONFIG_BRANCH_SECTION, "side",
  362. ConfigConstants.CONFIG_KEY_MERGEOPTIONS, FastForwardMode.FF));
  363. mergeConfig = c.get(MergeConfig.getParser("side"));
  364. assertSame(FastForwardMode.FF, mergeConfig.getFastForwardMode());
  365. c = parse("[branch \"side\"]\n\tmergeoptions = --no-ff\n");
  366. assertSame(FastForwardMode.NO_FF, c.getEnum(
  367. ConfigConstants.CONFIG_BRANCH_SECTION, "side",
  368. ConfigConstants.CONFIG_KEY_MERGEOPTIONS, FastForwardMode.NO_FF));
  369. mergeConfig = c.get(MergeConfig.getParser("side"));
  370. assertSame(FastForwardMode.NO_FF, mergeConfig.getFastForwardMode());
  371. }
  372. @Test
  373. public void testSetFastForwardMergeoptions() {
  374. final Config c = new Config();
  375. c.setEnum("branch", "side", "mergeoptions", FastForwardMode.FF);
  376. assertEquals("[branch \"side\"]\n\tmergeoptions = --ff\n", c.toText());
  377. c.setEnum("branch", "side", "mergeoptions", FastForwardMode.FF_ONLY);
  378. assertEquals("[branch \"side\"]\n\tmergeoptions = --ff-only\n",
  379. c.toText());
  380. c.setEnum("branch", "side", "mergeoptions", FastForwardMode.NO_FF);
  381. assertEquals("[branch \"side\"]\n\tmergeoptions = --no-ff\n",
  382. c.toText());
  383. }
  384. @Test
  385. public void testGetFastForwardMerge() throws ConfigInvalidException {
  386. Config c = new Config(null); // not set
  387. assertSame(FastForwardMode.Merge.TRUE, c.getEnum(
  388. ConfigConstants.CONFIG_KEY_MERGE, null,
  389. ConfigConstants.CONFIG_KEY_FF, FastForwardMode.Merge.TRUE));
  390. MergeConfig mergeConfig = c.get(MergeConfig.getParser("side"));
  391. assertSame(FastForwardMode.FF, mergeConfig.getFastForwardMode());
  392. c = parse("[merge]\n\tff = only\n");
  393. assertSame(FastForwardMode.Merge.ONLY, c.getEnum(
  394. ConfigConstants.CONFIG_KEY_MERGE, null,
  395. ConfigConstants.CONFIG_KEY_FF, FastForwardMode.Merge.ONLY));
  396. mergeConfig = c.get(MergeConfig.getParser("side"));
  397. assertSame(FastForwardMode.FF_ONLY, mergeConfig.getFastForwardMode());
  398. c = parse("[merge]\n\tff = true\n");
  399. assertSame(FastForwardMode.Merge.TRUE, c.getEnum(
  400. ConfigConstants.CONFIG_KEY_MERGE, null,
  401. ConfigConstants.CONFIG_KEY_FF, FastForwardMode.Merge.TRUE));
  402. mergeConfig = c.get(MergeConfig.getParser("side"));
  403. assertSame(FastForwardMode.FF, mergeConfig.getFastForwardMode());
  404. c = parse("[merge]\n\tff = false\n");
  405. assertSame(FastForwardMode.Merge.FALSE, c.getEnum(
  406. ConfigConstants.CONFIG_KEY_MERGE, null,
  407. ConfigConstants.CONFIG_KEY_FF, FastForwardMode.Merge.FALSE));
  408. mergeConfig = c.get(MergeConfig.getParser("side"));
  409. assertSame(FastForwardMode.NO_FF, mergeConfig.getFastForwardMode());
  410. }
  411. @Test
  412. public void testCombinedMergeOptions() throws ConfigInvalidException {
  413. Config c = new Config(null); // not set
  414. MergeConfig mergeConfig = c.get(MergeConfig.getParser("side"));
  415. assertSame(FastForwardMode.FF, mergeConfig.getFastForwardMode());
  416. assertTrue(mergeConfig.isCommit());
  417. assertFalse(mergeConfig.isSquash());
  418. // branch..mergeoptions should win over merge.ff
  419. c = parse("[merge]\n\tff = false\n"
  420. + "[branch \"side\"]\n\tmergeoptions = --ff-only\n");
  421. mergeConfig = c.get(MergeConfig.getParser("side"));
  422. assertSame(FastForwardMode.FF_ONLY, mergeConfig.getFastForwardMode());
  423. assertTrue(mergeConfig.isCommit());
  424. assertFalse(mergeConfig.isSquash());
  425. // merge.ff used for ff setting if not set via mergeoptions
  426. c = parse("[merge]\n\tff = only\n"
  427. + "[branch \"side\"]\n\tmergeoptions = --squash\n");
  428. mergeConfig = c.get(MergeConfig.getParser("side"));
  429. assertSame(FastForwardMode.FF_ONLY, mergeConfig.getFastForwardMode());
  430. assertTrue(mergeConfig.isCommit());
  431. assertTrue(mergeConfig.isSquash());
  432. // mergeoptions wins if it has ff options amongst other options
  433. c = parse("[merge]\n\tff = false\n"
  434. + "[branch \"side\"]\n\tmergeoptions = --ff-only --no-commit\n");
  435. mergeConfig = c.get(MergeConfig.getParser("side"));
  436. assertSame(FastForwardMode.FF_ONLY, mergeConfig.getFastForwardMode());
  437. assertFalse(mergeConfig.isCommit());
  438. assertFalse(mergeConfig.isSquash());
  439. }
  440. @Test
  441. public void testSetFastForwardMerge() {
  442. final Config c = new Config();
  443. c.setEnum("merge", null, "ff",
  444. FastForwardMode.Merge.valueOf(FastForwardMode.FF));
  445. assertEquals("[merge]\n\tff = true\n", c.toText());
  446. c.setEnum("merge", null, "ff",
  447. FastForwardMode.Merge.valueOf(FastForwardMode.FF_ONLY));
  448. assertEquals("[merge]\n\tff = only\n", c.toText());
  449. c.setEnum("merge", null, "ff",
  450. FastForwardMode.Merge.valueOf(FastForwardMode.NO_FF));
  451. assertEquals("[merge]\n\tff = false\n", c.toText());
  452. }
  453. @Test
  454. public void testReadLong() throws ConfigInvalidException {
  455. assertReadLong(1L);
  456. assertReadLong(-1L);
  457. assertReadLong(Long.MIN_VALUE);
  458. assertReadLong(Long.MAX_VALUE);
  459. assertReadLong(4L * 1024 * 1024 * 1024, "4g");
  460. assertReadLong(3L * 1024 * 1024, "3 m");
  461. assertReadLong(8L * 1024, "8 k");
  462. try {
  463. assertReadLong(-1, "1.5g");
  464. fail("incorrectly accepted 1.5g");
  465. } catch (IllegalArgumentException e) {
  466. assertEquals("Invalid integer value: s.a=1.5g", e.getMessage());
  467. }
  468. }
  469. @Test
  470. public void testBooleanWithNoValue() throws ConfigInvalidException {
  471. Config c = parse("[my]\n\tempty\n");
  472. assertEquals("", c.getString("my", null, "empty"));
  473. assertEquals(1, c.getStringList("my", null, "empty").length);
  474. assertEquals("", c.getStringList("my", null, "empty")[0]);
  475. assertTrue(c.getBoolean("my", "empty", false));
  476. assertEquals("[my]\n\tempty\n", c.toText());
  477. }
  478. @Test
  479. public void testUnsetBranchSection() throws ConfigInvalidException {
  480. Config c = parse("" //
  481. + "[branch \"keep\"]\n"
  482. + " merge = master.branch.to.keep.in.the.file\n"
  483. + "\n"
  484. + "[branch \"remove\"]\n"
  485. + " merge = this.will.get.deleted\n"
  486. + " remote = origin-for-some-long-gone-place\n"
  487. + "\n"
  488. + "[core-section-not-to-remove-in-test]\n"
  489. + " packedGitLimit = 14\n");
  490. c.unsetSection("branch", "does.not.exist");
  491. c.unsetSection("branch", "remove");
  492. assertEquals("" //
  493. + "[branch \"keep\"]\n"
  494. + " merge = master.branch.to.keep.in.the.file\n"
  495. + "\n"
  496. + "[core-section-not-to-remove-in-test]\n"
  497. + " packedGitLimit = 14\n", c.toText());
  498. }
  499. @Test
  500. public void testUnsetSingleSection() throws ConfigInvalidException {
  501. Config c = parse("" //
  502. + "[branch \"keep\"]\n"
  503. + " merge = master.branch.to.keep.in.the.file\n"
  504. + "\n"
  505. + "[single]\n"
  506. + " merge = this.will.get.deleted\n"
  507. + " remote = origin-for-some-long-gone-place\n"
  508. + "\n"
  509. + "[core-section-not-to-remove-in-test]\n"
  510. + " packedGitLimit = 14\n");
  511. c.unsetSection("single", null);
  512. assertEquals("" //
  513. + "[branch \"keep\"]\n"
  514. + " merge = master.branch.to.keep.in.the.file\n"
  515. + "\n"
  516. + "[core-section-not-to-remove-in-test]\n"
  517. + " packedGitLimit = 14\n", c.toText());
  518. }
  519. @Test
  520. public void test008_readSectionNames() throws ConfigInvalidException {
  521. final Config c = parse("[a]\n [B]\n");
  522. Set<String> sections = c.getSections();
  523. assertTrue("Sections should contain \"a\"", sections.contains("a"));
  524. assertTrue("Sections should contain \"b\"", sections.contains("b"));
  525. }
  526. @Test
  527. public void test009_readNamesInSection() throws ConfigInvalidException {
  528. String configString = "[core]\n" + "repositoryFormatVersion = 0\n"
  529. + "filemode = false\n" + "logAllRefUpdates = true\n";
  530. final Config c = parse(configString);
  531. Set<String> names = c.getNames("core");
  532. assertEquals("Core section size", 3, names.size());
  533. assertTrue("Core section should contain \"filemode\"", names
  534. .contains("filemode"));
  535. assertTrue("Core section should contain \"repositoryFormatVersion\"",
  536. names.contains("repositoryFormatVersion"));
  537. assertTrue("Core section should contain \"repositoryformatversion\"",
  538. names.contains("repositoryformatversion"));
  539. Iterator<String> itr = names.iterator();
  540. assertEquals("filemode", itr.next());
  541. assertEquals("logAllRefUpdates", itr.next());
  542. assertEquals("repositoryFormatVersion", itr.next());
  543. assertFalse(itr.hasNext());
  544. }
  545. @Test
  546. public void test_ReadNamesInSectionRecursive()
  547. throws ConfigInvalidException {
  548. String baseConfigString = "[core]\n" + "logAllRefUpdates = true\n";
  549. String configString = "[core]\n" + "repositoryFormatVersion = 0\n"
  550. + "filemode = false\n";
  551. final Config c = parse(configString, parse(baseConfigString));
  552. Set<String> names = c.getNames("core", true);
  553. assertEquals("Core section size", 3, names.size());
  554. assertTrue("Core section should contain \"filemode\"",
  555. names.contains("filemode"));
  556. assertTrue("Core section should contain \"repositoryFormatVersion\"",
  557. names.contains("repositoryFormatVersion"));
  558. assertTrue("Core section should contain \"logAllRefUpdates\"",
  559. names.contains("logAllRefUpdates"));
  560. assertTrue("Core section should contain \"logallrefupdates\"",
  561. names.contains("logallrefupdates"));
  562. Iterator<String> itr = names.iterator();
  563. assertEquals("filemode", itr.next());
  564. assertEquals("repositoryFormatVersion", itr.next());
  565. assertEquals("logAllRefUpdates", itr.next());
  566. assertFalse(itr.hasNext());
  567. }
  568. @Test
  569. public void test010_readNamesInSubSection() throws ConfigInvalidException {
  570. String configString = "[a \"sub1\"]\n"//
  571. + "x = 0\n" //
  572. + "y = false\n"//
  573. + "z = true\n"//
  574. + "[a \"sub2\"]\n"//
  575. + "a=0\n"//
  576. + "b=1\n";
  577. final Config c = parse(configString);
  578. Set<String> names = c.getNames("a", "sub1");
  579. assertEquals("Subsection size", 3, names.size());
  580. assertTrue("Subsection should contain \"x\"", names.contains("x"));
  581. assertTrue("Subsection should contain \"y\"", names.contains("y"));
  582. assertTrue("Subsection should contain \"z\"", names.contains("z"));
  583. names = c.getNames("a", "sub2");
  584. assertEquals("Subsection size", 2, names.size());
  585. assertTrue("Subsection should contain \"a\"", names.contains("a"));
  586. assertTrue("Subsection should contain \"b\"", names.contains("b"));
  587. }
  588. @Test
  589. public void readNamesInSubSectionRecursive() throws ConfigInvalidException {
  590. String baseConfigString = "[a \"sub1\"]\n"//
  591. + "x = 0\n" //
  592. + "y = false\n"//
  593. + "[a \"sub2\"]\n"//
  594. + "A=0\n";//
  595. String configString = "[a \"sub1\"]\n"//
  596. + "z = true\n"//
  597. + "[a \"sub2\"]\n"//
  598. + "B=1\n";
  599. final Config c = parse(configString, parse(baseConfigString));
  600. Set<String> names = c.getNames("a", "sub1", true);
  601. assertEquals("Subsection size", 3, names.size());
  602. assertTrue("Subsection should contain \"x\"", names.contains("x"));
  603. assertTrue("Subsection should contain \"y\"", names.contains("y"));
  604. assertTrue("Subsection should contain \"z\"", names.contains("z"));
  605. names = c.getNames("a", "sub2", true);
  606. assertEquals("Subsection size", 2, names.size());
  607. assertTrue("Subsection should contain \"A\"", names.contains("A"));
  608. assertTrue("Subsection should contain \"a\"", names.contains("a"));
  609. assertTrue("Subsection should contain \"B\"", names.contains("B"));
  610. }
  611. @Test
  612. public void testNoFinalNewline() throws ConfigInvalidException {
  613. Config c = parse("[a]\n"
  614. + "x = 0\n"
  615. + "y = 1");
  616. assertEquals("0", c.getString("a", null, "x"));
  617. assertEquals("1", c.getString("a", null, "y"));
  618. }
  619. @Test
  620. public void testExplicitlySetEmptyString() throws Exception {
  621. Config c = new Config();
  622. c.setString("a", null, "x", "0");
  623. c.setString("a", null, "y", "");
  624. assertEquals("0", c.getString("a", null, "x"));
  625. assertEquals(0, c.getInt("a", null, "x", 1));
  626. assertEquals("", c.getString("a", null, "y"));
  627. assertArrayEquals(new String[]{""}, c.getStringList("a", null, "y"));
  628. assertEquals(1, c.getInt("a", null, "y", 1));
  629. assertNull(c.getString("a", null, "z"));
  630. assertArrayEquals(new String[]{}, c.getStringList("a", null, "z"));
  631. }
  632. @Test
  633. public void testParsedEmptyString() throws Exception {
  634. Config c = parse("[a]\n"
  635. + "x = 0\n"
  636. + "y =\n");
  637. assertEquals("0", c.getString("a", null, "x"));
  638. assertEquals(0, c.getInt("a", null, "x", 1));
  639. assertNull(c.getString("a", null, "y"));
  640. assertArrayEquals(new String[]{null}, c.getStringList("a", null, "y"));
  641. assertEquals(1, c.getInt("a", null, "y", 1));
  642. assertNull(c.getString("a", null, "z"));
  643. assertArrayEquals(new String[]{}, c.getStringList("a", null, "z"));
  644. }
  645. @Test
  646. public void testSetStringListWithEmptyValue() throws Exception {
  647. Config c = new Config();
  648. c.setStringList("a", null, "x", Arrays.asList(""));
  649. assertArrayEquals(new String[]{""}, c.getStringList("a", null, "x"));
  650. }
  651. @Test
  652. public void testEmptyValueAtEof() throws Exception {
  653. String text = "[a]\nx =";
  654. Config c = parse(text);
  655. assertNull(c.getString("a", null, "x"));
  656. assertArrayEquals(new String[]{null},
  657. c.getStringList("a", null, "x"));
  658. c = parse(text + "\n");
  659. assertNull(c.getString("a", null, "x"));
  660. assertArrayEquals(new String[]{null},
  661. c.getStringList("a", null, "x"));
  662. }
  663. @Test
  664. public void testReadMultipleValuesForName() throws ConfigInvalidException {
  665. Config c = parse("[foo]\nbar=false\nbar=true\n");
  666. assertTrue(c.getBoolean("foo", "bar", false));
  667. }
  668. @Test
  669. public void testIncludeInvalidName() throws ConfigInvalidException {
  670. expectedEx.expect(ConfigInvalidException.class);
  671. expectedEx.expectMessage(JGitText.get().invalidLineInConfigFile);
  672. parse("[include]\nbar\n");
  673. }
  674. @Test
  675. public void testIncludeNoValue() throws ConfigInvalidException {
  676. expectedEx.expect(ConfigInvalidException.class);
  677. expectedEx.expectMessage(JGitText.get().invalidLineInConfigFile);
  678. parse("[include]\npath\n");
  679. }
  680. @Test
  681. public void testIncludeEmptyValue() throws ConfigInvalidException {
  682. expectedEx.expect(ConfigInvalidException.class);
  683. expectedEx.expectMessage(JGitText.get().invalidLineInConfigFile);
  684. parse("[include]\npath=\n");
  685. }
  686. @Test
  687. public void testIncludeValuePathNotFound() throws ConfigInvalidException {
  688. // we do not expect an exception, included path not found are ignored
  689. String notFound = "/not/found";
  690. Config parsed = parse("[include]\npath=" + notFound + "\n");
  691. assertEquals(1, parsed.getSections().size());
  692. assertEquals(notFound, parsed.getString("include", null, "path"));
  693. }
  694. @Test
  695. public void testIncludeValuePathWithTilde() throws ConfigInvalidException {
  696. // we do not expect an exception, included path not supported are
  697. // ignored
  698. String notSupported = "~/someFile";
  699. Config parsed = parse("[include]\npath=" + notSupported + "\n");
  700. assertEquals(1, parsed.getSections().size());
  701. assertEquals(notSupported, parsed.getString("include", null, "path"));
  702. }
  703. @Test
  704. public void testIncludeValuePathRelative() throws ConfigInvalidException {
  705. // we do not expect an exception, included path not supported are
  706. // ignored
  707. String notSupported = "someRelativeFile";
  708. Config parsed = parse("[include]\npath=" + notSupported + "\n");
  709. assertEquals(1, parsed.getSections().size());
  710. assertEquals(notSupported, parsed.getString("include", null, "path"));
  711. }
  712. @Test
  713. public void testIncludeTooManyRecursions() throws IOException {
  714. File config = tmp.newFile("config");
  715. String include = "[include]\npath=" + pathToString(config) + "\n";
  716. Files.write(config.toPath(), include.getBytes(UTF_8));
  717. try {
  718. loadConfig(config);
  719. fail();
  720. } catch (ConfigInvalidException cie) {
  721. for (Throwable t = cie; t != null; t = t.getCause()) {
  722. if (t.getMessage()
  723. .equals(JGitText.get().tooManyIncludeRecursions)) {
  724. return;
  725. }
  726. }
  727. fail("Expected to find expected exception message: "
  728. + JGitText.get().tooManyIncludeRecursions);
  729. }
  730. }
  731. @Test
  732. public void testIncludeIsNoop() throws IOException, ConfigInvalidException {
  733. File config = tmp.newFile("config");
  734. String fooBar = "[foo]\nbar=true\n";
  735. Files.write(config.toPath(), fooBar.getBytes(UTF_8));
  736. Config parsed = parse("[include]\npath=" + pathToString(config) + "\n");
  737. assertFalse(parsed.getBoolean("foo", "bar", false));
  738. }
  739. @Test
  740. public void testIncludeCaseInsensitiveSection()
  741. throws IOException, ConfigInvalidException {
  742. File included = tmp.newFile("included");
  743. String content = "[foo]\nbar=true\n";
  744. Files.write(included.toPath(), content.getBytes(UTF_8));
  745. File config = tmp.newFile("config");
  746. content = "[Include]\npath=" + pathToString(included) + "\n";
  747. Files.write(config.toPath(), content.getBytes(UTF_8));
  748. FileBasedConfig fbConfig = loadConfig(config);
  749. assertTrue(fbConfig.getBoolean("foo", "bar", false));
  750. }
  751. @Test
  752. public void testIncludeCaseInsensitiveKey()
  753. throws IOException, ConfigInvalidException {
  754. File included = tmp.newFile("included");
  755. String content = "[foo]\nbar=true\n";
  756. Files.write(included.toPath(), content.getBytes(UTF_8));
  757. File config = tmp.newFile("config");
  758. content = "[include]\nPath=" + pathToString(included) + "\n";
  759. Files.write(config.toPath(), content.getBytes(UTF_8));
  760. FileBasedConfig fbConfig = loadConfig(config);
  761. assertTrue(fbConfig.getBoolean("foo", "bar", false));
  762. }
  763. @Test
  764. public void testIncludeExceptionContainsLine() {
  765. try {
  766. parse("[include]\npath=\n");
  767. fail("Expected ConfigInvalidException");
  768. } catch (ConfigInvalidException e) {
  769. assertTrue(
  770. "Expected to find the problem line in the exception message",
  771. e.getMessage().contains("include.path"));
  772. }
  773. }
  774. @Test
  775. public void testIncludeExceptionContainsFile() throws IOException {
  776. File included = tmp.newFile("included");
  777. String includedPath = pathToString(included);
  778. String content = "[include]\npath=\n";
  779. Files.write(included.toPath(), content.getBytes(UTF_8));
  780. File config = tmp.newFile("config");
  781. String include = "[include]\npath=" + includedPath + "\n";
  782. Files.write(config.toPath(), include.getBytes(UTF_8));
  783. try {
  784. loadConfig(config);
  785. fail("Expected ConfigInvalidException");
  786. } catch (ConfigInvalidException e) {
  787. // Check that there is some exception in the chain that contains
  788. // includedPath
  789. for (Throwable t = e; t != null; t = t.getCause()) {
  790. if (t.getMessage().contains(includedPath)) {
  791. return;
  792. }
  793. }
  794. fail("Expected to find the path in the exception message: "
  795. + includedPath);
  796. }
  797. }
  798. @Test
  799. public void testIncludeSetValueMustNotTouchIncludedLines1()
  800. throws IOException, ConfigInvalidException {
  801. File includedFile = createAllTypesIncludedContent();
  802. File configFile = tmp.newFile("config");
  803. String content = createAllTypesSampleContent("Alice Parker", false, 11,
  804. 21, 31, CoreConfig.AutoCRLF.FALSE,
  805. "+refs/heads/*:refs/remotes/origin/*") + "\n[include]\npath="
  806. + pathToString(includedFile);
  807. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  808. FileBasedConfig fbConfig = loadConfig(configFile);
  809. assertValuesAsIncluded(fbConfig, REFS_ORIGIN, REFS_UPSTREAM);
  810. assertSections(fbConfig, "user", "core", "remote", "include");
  811. setAllValuesNew(fbConfig);
  812. assertValuesAsIsSaveLoad(fbConfig, config -> {
  813. assertValuesAsIncluded(config, REFS_BACKUP, REFS_UPSTREAM);
  814. assertSections(fbConfig, "user", "core", "remote", "include");
  815. });
  816. }
  817. @Test
  818. public void testIncludeSetValueMustNotTouchIncludedLines2()
  819. throws IOException, ConfigInvalidException {
  820. File includedFile = createAllTypesIncludedContent();
  821. File configFile = tmp.newFile("config");
  822. String content = "[include]\npath=" + pathToString(includedFile) + "\n"
  823. + createAllTypesSampleContent("Alice Parker", false, 11, 21, 31,
  824. CoreConfig.AutoCRLF.FALSE,
  825. "+refs/heads/*:refs/remotes/origin/*");
  826. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  827. FileBasedConfig fbConfig = loadConfig(configFile);
  828. assertValuesAsConfig(fbConfig, REFS_UPSTREAM, REFS_ORIGIN);
  829. assertSections(fbConfig, "include", "user", "core", "remote");
  830. setAllValuesNew(fbConfig);
  831. assertValuesAsIsSaveLoad(fbConfig, config -> {
  832. assertValuesAsNew(config, REFS_UPSTREAM, REFS_BACKUP);
  833. assertSections(fbConfig, "include", "user", "core", "remote");
  834. });
  835. }
  836. @Test
  837. public void testIncludeSetValueOnFileWithJustContainsInclude()
  838. throws IOException, ConfigInvalidException {
  839. File includedFile = createAllTypesIncludedContent();
  840. File configFile = tmp.newFile("config");
  841. String content = "[include]\npath=" + pathToString(includedFile);
  842. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  843. FileBasedConfig fbConfig = loadConfig(configFile);
  844. assertValuesAsIncluded(fbConfig, REFS_UPSTREAM);
  845. assertSections(fbConfig, "include", "user", "core", "remote");
  846. setAllValuesNew(fbConfig);
  847. assertValuesAsIsSaveLoad(fbConfig, config -> {
  848. assertValuesAsNew(config, REFS_UPSTREAM, REFS_BACKUP);
  849. assertSections(fbConfig, "include", "user", "core", "remote");
  850. });
  851. }
  852. @Test
  853. public void testIncludeSetValueOnFileWithJustEmptySection1()
  854. throws IOException, ConfigInvalidException {
  855. File includedFile = createAllTypesIncludedContent();
  856. File configFile = tmp.newFile("config");
  857. String content = "[user]\n[include]\npath="
  858. + pathToString(includedFile);
  859. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  860. FileBasedConfig fbConfig = loadConfig(configFile);
  861. assertValuesAsIncluded(fbConfig, REFS_UPSTREAM);
  862. assertSections(fbConfig, "user", "include", "core", "remote");
  863. setAllValuesNew(fbConfig);
  864. assertValuesAsIsSaveLoad(fbConfig, config -> {
  865. assertValuesAsNewWithName(config, "Alice Muller", REFS_UPSTREAM,
  866. REFS_BACKUP);
  867. assertSections(fbConfig, "user", "include", "core", "remote");
  868. });
  869. }
  870. @Test
  871. public void testIncludeSetValueOnFileWithJustEmptySection2()
  872. throws IOException, ConfigInvalidException {
  873. File includedFile = createAllTypesIncludedContent();
  874. File configFile = tmp.newFile("config");
  875. String content = "[include]\npath=" + pathToString(includedFile)
  876. + "\n[user]";
  877. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  878. FileBasedConfig fbConfig = loadConfig(configFile);
  879. assertValuesAsIncluded(fbConfig, REFS_UPSTREAM);
  880. assertSections(fbConfig, "include", "user", "core", "remote");
  881. setAllValuesNew(fbConfig);
  882. assertValuesAsIsSaveLoad(fbConfig, config -> {
  883. assertValuesAsNew(config, REFS_UPSTREAM, REFS_BACKUP);
  884. assertSections(fbConfig, "include", "user", "core", "remote");
  885. });
  886. }
  887. @Test
  888. public void testIncludeSetValueOnFileWithJustExistingSection1()
  889. throws IOException, ConfigInvalidException {
  890. File includedFile = createAllTypesIncludedContent();
  891. File configFile = tmp.newFile("config");
  892. String content = "[user]\nemail=alice@home\n[include]\npath="
  893. + pathToString(includedFile);
  894. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  895. FileBasedConfig fbConfig = loadConfig(configFile);
  896. assertValuesAsIncluded(fbConfig, REFS_UPSTREAM);
  897. assertSections(fbConfig, "user", "include", "core", "remote");
  898. setAllValuesNew(fbConfig);
  899. assertValuesAsIsSaveLoad(fbConfig, config -> {
  900. assertValuesAsNewWithName(config, "Alice Muller", REFS_UPSTREAM,
  901. REFS_BACKUP);
  902. assertSections(fbConfig, "user", "include", "core", "remote");
  903. });
  904. }
  905. @Test
  906. public void testIncludeSetValueOnFileWithJustExistingSection2()
  907. throws IOException, ConfigInvalidException {
  908. File includedFile = createAllTypesIncludedContent();
  909. File configFile = tmp.newFile("config");
  910. String content = "[include]\npath=" + pathToString(includedFile)
  911. + "\n[user]\nemail=alice@home\n";
  912. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  913. FileBasedConfig fbConfig = loadConfig(configFile);
  914. assertValuesAsIncluded(fbConfig, REFS_UPSTREAM);
  915. assertSections(fbConfig, "include", "user", "core", "remote");
  916. setAllValuesNew(fbConfig);
  917. assertValuesAsIsSaveLoad(fbConfig, config -> {
  918. assertValuesAsNew(config, REFS_UPSTREAM, REFS_BACKUP);
  919. assertSections(fbConfig, "include", "user", "core", "remote");
  920. });
  921. }
  922. @Test
  923. public void testIncludeUnsetSectionMustNotTouchIncludedLines()
  924. throws IOException, ConfigInvalidException {
  925. File includedFile = tmp.newFile("included");
  926. RefSpec includedRefSpec = new RefSpec(REFS_UPSTREAM);
  927. String includedContent = "[remote \"origin\"]\n" + "fetch="
  928. + includedRefSpec;
  929. Files.write(includedFile.toPath(), includedContent.getBytes(UTF_8));
  930. File configFile = tmp.newFile("config");
  931. RefSpec refSpec = new RefSpec(REFS_ORIGIN);
  932. String content = "[include]\npath=" + pathToString(includedFile) + "\n"
  933. + "[remote \"origin\"]\n" + "fetch=" + refSpec;
  934. Files.write(configFile.toPath(), content.getBytes(UTF_8));
  935. FileBasedConfig fbConfig = loadConfig(configFile);
  936. Consumer<FileBasedConfig> assertion = config -> {
  937. assertEquals(Arrays.asList(includedRefSpec, refSpec),
  938. config.getRefSpecs("remote", "origin", "fetch"));
  939. };
  940. assertion.accept(fbConfig);
  941. fbConfig.unsetSection("remote", "origin");
  942. assertValuesAsIsSaveLoad(fbConfig, config -> {
  943. assertEquals(Collections.singletonList(includedRefSpec),
  944. config.getRefSpecs("remote", "origin", "fetch"));
  945. });
  946. }
  947. private File createAllTypesIncludedContent() throws IOException {
  948. File includedFile = tmp.newFile("included");
  949. String includedContent = createAllTypesSampleContent("Alice Muller",
  950. true, 10, 20, 30, CoreConfig.AutoCRLF.TRUE,
  951. "+refs/heads/*:refs/remotes/upstream/*");
  952. Files.write(includedFile.toPath(), includedContent.getBytes(UTF_8));
  953. return includedFile;
  954. }
  955. private static void assertValuesAsIsSaveLoad(FileBasedConfig fbConfig,
  956. Consumer<FileBasedConfig> assertion)
  957. throws IOException, ConfigInvalidException {
  958. assertion.accept(fbConfig);
  959. fbConfig.save();
  960. assertion.accept(fbConfig);
  961. fbConfig = loadConfig(fbConfig.getFile());
  962. assertion.accept(fbConfig);
  963. }
  964. private static void setAllValuesNew(Config config) {
  965. config.setString("user", null, "name", "Alice Bauer");
  966. config.setBoolean("core", null, "fileMode", false);
  967. config.setInt("core", null, "deltaBaseCacheLimit", 12);
  968. config.setLong("core", null, "packedGitLimit", 22);
  969. config.setLong("core", null, "repositoryCacheExpireAfter", 32);
  970. config.setEnum("core", null, "autocrlf", CoreConfig.AutoCRLF.FALSE);
  971. config.setString("remote", "origin", "fetch",
  972. "+refs/heads/*:refs/remotes/backup/*");
  973. }
  974. private static void assertValuesAsIncluded(Config config, String... refs) {
  975. assertAllTypesSampleContent("Alice Muller", true, 10, 20, 30,
  976. CoreConfig.AutoCRLF.TRUE, config, refs);
  977. }
  978. private static void assertValuesAsConfig(Config config, String... refs) {
  979. assertAllTypesSampleContent("Alice Parker", false, 11, 21, 31,
  980. CoreConfig.AutoCRLF.FALSE, config, refs);
  981. }
  982. private static void assertValuesAsNew(Config config, String... refs) {
  983. assertValuesAsNewWithName(config, "Alice Bauer", refs);
  984. }
  985. private static void assertValuesAsNewWithName(Config config, String name,
  986. String... refs) {
  987. assertAllTypesSampleContent(name, false, 12, 22, 32,
  988. CoreConfig.AutoCRLF.FALSE, config, refs);
  989. }
  990. private static void assertSections(Config config, String... sections) {
  991. assertEquals(Arrays.asList(sections),
  992. new ArrayList<>(config.getSections()));
  993. }
  994. private static String createAllTypesSampleContent(String name,
  995. boolean fileMode, int deltaBaseCacheLimit, long packedGitLimit,
  996. long repositoryCacheExpireAfter, CoreConfig.AutoCRLF autoCRLF,
  997. String fetchRefSpec) {
  998. final StringBuilder builder = new StringBuilder();
  999. builder.append("[user]\n");
  1000. builder.append("name=");
  1001. builder.append(name);
  1002. builder.append("\n");
  1003. builder.append("[core]\n");
  1004. builder.append("fileMode=");
  1005. builder.append(fileMode);
  1006. builder.append("\n");
  1007. builder.append("deltaBaseCacheLimit=");
  1008. builder.append(deltaBaseCacheLimit);
  1009. builder.append("\n");
  1010. builder.append("packedGitLimit=");
  1011. builder.append(packedGitLimit);
  1012. builder.append("\n");
  1013. builder.append("repositoryCacheExpireAfter=");
  1014. builder.append(repositoryCacheExpireAfter);
  1015. builder.append("\n");
  1016. builder.append("autocrlf=");
  1017. builder.append(autoCRLF.name());
  1018. builder.append("\n");
  1019. builder.append("[remote \"origin\"]\n");
  1020. builder.append("fetch=");
  1021. builder.append(fetchRefSpec);
  1022. builder.append("\n");
  1023. return builder.toString();
  1024. }
  1025. private static void assertAllTypesSampleContent(String name,
  1026. boolean fileMode, int deltaBaseCacheLimit, long packedGitLimit,
  1027. long repositoryCacheExpireAfter, CoreConfig.AutoCRLF autoCRLF,
  1028. Config config, String... fetchRefSpecs) {
  1029. assertEquals(name, config.getString("user", null, "name"));
  1030. assertEquals(fileMode,
  1031. config.getBoolean("core", "fileMode", !fileMode));
  1032. assertEquals(deltaBaseCacheLimit,
  1033. config.getInt("core", "deltaBaseCacheLimit", -1));
  1034. assertEquals(packedGitLimit,
  1035. config.getLong("core", "packedGitLimit", -1));
  1036. assertEquals(repositoryCacheExpireAfter, config.getTimeUnit("core",
  1037. null, "repositoryCacheExpireAfter", -1, MILLISECONDS));
  1038. assertEquals(autoCRLF, config.getEnum("core", null, "autocrlf",
  1039. CoreConfig.AutoCRLF.INPUT));
  1040. final List<RefSpec> refspecs = new ArrayList<>();
  1041. for (String fetchRefSpec : fetchRefSpecs) {
  1042. refspecs.add(new RefSpec(fetchRefSpec));
  1043. }
  1044. assertEquals(refspecs, config.getRefSpecs("remote", "origin", "fetch"));
  1045. }
  1046. private static void assertReadLong(long exp) throws ConfigInvalidException {
  1047. assertReadLong(exp, String.valueOf(exp));
  1048. }
  1049. private static void assertReadLong(long exp, String act)
  1050. throws ConfigInvalidException {
  1051. final Config c = parse("[s]\na = " + act + "\n");
  1052. assertEquals(exp, c.getLong("s", null, "a", 0L));
  1053. }
  1054. private static Config parse(String content)
  1055. throws ConfigInvalidException {
  1056. return parse(content, null);
  1057. }
  1058. private static Config parse(String content, Config baseConfig)
  1059. throws ConfigInvalidException {
  1060. final Config c = new Config(baseConfig);
  1061. c.fromText(content);
  1062. return c;
  1063. }
  1064. @Test
  1065. public void testTimeUnit() throws ConfigInvalidException {
  1066. assertEquals(0, parseTime("0", NANOSECONDS));
  1067. assertEquals(2, parseTime("2ns", NANOSECONDS));
  1068. assertEquals(200, parseTime("200 nanoseconds", NANOSECONDS));
  1069. assertEquals(0, parseTime("0", MICROSECONDS));
  1070. assertEquals(2, parseTime("2us", MICROSECONDS));
  1071. assertEquals(2, parseTime("2000 nanoseconds", MICROSECONDS));
  1072. assertEquals(200, parseTime("200 microseconds", MICROSECONDS));
  1073. assertEquals(0, parseTime("0", MILLISECONDS));
  1074. assertEquals(2, parseTime("2ms", MILLISECONDS));
  1075. assertEquals(2, parseTime("2000microseconds", MILLISECONDS));
  1076. assertEquals(200, parseTime("200 milliseconds", MILLISECONDS));
  1077. assertEquals(0, parseTime("0s", SECONDS));
  1078. assertEquals(2, parseTime("2s", SECONDS));
  1079. assertEquals(231, parseTime("231sec", SECONDS));
  1080. assertEquals(1, parseTime("1second", SECONDS));
  1081. assertEquals(300, parseTime("300 seconds", SECONDS));
  1082. assertEquals(2, parseTime("2m", MINUTES));
  1083. assertEquals(2, parseTime("2min", MINUTES));
  1084. assertEquals(1, parseTime("1 minute", MINUTES));
  1085. assertEquals(10, parseTime("10 minutes", MINUTES));
  1086. assertEquals(5, parseTime("5h", HOURS));
  1087. assertEquals(5, parseTime("5hr", HOURS));
  1088. assertEquals(1, parseTime("1hour", HOURS));
  1089. assertEquals(48, parseTime("48hours", HOURS));
  1090. assertEquals(5, parseTime("5 h", HOURS));
  1091. assertEquals(5, parseTime("5 hr", HOURS));
  1092. assertEquals(1, parseTime("1 hour", HOURS));
  1093. assertEquals(48, parseTime("48 hours", HOURS));
  1094. assertEquals(48, parseTime("48 \t \r hours", HOURS));
  1095. assertEquals(4, parseTime("4d", DAYS));
  1096. assertEquals(1, parseTime("1day", DAYS));
  1097. assertEquals(14, parseTime("14days", DAYS));
  1098. assertEquals(7, parseTime("1w", DAYS));
  1099. assertEquals(7, parseTime("1week", DAYS));
  1100. assertEquals(14, parseTime("2w", DAYS));
  1101. assertEquals(14, parseTime("2weeks", DAYS));
  1102. assertEquals(30, parseTime("1mon", DAYS));
  1103. assertEquals(30, parseTime("1month", DAYS));
  1104. assertEquals(60, parseTime("2mon", DAYS));
  1105. assertEquals(60, parseTime("2months", DAYS));
  1106. assertEquals(365, parseTime("1y", DAYS));
  1107. assertEquals(365, parseTime("1year", DAYS));
  1108. assertEquals(365 * 2, parseTime("2years", DAYS));
  1109. }
  1110. private long parseTime(String value, TimeUnit unit)
  1111. throws ConfigInvalidException {
  1112. Config c = parse("[a]\na=" + value + "\n");
  1113. return c.getTimeUnit("a", null, "a", 0, unit);
  1114. }
  1115. @Test
  1116. public void testTimeUnitDefaultValue() throws ConfigInvalidException {
  1117. // value not present
  1118. assertEquals(20, parse("[a]\na=0\n").getTimeUnit("a", null, "b", 20,
  1119. MILLISECONDS));
  1120. // value is empty
  1121. assertEquals(20, parse("[a]\na=\" \"\n").getTimeUnit("a", null, "a", 20,
  1122. MILLISECONDS));
  1123. // value is not numeric
  1124. assertEquals(20, parse("[a]\na=test\n").getTimeUnit("a", null, "a", 20,
  1125. MILLISECONDS));
  1126. }
  1127. @Test
  1128. public void testTimeUnitInvalid() throws ConfigInvalidException {
  1129. expectedEx.expect(IllegalArgumentException.class);
  1130. expectedEx
  1131. .expectMessage("Invalid time unit value: a.a=1 monttthhh");
  1132. parseTime("1 monttthhh", DAYS);
  1133. }
  1134. @Test
  1135. public void testTimeUnitInvalidWithSection() throws ConfigInvalidException {
  1136. Config c = parse("[a \"b\"]\na=1 monttthhh\n");
  1137. expectedEx.expect(IllegalArgumentException.class);
  1138. expectedEx.expectMessage("Invalid time unit value: a.b.a=1 monttthhh");
  1139. c.getTimeUnit("a", "b", "a", 0, DAYS);
  1140. }
  1141. @Test
  1142. public void testTimeUnitNegative() throws ConfigInvalidException {
  1143. expectedEx.expect(IllegalArgumentException.class);
  1144. parseTime("-1", MILLISECONDS);
  1145. }
  1146. @Test
  1147. public void testEscapeSpacesOnly() throws ConfigInvalidException {
  1148. // Empty string is read back as null, so this doesn't round-trip.
  1149. assertEquals("", Config.escapeValue(""));
  1150. assertValueRoundTrip(" ", "\" \"");
  1151. assertValueRoundTrip(" ", "\" \"");
  1152. }
  1153. @Test
  1154. public void testEscapeLeadingSpace() throws ConfigInvalidException {
  1155. assertValueRoundTrip("x", "x");
  1156. assertValueRoundTrip(" x", "\" x\"");
  1157. assertValueRoundTrip(" x", "\" x\"");
  1158. }
  1159. @Test
  1160. public void testEscapeTrailingSpace() throws ConfigInvalidException {
  1161. assertValueRoundTrip("x", "x");
  1162. assertValueRoundTrip("x ","\"x \"");
  1163. assertValueRoundTrip("x ","\"x \"");
  1164. }
  1165. @Test
  1166. public void testEscapeLeadingAndTrailingSpace()
  1167. throws ConfigInvalidException {
  1168. assertValueRoundTrip(" x ", "\" x \"");
  1169. assertValueRoundTrip(" x ", "\" x \"");
  1170. assertValueRoundTrip(" x ", "\" x \"");
  1171. assertValueRoundTrip(" x ", "\" x \"");
  1172. }
  1173. @Test
  1174. public void testNoEscapeInternalSpaces() throws ConfigInvalidException {
  1175. assertValueRoundTrip("x y");
  1176. assertValueRoundTrip("x y");
  1177. assertValueRoundTrip("x y");
  1178. assertValueRoundTrip("x y z");
  1179. assertValueRoundTrip("x " + WS + " y");
  1180. }
  1181. @Test
  1182. public void testNoEscapeSpecialCharacters() throws ConfigInvalidException {
  1183. assertValueRoundTrip("x\\y", "x\\\\y");
  1184. assertValueRoundTrip("x\"y", "x\\\"y");
  1185. assertValueRoundTrip("x\ny", "x\\ny");
  1186. assertValueRoundTrip("x\ty", "x\\ty");
  1187. assertValueRoundTrip("x\by", "x\\by");
  1188. }
  1189. @Test
  1190. public void testParseLiteralBackspace() throws ConfigInvalidException {
  1191. // This is round-tripped with an escape sequence by JGit, but C git writes
  1192. // it out as a literal backslash.
  1193. assertEquals("x\by", parseEscapedValue("x\by"));
  1194. }
  1195. @Test
  1196. public void testEscapeCommentCharacters() throws ConfigInvalidException {
  1197. assertValueRoundTrip("x#y", "\"x#y\"");
  1198. assertValueRoundTrip("x;y", "\"x;y\"");
  1199. }
  1200. @Test
  1201. public void testEscapeValueInvalidCharacters() {
  1202. assertIllegalArgumentException(() -> Config.escapeSubsection("x\0y"));
  1203. }
  1204. @Test
  1205. public void testEscapeSubsectionInvalidCharacters() {
  1206. assertIllegalArgumentException(() -> Config.escapeSubsection("x\ny"));
  1207. assertIllegalArgumentException(() -> Config.escapeSubsection("x\0y"));
  1208. }
  1209. @Test
  1210. public void testParseMultipleQuotedRegions() throws ConfigInvalidException {
  1211. assertEquals("b a z; \n", parseEscapedValue("b\" a\"\" z; \\n\""));
  1212. }
  1213. @Test
  1214. public void testParseComments() throws ConfigInvalidException {
  1215. assertEquals("baz", parseEscapedValue("baz; comment"));
  1216. assertEquals("baz", parseEscapedValue("baz# comment"));
  1217. assertEquals("baz", parseEscapedValue("baz ; comment"));
  1218. assertEquals("baz", parseEscapedValue("baz # comment"));
  1219. assertEquals("baz", parseEscapedValue("baz ; comment"));
  1220. assertEquals("baz", parseEscapedValue("baz # comment"));
  1221. assertEquals("baz", parseEscapedValue("baz " + WS + " ; comment"));
  1222. assertEquals("baz", parseEscapedValue("baz " + WS + " # comment"));
  1223. assertEquals("baz ", parseEscapedValue("\"baz \"; comment"));
  1224. assertEquals("baz ", parseEscapedValue("\"baz \"# comment"));
  1225. assertEquals("baz ", parseEscapedValue("\"baz \" ; comment"));
  1226. assertEquals("baz ", parseEscapedValue("\"baz \" # comment"));
  1227. }
  1228. @Test
  1229. public void testEscapeSubsection() throws ConfigInvalidException {
  1230. assertSubsectionRoundTrip("", "\"\"");
  1231. assertSubsectionRoundTrip("x", "\"x\"");
  1232. assertSubsectionRoundTrip(" x", "\" x\"");
  1233. assertSubsectionRoundTrip("x ", "\"x \"");
  1234. assertSubsectionRoundTrip(" x ", "\" x \"");
  1235. assertSubsectionRoundTrip("x y", "\"x y\"");
  1236. assertSubsectionRoundTrip("x y", "\"x y\"");
  1237. assertSubsectionRoundTrip("x\\y", "\"x\\\\y\"");
  1238. assertSubsectionRoundTrip("x\"y", "\"x\\\"y\"");
  1239. // Unlike for values, \b and \t are not escaped.
  1240. assertSubsectionRoundTrip("x\by", "\"x\by\"");
  1241. assertSubsectionRoundTrip("x\ty", "\"x\ty\"");
  1242. }
  1243. @Test
  1244. public void testParseInvalidValues() {
  1245. assertInvalidValue(JGitText.get().newlineInQuotesNotAllowed, "x\"\n\"y");
  1246. assertInvalidValue(JGitText.get().endOfFileInEscape, "x\\");
  1247. assertInvalidValue(
  1248. MessageFormat.format(JGitText.get().badEscape, 'q'), "x\\q");
  1249. }
  1250. @Test
  1251. public void testParseInvalidSubsections() {
  1252. assertInvalidSubsection(
  1253. JGitText.get().newlineInQuotesNotAllowed, "\"x\ny\"");
  1254. }
  1255. @Test
  1256. public void testDropBackslashFromInvalidEscapeSequenceInSubsectionName()
  1257. throws ConfigInvalidException {
  1258. assertEquals("x0", parseEscapedSubsection("\"x\\0\""));
  1259. assertEquals("xq", parseEscapedSubsection("\"x\\q\""));
  1260. // Unlike for values, \b, \n, and \t are not valid escape sequences.
  1261. assertEquals("xb", parseEscapedSubsection("\"x\\b\""));
  1262. assertEquals("xn", parseEscapedSubsection("\"x\\n\""));
  1263. assertEquals("xt", parseEscapedSubsection("\"x\\t\""));
  1264. }
  1265. @Test
  1266. public void testInvalidGroupHeader() throws ConfigInvalidException {
  1267. expectedEx.expect(ConfigInvalidException.class);
  1268. expectedEx.expectMessage(JGitText.get().badGroupHeader);
  1269. parse("[foo \"bar\" ]\nfoo=bar\n");
  1270. }
  1271. @Test
  1272. public void testCrLf() throws ConfigInvalidException {
  1273. assertEquals("true", parseEscapedValue("true\r\n"));
  1274. }
  1275. @Test
  1276. public void testLfContinuation() throws ConfigInvalidException {
  1277. assertEquals("true", parseEscapedValue("tr\\\nue"));
  1278. }
  1279. @Test
  1280. public void testCrCharContinuation() throws ConfigInvalidException {
  1281. expectedEx.expect(ConfigInvalidException.class);
  1282. expectedEx.expectMessage("Bad escape: \\u000d");
  1283. parseEscapedValue("tr\\\rue");
  1284. }
  1285. @Test
  1286. public void testCrEOFContinuation() throws ConfigInvalidException {
  1287. expectedEx.expect(ConfigInvalidException.class);
  1288. expectedEx.expectMessage("Bad escape: \\u000d");
  1289. parseEscapedValue("tr\\\r");
  1290. }
  1291. @Test
  1292. public void testCrLfContinuation() throws ConfigInvalidException {
  1293. assertEquals("true", parseEscapedValue("tr\\\r\nue"));
  1294. }
  1295. @Test
  1296. public void testWhitespaceContinuation() throws ConfigInvalidException {
  1297. assertEquals("tr ue", parseEscapedValue("tr \\\n ue"));
  1298. assertEquals("tr ue", parseEscapedValue("tr \\\r\n ue"));
  1299. }
  1300. private static void assertValueRoundTrip(String value)
  1301. throws ConfigInvalidException {
  1302. assertValueRoundTrip(value, value);
  1303. }
  1304. private static void assertValueRoundTrip(String value, String expectedEscaped)
  1305. throws ConfigInvalidException {
  1306. String escaped = Config.escapeValue(value);
  1307. assertEquals("escape failed;", expectedEscaped, escaped);
  1308. assertEquals("parse failed;", value, parseEscapedValue(escaped));
  1309. }
  1310. private static String parseEscapedValue(String escapedValue)
  1311. throws ConfigInvalidException {
  1312. String text = "[foo]\nbar=" + escapedValue;
  1313. Config c = parse(text);
  1314. return c.getString("foo", null, "bar");
  1315. }
  1316. private static void assertInvalidValue(String expectedMessage,
  1317. String escapedValue) {
  1318. try {
  1319. parseEscapedValue(escapedValue);
  1320. fail("expected ConfigInvalidException");
  1321. } catch (ConfigInvalidException e) {
  1322. assertEquals(expectedMessage, e.getMessage());
  1323. }
  1324. }
  1325. private static void assertSubsectionRoundTrip(String subsection,
  1326. String expectedEscaped) throws ConfigInvalidException {
  1327. String escaped = Config.escapeSubsection(subsection);
  1328. assertEquals("escape failed;", expectedEscaped, escaped);
  1329. assertEquals("parse failed;", subsection, parseEscapedSubsection(escaped));
  1330. }
  1331. private static String parseEscapedSubsection(String escapedSubsection)
  1332. throws ConfigInvalidException {
  1333. String text = "[foo " + escapedSubsection + "]\nbar = value";
  1334. Config c = parse(text);
  1335. Set<String> subsections = c.getSubsections("foo");
  1336. assertEquals("only one section", 1, subsections.size());
  1337. return subsections.iterator().next();
  1338. }
  1339. private static void assertIllegalArgumentException(Runnable r) {
  1340. try {
  1341. r.run();
  1342. fail("expected IllegalArgumentException");
  1343. } catch (IllegalArgumentException e) {
  1344. // Expected.
  1345. }
  1346. }
  1347. private static void assertInvalidSubsection(String expectedMessage,
  1348. String escapedSubsection) {
  1349. try {
  1350. parseEscapedSubsection(escapedSubsection);
  1351. fail("expected ConfigInvalidException");
  1352. } catch (ConfigInvalidException e) {
  1353. assertEquals(expectedMessage, e.getMessage());
  1354. }
  1355. }
  1356. private static FileBasedConfig loadConfig(File file)
  1357. throws IOException, ConfigInvalidException {
  1358. final FileBasedConfig config = new FileBasedConfig(null, file,
  1359. FS.DETECTED);
  1360. config.load();
  1361. return config;
  1362. }
  1363. }