@@ -251,4 +251,65 @@ public static void addNewVersionToTestsIndex(ProjectLayout layout, Coordinates t
251251 }
252252 Files .writeString (indexPath , json , StandardCharsets .UTF_8 );
253253 }
254+
255+ /**
256+ * Adds a new entry to tests/src/index.json for the given coordinates.
257+ * The entry is inserted by lexicographic order of test-project-path value.
258+ */
259+ public static void addNewEntryToTestsIndex (ProjectLayout layout , Coordinates newCoords ) throws IOException {
260+ Path indexPath = GeneralUtils .getPathFromProject (layout , "tests/src/index.json" );
261+ if (!Files .exists (indexPath )) {
262+ return ;
263+ }
264+
265+ ObjectMapper mapper = new ObjectMapper ().enable (SerializationFeature .INDENT_OUTPUT );
266+
267+ String content = Files .readString (indexPath , StandardCharsets .UTF_8 );
268+ if (content == null || content .isBlank ()) {
269+ throw new GradleException ("Cannot find test index file at: " + indexPath );
270+ }
271+
272+ List <TestIndexEntry > entries = mapper .readValue (content , new TypeReference <>() {});
273+ String group = newCoords .group ();
274+ String artifact = newCoords .artifact ();
275+ String newVersion = newCoords .version ();
276+ String prefix = group + "/" + artifact + "/" ;
277+ String newTestProjectPath = prefix + newVersion ;
278+
279+ // If the new entry already exists, do nothing
280+ for (TestIndexEntry e : entries ) {
281+ if (newTestProjectPath .equals (e .testProjectPath ())) {
282+ return ;
283+ }
284+ }
285+
286+ // Build new entry
287+ String libName = group + ":" + artifact ;
288+ List <String > versions = new ArrayList <>();
289+ versions .add (newVersion );
290+ LibraryEntry libraryEntry = new LibraryEntry (libName , versions );
291+ List <LibraryEntry > libraries = new ArrayList <>();
292+ libraries .add (libraryEntry );
293+ TestIndexEntry newEntry = new TestIndexEntry (newTestProjectPath , libraries );
294+
295+ // Insert lexicographic order of test-project-path
296+ int insertAt = entries .size ();
297+ for (int i = 0 ; i < entries .size (); i ++) {
298+ String tp = entries .get (i ).testProjectPath ();
299+ if (tp != null && newTestProjectPath .compareTo (tp ) < 0 ) {
300+ insertAt = i ;
301+ break ;
302+ }
303+ }
304+
305+ entries .add (insertAt , newEntry );
306+
307+ DefaultPrettyPrinter prettyPrinterNew = new DefaultPrettyPrinter ();
308+ prettyPrinterNew .indentArraysWith (DefaultIndenter .SYSTEM_LINEFEED_INSTANCE );
309+ String jsonNew = mapper .writer (prettyPrinterNew ).writeValueAsString (entries );
310+ if (!jsonNew .endsWith (System .lineSeparator ())) {
311+ jsonNew = jsonNew + System .lineSeparator ();
312+ }
313+ Files .writeString (indexPath , jsonNew , StandardCharsets .UTF_8 );
314+ }
254315}
0 commit comments