-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathutils.ts
More file actions
259 lines (223 loc) · 7.88 KB
/
utils.ts
File metadata and controls
259 lines (223 loc) · 7.88 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
258
259
import { S3Settings } from './settings';
import settings from '../settings';
import * as mime from 'mime-types';
import * as path from 'path';
import * as crypto from 'crypto';
import * as fs from 'fs';
import S3 from 'aws-sdk/clients/s3';
import { GitlabHelper } from './gitlabHelper';
export const sleep = (milliseconds: number) => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};
export const readProjectsFromCsv = (
filePath: string,
idColumn: number = 0,
gitlabPathColumn: number = 1,
githubPathColumn: number = 2
): Map<number, [string, string]> => {
try {
if (!fs.existsSync(filePath)) {
throw new Error(`CSV file not found: ${filePath}`);
}
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split(/\r?\n/);
const projectMap = new Map<number, [string, string]>();
let headerSkipped = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (!line || line.startsWith('#')) {
continue;
}
const values = line.split(',').map(v => v.trim());
const maxColumn = Math.max(idColumn, gitlabPathColumn, githubPathColumn);
if (maxColumn >= values.length) {
console.warn(`Warning: Line ${i + 1} has only ${values.length} column(s), skipping (need column ${maxColumn})`);
if (!headerSkipped) {
headerSkipped = true;
}
continue;
}
const idStr = values[idColumn];
const gitlabPath = values[gitlabPathColumn];
const githubPath = values[githubPathColumn];
if (!headerSkipped) {
const num = parseInt(idStr, 10);
if (isNaN(num) || idStr.toLowerCase().includes('id') || idStr.toLowerCase().includes('project')) {
console.log(`Skipping CSV header row: "${line}"`);
headerSkipped = true;
continue;
}
headerSkipped = true;
}
if (!idStr || !gitlabPath || !githubPath) {
console.warn(`Warning: Line ${i + 1} has empty values, skipping`);
continue;
}
const projectId = parseInt(idStr, 10);
if (isNaN(projectId)) {
console.warn(`Warning: Line ${i + 1}: Invalid project ID "${idStr}", skipping`);
continue;
}
projectMap.set(projectId, [gitlabPath, githubPath]);
}
if (projectMap.size === 0) {
throw new Error(`No valid project mappings found in CSV file: ${filePath}`);
}
console.log(`✓ Loaded ${projectMap.size} project mappings from CSV`);
return projectMap;
} catch (err) {
console.error(`Error reading project mapping CSV file: ${err.message}`);
throw err;
}
};
// Creates new attachments and replaces old links
export const migrateAttachments = async (
body: string,
githubRepoId: number | undefined,
s3: S3Settings | undefined,
gitlabHelper: GitlabHelper
) => {
const regexp = /(!?)\[([^\]]+)\]\((\/uploads[^)]+)\)/g;
// Maps link offset to a new name in S3
const offsetToAttachment: {
[key: number]: string;
} = {};
// Find all local links
const matches = body.matchAll(regexp);
for (const match of matches) {
const prefix = match[1] || '';
const name = match[2];
const url = match[3];
if (s3 && s3.bucket) {
const basename = path.basename(url);
const mimeType = mime.lookup(basename);
const attachmentBuffer = await gitlabHelper.getAttachment(url);
if (!attachmentBuffer) {
continue;
}
// // Generate file name for S3 bucket from URL
const hash = crypto.createHash('sha256');
hash.update(url);
const newFileName = hash.digest('hex') + '/' + basename;
const relativePath = githubRepoId
? `${githubRepoId}/${newFileName}`
: newFileName;
// Doesn't seem like it is easy to upload an issue to github, so upload to S3
//https://stackoverflow.com/questions/41581151/how-to-upload-an-image-to-use-in-issue-comments-via-github-api
// Attempt to fix issue #140
//const s3url = `https://${s3.bucket}.s3.amazonaws.com/${relativePath}`;
let hostname = `${s3.bucket}.s3.amazonaws.com`;
if (s3.region) {
hostname = `s3.${s3.region}.amazonaws.com/${s3.bucket}`;
}
const s3url = `https://${hostname}/${relativePath}`;
const s3bucket = new S3();
s3bucket.createBucket(() => {
const params: S3.PutObjectRequest = {
Key: relativePath,
Body: attachmentBuffer,
ContentType: mimeType === false ? undefined : mimeType,
Bucket: s3.bucket,
};
s3bucket.upload(params, function (err, data) {
console.log(`\tUploading ${basename} to ${s3url}... `);
if (err) {
console.log('ERROR: ', err);
} else {
console.log(`\t...Done uploading`);
}
});
});
// Add the new URL to the map
offsetToAttachment[
match.index as number
] = `${prefix}[${name}](${s3url})`;
} else {
// Not using S3: default to old URL, adding absolute path
const host = gitlabHelper.host.endsWith('/')
? gitlabHelper.host
: gitlabHelper.host + '/';
const attachmentUrl = host + gitlabHelper.projectPath + url;
offsetToAttachment[
match.index as number
] = `${prefix}[${name}](${attachmentUrl})`;
}
}
return body.replace(
regexp,
({}, {}, {}, {}, offset, {}) => offsetToAttachment[offset]
);
};
export const organizationUsersString = (users: string[], prefix: string): string => {
let organizationUsers = [];
for (let assignee of users) {
let githubUser = settings.usermap[assignee as string];
if (githubUser) {
githubUser = '@' + githubUser;
} else {
githubUser = assignee as string;
}
organizationUsers.push(githubUser);
}
if (organizationUsers.length > 0) {
return `\n\n**${prefix}:** ` + organizationUsers.join(', ');
}
return '';
}
export interface GitLabMetadata {
timeEstimate?: string;
timeSpent?: string;
weight?: number;
dueDate?: string;
healthStatus?: string;
}
const WEIGHT_LABEL_COLOR = 'D4C5F9'; // Light purple
/**
* Extracts GitLab-specific metadata from an issue
*/
export function extractGitLabMetadata(issue: any): GitLabMetadata {
return {
timeEstimate: issue.time_stats?.human_time_estimate,
timeSpent: issue.time_stats?.human_total_time_spent,
weight: issue.weight,
dueDate: issue.due_date,
healthStatus: issue.health_status,
};
}
/**
* Formats GitLab metadata as a markdown section
* Returns empty string if no metadata exists
*/
export function formatGitLabMetadata(metadata: GitLabMetadata): string {
const hasAnyMetadata = metadata.timeEstimate || metadata.timeSpent || metadata.weight || metadata.dueDate || metadata.healthStatus;
if (!hasAnyMetadata) return '';
let result = '\n---\n**GitLab Metadata**\n\n';
if (metadata.timeEstimate) result += `- ⏱️ Time Estimate: ${metadata.timeEstimate}\n`;
if (metadata.timeSpent) result += `- ⏲️ Time Spent: ${metadata.timeSpent}\n`;
if (metadata.weight) result += `- ⚖️ Weight: ${metadata.weight}\n`;
if (metadata.dueDate) result += `- 📅 Due Date: ${metadata.dueDate}\n`;
if (metadata.healthStatus) result += `- 🏥 Health: ${metadata.healthStatus}\n`;
result += '---\n';
return result;
}
/**
* Ensures a weight label exists in the GitHub repository
* Silently ignores if label already exists
*/
export async function ensureWeightLabel(octokit: any, owner: string, repo: string, weight: number): Promise<void> {
try {
await octokit.rest.issues.createLabel({
owner,
repo,
name: `weight::${weight}`,
color: WEIGHT_LABEL_COLOR,
description: `GitLab issue weight: ${weight}`,
});
} catch (error) {
if ((error as any).status === 422) {
// Label already exists, this is expected
return;
}
console.warn(`Warning: Could not create label weight::${weight}:`, (error as any).message);
}
}