-
Notifications
You must be signed in to change notification settings - Fork 15
/
travis-status.ts
278 lines (231 loc) · 9.77 KB
/
travis-status.ts
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { window, commands, StatusBarAlignment, StatusBarItem, workspace, extensions } from 'vscode';
import path = require('path');
import fs = require('fs');
var Travis = require('travis-ci');
var Git = require('git-rev-2');
export default class TravisStatusIndicator {
private _travis;
private _statusBarItem: StatusBarItem;
private _useProxy: boolean = false;
private _proxyData = { host: null, port: null };
// Private variables for automatic status polling
private _statusPollingTimeout = null;
private _statusPolling: boolean = workspace.getConfiguration('travis').get<boolean>('statusPolling');
private _statusPollingInterval: number = workspace.getConfiguration('travis').get<number>('statusPollingInterval');
constructor() {
// Listen for changes to configuration
workspace.onDidChangeConfiguration(this.updateStatusPollingConfiguration.bind(this));
}
public updateStatus(): void {
if (!this._statusBarItem) {
this._statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
this._statusBarItem.command = 'extension.updateTravis';
}
// Mark statusBarItem as 'loading'
this._statusBarItem.text = 'Travis CI $(sync)';
this._statusBarItem.tooltip = 'Fetching Travis CI status for this project...'
if (this.isTravisProject()) {
let userRepo = this.getUserRepo();
// Display Message Box if not actually a Travis
if (!userRepo || userRepo.length < 2 || userRepo[0].length === 0 || userRepo[1].length === 0) {
this.displayError('Fetching Travis CI build status failed: Could not detect username and repository');
}
let [username, repoName] = userRepo;
//Get active branch
Git.branch(workspace.rootPath, (err1, currentActiveBranch: string) => {
//Get head commit hash
Git.long(workspace.rootPath, (err2, currentCommitSha: string) => {
// Let's attempt getting a build status from Travis
this.getTravis().repos(username, repoName).branches(currentActiveBranch).get((branchError, branchResponse) => {
if (!branchError && branchResponse.commit.sha === currentCommitSha) {
let started: Date = new Date(branchResponse.branch.started_at);
let state: string = branchResponse.branch.state;
let buildNumber: number = branchResponse.branch.number;
let durationInSeconds: number = branchResponse.branch.duration;
this.show(durationInSeconds, state, buildNumber, started, currentCommitSha.substr(0, 7));
} else {
this.getTravis().repos(username, repoName).get((repoError, repoResponse) => {
if (repoError) return this.displayError(`Travis could not find ${userRepo[0]}/${userRepo[1]}`);
if (!repoResponse || !repoResponse.repo) return this.displayError('Travis CI could not find your repository.');
if (repoResponse.repo.last_build_number === null) return this.displayError('Travis found your repository, but it never ran a test.');
let started: Date = new Date(repoResponse.repo.last_build_started_at);
let state: string = repoResponse.repo.last_build_state;
let buildNumber: number = repoResponse.repo.last_build_number;
let durationInSeconds: number = repoResponse.repo.last_build_duration;
this.show(durationInSeconds, state, buildNumber, started, 'master');
});
}
});
});
});
}
// Should the status be polled?
if (this._statusPolling === true) {
// Run the update function again in the specified number of seconds
this._statusPollingTimeout = setTimeout(this.updateStatus.bind(this), this._statusPollingInterval * 1000);
}
}
private show(buildDuration: number, state: string, buildNumber: number, started: Date, identifier?: string) {
let duration = Math.round(buildDuration / 60).toString();
duration += (duration === '1') ? ' minute' : ' minutes';
let timeInfo: string = `Started: ${started.toLocaleDateString()}\nDuration: ${duration}`
switch (state) {
case 'passed':
return this.displaySuccess(`Build ${buildNumber} has passed.\n${timeInfo}`, identifier);
case 'started':
return this.displayRunning(`Build ${buildNumber} has started.\n${timeInfo}`, identifier);
case 'running':
return this.displayRunning(`Build ${buildNumber} is currently running.\n${timeInfo}`, identifier);
case 'failed':
return this.displayFailure(`Build ${buildNumber} failed.\n${timeInfo}`, identifier);
default:
// Don't throw, but instead try to display something.
return this.displayRunning(`Build ${buildNumber} has ${state}. \n${timeInfo}`, identifier);
}
}
// Opens the current project on Travis
public openInTravis(): void {
if (!workspace || !workspace.rootPath || !this.isTravisProject()) return;
let open = require('open');
let repo = this.getUserRepo();
let base = "https://travis-ci"
if (workspace.getConfiguration('travis')['pro']) {
base += '.com/'
} else {
base += '.org/'
}
if (repo && repo.length === 2) {
return open(`${base}${repo[0]}/${repo[1]}`);
}
}
// Check if a .travis.yml file is present, which indicates whether or not
// this is a Travis project
public isTravisProject(): Boolean {
if (!workspace || !workspace.rootPath) return false;
let conf = path.join(workspace.rootPath, '.travis.yml');
try {
return fs.statSync(conf).isFile();
}
catch (err) {
return false;
}
}
// Checks whether or not the current folder has a GitHub remote
public getUserRepo(): Array<String> {
if (!workspace || !workspace.rootPath) return null;
let fSettings = this.getUserRepoFromSettings();
let fTravis = this.getUserRepoFromTravis();
// Quick sanity check
let user = (fSettings && fSettings.length > 0 && fSettings[0]) ? fSettings[0] : fTravis[0];
let repo = (fSettings && fSettings.length > 1 && fSettings[1]) ? fSettings[1] : fTravis[1];
return [user, repo];
}
// Setup status bar item to display that this plugin is in trouble
private displayError(err: string, identifier?: string): void {
this.setupStatusBarItem(err, 'stop', identifier);
}
// Setup status bar item to display that the build has passed;
private displaySuccess(text: string, identifier?: string): void {
this.setupStatusBarItem(text, 'check', identifier);
}
// Setup status bar item to display that the build has failed;
private displayFailure(text: string, identifier?: string): void {
this.setupStatusBarItem(text, 'x', identifier);
}
// Setup status bar item to display that the build is running;
private displayRunning(text: string, identifier?: string): void {
this.setupStatusBarItem(text, 'clock', identifier);
}
// Setup StatusBarItem with an icon and a tooltip
private setupStatusBarItem(tooltip: string, icon: string, identifier?: string): void {
if (!this._statusBarItem) {
this._statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
}
this._statusBarItem.text = identifier ? `Travis CI ${identifier} $(${icon})` : `Travis CI $(${icon})`;
this._statusBarItem.tooltip = tooltip;
this._statusBarItem.show();
}
// Get the username/repository combo from .vscode/settings.json
private getUserRepoFromSettings(): Array<String> {
if (!workspace || !workspace.rootPath) return null;
let settingsFile = path.join(workspace.rootPath, '.vscode', 'settings.json');
try {
let settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
if (settings) {
let repo = settings['travis.repository'];
let user = settings['travis.username'];
return [user, repo];
} else {
return ['', ''];
}
} catch (e) {
return ['', ''];
}
}
// Get the username/repository combo from .travis.yml
private getUserRepoFromTravis(): Array<String> {
let ini = require('ini');
let configFile = path.join(workspace.rootPath, '.git', 'config');
try {
let config = ini.parse(fs.readFileSync(configFile, 'utf-8'));
let origin = config['remote "origin"']
if (origin && origin.url) {
// Parse URL, get GitHub username
let repo = origin.url.replace(/^(.*\/\/)?[^\/:]+[\/:]/, '');
let combo = repo;
if (repo.substr(repo.length - 4) === '.git') {
combo = repo.substr(0, repo.length - 4);
}
let split = combo.split('/');
return (split && split.length > 1) ? split : ['', ''];
}
}
catch (err) {
return ['', ''];
}
}
// Updates the configuration if it changes
private updateStatusPollingConfiguration(): void {
// Get the status polling settings
let statusPolling = workspace.getConfiguration('travis').get<boolean>('statusPolling');
let statusPollingInterval = workspace.getConfiguration('travis').get<number>('statusPollingInterval');
// If the status polling settings have changed, clear the current setTimeout
if (statusPolling !== this._statusPolling || statusPollingInterval !== this._statusPollingInterval) {
clearTimeout(this._statusPollingTimeout);
// Remember the new values
this._statusPolling = statusPolling;
this._statusPollingInterval = statusPollingInterval;
// If still set to poll, start again now
if (statusPolling === true) {
this.updateStatus();
}
}
}
private getTravis(): any {
if (this._travis == null) {
this._travis = new Travis({
version: '2.0.0',
pro: workspace.getConfiguration('travis')['pro']
})
}
// Make sure that we have github token or basic credentials
if (workspace.getConfiguration('travis')['github_oauth_token'] != "") {
this._travis.authenticate({
github_token: workspace.getConfiguration('travis')['github_oauth_token']
}, function (err) {
// we've authenticated!
});
} else if (workspace.getConfiguration('travis')['github_user'] != "" && workspace.getConfiguration('travis')['github_password'] != "") {
this._travis.authenticate({
username: workspace.getConfiguration('travis')['github_user'],
password: workspace.getConfiguration('travis')['github_password']
}, function (err) {
//we've authenticated!
});
}
return this._travis
}
dispose() {
this._statusBarItem.dispose();
}
}