Enhance download options and improve git error handling (#100)

* Fix download dialog to show gitignored paths with opt-in selection

- Add getIgnoredPathsList API to detect gitignored files from git root
- Fix git check-ignore to run from proper git root directory
- Add ignored paths checkboxes in download dialog for opt-in inclusion
- Support includeGit and includePaths options in download endpoints
- Fix dialog button event handling to prevent page reload

* Add clone timeout and improve git error handling

* Refactor path extraction in download-zip endpoint
This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-31 09:39:45 -05:00
1 parent a02f7a2e98
commit eccd49e877
12 files changed
+542 -121

No files matched your search

+66 -42
View File
@@ -8,52 +8,76 @@ import { getErrorMessage, getStatusCode } from '../utils/error-utils'
export function createFileRoutes() {
const app = new Hono()
app.get('download-zip', async(c) => {
return c.json({ error: 'No path provided' }, 400)
})
app.get('*', async (c) => {
const path = c.req.path
app.get(':path{.+}/download-zip', async (c) => {
const userPath = c.req.param('path')
if (path.endsWith('/download-zip')) {
const match = path.match(/\/api\/files\/(.+?)\/download-zip$/)
const userPath = match?.[1]
if (!userPath) {
return c.json({ error: 'No path provided' }, 400)
if (!userPath) {
return c.json({ error: 'No path provided' }, 400)
}
try {
logger.info(`Starting ZIP archive creation for ${userPath}`)
const includeGit = c.req.query('includeGit') === 'true'
const includePathsParam = c.req.query('includePaths')
const includePaths = includePathsParam ? includePathsParam.split(',').map((p: string) => p.trim()) : undefined
const options: import('../services/archive').ArchiveOptions = {
includeGit,
includePaths
}
const archivePath = await archiveService.createDirectoryArchive(userPath, undefined, options)
const archiveSize = await archiveService.getArchiveSize(archivePath)
const archiveStream = archiveService.getArchiveStream(archivePath)
const dirName = userPath.split('/').pop() || 'download'
logger.info(`ZIP archive created: ${archivePath} (${archiveSize} bytes)`)
archiveStream.on('end', () => {
archiveService.deleteArchive(archivePath)
})
archiveStream.on('error', () => {
archiveService.deleteArchive(archivePath)
})
return new Response(archiveStream as unknown as ReadableStream, {
status: 200,
headers: {
'Content-Type': 'application/zip',
'Content-Disposition': `attachment; filename="${dirName}.zip"`,
'Content-Length': archiveSize.toString(),
},
})
} catch (error: unknown) {
logger.error('Failed to create directory archive:', error)
return c.json({ error: getErrorMessage(error) || 'Failed to create archive' }, getStatusCode(error) as ContentfulStatusCode)
}
}
if (path.endsWith('/ignored-paths')) {
const userPath = path.replace(/\/api\/files\/(.+?)\/ignored-paths$/, '$1')
if (!userPath || userPath === '/ignored-paths') {
return c.json({ error: 'No path provided' }, 400)
}
try {
const ignoredPaths = await archiveService.getIgnoredPathsList(userPath)
return c.json({ ignoredPaths })
} catch (error: unknown) {
logger.error('Failed to get ignored paths:', error)
return c.json({ error: getErrorMessage(error) || 'Failed to get ignored paths' }, getStatusCode(error) as ContentfulStatusCode)
}
}
try {
logger.info(`Starting ZIP archive creation for ${userPath}`)
const archivePath = await archiveService.createDirectoryArchive(userPath)
const archiveSize = await archiveService.getArchiveSize(archivePath)
const archiveStream = archiveService.getArchiveStream(archivePath)
const dirName = userPath.split('/').pop() || 'download'
logger.info(`ZIP archive created: ${archivePath} (${archiveSize} bytes)`)
archiveStream.on('end', () => {
archiveService.deleteArchive(archivePath)
})
archiveStream.on('error', () => {
archiveService.deleteArchive(archivePath)
})
return new Response(archiveStream as unknown as ReadableStream, {
status: 200,
headers: {
'Content-Type': 'application/zip',
'Content-Disposition': `attachment; filename="${dirName}.zip"`,
'Content-Length': archiveSize.toString(),
},
})
} catch (error: unknown) {
logger.error('Failed to create directory archive:', error)
return c.json({ error: getErrorMessage(error) || 'Failed to create archive' }, getStatusCode(error) as ContentfulStatusCode)
}
})
app.get('/*', async (c) => {
try {
const userPath = c.req.path.replace(/^\/api\/files\//, '') || ''
const userPath = path.replace(/^\/api\/files\//, '') || ''
const download = c.req.query('download') === 'true'
const raw = c.req.query('raw') === 'true'
const startLineParam = c.req.query('startLine')
@@ -164,4 +188,4 @@ export function createFileRoutes() {
})
return app
}
}
+15 -6
View File
@@ -261,23 +261,32 @@ app.get('/', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const repoPath = path.resolve(getReposPath(), repo.localPath)
const repoName = path.basename(repo.localPath)
const includeGit = c.req.query('includeGit') === 'true'
const includePathsParam = c.req.query('includePaths')
const includePaths = includePathsParam ? includePathsParam.split(',').map(p => p.trim()) : undefined
const options: import('../services/archive').ArchiveOptions = {
includeGit,
includePaths
}
logger.info(`Starting archive creation for repo ${id}: ${repoPath}`)
const archivePath = await archiveService.createRepoArchive(repoPath)
const archivePath = await archiveService.createRepoArchive(repoPath, options)
const archiveSize = await archiveService.getArchiveSize(archivePath)
const archiveStream = archiveService.getArchiveStream(archivePath)
archiveStream.on('end', () => {
archiveService.deleteArchive(archivePath)
})
archiveStream.on('error', () => {
archiveService.deleteArchive(archivePath)
})
+181 -20
View File
@@ -5,16 +5,71 @@ import path from 'path'
import os from 'os'
import { logger } from '../utils/logger'
async function getIgnoredPaths(repoPath: string, paths: string[]): Promise<Set<string>> {
export interface ArchiveOptions {
includeGit?: boolean
includePaths?: string[]
}
async function findGitRoot(startPath: string): Promise<string | null> {
try {
const { spawn } = await import('child_process')
return new Promise((resolve) => {
const proc = spawn('git', ['rev-parse', '--show-toplevel'], {
cwd: startPath,
shell: false
})
let stdout = ''
let stderr = ''
proc.stdout?.on('data', (data: Buffer) => {
stdout += data.toString()
})
proc.stderr?.on('data', (data: Buffer) => {
stderr += data.toString()
})
proc.on('close', (code) => {
if (code === 0 && stdout.trim()) {
resolve(stdout.trim())
} else {
logger.debug(`Not a git repository: ${startPath}`, { stderr: stderr.trim() })
resolve(null)
}
})
proc.on('error', (err) => {
logger.debug(`Failed to find git root: ${err.message}`)
resolve(null)
})
})
} catch {
return null
}
}
async function getIgnoredPaths(gitRoot: string, targetPath: string, paths: string[]): Promise<Set<string>> {
if (paths.length === 0) return new Set()
try {
const { spawn } = await import('child_process')
const targetRelativeToRoot = path.relative(gitRoot, targetPath)
console.log('[getIgnoredPaths] gitRoot:', gitRoot, 'targetPath:', targetPath, 'targetRelativeToRoot:', targetRelativeToRoot)
const relativePaths = paths.map(p => {
const relativeToTarget = p
return targetRelativeToRoot ? path.join(targetRelativeToRoot, relativeToTarget) : relativeToTarget
})
console.log('[getIgnoredPaths] First 5 relativePaths:', relativePaths.slice(0, 5))
return new Promise((resolve) => {
const ignored = new Set<string>()
const proc = spawn('git', ['check-ignore', '--stdin'], {
cwd: repoPath,
cwd: gitRoot,
shell: false
})
@@ -24,29 +79,45 @@ async function getIgnoredPaths(repoPath: string, paths: string[]): Promise<Set<s
stdout += data.toString()
})
proc.stdin?.write(paths.join('\n'))
proc.stdin?.write(relativePaths.join('\n'))
proc.stdin?.end()
proc.on('close', () => {
const ignoredPaths = stdout.split('\n').filter(p => p.trim())
for (const p of ignoredPaths) {
ignored.add(p)
proc.on('close', (code) => {
console.log('[getIgnoredPaths] git check-ignore exited with code:', code)
const ignoredFullPaths = stdout.split('\n').filter(p => p.trim())
console.log('[getIgnoredPaths] Raw ignored count:', ignoredFullPaths.length, 'first 5:', ignoredFullPaths.slice(0, 5))
const targetRelativeToRoot = path.relative(gitRoot, targetPath)
for (const fullPath of ignoredFullPaths) {
let relativePath = fullPath
if (targetRelativeToRoot && fullPath.startsWith(targetRelativeToRoot + '/')) {
relativePath = fullPath.slice(targetRelativeToRoot.length + 1)
} else if (targetRelativeToRoot && fullPath === targetRelativeToRoot) {
relativePath = ''
}
if (relativePath) {
ignored.add(relativePath)
}
}
console.log('[getIgnoredPaths] Final ignored set size:', ignored.size)
resolve(ignored)
})
proc.on('error', () => {
proc.on('error', (err) => {
logger.debug(`git check-ignore error: ${err.message}`)
resolve(new Set())
})
})
} catch {
} catch (err) {
logger.debug(`getIgnoredPaths error: ${err}`)
return new Set()
}
}
async function collectFiles(
repoPath: string,
relativePath: string = ''
relativePath: string = '',
options?: ArchiveOptions
): Promise<string[]> {
const fullPath = path.join(repoPath, relativePath)
const entries = await readdir(fullPath, { withFileTypes: true })
@@ -55,11 +126,11 @@ async function collectFiles(
for (const entry of entries) {
const entryRelPath = relativePath ? path.join(relativePath, entry.name) : entry.name
if (entry.name === '.git') continue
if (entry.name === '.git' && !options?.includeGit) continue
if (entry.isDirectory()) {
files.push(entryRelPath + '/')
const subFiles = await collectFiles(repoPath, entryRelPath)
const subFiles = await collectFiles(repoPath, entryRelPath, options)
files.push(...subFiles)
} else {
files.push(entryRelPath)
@@ -69,13 +140,19 @@ async function collectFiles(
return files
}
async function filterIgnoredPaths(repoPath: string, allPaths: string[]): Promise<string[]> {
async function filterIgnoredPaths(targetPath: string, allPaths: string[], options?: ArchiveOptions): Promise<string[]> {
const gitRoot = await findGitRoot(targetPath)
if (!gitRoot) {
return allPaths
}
const batchSize = 1000
const ignoredSet = new Set<string>()
for (let i = 0; i < allPaths.length; i += batchSize) {
const batch = allPaths.slice(i, i + batchSize)
const ignored = await getIgnoredPaths(repoPath, batch)
const ignored = await getIgnoredPaths(gitRoot, targetPath, batch)
for (const p of ignored) {
ignoredSet.add(p)
if (p.endsWith('/')) {
@@ -88,11 +165,17 @@ async function filterIgnoredPaths(repoPath: string, allPaths: string[]): Promise
const filteredPaths: string[] = []
const ignoredDirs = new Set<string>()
const includePathsSet = new Set(options?.includePaths || [])
for (const p of allPaths) {
const isDir = p.endsWith('/')
const cleanPath = isDir ? p.slice(0, -1) : p
if (includePathsSet.has(cleanPath) || includePathsSet.has(p)) {
filteredPaths.push(p)
continue
}
let isUnderIgnoredDir = false
for (const ignoredDir of ignoredDirs) {
if (cleanPath.startsWith(ignoredDir + '/')) {
@@ -116,14 +199,14 @@ async function filterIgnoredPaths(repoPath: string, allPaths: string[]): Promise
return filteredPaths
}
export async function createRepoArchive(repoPath: string): Promise<string> {
export async function createRepoArchive(repoPath: string, options?: ArchiveOptions): Promise<string> {
const repoName = path.basename(repoPath)
const tempFile = path.join(os.tmpdir(), `${repoName}-${Date.now()}.zip`)
logger.info(`Creating archive for ${repoPath} at ${tempFile}`)
const allPaths = await collectFiles(repoPath)
const filteredPaths = await filterIgnoredPaths(repoPath, allPaths)
const allPaths = await collectFiles(repoPath, '', options)
const filteredPaths = await filterIgnoredPaths(repoPath, allPaths, options)
const output = createWriteStream(tempFile)
const archive = archiver('zip', { zlib: { level: 5 } })
@@ -153,15 +236,15 @@ export async function createRepoArchive(repoPath: string): Promise<string> {
})
}
export async function createDirectoryArchive(directoryPath: string, archiveName?: string): Promise<string> {
export async function createDirectoryArchive(directoryPath: string, archiveName?: string, options?: ArchiveOptions): Promise<string> {
const dirName = archiveName || path.basename(directoryPath)
const tempFile = path.join(os.tmpdir(), `${dirName}-${Date.now()}.zip`)
logger.info(`Creating archive for directory ${directoryPath} at ${tempFile}`)
const allPaths = await collectFiles(directoryPath)
const allPaths = await collectFiles(directoryPath, '', options)
const filteredPaths = await filterIgnoredPaths(directoryPath, allPaths)
const filteredPaths = await filterIgnoredPaths(directoryPath, allPaths, options)
const output = createWriteStream(tempFile)
const archive = archiver('zip', { zlib: { level: 5 } })
@@ -208,3 +291,81 @@ export async function getArchiveSize(filePath: string): Promise<number> {
const stats = await stat(filePath)
return stats.size
}
export async function getIgnoredPathsList(directoryPath: string): Promise<string[]> {
console.log('[getIgnoredPathsList] Starting for:', directoryPath)
const gitRoot = await findGitRoot(directoryPath)
console.log('[getIgnoredPathsList] Git root:', gitRoot)
if (!gitRoot) {
console.log('[getIgnoredPathsList] No git root found')
const hasGitDir = await collectFiles(directoryPath).then(
paths => paths.some(p => p.startsWith('.git/') || p === '.git')
).catch(() => false)
if (hasGitDir) {
console.log('[getIgnoredPathsList] Has .git dir, returning [.git/]')
return ['.git/']
}
console.log('[getIgnoredPathsList] No .git dir, returning []')
return []
}
const allPaths = await collectFiles(directoryPath)
console.log('[getIgnoredPathsList] Collected', allPaths.length, 'paths')
const ignoredSet = new Set<string>()
const batchSize = 1000
for (let i = 0; i < allPaths.length; i += batchSize) {
const batch = allPaths.slice(i, i + batchSize)
console.log('[getIgnoredPathsList] Checking batch', i, 'to', i + batch.length)
const ignored = await getIgnoredPaths(gitRoot, directoryPath, batch)
console.log('[getIgnoredPathsList] Batch ignored count:', ignored.size)
for (const p of ignored) {
ignoredSet.add(p)
if (p.endsWith('/')) {
ignoredSet.add(p.slice(0, -1))
} else {
ignoredSet.add(p + '/')
}
}
}
console.log('[getIgnoredPathsList] Total ignored set size:', ignoredSet.size)
const ignoredDirs: string[] = []
const processedDirs = new Set<string>()
for (const p of allPaths) {
const isDir = p.endsWith('/')
const cleanPath = isDir ? p.slice(0, -1) : p
if (ignoredSet.has(p) || ignoredSet.has(cleanPath)) {
let isUnderIgnoredDir = false
for (const ignoredDir of processedDirs) {
if (cleanPath.startsWith(ignoredDir + '/')) {
isUnderIgnoredDir = true
break
}
}
if (!isUnderIgnoredDir) {
const dirPath = isDir ? p : cleanPath + '/'
ignoredDirs.push(dirPath)
processedDirs.add(cleanPath)
}
}
}
const gitDirExists = await stat(path.join(directoryPath, '.git')).then(() => true).catch(() => false)
console.log('[getIgnoredPathsList] .git exists:', gitDirExists)
if (gitDirExists && !ignoredDirs.some(p => p.startsWith('.git'))) {
ignoredDirs.push('.git/')
}
ignoredDirs.sort()
console.log('[getIgnoredPathsList] Final result:', ignoredDirs)
return ignoredDirs
}
+53 -13
View File
@@ -6,8 +6,33 @@ import type { Repo, CreateRepoInput } from '../types/repo'
import { logger } from '../utils/logger'
import { getReposPath } from '@opencode-manager/shared/config/env'
import type { GitAuthService } from './git-auth'
import { isGitHubHttpsUrl } from '../utils/git-auth'
import path from 'path'
const GIT_CLONE_TIMEOUT = 300000
function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error {
const message = originalMessage.toLowerCase()
if (message.includes('authentication failed') || message.includes('could not authenticate') || message.includes('invalid credentials')) {
return new Error(`Authentication failed for ${repoUrl}. Please add your credentials in Settings > Git Credentials.`)
}
if (message.includes('repository not found') || message.includes('404')) {
return new Error(`Repository not found: ${repoUrl}. Check the URL and ensure you have access to it.`)
}
if (message.includes('permission denied') || (isGitHubHttpsUrl(repoUrl) && message.includes('fatal'))) {
return new Error(`Access denied to ${repoUrl}. Please add your credentials in Settings > Git Credentials and ensure you have proper access.`)
}
if (message.includes('timed out')) {
return new Error(`Clone timed out for ${repoUrl}. The repository might be too large or there could be network issues. Try again or verify the repository exists.`)
}
return error instanceof Error ? error : new Error(originalMessage)
}
interface ErrorWithMessage {
message: string
}
@@ -349,27 +374,37 @@ export async function cloneRepo(
}
try {
await executeCommand(['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
await executeCommand(['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`)
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = 'exists'
} catch {
localBranchExists = 'missing'
}
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (cloneError: unknown) {
throw enhanceCloneError(cloneError, normalizedRepoUrl, getErrorMessage(cloneError))
}
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = 'exists'
} catch {
localBranchExists = 'missing'
}
if (localBranchExists.trim() === 'missing') {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', '-b', branch])
} else {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw enhanceCloneError(error, normalizedRepoUrl, getErrorMessage(error))
}
}
} else {
if (baseRepoExists.trim() === 'exists') {
@@ -442,7 +477,7 @@ export async function cloneRepo(
? ['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName]
: ['git', 'clone', normalizedRepoUrl, worktreeDirName]
await executeCommand(cloneCmd, { cwd: getReposPath(), env })
await executeCommand(cloneCmd, { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
@@ -451,7 +486,12 @@ export async function cloneRepo(
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (cloneError: unknown) {
throw enhanceCloneError(cloneError, normalizedRepoUrl, getErrorMessage(cloneError))
}
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
@@ -466,7 +506,7 @@ export async function cloneRepo(
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw error
throw enhanceCloneError(error, normalizedRepoUrl, getErrorMessage(error))
}
}
}
+22 -3
View File
@@ -6,6 +6,7 @@ interface ExecuteCommandOptions {
silent?: boolean
env?: Record<string, string>
ignoreExitCode?: boolean
timeout?: number
}
export async function executeCommand(
@@ -45,6 +46,15 @@ export async function executeCommand(
let stdout = ''
let stderr = ''
let isResolved = false
const timeoutId = options.timeout ? setTimeout(() => {
if (!isResolved) {
isResolved = true
proc.kill('SIGKILL')
reject(new Error(`Command timed out after ${options.timeout}ms: ${args.join(' ')}`))
}
}, options.timeout) : undefined
proc.stdout?.on('data', (data: Buffer) => {
stdout += data.toString()
@@ -55,13 +65,22 @@ export async function executeCommand(
})
proc.on('error', (error: Error) => {
if (!options.silent) {
logger.error(`Command failed: ${args.join(' ')}`, error)
if (!isResolved) {
isResolved = true
if (timeoutId) clearTimeout(timeoutId)
if (!options.silent) {
logger.error(`Command failed: ${args.join(' ')}`, error)
}
reject(error)
}
reject(error)
})
proc.on('close', (code: number | null) => {
if (isResolved) return
isResolved = true
if (timeoutId) clearTimeout(timeoutId)
if (options.ignoreExitCode) {
resolve({ exitCode: code || 0, stdout, stderr })
} else if (code === 0) {