use of org.jenkinsci.plugin.gitea.client.api.GiteaConnection in project gitea-plugin by jenkinsci.
the class GiteaSCMSource method retrieveActions.
@NonNull
@Override
protected List<Action> retrieveActions(SCMSourceEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException {
if (giteaRepository == null) {
try (GiteaConnection c = gitea().open()) {
listener.getLogger().format("Looking up repository %s/%s%n", repoOwner, repository);
giteaRepository = c.fetchRepository(repoOwner, repository);
}
}
List<Action> result = new ArrayList<>();
result.add(new ObjectMetadataAction(null, giteaRepository.getDescription(), giteaRepository.getWebsite()));
result.add(new GiteaLink("icon-gitea-repo", UriTemplate.buildFromTemplate(serverUrl).path(UriTemplateBuilder.var("owner")).path(UriTemplateBuilder.var("repository")).build().set("owner", repoOwner).set("repository", repository).expand()));
return result;
}
use of org.jenkinsci.plugin.gitea.client.api.GiteaConnection in project gitea-plugin by jenkinsci.
the class GiteaNotifier method sendNotifications.
/**
* Sends notifications to Bitbucket on Checkout (for the "In Progress" Status).
*/
private static void sendNotifications(Run<?, ?> build, TaskListener listener) throws IOException, InterruptedException {
final SCMSource s = SCMSource.SourceByItem.findSource(build.getParent());
if (!(s instanceof GiteaSCMSource)) {
return;
}
GiteaSCMSource source = (GiteaSCMSource) s;
if (new GiteaSCMSourceContext(null, SCMHeadObserver.none()).withTraits(source.getTraits()).notificationsDisabled()) {
return;
}
String url;
try {
url = DisplayURLProvider.get().getRunURL(build);
} catch (IllegalStateException e) {
listener.getLogger().println("Can not determine Jenkins root URL. Commit status notifications are disabled until a root URL is" + " configured in Jenkins global configuration.");
return;
}
Result result = build.getResult();
GiteaCommitStatus status = new GiteaCommitStatus();
status.setTargetUrl(url);
status.setContext(build.getParent().getFullName());
if (Result.SUCCESS.equals(result)) {
status.setDescription("This commit looks good");
status.setState(GiteaCommitState.SUCCESS);
} else if (Result.UNSTABLE.equals(result)) {
status.setDescription("This commit has test failures");
status.setState(GiteaCommitState.FAILURE);
} else if (Result.FAILURE.equals(result)) {
status.setDescription("There was a failure building this commit");
status.setState(GiteaCommitState.FAILURE);
} else if (result != null) {
// ABORTED etc.
status.setDescription("Something is wrong with the build of this commit");
status.setState(GiteaCommitState.ERROR);
} else {
status.setDescription("Build started...");
status.setState(GiteaCommitState.PENDING);
}
SCMRevision revision = SCMRevisionAction.getRevision(source, build);
String hash;
if (revision instanceof BranchSCMRevision) {
listener.getLogger().format("[Gitea] Notifying branch build status: %s %s%n", status.getState().name(), status.getDescription());
hash = ((BranchSCMRevision) revision).getHash();
} else if (revision instanceof PullRequestSCMRevision) {
listener.getLogger().format("[Gitea] Notifying pull request build status: %s %s%n", status.getState().name(), status.getDescription());
hash = ((PullRequestSCMRevision) revision).getOrigin().getHash();
} else {
// TODO tags
return;
}
JobScheduledListener jsl = ExtensionList.lookup(QueueListener.class).get(JobScheduledListener.class);
if (jsl != null) {
// we are setting the status, so don't let the queue listener background thread change it to pending
synchronized (jsl.resolving) {
jsl.resolving.remove(build.getParent());
}
}
try (GiteaConnection c = source.gitea().open()) {
int tries = 3;
while (true) {
tries--;
try {
c.createCommitStatus(source.getRepoOwner(), source.getRepository(), hash, status);
break;
} catch (GiteaHttpStatusException e) {
if (e.getStatusCode() == 500 && tries > 0) {
// server may be overloaded
continue;
}
throw e;
}
}
listener.getLogger().format("[Gitea] Notified%n");
}
}
use of org.jenkinsci.plugin.gitea.client.api.GiteaConnection in project gitea-plugin by jenkinsci.
the class GiteaWebhookListener method register.
public static void register(SCMNavigatorOwner owner, GiteaSCMNavigator navigator, WebhookRegistration mode, String credentialsId) {
StandardCredentials credentials;
String serverUrl = navigator.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 = navigator.credentials(owner);
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)) {
GiteaUser user = c.fetchUser(navigator.getRepoOwner());
if (StringUtils.isNotBlank(user.getEmail())) {
// it's a user not an org
return;
}
GiteaOrganization org = c.fetchOrganization(navigator.getRepoOwner());
if (org == null) {
return;
}
List<GiteaHook> hooks = c.fetchHooks(org);
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(org, 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(org, hook);
}
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.WARNING, "Could not manage organization hooks for " + navigator.getRepoOwner() + " on " + serverUrl, e);
}
}
use of org.jenkinsci.plugin.gitea.client.api.GiteaConnection 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;
}
}
}
}
use of org.jenkinsci.plugin.gitea.client.api.GiteaConnection 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);
}
}
Aggregations