/
MainLogic.java
212 lines (193 loc) · 8.79 KB
/
MainLogic.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package org.jenkinsci.plugins.orgfolder.github;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import hudson.BulkChange;
import hudson.Extension;
import hudson.model.AbstractItem;
import hudson.model.AllView;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.ListView;
import hudson.model.listeners.ItemListener;
import hudson.util.DescribableList;
import hudson.views.JobColumn;
import hudson.views.ListViewColumn;
import hudson.views.StatusColumn;
import hudson.views.WeatherColumn;
import jenkins.branch.Branch;
import jenkins.branch.OrganizationFolder;
import jenkins.model.Jenkins;
import jenkins.scm.api.SCMSourceOwner;
import jenkins.util.io.FileBoolean;
import org.jenkinsci.plugins.github_branch_source.Connector;
import org.jenkinsci.plugins.github_branch_source.GitHubSCMNavigator;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject;
import org.kohsuke.github.GHEvent;
import org.kohsuke.github.GHHook;
import org.kohsuke.github.GHOrganization;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.GitHub;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.Arrays.*;
import org.jenkinsci.plugins.github_branch_source.RateLimitExceededException;
/**
* Main logic of UI customization.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class MainLogic {
/**
* Applies UI customizations to {@link OrganizationFolder} for GitHub
*/
public void applyOrg(OrganizationFolder of, GitHubSCMNavigator scm) throws IOException {
if (UPDATING.get().add(of)) {
BulkChange bc = new BulkChange(of);
try {
GitHub hub = connect(of, scm);
GHUser u = hub.getUser(scm.getRepoOwner());
of.setIcon(new GitHubOrgIcon());
of.replaceAction(new GitHubOrgAction(u));
of.replaceAction(new GitHubLink("logo",u.getHtmlUrl()));
if (of.getDisplayNameOrNull()==null)
of.setDisplayName(u.getName());
if (of.getView("Repositories")==null && of.getView("All") instanceof AllView) {
// need to set the default view
ListView lv = new ListView("Repositories");
lv.getColumns().replaceBy(asList(
new StatusColumn(),
new WeatherColumn(),
new CustomNameJobColumn(Messages.class,Messages._ListViewColumn_Repository()),
new RepositoryDescriptionColumn()
));
lv.setIncludeRegex(".*"); // show all
of.addView(lv);
of.deleteView(of.getView("All"));
of.setPrimaryView(lv);
}
FileBoolean orghook = new FileBoolean(new File(of.getRootDir(),"GitHubOrgHook."+scm.getRepoOwner()));
if (orghook.isOff()) {
try {
GHOrganization org = hub.getOrganization(scm.getRepoOwner());
String url = Jenkins.getActiveInstance().getRootUrl() + "github-webhook/";
if (!existsHook(org, url)) {
org.createWebHook(new URL(url), Arrays.asList(GHEvent.REPOSITORY,GHEvent.PUSH));
LOGGER.log(Level.INFO, "A webhook was registered for the organization {0}", org.getHtmlUrl());
}
// keep trying until the hook gets successfully installed
// if the user doesn't have the proper permission, this will cause
// a repeated failure, but this code doesn't execute too often.
orghook.on();
} catch (FileNotFoundException e) {
LOGGER.log(Level.WARNING, "Failed to register GitHub Org hook to {0} (missing permissions?): {1}", new Object[] {u.getHtmlUrl(), e.getMessage()});
LOGGER.log(Level.FINE, null, e);
} catch (RateLimitExceededException e) {
LOGGER.log(Level.WARNING, "Failed to register GitHub Org hook to {0}: {1}", new Object[] {u.getHtmlUrl(), e.getMessage()});
LOGGER.log(Level.FINE, null, e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to register GitHub Org hook to "+u.getHtmlUrl(), e);
}
}
bc.commit();
} finally {
bc.abort();
UPDATING.get().remove(of);
}
}
}
/**
* Applies UI customizations to a level below {@link OrganizationFolder}, which maps to a repository.
*/
public void applyRepo(WorkflowMultiBranchProject item, GitHubSCMNavigator scm) throws IOException {
if (UPDATING.get().add(item)) {
GitHub hub = connect(item, scm);
GHRepository repo = hub.getRepository(scm.getRepoOwner() + '/' + item.getName());
BulkChange bc = new BulkChange(item);
try {
item.setIcon(new GitHubRepoIcon());
item.replaceAction(new GitHubRepoAction(repo));
item.replaceAction(new GitHubLink("repo",repo.getHtmlUrl()));
if (item.getView("Branches")==null && item.getView("All") instanceof AllView) {
// create initial views
ListView bv = new ListView("Branches");
DescribableList<ListViewColumn, Descriptor<ListViewColumn>> cols = bv.getColumns();
JobColumn name = cols.get(JobColumn.class);
if (name!=null)
cols.replace(name,new CustomNameJobColumn(Messages.class, Messages._ListViewColumn_Branch()));
bv.getJobFilters().add(new BranchJobFilter());
ListView pv = new ListView("Pull Requests");
cols = pv.getColumns();
name = cols.get(JobColumn.class);
if (name!=null)
cols.replace(name,new CustomNameJobColumn(Messages.class, Messages._ListViewColumn_PullRequest()));
bv.getJobFilters().add(new PullRequestJobFilter());
item.addView(bv);
item.addView(pv);
item.deleteView(item.getView("All"));
item.setPrimaryView(bv);
}
bc.commit();
} finally {
bc.abort();
UPDATING.get().remove(item);
}
}
}
/**
* Applies UI customizations to two levels below {@link OrganizationFolder}, which maps to a branch.
*/
public void applyBranch(WorkflowJob branch, WorkflowMultiBranchProject repo, GitHubSCMNavigator scm) throws IOException {
if (UPDATING.get().add(branch)) {
Branch b = repo.getProjectFactory().getBranch(branch);
GitHubLink repoLink = repo.getAction(GitHubLink.class);
if (repoLink!=null) {
BulkChange bc = new BulkChange(branch);
try {
branch.replaceAction(new GitHubLink("branch",repoLink.getUrl()+"/tree/"+b.getName()));
bc.commit();
} finally {
bc.abort();
UPDATING.get().remove(branch);
}
}
}
}
GitHub connect(SCMSourceOwner of, GitHubSCMNavigator n) throws IOException {
StandardCredentials credentials = Connector.lookupScanCredentials(of, n.getApiUri(), n.getScanCredentialsId());
return Connector.connect(n.getApiUri(), credentials);
}
/**
* Verify if exists a webhook by its URL.
*/
private boolean existsHook(GHOrganization org, String url) throws IOException {
for (GHHook hook : org.getHooks()) {
if (hook.getConfig().get("url").equals(url)) {
return true;
}
}
return false;
}
public static MainLogic get() {
return Jenkins.getActiveInstance().getInjector().getInstance(MainLogic.class);
}
/**
* Keeps track of what we are updating to avoid recursion, because {@link AbstractItem#save()}
* triggers {@link ItemListener}.
*/
private final ThreadLocal<Set<Item>> UPDATING = new ThreadLocal<Set<Item>>() {
@Override
protected Set<Item> initialValue() {
return new HashSet<>();
}
};
private static final Logger LOGGER = Logger.getLogger(MainLogic.class.getName());
}