001/*
002 * JDrupes Builder
003 * Copyright (C) 2025, 2026 Michael N. Lipp
004 * 
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.builder.core;
020
021import java.nio.file.Path;
022import java.util.List;
023import java.util.Properties;
024import org.apache.commons.cli.CommandLine;
025import org.jdrupes.builder.api.Project;
026import org.jdrupes.builder.api.RootProject;
027
028/// Provides support for creating projects based on [AbstractProject].
029///
030public final class LauncherSupport {
031
032    private LauncherSupport() {
033    }
034
035    /// Creates and initializes the root project and the sub projects.
036    /// Adds the sub projects to the root project automatically. This
037    /// method should be used if the launcher detects the sub projects
038    /// e.g. by reflection and the root project does not add its sub
039    /// projects itself.
040    ///
041    /// @param buildRoot the build root
042    /// @param rootProject the root project
043    /// @param subprojects the sub projects
044    /// @param jdbldProps the builder properties
045    /// @param commandLine the command line
046    /// @return the root project
047    ///
048    public static AbstractRootProject createProjects(
049            Path buildRoot, Class<? extends RootProject> rootProject,
050            List<Class<? extends Project>> subprojects,
051            Properties jdbldProps, CommandLine commandLine) {
052        try {
053            return ScopedValue
054                .where(DefaultBuildContext.scopedBuildContext,
055                    new DefaultBuildContext(buildRoot, jdbldProps, commandLine))
056                .call(() -> {
057                    var result = (AbstractRootProject) rootProject
058                        .getConstructor().newInstance();
059                    subprojects.forEach(result::project);
060                    return result;
061
062                });
063        } catch (SecurityException | NegativeArraySizeException
064                | IllegalArgumentException | ReflectiveOperationException e) {
065            throw new IllegalArgumentException(e);
066        }
067    }
068}