-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
257 lines (230 loc) · 7.22 KB
/
index.js
File metadata and controls
257 lines (230 loc) · 7.22 KB
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
#!/usr/bin/env node
import { program } from "commander";
import inquirer from "inquirer";
import fs from "fs-extra";
import { execSync } from "child_process";
import { rmSync } from "fs";
import axios from "axios";
/**
* Get the Bitbucket credentials from the credentials file
* @returns {Object} The Bitbucket credentials
*/
function getBitbucketCredentials() {
try {
const bitbucketCredentials = JSON.parse(
fs.readFileSync("./bitbucket-credentials.json", "utf8")
);
return bitbucketCredentials;
} catch (error) {
console.error(`❌ Le fichier de credentials n'existe pas.
Pour créer le fichier, veuillez créer ./bitbucket-credentials.json avec le format :
{
"username": "votre_username",
"token": "votre_token"
}`);
throw error;
}
}
/**
* Update the permissions of a Bitbucket repository for a specific group
* @param {string} repoName - The name of the repository
* @returns {Promise<Object>} The response from the Bitbucket API
* @throws {Error} If the credentials are invalid or the API request fails
*/
async function updateBitbucketRepoPermissions(repoName) {
let credentials;
// Gestion de la lecture du fichier de credentials
try {
credentials = getBitbucketCredentials();
} catch (error) {
if (error.code === "ENOENT") {
console.error(`❌ Le fichier de credentials n'existe pas.
Pour créer le fichier, veuillez créer ./bitbucket-credentials.json avec le format :
{
"username": "votre_username",
"token": "votre_token"
}`);
} else if (error instanceof SyntaxError) {
console.error(
"❌ Le fichier bitbucket-credentials.json contient du JSON invalide"
);
} else {
console.error(
"❌ Erreur lors de la lecture du fichier de credentials:",
error.message
);
}
throw error;
}
// Validation du contenu du fichier
if (!credentials.token || !credentials.username) {
throw new Error(`❌ Format de credentials invalide.
Le fichier doit contenir les champs obligatoires :
{
"username": "votre_username",
"token": "votre_token"
}`);
}
// Validation des paramètres d'entrée
if (!repoName) {
throw new Error("❌ Le nom du repository est requis");
}
const normalizedPermission = permission.toLowerCase();
if (!Object.keys(permissionMap).includes(normalizedPermission)) {
throw new Error('❌ La permission doit être "read", "write" ou "admin"');
}
const auth = Buffer.from(
`${credentials.username}:${credentials.token}`
).toString("base64");
try {
const response = await axios({
method: "PUT",
url: `https://api.bitbucket.org/2.0/repositories/lefigaro/${repoName}/permissions-config/groups/datavis-developers`,
headers: {
Authorization: `Basic ${auth}`,
"Content-Type": "application/json",
Accept: "application/json",
},
data: {
permission: "admin",
},
});
console.log(
`✅ Permissions mises à jour pour le groupe Datavis developers sur le repository ${repoName}`
);
return response.status;
} catch (error) {
console.log(error.response.data);
console.error(
"❌ Erreur lors de la mise à jour des permissions:",
error.response?.data?.error?.message || error.message
);
throw error;
}
}
/**
* Create a Bitbucket repository
* @param {*} repoName
* @returns
*/
async function createBitbucketRepo(repoName) {
let credentials;
// Gestion de la lecture du fichier de credentials
try {
credentials = getBitbucketCredentials();
} catch (error) {
if (error.code === "ENOENT") {
console.error(`❌ Le fichier de credentials n'existe pas.
Pour créer le fichier, veuillez créer ./bitbucket-credentials.json avec le format :
{
"username": "votre_username",
"token": "votre_token"
}`);
} else if (error instanceof SyntaxError) {
console.error(
"❌ Le fichier bitbucket-credentials.json contient du JSON invalide"
);
} else {
console.error(
"❌ Erreur lors de la lecture du fichier de credentials:",
error.message
);
}
throw error;
}
// Validation du contenu du fichier
if (!credentials.token || !credentials.username) {
throw new Error(`❌ Format de credentials invalide.
Le fichier doit contenir les champs obligatoires :
{
"username": "votre_username",
"token": "votre_token"
}`);
}
const auth = Buffer.from(
`${credentials.username}:${credentials.token}`
).toString("base64");
try {
const response = await axios({
method: "POST",
url: `https://api.bitbucket.org/2.0/repositories/lefigaro/${repoName}`,
headers: {
Authorization: `Basic ${auth}`,
"Content-Type": "application/json",
},
data: {
scm: "git",
is_private: true,
project: {
key: "DAT",
},
},
});
// Convertir l'URL HTTP en URL SSH
const httpUrl = response.data.links.html.href;
// Format attendu: https://bitbucket.org/lefigaro/nom-repo
const repoPath = httpUrl.replace("https://bitbucket.org/", "");
const sshUrl = `git@bitbucket.org:${repoPath}.git`;
return sshUrl;
} catch (error) {
console.error(
"❌ Erreur lors de la création du repo Bitbucket:",
error.response?.data?.error?.message || error.message
);
throw error;
}
}
program
.name("create-figdata")
.description("Initialise un projet figdata à partir d’un repo template")
.option("-d, --dir <dir>", "Nom du dossier cible", "figdata");
program.parse();
const options = program.opts();
// Questions interactives
const answers = await inquirer.prompt([
{
type: "input",
name: "name",
message: "Id du projet figdata ?",
},
]);
const projectDir = answers.name;
console.log("➡️ Création du repo Bitbucket...");
let repoUrl;
try {
repoUrl = await createBitbucketRepo(projectDir);
console.log("✅ Repo Bitbucket créé:", repoUrl);
} catch (error) {
console.error("❌ Impossible de créer le repo Bitbucket");
process.exit(1);
}
// console.log("➡️ Mise à jour des permissions du repo...");
// try {
// await updateBitbucketRepoPermissions(projectDir, "DAT", "admin");
// console.log("✅ Permissions mises à jour");
// } catch (error) {
// console.error("❌ Impossible de mettre à jour les permissions");
// process.exit(1);
// }
console.log("➡️ Clonage du repo de base...");
execSync(
`git clone --depth 1 git@bitbucket.org:lefigaro/data-vite-scaffolder.git ${projectDir}`,
{ stdio: "inherit" }
);
// Supprimer le dossier .git de manière compatible avec Windows
rmSync(`${projectDir}/.git`, { recursive: true, force: true });
// Sauvegarder le répertoire courant
const initialDir = process.cwd();
// Initialiser un nouveau dépôt Git
process.chdir(projectDir);
execSync("git init", { stdio: "inherit" });
execSync(`git remote add origin ${repoUrl}`, { stdio: "inherit" });
console.log("➡️ Customisation des fichiers...");
const pkgPath = "package.json";
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
pkg["name"] = projectDir;
pkg["figdata"]["id"] = projectDir;
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
// Revenir au répertoire initial
process.chdir(initialDir);
console.log("✅ Projet initialisé et créé sur Bitbucket !");