Search in sources :

Example 1 with GiteaRepository

use of org.jenkinsci.plugin.gitea.client.api.GiteaRepository in project gitea-plugin by jenkinsci.

the class MockGiteaConnection method withRepo.

public MockGiteaConnection withRepo(GiteaRepository repo) {
    GiteaRepository clone = repo.clone();
    clone.setId(nextId.incrementAndGet());
    clone.setCreatedAt(new Date());
    clone.setUpdatedAt(new Date());
    this.repositories.put(keyOf(clone), clone);
    this.repoHooks.put(keyOf(clone), new ArrayList<GiteaHook>());
    this.branches.put(keyOf(clone), new HashMap<String, GiteaBranch>());
    this.pulls.put(keyOf(clone), new HashMap<Long, GiteaPullRequest>());
    this.issues.put(keyOf(clone), new HashMap<Long, GiteaIssue>());
    this.collaborators.put(keyOf(clone), new TreeSet<String>());
    this.files.put(keyOf(clone), new TreeMap<String, Map<String, byte[]>>());
    return this;
}
Also used : GiteaIssue(org.jenkinsci.plugin.gitea.client.api.GiteaIssue) GiteaBranch(org.jenkinsci.plugin.gitea.client.api.GiteaBranch) GiteaHook(org.jenkinsci.plugin.gitea.client.api.GiteaHook) Date(java.util.Date) AtomicLong(java.util.concurrent.atomic.AtomicLong) GiteaPullRequest(org.jenkinsci.plugin.gitea.client.api.GiteaPullRequest) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) GiteaRepository(org.jenkinsci.plugin.gitea.client.api.GiteaRepository)

Example 2 with GiteaRepository

use of org.jenkinsci.plugin.gitea.client.api.GiteaRepository in project gitea-plugin by jenkinsci.

the class GiteaSCMNavigator method visitSources.

@Override
public void visitSources(@NonNull final SCMSourceObserver observer) throws IOException, InterruptedException {
    try (GiteaSCMNavigatorRequest request = new GiteaSCMNavigatorContext().withTraits(traits).newRequest(this, observer);
        GiteaConnection c = gitea(observer.getContext()).open()) {
        giteaOwner = c.fetchUser(repoOwner);
        if (StringUtils.isBlank(giteaOwner.getEmail())) {
            giteaOwner = c.fetchOrganization(repoOwner);
        }
        List<GiteaRepository> repositories = c.fetchRepositories(giteaOwner);
        int count = 0;
        observer.getListener().getLogger().format("%n  Checking repositories...%n");
        Set<Long> seen = new HashSet<>();
        for (GiteaRepository r : repositories) {
            // TODO remove this hack for Gitea listing the repositories multiple times
            if (seen.contains(r.getId())) {
                continue;
            } else {
                seen.add(r.getId());
            }
            if (!StringUtils.equalsIgnoreCase(r.getOwner().getUsername(), repoOwner)) {
                // this is the user repos which includes all organizations that they are a member of
                continue;
            }
            count++;
            if (r.isEmpty()) {
                observer.getListener().getLogger().format("%n    Ignoring empty repository %s%n", HyperlinkNote.encodeTo(r.getHtmlUrl(), r.getName()));
                continue;
            }
            observer.getListener().getLogger().format("%n    Checking repository %s%n", HyperlinkNote.encodeTo(r.getHtmlUrl(), r.getName()));
            if (request.process(r.getName(), new SCMNavigatorRequest.SourceLambda() {

                @NonNull
                @Override
                public SCMSource create(@NonNull String projectName) throws IOException, InterruptedException {
                    return new GiteaSCMSourceBuilder(getId() + "::" + projectName, serverUrl, credentialsId, repoOwner, projectName).withTraits(traits).build();
                }
            }, null, new SCMNavigatorRequest.Witness() {

                @Override
                public void record(@NonNull String projectName, boolean isMatch) {
                    if (isMatch) {
                        observer.getListener().getLogger().format("      Proposing %s%n", projectName);
                    } else {
                        observer.getListener().getLogger().format("      Ignoring %s%n", projectName);
                    }
                }
            })) {
                observer.getListener().getLogger().format("%n  %d repositories were processed (query complete)%n", count);
                return;
            }
        }
        observer.getListener().getLogger().format("%n  %d repositories were processed%n", count);
    }
}
Also used : SCMNavigatorRequest(jenkins.scm.api.trait.SCMNavigatorRequest) GiteaConnection(org.jenkinsci.plugin.gitea.client.api.GiteaConnection) IOException(java.io.IOException) SCMSource(jenkins.scm.api.SCMSource) NonNull(edu.umd.cs.findbugs.annotations.NonNull) GiteaRepository(org.jenkinsci.plugin.gitea.client.api.GiteaRepository) HashSet(java.util.HashSet)

Example 3 with GiteaRepository

use of org.jenkinsci.plugin.gitea.client.api.GiteaRepository 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 4 with GiteaRepository

use of org.jenkinsci.plugin.gitea.client.api.GiteaRepository in project gitea-plugin by jenkinsci.

the class GiteaWebhookListener method register.

public static void register(SCMSourceOwner owner, GiteaSCMSource source, WebhookRegistration mode, String credentialsId) {
    StandardCredentials credentials;
    String serverUrl = source.getServerUrl();
    switch(mode) {
        case DISABLE:
            return;
        case SYSTEM:
            GiteaServer server = GiteaServers.get().findServer(serverUrl);
            if (server == null || !server.isManageHooks()) {
                return;
            }
            credentials = server.credentials();
            break;
        case ITEM:
            credentials = source.credentials();
            break;
        default:
            return;
    }
    if (credentials == null) {
        return;
    }
    JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
    if (locationConfiguration == null) {
        return;
    }
    String rootUrl = locationConfiguration.getUrl();
    if (StringUtils.isBlank(rootUrl) || rootUrl.startsWith("http://localhost:")) {
        return;
    }
    String hookUrl = UriTemplate.buildFromTemplate(rootUrl).literal("gitea-webhook").literal("/post").build().expand();
    try (GiteaConnection c = connect(serverUrl, credentials)) {
        GiteaRepository repo = c.fetchRepository(source.getRepoOwner(), source.getRepository());
        if (repo == null) {
            return;
        }
        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 " + source.getRepoOwner() + "/" + source.getRepository() + " on " + serverUrl, e);
    }
}
Also used : JenkinsLocationConfiguration(jenkins.model.JenkinsLocationConfiguration) JenkinsLocationConfiguration(jenkins.model.JenkinsLocationConfiguration) GiteaConnection(org.jenkinsci.plugin.gitea.client.api.GiteaConnection) GiteaHook(org.jenkinsci.plugin.gitea.client.api.GiteaHook) IOException(java.io.IOException) GiteaServer(org.jenkinsci.plugin.gitea.servers.GiteaServer) GiteaEventType(org.jenkinsci.plugin.gitea.client.api.GiteaEventType) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) GiteaRepository(org.jenkinsci.plugin.gitea.client.api.GiteaRepository)

Aggregations

GiteaRepository (org.jenkinsci.plugin.gitea.client.api.GiteaRepository)4 GiteaConnection (org.jenkinsci.plugin.gitea.client.api.GiteaConnection)3 GiteaHook (org.jenkinsci.plugin.gitea.client.api.GiteaHook)3 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 JenkinsLocationConfiguration (jenkins.model.JenkinsLocationConfiguration)2 GiteaEventType (org.jenkinsci.plugin.gitea.client.api.GiteaEventType)2 GiteaServer (org.jenkinsci.plugin.gitea.servers.GiteaServer)2 StandardCredentials (com.cloudbees.plugins.credentials.common.StandardCredentials)1 NonNull (edu.umd.cs.findbugs.annotations.NonNull)1 IgnoreNotifyCommit (hudson.plugins.git.extensions.impl.IgnoreNotifyCommit)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1