Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ConfigTest.java 58KB

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