<commit_before>/*******************************************************************************
 * Copyright (c) 2010 <NAME>.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     <NAME> - initial API and implementation
 *******************************************************************************/
package bndtools.release;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import aQute.bnd.build.Project;
import aQute.bnd.build.ProjectBuilder;
import aQute.bnd.build.model.BndEditModel;
import aQute.bnd.differ.Baseline;
import aQute.bnd.differ.Baseline.Info;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.JarResource;
import aQute.bnd.properties.Document;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.version.Version;
import aQute.lib.io.IO;
import aQute.service.reporter.Reporter;
import bndtools.central.Central;
import bndtools.release.api.IReleaseParticipant;
import bndtools.release.api.ReleaseOption;
import bndtools.release.api.IReleaseParticipant.Scope;
import bndtools.release.api.ReleaseContext;
import bndtools.release.api.ReleaseContext.Error;
import bndtools.release.api.ReleaseUtils;
import bndtools.release.nl.Messages;

public class ReleaseHelper {

    public final static String VERSION_WITH_MACRO_STRING = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\$\\{[-_\\.\\da-zA-Z]+\\})";//$NON-NLS-1$
    public final static Pattern VERSION_WITH_MACRO = Pattern.compile(VERSION_WITH_MACRO_STRING);

    public static void updateProject(ReleaseContext context) throws Exception {
        try (ProjectBuilder pb = context.getProject()
            .getBuilder(null)) {
            for (Builder builder : pb.getSubBuilders()) {

                Baseline current = getBaselineForBuilder(builder, context);
                if (current == null) {
                    continue;
                }
                for (Info info : current.getPackageInfos()) {
                    context.getProject()
                        .setPackageInfo(info.packageName, info.suggestedVersion);
                }

                updateBundleVersion(context, current, builder);
            }
        }
    }

    private static void updateBundleVersion(ReleaseContext context, Baseline current, Builder builder) throws IOException, CoreException {

        Version bundleVersion = current.getSuggestedVersion();
        if (bundleVersion != null) {

            File file = builder.getPropertiesFile();
            Properties properties = builder.getProperties();
            if (file == null) {
                file = context.getProject()
                    .getPropertiesFile();
                properties = context.getProject()
                    .getProperties();
            }
            final IFile resource = (IFile) ReleaseUtils.toResource(file);

            final Document document;
            if (resource.exists()) {
                byte[] bytes = readFully(resource.getContents());
                document = new Document(new String(bytes, resource.getCharset()));
            } else {
                document = new Document(""); //$NON-NLS-1$
            }

            final BndEditModel model;
            BndEditModel model2;
            try {
                model2 = new BndEditModel(Central.getWorkspace());
            } catch (Exception e) {
                System.err.println("Unable to create BndEditModel with Workspace, defaulting to without Workspace");
                model2 = new BndEditModel();
            }
            model = model2;
            model.loadFrom(document);

            String currentVersion = model.getBundleVersionString();
            String templateVersion = updateTemplateVersion(currentVersion, bundleVersion);
            model.setBundleVersion(templateVersion);
            properties.setProperty(Constants.BUNDLE_VERSION, templateVersion);

            final Document finalDoc = document;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    model.saveChangesTo(finalDoc);

                    try {
                        writeFully(finalDoc.get(), resource, false);
                        resource.refreshLocal(IResource.DEPTH_ZERO, null);
                    } catch (CoreException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
            if (Display.getCurrent() == null) {
                Display.getDefault()
                    .syncExec(run);
            } else
                run.run();
        }
    }

    private static Baseline getBaselineForBuilder(Builder builder, ReleaseContext context) {
        Baseline current = null;
        for (Baseline jd : context.getBaselines()) {
            if (jd.getBsn()
                .equals(builder.getBsn())) {
                current = jd;
                break;
            }
        }
        return current;
    }

    public static boolean release(ReleaseContext context, List<Baseline> diffs) throws Exception {

        boolean ret = true;

        List<IReleaseParticipant> participants = Activator.getReleaseParticipants();

        switch (context.getReleaseOption()) {
            case UPDATE :
            default :
                if (!doUpdateVersions(context, participants)) {
                    return false;
                }
                break;
            case RELEASE :
                ret = doRelease(context, diffs, participants);
                break;
            case UPDATE_RELEASE :
                if (!doUpdateVersions(context, participants)) {
                    return false;
                }
                ret = doRelease(context, diffs, participants);
                break;
        }

        postRelease(context, participants, ret);
        return ret;
    }

    private static boolean doUpdateVersions(ReleaseContext context, List<IReleaseParticipant> participants) throws Exception {

        if (!preUpdateProjectVersions(context, participants)) {
            postRelease(context, participants, false);
            displayErrors(context);
            return false;
        }

        ReleaseHelper.updateProject(context);

        IProject proj = ReleaseUtils.getProject(context.getProject());
        proj.refreshLocal(IResource.DEPTH_INFINITE, context.getProgressMonitor());

        return true;
    }

    private static boolean doRelease(ReleaseContext context, List<Baseline> diffs, List<IReleaseParticipant> participants) throws Exception {
        boolean ret = true;
        if (!preRelease(context, participants)) {
            postRelease(context, participants, false);
            displayErrors(context);
            return false;
        }

        try (ProjectBuilder pb = context.getProject()
            .getBuilder(null)) {
            List<Builder> builders = pb.getSubBuilders();<commit_msg>Clear project warnings after version update<commit_after>/*******************************************************************************
 * Copyright (c) 2010 <NAME>.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     <NAME> - initial API and implementation
 *******************************************************************************/
package bndtools.release;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import aQute.bnd.build.Project;
import aQute.bnd.build.ProjectBuilder;
import aQute.bnd.build.model.BndEditModel;
import aQute.bnd.differ.Baseline;
import aQute.bnd.differ.Baseline.Info;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.JarResource;
import aQute.bnd.properties.Document;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.version.Version;
import aQute.lib.io.IO;
import aQute.service.reporter.Reporter;
import bndtools.central.Central;
import bndtools.release.api.IReleaseParticipant;
import bndtools.release.api.ReleaseOption;
import bndtools.release.api.IReleaseParticipant.Scope;
import bndtools.release.api.ReleaseContext;
import bndtools.release.api.ReleaseContext.Error;
import bndtools.release.api.ReleaseUtils;
import bndtools.release.nl.Messages;

public class ReleaseHelper {

    public final static String VERSION_WITH_MACRO_STRING = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\$\\{[-_\\.\\da-zA-Z]+\\})";//$NON-NLS-1$
    public final static Pattern VERSION_WITH_MACRO = Pattern.compile(VERSION_WITH_MACRO_STRING);

    public static void updateProject(ReleaseContext context) throws Exception {
        try (ProjectBuilder pb = context.getProject()
            .getBuilder(null)) {
            for (Builder builder : pb.getSubBuilders()) {

                Baseline current = getBaselineForBuilder(builder, context);
                if (current == null) {
                    continue;
                }
                for (Info info : current.getPackageInfos()) {
                    context.getProject()
                        .setPackageInfo(info.packageName, info.suggestedVersion);
                }

                updateBundleVersion(context, current, builder);
            }
        }
    }

    private static void updateBundleVersion(ReleaseContext context, Baseline current, Builder builder) throws IOException, CoreException {

        Version bundleVersion = current.getSuggestedVersion();
        if (bundleVersion != null) {

            File file = builder.getPropertiesFile();
            Properties properties = builder.getProperties();
            if (file == null) {
                file = context.getProject()
                    .getPropertiesFile();
                properties = context.getProject()
                    .getProperties();
            }
            final IFile resource = (IFile) ReleaseUtils.toResource(file);

            final Document document;
            if (resource.exists()) {
                byte[] bytes = readFully(resource.getContents());
                document = new Document(new String(bytes, resource.getCharset()));
            } else {
                document = new Document(""); //$NON-NLS-1$
            }

            final BndEditModel model;
            BndEditModel model2;
            try {
                model2 = new BndEditModel(Central.getWorkspace());
            } catch (Exception e) {
                System.err.println("Unable to create BndEditModel with Workspace, defaulting to without Workspace");
                model2 = new BndEditModel();
            }
            model = model2;
            model.loadFrom(document);

            String currentVersion = model.getBundleVersionString();
            String templateVersion = updateTemplateVersion(currentVersion, bundleVersion);
            model.setBundleVersion(templateVersion);
            properties.setProperty(Constants.BUNDLE_VERSION, templateVersion);

            final Document finalDoc = document;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    model.saveChangesTo(finalDoc);

                    try {
                        writeFully(finalDoc.get(), resource, false);
                        resource.refreshLocal(IResource.DEPTH_ZERO, null);
                    } catch (CoreException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
            if (Display.getCurrent() == null) {
                Display.getDefault()
                    .syncExec(run);
            } else
                run.run();
        }
    }

    private static Baseline getBaselineForBuilder(Builder builder, ReleaseContext context) {
        Baseline current = null;
        for (Baseline jd : context.getBaselines()) {
            if (jd.getBsn()
                .equals(builder.getBsn())) {
                current = jd;
                break;
            }
        }
        return current;
    }

    public static boolean release(ReleaseContext context, List<Baseline> diffs) throws Exception {

        boolean ret = true;

        List<IReleaseParticipant> participants = Activator.getReleaseParticipants();

        switch (context.getReleaseOption()) {
            case UPDATE :
            default :
                if (!doUpdateVersions(context, participants)) {
                    return false;
                }
                break;
            case RELEASE :
                ret = doRelease(context, diffs, participants);
                break;
            case UPDATE_RELEASE :
                if (!doUpdateVersions(context, participants)) {
                    return false;
                }
                ret = doRelease(context, diffs, participants);
                break;
        }

        postRelease(context, participants, ret);
        return ret;
    }

    private static boolean doUpdateVersions(ReleaseContext context, List<IReleaseParticipant> participants) throws Exception {

        if (!preUpdateProjectVersions(context, participants)) {
            postRelease(context, participants, false);
            displayErrors(context);
            return false;
        }

        ReleaseHelper.updateProject(context);

        IProject proj = ReleaseUtils.getProject(context.getProject());
        proj.refreshLocal(IResource.DEPTH_INFINITE, context.getProgressMonitor());

        context.getProject()
            .clear();

        return true;
    }

    private static boolean doRelease(ReleaseContext context, List<Baseline> diffs, List<IReleaseParticipant> participants) throws Exception {
        boolean ret = true;
        if (!preRelease(context, participants)) {
            postRelease(context, participants, false);
            displayErrors(context);
            return false;
        }

        try (ProjectBuilder pb = context.getProject()
            .getBuilder(null)) {
            List<Builder> builders = pb.getSubBuilders();
{'fraction_non_alphanumeric': 0.11372373141978473, 'fraction_numerical': 0.0017939518195797027, 'mean_word_length': 2.2593443307579872, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '252946', 'n_tokens_mistral': 4073, 'n_tokens_neox': 3841, 'n_words': 868}