-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.js
More file actions
216 lines (180 loc) · 6.25 KB
/
Copy pathgithub.js
File metadata and controls
216 lines (180 loc) · 6.25 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
// ============================================================
// github.js — Integración con GitHub Projects v2
// ============================================================
const config = require("./config");
const GH = config.GITHUB;
const GRAPHQL_URL = "https://api.github.com/graphql";
// ─── Helper base ──────────────────────────────────────────────
async function graphql(query, variables = {}) {
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error("GITHUB_TOKEN no está definido. Revisa tu archivo .env");
}
const response = await fetch(GRAPHQL_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ query, variables }),
});
const json = await response.json();
if (json.errors) {
throw new Error(`GitHub GraphQL error: ${json.errors.map(e => e.message).join(", ")}`);
}
return json.data;
}
// ─── Cache de IDs del Project ────────────────────────────────
let _projectCache = null;
async function getProjectMeta() {
if (_projectCache) return _projectCache;
const data = await graphql(`
query($owner: String!, $number: Int!) {
user(login: $owner) {
projectV2(number: $number) {
id
fields(first: 20) {
nodes {
... on ProjectV2SingleSelectField {
id
name
options {
id
name
}
}
}
}
}
}
}
`, { owner: GH.OWNER, number: GH.PROJECT_NUMBER });
const project = data.user.projectV2;
if (!project) {
throw new Error(`No se encontró el Project #${GH.PROJECT_NUMBER} para el usuario ${GH.OWNER}`);
}
const statusField = project.fields.nodes.find(
f => f.name && f.name.toLowerCase() === "status"
);
if (!statusField) {
throw new Error('No se encontró el campo "Status" en el Project.');
}
const options = {};
for (const opt of statusField.options) {
options[opt.name.toLowerCase()] = opt.id;
}
if (config.VERBOSE) console.log("Columnas detectadas en GitHub:", Object.keys(options));
_projectCache = {
projectId: project.id,
statusFieldId: statusField.id,
options,
};
return _projectCache;
}
// ─── Funciones públicas ───────────────────────────────────────
async function createIssueAndAddToProject(filename, stage) {
const token = process.env.GITHUB_TOKEN;
const issueRes = await fetch(
`https://api.github.com/repos/${GH.OWNER}/${GH.REPO}/issues`,
{
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: filename,
body: `Contenido del Codex SPU\n\n**Pipeline stage:** ${stage}\n\n*Creado automáticamente*`,
labels: ["codex-spu", stage],
}),
}
);
if (!issueRes.ok) {
const err = await issueRes.json();
throw new Error(`Error creando Issue: ${err.message}`);
}
const issue = await issueRes.json();
const meta = await getProjectMeta();
const addData = await graphql(`
mutation($projectId: ID!, $contentId: ID!) {
addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) {
item { id }
}
}
`, { projectId: meta.projectId, contentId: issue.node_id });
const itemId = addData.addProjectV2ItemById.item.id;
await moveItemToStage(itemId, stage, meta);
return { issueUrl: issue.html_url, itemId };
}
async function moveItemByFilename(filename, newStage) {
const meta = await getProjectMeta();
const data = await graphql(`
query($owner: String!, $number: Int!) {
user(login: $owner) {
projectV2(number: $number) {
items(first: 100) {
nodes {
id
content {
... on Issue { title }
}
}
}
}
}
}
`, { owner: GH.OWNER, number: GH.PROJECT_NUMBER });
const items = data.user.projectV2.items.nodes;
const match = items.find(item => item.content && item.content.title === filename);
if (!match) {
throw new Error(`No se encontró la tarjeta "${filename}" en GitHub Projects`);
}
await moveItemToStage(match.id, newStage, meta);
}
/**
* Lógica mejorada para encontrar la columna correcta
*/
async function moveItemToStage(itemId, stage, meta) {
// 1. Normalización total
// Quitamos números iniciales, guiones, espacios y pasamos a minúsculas
const normalize = (str) => str.toLowerCase().replace(/[^a-z]/g, "").trim();
const cleanStage = normalize(stage);
if (config.VERBOSE) console.log(`DEBUG: Intentando mover a stage: "${stage}" (Normalizado: "${cleanStage}")`);
// 2. Buscamos la opción en el mapa de GitHub
const optionEntry = Object.entries(meta.options).find(([name]) => {
const normName = normalize(name);
return normName === cleanStage;
});
if (!optionEntry) {
const available = Object.keys(meta.options).map(normalize).join(", ");
throw new Error(`No hubo coincidencia para "${cleanStage}". Columnas en GitHub: ${available}`);
}
const [originalName, optionId] = optionEntry;
if (config.VERBOSE) console.log(`🎯 Coincidencia encontrada: "${originalName}" (ID: ${optionId})`);
try {
await graphql(`
mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
updateProjectV2ItemFieldValue(input: {
projectId: $projectId
itemId: $itemId
fieldId: $fieldId
value: { singleSelectOptionId: $optionId }
}) {
projectV2Item { id }
}
}
`, {
projectId: meta.projectId,
itemId,
fieldId: meta.statusFieldId,
optionId,
});
if (config.VERBOSE) console.log(`✅ Tarjeta movida a "${originalName}" en GitHub.`);
} catch (error) {
throw new Error(`Error en mutación GraphQL al mover a "${originalName}": ${error.message}`);
}
}
module.exports = {
createIssueAndAddToProject,
moveItemByFilename,
};