Search in sources :

Example 31 with RemoteConfig

use of org.eclipse.jgit.transport.RemoteConfig in project gitea-plugin by jenkinsci.

the class GiteaPushSCMEvent method isMatch.

/**
 * {@inheritDoc}
 */
@Override
public boolean isMatch(@NonNull SCM scm) {
    URIish uri;
    try {
        uri = new URIish(getPayload().getRepository().getHtmlUrl());
    } catch (URISyntaxException e) {
        return false;
    }
    String ref = getPayload().getRef();
    ref = ref.startsWith(Constants.R_HEADS) ? ref.substring(Constants.R_HEADS.length()) : ref;
    if (scm instanceof GitSCM) {
        GitSCM git = (GitSCM) scm;
        if (git.getExtensions().get(IgnoreNotifyCommit.class) != null) {
            return false;
        }
        for (RemoteConfig repository : git.getRepositories()) {
            for (URIish remoteURL : repository.getURIs()) {
                if (GitStatus.looselyMatches(uri, remoteURL)) {
                    for (BranchSpec branchSpec : git.getBranches()) {
                        if (branchSpec.getName().contains("$")) {
                            // If the branchspec is parametrized, always run the polling
                            return true;
                        } else {
                            if (branchSpec.matches(repository.getName() + "/" + ref)) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }
    return false;
}
Also used : URIish(org.eclipse.jgit.transport.URIish) BranchSpec(hudson.plugins.git.BranchSpec) IgnoreNotifyCommit(hudson.plugins.git.extensions.impl.IgnoreNotifyCommit) URISyntaxException(java.net.URISyntaxException) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) GitSCM(hudson.plugins.git.GitSCM)

Example 32 with RemoteConfig

use of org.eclipse.jgit.transport.RemoteConfig in project gitea-plugin by jenkinsci.

the class GiteaWebhookListener method register.

public static void register(SCMTriggerItem item, GitSCM scm) {
    JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
    if (locationConfiguration == null) {
        // Jenkins URL not configured, can't register hooks
        return;
    }
    String rootUrl = locationConfiguration.getUrl();
    if (StringUtils.isBlank(rootUrl) || rootUrl.startsWith("http://localhost:")) {
        // Jenkins URL not configured, can't register hooks
        return;
    }
    if (scm.getExtensions().get(IgnoreNotifyCommit.class) != null) {
        // GitSCM special case to ignore commits, so no point registering hooks
        return;
    }
    List<GiteaServer> serverList = new ArrayList<>(GiteaServers.get().getServers());
    if (serverList.isEmpty()) {
        // Not configured to register hooks, so no point registering.
        return;
    }
    // track attempts to register in case there are multiple remotes for the same repo
    Set<String> registered = new HashSet<>();
    String hookUrl = UriTemplate.buildFromTemplate(rootUrl).literal("gitea-webhook").literal("/post").build().expand();
    for (RemoteConfig repository : scm.getRepositories()) {
        REMOTES: for (URIish remoteURL : repository.getURIs()) {
            for (Iterator<GiteaServer> iterator = serverList.iterator(); iterator.hasNext(); ) {
                GiteaServer server = iterator.next();
                if (!server.isManageHooks()) {
                    // not allowed to manage hooks for this server, don't check it against any other remotes
                    iterator.remove();
                    continue;
                }
                URIish serverURL;
                try {
                    serverURL = new URIish(server.getServerUrl());
                } catch (URISyntaxException e) {
                    continue;
                }
                if (!StringUtils.equals(serverURL.getHost(), remoteURL.getHost())) {
                    // different hosts, so none of our business
                    continue;
                }
                if (serverURL.getPort() != -1 && remoteURL.getPort() != -1 && serverURL.getPort() != remoteURL.getPort()) {
                    // different explicit ports, so none of our business
                    continue;
                }
                String serverPath = serverURL.getPath();
                if (!serverPath.startsWith("/")) {
                    serverPath = "/" + serverPath;
                }
                if (!serverPath.endsWith("/")) {
                    serverPath = serverPath + "/";
                }
                String remotePath = remoteURL.getPath();
                if (!remotePath.startsWith("/")) {
                    remotePath = "/" + remotePath;
                }
                if (!remotePath.startsWith(serverPath)) {
                    // different context path, so none of our business
                    continue;
                }
                remotePath = remotePath.substring(serverPath.length());
                int index = remotePath.indexOf('/');
                if (index == -1) {
                    // not matching expected structure of repoOwner/repository[.git]
                    continue REMOTES;
                }
                String repoOwner = remotePath.substring(0, index);
                String repoName = StringUtils.removeEnd(remotePath.substring(index + 1), ".git");
                String registeredKey = server.getServerUrl() + "::" + repoOwner + "::" + repoName;
                if (registered.contains(registeredKey)) {
                    // have already tried to register this repo during this method, so don't repeat
                    continue REMOTES;
                }
                registered.add(registeredKey);
                try (GiteaConnection c = connect(server.getServerUrl(), server.credentials())) {
                    GiteaRepository repo = c.fetchRepository(repoOwner, repoName);
                    if (repo == null) {
                        continue REMOTES;
                    }
                    List<GiteaHook> hooks = c.fetchHooks(repo);
                    GiteaHook hook = null;
                    for (GiteaHook h : hooks) {
                        if (hookUrl.equals(h.getConfig().getUrl())) {
                            if (hook == null && h.getType() == GiteaHookType.GITEA && h.getConfig().getContentType() == GiteaPayloadType.JSON && h.isActive() && EnumSet.allOf(GiteaEventType.class).equals(h.getEvents())) {
                                hook = h;
                            } else {
                                c.deleteHook(repo, h);
                            }
                        }
                    }
                    if (hook == null) {
                        hook = new GiteaHook();
                        GiteaHook.Configuration configuration = new GiteaHook.Configuration();
                        configuration.setContentType(GiteaPayloadType.JSON);
                        configuration.setUrl(hookUrl);
                        hook.setType(GiteaHookType.GITEA);
                        hook.setConfig(configuration);
                        hook.setEvents(EnumSet.allOf(GiteaEventType.class));
                        hook.setActive(true);
                        c.createHook(repo, hook);
                    }
                } catch (IOException | InterruptedException e) {
                    LOGGER.log(Level.WARNING, "Could not manage repository hooks for " + repoOwner + "/" + repoName + " on " + server.getServerUrl(), e);
                }
            }
            if (serverList.isEmpty()) {
                // none of the servers are allowed manage hooks, no point checking the remaining remotes
                return;
            }
        }
    }
}
Also used : URIish(org.eclipse.jgit.transport.URIish) JenkinsLocationConfiguration(jenkins.model.JenkinsLocationConfiguration) JenkinsLocationConfiguration(jenkins.model.JenkinsLocationConfiguration) ArrayList(java.util.ArrayList) GiteaConnection(org.jenkinsci.plugin.gitea.client.api.GiteaConnection) GiteaHook(org.jenkinsci.plugin.gitea.client.api.GiteaHook) URISyntaxException(java.net.URISyntaxException) GiteaServer(org.jenkinsci.plugin.gitea.servers.GiteaServer) Iterator(java.util.Iterator) GiteaEventType(org.jenkinsci.plugin.gitea.client.api.GiteaEventType) IgnoreNotifyCommit(hudson.plugins.git.extensions.impl.IgnoreNotifyCommit) ArrayList(java.util.ArrayList) List(java.util.List) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) HashSet(java.util.HashSet) GiteaRepository(org.jenkinsci.plugin.gitea.client.api.GiteaRepository)

Example 33 with RemoteConfig

use of org.eclipse.jgit.transport.RemoteConfig in project jbosstools-openshift by jbosstools.

the class EGitUtils method getRemoteGitReposFilteredStream.

private static Stream<String> getRemoteGitReposFilteredStream(IProject project) throws CoreException {
    if (project == null) {
        return null;
    }
    Repository repo = getRepository(project);
    if (repo == null) {
        return null;
    }
    // Returned configurations are ordered lexicographically by names.
    List<RemoteConfig> remoteConfigs = getAllRemoteConfigs(repo);
    Collections.sort(remoteConfigs, new Comparator<RemoteConfig>() {

        @Override
        public int compare(RemoteConfig o1, RemoteConfig o2) {
            if (ORIGIN.equals(o1.getName())) {
                return -1;
            }
            if (ORIGIN.equals(o2.getName())) {
                return 1;
            }
            return o1.getName().compareToIgnoreCase(o2.getName());
        }
    });
    return remoteConfigs.stream().map(rc -> getFetchURI(rc)).filter(uri -> uri != null && uri.toString().startsWith("http")).map(URIish::toString);
}
Also used : Arrays(java.util.Arrays) IndexDiff(org.eclipse.jgit.lib.IndexDiff) URISyntaxException(java.net.URISyntaxException) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) CoreException(org.eclipse.core.runtime.CoreException) IteratorService(org.eclipse.egit.core.IteratorService) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) RevWalk(org.eclipse.jgit.revwalk.RevWalk) PostCloneTask(org.eclipse.egit.core.op.CloneOperation.PostCloneTask) Config(org.eclipse.jgit.lib.Config) IStatus(org.eclipse.core.runtime.IStatus) Matcher(java.util.regex.Matcher) URIish(org.eclipse.jgit.transport.URIish) ConnectProviderOperation(org.eclipse.egit.core.op.ConnectProviderOperation) FetchResult(org.eclipse.jgit.transport.FetchResult) EGitCoreActivator(org.jboss.tools.openshift.egit.core.internal.EGitCoreActivator) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) EclipseGitProgressTransformer(org.eclipse.egit.core.EclipseGitProgressTransformer) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) NLS(org.eclipse.osgi.util.NLS) RefSpec(org.eclipse.jgit.transport.RefSpec) Collection(java.util.Collection) Assert(org.eclipse.core.runtime.Assert) Set(java.util.Set) Status(org.eclipse.core.runtime.Status) Constants(org.eclipse.jgit.lib.Constants) RevWalkUtils(org.eclipse.jgit.revwalk.RevWalkUtils) RepositoryProvider(org.eclipse.team.core.RepositoryProvider) Collectors(java.util.stream.Collectors) MergeStrategy(org.eclipse.jgit.merge.MergeStrategy) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) List(java.util.List) Stream(java.util.stream.Stream) NoWorkTreeException(org.eclipse.jgit.errors.NoWorkTreeException) AddToIndexOperation(org.eclipse.egit.core.op.AddToIndexOperation) Ref(org.eclipse.jgit.lib.Ref) PushResult(org.eclipse.jgit.transport.PushResult) FetchOperation(org.eclipse.egit.core.op.FetchOperation) Pattern(java.util.regex.Pattern) NotSupportedException(org.eclipse.jgit.errors.NotSupportedException) BranchTrackingStatus(org.eclipse.jgit.lib.BranchTrackingStatus) RepositoryMapping(org.eclipse.egit.core.project.RepositoryMapping) CheckoutResult(org.eclipse.jgit.api.CheckoutResult) RevCommit(org.eclipse.jgit.revwalk.RevCommit) CloneOperation(org.eclipse.egit.core.op.CloneOperation) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) Transport(org.eclipse.jgit.transport.Transport) StringUtils(org.eclipse.jgit.util.StringUtils) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) CommitOperation(org.eclipse.egit.core.op.CommitOperation) HashSet(java.util.HashSet) IProject(org.eclipse.core.resources.IProject) UserConfig(org.eclipse.jgit.lib.UserConfig) PushOperationSpecification(org.eclipse.egit.core.op.PushOperationSpecification) MergeOperation(org.eclipse.egit.core.op.MergeOperation) PushOperationResult(org.eclipse.egit.core.op.PushOperationResult) OutputStream(java.io.OutputStream) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) MalformedURLException(java.net.MalformedURLException) CreateLocalBranchOperation(org.eclipse.egit.core.op.CreateLocalBranchOperation) InitCommand(org.eclipse.jgit.api.InitCommand) ConfigConstants(org.eclipse.jgit.lib.ConfigConstants) IOException(java.io.IOException) File(java.io.File) ObjectId(org.eclipse.jgit.lib.ObjectId) RegexUtils(org.jboss.tools.openshift.egit.core.internal.utils.RegexUtils) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) IResource(org.eclipse.core.resources.IResource) Platform(org.eclipse.core.runtime.Platform) MergeResult(org.eclipse.jgit.api.MergeResult) StoredConfig(org.eclipse.jgit.lib.StoredConfig) PushOperation(org.eclipse.egit.core.op.PushOperation) Git(org.eclipse.jgit.api.Git) Comparator(java.util.Comparator) BranchOperation(org.eclipse.egit.core.op.BranchOperation) Collections(java.util.Collections) Repository(org.eclipse.jgit.lib.Repository) URIish(org.eclipse.jgit.transport.URIish) Repository(org.eclipse.jgit.lib.Repository) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig)

Example 34 with RemoteConfig

use of org.eclipse.jgit.transport.RemoteConfig in project jbosstools-openshift by jbosstools.

the class EGitUtils method getAllRemoteURIs.

/**
 * Returns all uris of alls remotes for the given project.
 *
 * @param project
 *            the project to get all remotes and all uris from
 * @return all uris
 * @throws CoreException
 */
public static List<URIish> getAllRemoteURIs(IProject project) throws CoreException {
    List<RemoteConfig> remoteConfigs = getAllRemoteConfigs(getRepository(project));
    List<URIish> uris = new ArrayList<>();
    if (remoteConfigs != null) {
        for (RemoteConfig remoteConfig : remoteConfigs) {
            uris.addAll(remoteConfig.getURIs());
        }
    }
    return uris;
}
Also used : URIish(org.eclipse.jgit.transport.URIish) ArrayList(java.util.ArrayList) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig)

Example 35 with RemoteConfig

use of org.eclipse.jgit.transport.RemoteConfig in project jbosstools-openshift by jbosstools.

the class ImportProjectOperation method checkoutBranch.

protected void checkoutBranch(String gitRef, String gitUrl, List<IProject> importedProjects, File repositoryFolder, IProgressMonitor monitor) throws CoreException {
    if (!StringUtils.isEmpty(gitRef) && !CollectionUtils.isEmpty(importedProjects)) {
        // all projects are in the same repo
        IProject project = importedProjects.get(0);
        Repository repository = EGitUtils.getRepository(project);
        try {
            if (!EGitUtils.hasBranch(gitRef, repository)) {
                Pattern gitURIPattern = Pattern.compile(RegExUtils.escapeRegex(gitUrl));
                RemoteConfig remote = EGitUtils.getRemoteByUrl(gitURIPattern, repository);
                fetchBranch(gitRef, remote, repository, monitor);
            }
            CheckoutResult result = EGitUtils.checkoutBranch(gitRef, repository, monitor);
            switch(result.getStatus()) {
                case CONFLICTS:
                case ERROR:
                    throw new CoreException(StatusFactory.errorStatus(OpenShiftCoreActivator.PLUGIN_ID, NLS.bind("Could not check out the branch {0} of the (reused) local repository at {1} because of {2}." + " Please resolve the problem and check out the branch manually so that it matches the code that's used in your OpenShift application.", new Object[] { gitRef, repositoryFolder, result.getStatus().toString().toLowerCase() })));
                default:
            }
        } catch (IOException e) {
            throw new CoreException(StatusFactory.errorStatus(OpenShiftCoreActivator.PLUGIN_ID, NLS.bind("Could check that branch {0} exists within the (reused) local repository at {1}.", gitRef, repositoryFolder), e));
        } catch (InvocationTargetException e) {
            throw new CoreException(StatusFactory.errorStatus(OpenShiftCoreActivator.PLUGIN_ID, NLS.bind("Could not fetch branch {0} from check that branch {0} exists within the (reused) local repository at {1}.", gitRef, repositoryFolder), e));
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) Repository(org.eclipse.jgit.lib.Repository) CoreException(org.eclipse.core.runtime.CoreException) CheckoutResult(org.eclipse.jgit.api.CheckoutResult) IOException(java.io.IOException) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) IProject(org.eclipse.core.resources.IProject) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

RemoteConfig (org.eclipse.jgit.transport.RemoteConfig)63 URISyntaxException (java.net.URISyntaxException)23 StoredConfig (org.eclipse.jgit.lib.StoredConfig)21 URIish (org.eclipse.jgit.transport.URIish)21 IOException (java.io.IOException)16 RefSpec (org.eclipse.jgit.transport.RefSpec)14 Repository (org.eclipse.jgit.lib.Repository)13 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)7 Button (org.eclipse.swt.widgets.Button)6 Composite (org.eclipse.swt.widgets.Composite)6 File (java.io.File)5 Git (org.eclipse.jgit.api.Git)5 Ref (org.eclipse.jgit.lib.Ref)5 SelectionAdapter (org.eclipse.swt.events.SelectionAdapter)5 SelectionEvent (org.eclipse.swt.events.SelectionEvent)5 Label (org.eclipse.swt.widgets.Label)5 List (java.util.List)4 CoreException (org.eclipse.core.runtime.CoreException)4 UIText (org.eclipse.egit.ui.internal.UIText)4