-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
98 lines (91 loc) · 2.85 KB
/
index.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
import { AlmSettingContainer } from './Interfaces';
import fetch from './proxyFetch';
const sonarqubeServer: string = process.env.SONARQUBE_SERVER;
const sonarqubeUser: string = process.env.SONARQUBE_USER;
const key: string = process.env.SONARQUBE_KEY;
const azureUrl: string = process.env.AZURE_URL;
const azurePat: string = process.env.AZURE_PAT;
class SonarqubeApi {
private _user: string;
private _deleteUrl: URL;
private _createUrl: URL;
private _listUrl: URL;
constructor(
server: string,
user: string
) {
this._user = `${user}:`;
this._deleteUrl = new URL('/api/alm_settings/delete', server);
this._createUrl = new URL('/api/alm_settings/create_azure', server);
this._listUrl = new URL('/api/alm_settings/list', server);
}
CreateAuth(): string {
return `Basic ${Buffer.from(this._user).toString('base64')}`;
}
async DeleteBindingAsync(id: string): Promise<boolean> {
console.log(`Deleting existing binding: ${id}`);
const response = await fetch(`${this._deleteUrl.href}?key=${id}`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': this.CreateAuth()
}
});
console.log(await response.text())
const isOK = response.ok;
if (isOK) {
console.log(`Binding deleted`);
} else {
throw new Error('Can not delete binding');
}
return isOK;
}
async CreateBindngAsync(id: string,
pat: string,
url: string): Promise<boolean> {
console.log(`Creating binding: ${id}`);
const response = await fetch(`${this._createUrl.href}?key=${id}&personalAccessToken=${pat}&url=${url}`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': this.CreateAuth()
}
});
console.log(await response.text())
const isOK = response.ok;
if (isOK) {
console.log(`Binding created`);
} else {
throw new Error('Can not create binding');
}
return isOK;
}
async HasBindingAsync(id: string): Promise<boolean> {
console.log(`Checking for binding : ${id}`);
const bindingsRequest = await fetch(this._listUrl.href, {
headers: {
'Content-Type': 'application/json',
'Authorization': this.CreateAuth()
}
});
const json = await bindingsRequest.json() as AlmSettingContainer;
const bindings = json.almSettings;
const exists = bindings.some(b => b.key == id && b.alm == "azure");
if (exists) {
console.log('Binding exists');
} else {
console.log('No existing binding');
}
return exists;
}
}
async function main() {
const api = new SonarqubeApi(sonarqubeServer, sonarqubeUser);
if (await api.HasBindingAsync(key)) {
await api.DeleteBindingAsync(key);
}
await api.CreateBindngAsync(key, azurePat, azureUrl);
}
main()
.catch(err => console.error(err))
.finally(process.exit);