Spaces:
Running
Running
File size: 15,543 Bytes
daff0c0 |
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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
document.getElementById('repoForm').addEventListener('submit', async function (e) {
e.preventDefault();
const repoUrl = document.getElementById('repoUrl').value;
const ref = document.getElementById('ref').value || '';
const path = document.getElementById('path').value || '';
const accessToken = document.getElementById('accessToken').value;
const outputText = document.getElementById('outputText');
outputText.value = '';
try {
const { owner, repo, refFromUrl, pathFromUrl } = parseRepoUrl(repoUrl);
const finalRef = ref || refFromUrl;
const finalPath = path || pathFromUrl;
const sha = await fetchRepoSha(owner, repo, finalRef, finalPath, accessToken);
const tree = await fetchRepoTree(owner, repo, sha, accessToken);
displayDirectoryStructure(tree);
document.getElementById('generateTextButton').style.display = 'flex';
} catch (error) {
outputText.value = `Error fetching repository contents: ${error.message}\n\nPlease ensure:\n1. The repository URL is correct and accessible.\n2. You have the necessary permissions to access the repository.\n3. If it's a private repository, you've provided a valid access token.\n4. The specified branch/tag and path (if any) exist in the repository.`;
}
});
document.getElementById('generateTextButton').addEventListener('click', async function () {
const accessToken = document.getElementById('accessToken').value;
const outputText = document.getElementById('outputText');
outputText.value = '';
try {
const selectedFiles = getSelectedFiles();
if (selectedFiles.length === 0) {
throw new Error('No files selected');
}
const fileContents = await fetchFileContents(selectedFiles, accessToken);
const formattedText = formatRepoContents(fileContents);
outputText.value = formattedText;
document.getElementById('copyButton').style.display = 'flex';
document.getElementById('downloadButton').style.display = 'flex';
} catch (error) {
outputText.value = `Error generating text file: ${error.message}\n\nPlease ensure:\n1. You have selected at least one file from the directory structure.\n2. Your access token (if provided) is valid and has the necessary permissions.\n3. You have a stable internet connection.\n4. The GitHub API is accessible and functioning normally.`;
}
});
document.getElementById('copyButton').addEventListener('click', function () {
const outputText = document.getElementById('outputText');
outputText.select();
navigator.clipboard.writeText(outputText.value).then(() => {
console.log('Text copied to clipboard');
}).catch(err => {
console.error('Failed to copy text: ', err);
});
});
document.getElementById('downloadButton').addEventListener('click', function () {
const outputText = document.getElementById('outputText').value;
if (!outputText.trim()) {
document.getElementById('outputText').value = 'Error: No content to download. Please generate the text file first.';
return;
}
const blob = new Blob([outputText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'file.txt';
a.click();
URL.revokeObjectURL(url);
});
function parseRepoUrl(url) {
url = url.replace(/\/$/, '');
const urlPattern = /^https:\/\/github\.com\/([^\/]+)\/([^\/]+)(\/tree\/([^\/]+)(\/(.+))?)?$/;
const match = url.match(urlPattern);
if (!match) {
throw new Error('Invalid GitHub repository URL. Please ensure the URL is in the correct format: https://github.com/owner/repo or https://github.com/owner/repo/tree/branch/path');
}
return {
owner: match[1],
repo: match[2],
refFromUrl: match[4],
pathFromUrl: match[6]
};
}
async function fetchRepoSha(owner, repo, ref, path, token) {
const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path ? `${path}` : ''}${ref ? `?ref=${ref}` : ''}`;
const headers = {
'Accept': 'application/vnd.github.object+json'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
if (response.status === 403 && response.headers.get('X-RateLimit-Remaining') === '0') {
throw new Error('GitHub API rate limit exceeded. Please try again later or provide a valid access token to increase your rate limit.');
}
if (response.status === 404) {
throw new Error(`Repository, branch, or path not found. Please check that the URL, branch/tag, and path are correct and accessible.`);
}
throw new Error(`Failed to fetch repository SHA. Status: ${response.status}. Please check your input and try again.`);
}
const data = await response.json();
return data.sha;
}
async function fetchRepoTree(owner, repo, sha, token) {
const url = `https://api.github.com/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`;
const headers = {
'Accept': 'application/vnd.github+json'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
if (response.status === 403 && response.headers.get('X-RateLimit-Remaining') === '0') {
throw new Error('GitHub API rate limit exceeded. Please try again later or provide a valid access token to increase your rate limit.');
}
throw new Error(`Failed to fetch repository tree. Status: ${response.status}. Please check your input and try again.`);
}
const data = await response.json();
return data.tree;
}
function displayDirectoryStructure(tree) {
tree = tree.filter(item => item.type === 'blob');
tree = sortContents(tree);
const container = document.getElementById('directoryStructure');
container.innerHTML = '';
const rootUl = document.createElement('ul');
container.appendChild(rootUl);
const directoryStructure = {};
tree.forEach(item => {
item.path = item.path.startsWith('/') ? item.path : '/' + item.path;
const pathParts = item.path.split('/');
let currentLevel = directoryStructure;
pathParts.forEach((part, index) => {
if (part === '') {
part = './';
}
if (!currentLevel[part]) {
currentLevel[part] = index === pathParts.length - 1 ? item : {};
}
currentLevel = currentLevel[part];
});
});
function createTreeNode(name, item, parentUl) {
const li = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
const commonExtensions = ['.js', '.py', '.java', '.cpp', '.html', '.css', '.ts', '.jsx', '.tsx'];
const fileName = name.toLowerCase();
const isCommonFile = commonExtensions.some(ext => fileName.endsWith(ext));
checkbox.checked = isCommonFile;
checkbox.className = 'mr-2';
if (typeof item === 'object' && (!item.type || typeof item.type !== 'string')) {
// Directory
checkbox.classList.add('directory-checkbox');
li.appendChild(checkbox);
// Add collapse/expand button
const collapseButton = document.createElement('button');
collapseButton.innerHTML = '<i data-lucide="chevron-down" class="w-4 h-4"></i>';
collapseButton.className = 'mr-1 focus:outline-none';
li.appendChild(collapseButton);
const folderIcon = document.createElement('i');
folderIcon.setAttribute('data-lucide', 'folder');
folderIcon.className = 'inline-block w-4 h-4 mr-1';
li.appendChild(folderIcon);
li.appendChild(document.createTextNode(name));
const ul = document.createElement('ul');
ul.className = 'ml-6 mt-2';
li.appendChild(ul);
for (const [childName, childItem] of Object.entries(item)) {
createTreeNode(childName, childItem, ul);
}
checkbox.addEventListener('change', function() {
const childCheckboxes = li.querySelectorAll('input[type="checkbox"]');
childCheckboxes.forEach(childBox => {
childBox.checked = this.checked;
childBox.indeterminate = false;
});
});
// Add collapse/expand functionality
collapseButton.addEventListener('click', function() {
ul.classList.toggle('hidden');
const icon = this.querySelector('[data-lucide]');
if (ul.classList.contains('hidden')) {
icon.setAttribute('data-lucide', 'chevron-right');
} else {
icon.setAttribute('data-lucide', 'chevron-down');
}
lucide.createIcons();
});
} else {
// File
checkbox.value = JSON.stringify({ url: item.url, path: item.path });
li.appendChild(checkbox);
const fileIcon = document.createElement('i');
fileIcon.setAttribute('data-lucide', 'file');
fileIcon.className = 'inline-block w-4 h-4 mr-1';
li.appendChild(fileIcon);
li.appendChild(document.createTextNode(name));
}
li.className = 'my-2';
parentUl.appendChild(li);
updateParentCheckbox(checkbox);
}
for (const [name, item] of Object.entries(directoryStructure)) {
createTreeNode(name, item, rootUl);
}
// Add event listener to container for checkbox changes
container.addEventListener('change', function(event) {
if (event.target.type === 'checkbox') {
updateParentCheckbox(event.target);
}
});
function updateParentCheckbox(checkbox) {
if (!checkbox) return;
const li = checkbox.closest('li');
if (!li) return;
if (!li.parentElement) return;
const parentLi = li.parentElement.closest('li');
if (!parentLi) return;
const parentCheckbox = parentLi.querySelector(':scope > input[type="checkbox"]');
const siblingCheckboxes = parentLi.querySelectorAll(':scope > ul > li > input[type="checkbox"]');
const checkedCount = Array.from(siblingCheckboxes).filter(cb => cb.checked).length;
const indeterminateCount = Array.from(siblingCheckboxes).filter(cb => cb.indeterminate).length;
if (indeterminateCount !== 0) {
parentCheckbox.checked = false;
parentCheckbox.indeterminate = true;
} else if (checkedCount === 0) {
parentCheckbox.checked = false;
parentCheckbox.indeterminate = false;
} else if (checkedCount === siblingCheckboxes.length) {
parentCheckbox.checked = true;
parentCheckbox.indeterminate = false;
} else {
parentCheckbox.checked = false;
parentCheckbox.indeterminate = true;
}
// Recursively update parent checkboxes
updateParentCheckbox(parentCheckbox);
}
lucide.createIcons();
}
function getSelectedFiles() {
const checkboxes = document.querySelectorAll('#directoryStructure input[type="checkbox"]:checked:not(.directory-checkbox)');
return Array.from(checkboxes).map(checkbox => JSON.parse(checkbox.value));
}
async function fetchFileContents(files, token) {
const headers = {
'Accept': 'application/vnd.github.v3.raw'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const contents = await Promise.all(files.map(async file => {
const response = await fetch(file.url, { headers });
if (!response.ok) {
if (response.status === 403 && response.headers.get('X-RateLimit-Remaining') === '0') {
throw new Error(`GitHub API rate limit exceeded while fetching ${file.path}. Please try again later or provide a valid access token to increase your rate limit.`);
}
throw new Error(`Failed to fetch content for ${file.path}. Status: ${response.status}. Please check your permissions and try again.`);
}
const text = await response.text();
return { url: file.url, path: file.path, text };
}));
return contents;
}
function formatRepoContents(contents) {
let text = '';
let index = '';
contents = sortContents(contents);
// Create a directory tree structure
const tree = {};
contents.forEach(item => {
const parts = item.path.split('/');
let currentLevel = tree;
parts.forEach((part, i) => {
if (!currentLevel[part]) {
currentLevel[part] = i === parts.length - 1 ? null : {};
}
currentLevel = currentLevel[part];
});
});
// Function to recursively build the index
function buildIndex(node, prefix = '') {
let result = '';
const entries = Object.entries(node);
entries.forEach(([name, subNode], index) => {
const isLastItem = index === entries.length - 1;
const linePrefix = isLastItem ? 'βββ ' : 'βββ ';
const childPrefix = isLastItem ? ' ' : 'β ';
if (name === '') {
name = './';
}
result += `${prefix}${linePrefix}${name}\n`;
if (subNode) {
result += buildIndex(subNode, `${prefix}${childPrefix}`);
}
});
return result;
}
index = buildIndex(tree);
contents.forEach((item) => {
text += `\n\n---\nFile: ${item.path}\n---\n\n${item.text}\n`;
});
return `Directory Structure:\n\n${index}\n${text}`;
}
function sortContents(contents) {
contents.sort((a, b) => {
const aPath = a.path.split('/');
const bPath = b.path.split('/');
const minLength = Math.min(aPath.length, bPath.length);
for (let i = 0; i < minLength; i++) {
if (aPath[i] !== bPath[i]) {
if (i === aPath.length - 1 && i < bPath.length - 1) return 1; // a is a directory, b is a file or subdirectory
if (i === bPath.length - 1 && i < aPath.length - 1) return -1; // b is a directory, a is a file or subdirectory
return aPath[i].localeCompare(bPath[i]);
}
}
return aPath.length - bPath.length;
});
return contents;
}
document.addEventListener('DOMContentLoaded', function() {
lucide.createIcons();
// Add event listener for the showMoreInfo button
const showMoreInfoButton = document.getElementById('showMoreInfo');
const tokenInfo = document.getElementById('tokenInfo');
showMoreInfoButton.addEventListener('click', function() {
tokenInfo.classList.toggle('hidden');
// Change the icon based on the visibility state
const icon = this.querySelector('[data-lucide]');
if (icon) {
if (tokenInfo.classList.contains('hidden')) {
icon.setAttribute('data-lucide', 'info');
} else {
icon.setAttribute('data-lucide', 'x');
}
lucide.createIcons();
}
});
}); |