diff --git a/README.es.md b/README.es.md index 8dde37490..49adca90b 100644 --- a/README.es.md +++ b/README.es.md @@ -19,7 +19,7 @@ ## ✨ Características - **Documentación Instantánea**: Convierte cualquier repositorio de GitHub, GitLab o BitBucket en una wiki en segundos -- **Soporte para Repositorios Privados**: Accede de forma segura a repositorios privados con tokens de acceso personal +- **Soporte para Repositorios Privados**: Accede de forma segura a repositorios privados con tokens de acceso personal y soporte para configuraciones de dominio personalizado - **Análisis Inteligente**: Comprensión de la estructura y relaciones del código impulsada por IA - **Diagramas Hermosos**: Diagramas Mermaid automáticos para visualizar la arquitectura y el flujo de datos - **Navegación Sencilla**: Interfaz simple e intuitiva para explorar la wiki @@ -217,6 +217,11 @@ DeepWiki utiliza archivos de configuración JSON para gestionar varios aspectos - Contiene filtros de archivos para excluir ciertos archivos y directorios - Define límites de tamaño de repositorio y reglas de procesamiento +4. **`repository-providers.json`**: Configuración para coincidencia de proveedores de repositorio + - Define los proveedores de repositorio soportados (GitHub, GitLab, Bitbucket) + - Contiene patrones de URL para detección automática de proveedores + - Soporta coincidencia con comodines para despliegues de dominio personalizado + Por defecto, estos archivos se encuentran en el directorio `api/config/`. Puedes personalizar su ubicación usando la variable de entorno `DEEPWIKI_CONFIG_DIR`. ### Selección de Modelos Personalizados para Proveedores de Servicios diff --git a/README.fr.md b/README.fr.md index f75bd862e..170e8c871 100644 --- a/README.fr.md +++ b/README.fr.md @@ -20,7 +20,7 @@ ## ✨ Fonctionnalités - **Documentation instantanée** : Transforme un dépôt GitHub, GitLab ou Bitbucket en wiki en quelques secondes -- **Support des dépôts privés** : Accès sécurisé avec jetons d’accès personnels +- **Support des dépôts privés** : Accès sécurisé avec jetons d'accès personnels et support pour les configurations de domaine personnalisé - **Analyse intelligente** : Compréhension de la structure et des relations du code via l’IA - **Diagrammes élégants** : Diagrammes Mermaid automatiques pour visualiser l’architecture et les flux de données - **Navigation facile** : Interface simple et intuitive @@ -234,6 +234,11 @@ DeepWiki utilise des fichiers de configuration JSON pour gérer différents aspe - Contient des filtres de fichiers pour exclure certains fichiers et répertoires - Définit les limites de taille des dépôts et les règles de traitement +4. **`repository-providers.json`** : Configuration de correspondance des fournisseurs de dépôts + - Définit les fournisseurs de dépôts pris en charge (GitHub, GitLab, Bitbucket) + - Contient des modèles d'URL pour la détection automatique des fournisseurs + - Prend en charge la correspondance par caractères génériques pour les déploiements de domaine personnalisé + Par défaut, ces fichiers sont situés dans le répertoire `api/config/`. Vous pouvez personnaliser leur emplacement à l'aide de la variable d'environnement `DEEPWIKI_CONFIG_DIR`. ### Sélection de Modèles Personnalisés pour les Fournisseurs de Services diff --git a/README.ja.md b/README.ja.md index 1819c0f60..72ef4a6e8 100644 --- a/README.ja.md +++ b/README.ja.md @@ -19,7 +19,7 @@ ## ✨ 特徴 - **即時ドキュメント生成**: あらゆる GitHub、GitLab、または Bitbucket リポジトリを数秒で Wiki に変換 -- **プライベートリポジトリ対応**: 個人アクセストークンを使用してプライベートリポジトリに安全にアクセス +- **プライベートリポジトリ対応**: 個人アクセストークンを使用してプライベートリポジトリに安全にアクセス、カスタムドメイン設定をサポート - **スマート分析**: AI を活用したコード構造と関係の理解 - **美しい図表**: アーキテクチャとデータフローを視覚化する自動 Mermaid 図 - **簡単なナビゲーション**: Wiki を探索するためのシンプルで直感的なインターフェース @@ -203,6 +203,11 @@ DeepWikiはシステムの様々な側面を管理するためにJSON設定フ - 特定のファイルやディレクトリを除外するファイルフィルターを含む - リポジトリサイズ制限と処理ルールを定義 +4. **`repository-providers.json`**: リポジトリプロバイダーマッチングの設定 + - サポートされているリポジトリプロバイダー(GitHub、GitLab、Bitbucket)を定義 + - 自動プロバイダー検出のためのURLパターンを含む + - カスタムドメインデプロイメントのワイルドカードマッチングをサポート + デフォルトでは、これらのファイルは`api/config/`ディレクトリにあります。`DEEPWIKI_CONFIG_DIR`環境変数を使用して、その場所をカスタマイズできます。 ### Docker セットアップ diff --git a/README.kr.md b/README.kr.md index d22edef7c..c5fa8ad90 100644 --- a/README.kr.md +++ b/README.kr.md @@ -19,7 +19,7 @@ ## ✨ 주요 기능 - **즉시 문서화**: 어떤 GitHub, GitLab 또는 BitBucket 저장소든 몇 초 만에 위키로 변환 -- **비공개 저장소 지원**: 개인 액세스 토큰으로 비공개 저장소 안전하게 접근 +- **비공개 저장소 지원**: 개인 액세스 토큰으로 비공개 저장소 안전하게 접근, 사용자 정의 도메인 구성 지원 - **스마트 분석**: AI 기반 코드 구조 및 관계 이해 - **아름다운 다이어그램**: 아키텍처와 데이터 흐름을 시각화하는 자동 Mermaid 다이어그램 - **쉬운 탐색**: 간단하고 직관적인 인터페이스로 위키 탐색 가능 @@ -194,6 +194,11 @@ DeepWiki는 시스템의 다양한 측면을 관리하기 위해 JSON 설정 파 - 특정 파일 및 디렉토리를 제외하는 파일 필터 포함 - 저장소 크기 제한 및 처리 규칙 정의 +4. **`repository-providers.json`**: 저장소 제공자 매칭 설정 + - 지원되는 저장소 제공자(GitHub, GitLab, Bitbucket) 정의 + - 자동 제공자 감지를 위한 URL 패턴 포함 + - 사용자 정의 도메인 배포를 위한 와일드카드 매칭 지원 + 기본적으로 이러한 파일은 `api/config/` 디렉토리에 위치합니다. `DEEPWIKI_CONFIG_DIR` 환경 변수를 사용하여 위치를 사용자 정의할 수 있습니다. ### Docker 설정 diff --git a/README.md b/README.md index f32767de6..c59019351 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ ## ✨ Features - **Instant Documentation**: Turn any GitHub, GitLab or BitBucket repo into a wiki in seconds -- **Private Repository Support**: Securely access private repositories with personal access tokens +- **Private Repository Support**: Securely access private repositories with personal access tokens and support for custom domain configurations - **Smart Analysis**: AI-powered understanding of code structure and relationships - **Beautiful Diagrams**: Automatic Mermaid diagrams to visualize architecture and data flow - **Easy Navigation**: Simple, intuitive interface to explore the wiki @@ -233,6 +233,11 @@ DeepWiki uses JSON configuration files to manage various aspects of the system: - Contains file filters to exclude certain files and directories - Defines repository size limits and processing rules +4. **`repository-providers.json`**: Configuration for repository provider matching + - Defines supported repository providers (GitHub, GitLab, Bitbucket) + - Contains URL patterns for automatic provider detection + - Supports wildcard matching for custom domain deployments + By default, these files are located in the `api/config/` directory. You can customize their location using the `DEEPWIKI_CONFIG_DIR` environment variable. ### Custom Model Selection for Service Providers diff --git a/README.pt-br.md b/README.pt-br.md index f2f13b58b..84749ab4b 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -19,7 +19,7 @@ ## ✨ Recursos - **Documentação Instantânea**: Transforme qualquer repositório GitHub, GitLab ou BitBucket em uma wiki em segundos -- **Suporte a Repositórios Privados**: Acesse repositórios privados com segurança usando tokens de acesso pessoal +- **Suporte a Repositórios Privados**: Acesse repositórios privados com segurança usando tokens de acesso pessoal e suporte para configurações de domínio personalizado - **Análise Inteligente**: Compreensão da estrutura e relacionamentos do código com IA - **Diagramas Bonitos**: Diagramas Mermaid automáticos para visualizar arquitetura e fluxo de dados - **Navegação Fácil**: Interface simples e intuitiva para explorar a wiki @@ -219,6 +219,11 @@ O DeepWiki usa arquivos de configuração JSON para gerenciar vários aspectos d - Contém filtros de arquivos para excluir certos arquivos e diretórios - Define limites de tamanho de repositório e regras de processamento +4. **`repository-providers.json`**: Configuração para correspondência de provedores de repositório + - Define os provedores de repositório suportados (GitHub, GitLab, Bitbucket) + - Contém padrões de URL para detecção automática de provedores + - Suporta correspondência com curingas para implantações de domínio personalizado + Por padrão, esses arquivos estão localizados no diretório `api/config/`. Você pode personalizar sua localização usando a variável de ambiente `DEEPWIKI_CONFIG_DIR`. ### Seleção de Modelo Personalizado para Provedores de Serviço diff --git a/README.ru.md b/README.ru.md index f74a9d0a0..e6a0b4f94 100644 --- a/README.ru.md +++ b/README.ru.md @@ -19,7 +19,7 @@ ## ✨ Возможности - **Мгновенная документация**: Превращение любого репозитория в вики за считанные секунды -- **Поддержка приватных репозиториев**: Безопасный доступ с помощью персональных токенов +- **Поддержка приватных репозиториев**: Безопасный доступ с помощью персональных токенов и поддержка настройки пользовательских доменов - **Умный анализ**: Понимание структуры и взаимосвязей в коде с помощью ИИ - **Красивые диаграммы**: Автоматическая генерация диаграмм Mermaid для отображения архитектуры и потоков данных - **Простая навигация**: Интуитивный интерфейс для изучения вики @@ -221,6 +221,10 @@ DeepWiki использует JSON-файлы для настройки: 1. **`generator.json`** — конфигурация генерации текста и моделей 2. **`embedder.json`** — настройки эмбеддингов и ретривера 3. **`repo.json`** — правила обработки репозиториев +4. **`repository-providers.json`** — конфигурация сопоставления провайдеров репозиториев + - Определяет поддерживаемых провайдеров репозиториев (GitHub, GitLab, Bitbucket) + - Содержит шаблоны URL для автоматического определения провайдера + - Поддерживает сопоставление с подстановочными знаками для развертывания пользовательских доменов По умолчанию хранятся в `api/config/`, путь можно изменить через `DEEPWIKI_CONFIG_DIR`. diff --git a/README.vi.md b/README.vi.md index f5262135b..8500621c3 100644 --- a/README.vi.md +++ b/README.vi.md @@ -19,7 +19,7 @@ ## ✨ Tính năng - **Tạo Tài liệu tức thì**: Biến bất kỳ Repository GitHub, GitLab hoặc BitBucket nào thành wiki chỉ trong vài giây -- **Hỗ trợ Private Repository**: Truy cập Private Repository một cách an toàn với personal access tokens +- **Hỗ trợ Private Repository**: Truy cập Private Repository một cách an toàn với personal access tokens và hỗ trợ cấu hình tên miền tùy chỉnh - **Phân tích thông minh**: Hiểu cấu trúc và mối quan hệ của source codes nhờ AI - **Tự động tạo Sơ đồ**: Tự động tạo sơ đồ Mermaid để trực quan hóa kiến trúc và luồng dữ liệu - **Dễ dàng thao tác**:Giao diện wiki đơn giản, trực quan để khám phá @@ -291,6 +291,11 @@ DeepWiki sử dụng các tệp cấu hình JSON để quản lý các khía c - Chứa bộ lọc tệp để loại trừ một số tệp và thư mục nhất định - Xác định giới hạn kích thước repository và quy tắc xử lý +4. **`repository-providers.json`**: Cấu hình khớp nhà cung cấp repository + - Xác định các nhà cung cấp repository được hỗ trợ (GitHub, GitLab, Bitbucket) + - Chứa các mẫu URL để tự động phát hiện nhà cung cấp + - Hỗ trợ khớp ký tự đại diện cho triển khai tên miền tùy chỉnh + Mặc định, các tệp này nằm trong thư mục `api/config/`. Bạn có thể tùy chỉnh vị trí của chúng bằng biến môi trường `DEEPWIKI_CONFIG_DIR`. ### Lựa chọn mô hình tùy chỉnh cho nhà cung cấp dịch vụ diff --git a/README.zh-tw.md b/README.zh-tw.md index 08e415087..2dc21b8ed 100644 --- a/README.zh-tw.md +++ b/README.zh-tw.md @@ -19,7 +19,7 @@ ## ✨ 特點 - **即時文件**:幾秒鐘內將任何 GitHub、GitLab 或 BitBucket 儲存庫轉換為 Wiki -- **私人儲存庫支援**:使用個人存取權杖安全存取私人儲存庫 +- **私人儲存庫支援**:使用個人存取權杖安全存取私人儲存庫,支援自訂網域設定 - **智慧分析**:AI 驅動的程式碼結構和關係理解 - **精美圖表**:自動產生 Mermaid 圖表視覺化架構和資料流 - **簡易導覽**:簡單、直觀的介面探索 Wiki @@ -226,6 +226,11 @@ DeepWiki 使用 JSON 設定檔來管理系統的各個層面: - 包含排除特定檔案和目錄的檔案篩選器 - 定義儲存庫大小限制和處理規則 +4. **`repository-providers.json`**:儲存庫提供商匹配設定 + - 定義支援的儲存庫提供商(GitHub、GitLab、Bitbucket) + - 包含用於自動提供商檢測的 URL 模式 + - 支援自訂網域部署的萬用字元匹配 + 預設情況下,這些檔案位於 `api/config/` 目錄中。您可以使用 `DEEPWIKI_CONFIG_DIR` 環境變數自訂它們的位置。 ### 為服務提供商設計的自訂模型選擇 diff --git a/README.zh.md b/README.zh.md index e05ce05cf..fa08f1a9d 100644 --- a/README.zh.md +++ b/README.zh.md @@ -19,7 +19,7 @@ ## ✨ 特点 - **即时文档**:几秒钟内将任何GitHub、GitLab或BitBucket仓库转换为Wiki -- **私有仓库支持**:使用个人访问令牌安全访问私有仓库 +- **私有仓库支持**:使用个人访问令牌安全访问私有仓库,支持自定义域名配置 - **智能分析**:AI驱动的代码结构和关系理解 - **精美图表**:自动生成Mermaid图表可视化架构和数据流 - **简易导航**:简单、直观的界面探索Wiki @@ -347,6 +347,11 @@ DeepWiki使用JSON配置文件管理系统的各个方面: - 包含排除特定文件和目录的文件过滤器 - 定义仓库大小限制和处理规则 +4. **`repository-providers.json`**:仓库提供商匹配配置 + - 定义支持的仓库提供商(GitHub、GitLab、Bitbucket) + - 包含用于自动提供商检测的URL模式 + - 支持自定义域名部署的通配符匹配 + 默认情况下,这些文件位于`api/config/`目录中。您可以使用`DEEPWIKI_CONFIG_DIR`环境变量自定义它们的位置。 ### 面向服务提供商的自定义模型选择 diff --git a/src/app/[owner]/[repo]/page.tsx b/src/app/[owner]/[repo]/page.tsx index 80e403b8f..953049076 100644 --- a/src/app/[owner]/[repo]/page.tsx +++ b/src/app/[owner]/[repo]/page.tsx @@ -9,7 +9,7 @@ import WikiTreeView from '@/components/WikiTreeView'; import { useLanguage } from '@/contexts/LanguageContext'; import { RepoInfo } from '@/types/repoinfo'; import getRepoUrl from '@/utils/getRepoUrl'; -import { extractUrlDomain, extractUrlPath } from '@/utils/urlDecoder'; +import { extractUrlDomain, extractUrlPath, detectRepositoryType } from '@/utils/urlDecoder'; import Link from 'next/link'; import { useParams, useSearchParams } from 'next/navigation'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -192,13 +192,9 @@ export default function RepoWikiPage() { const isCustomModelParam = searchParams.get('is_custom_model') === 'true'; const customModelParam = searchParams.get('custom_model') || ''; const language = searchParams.get('language') || 'en'; - const repoType = repoUrl?.includes('bitbucket.org') - ? 'bitbucket' - : repoUrl?.includes('gitlab.com') - ? 'gitlab' - : repoUrl?.includes('github.com') - ? 'github' - : searchParams.get('type') || 'github'; + const repoType = repoUrl + ? detectRepositoryType(repoUrl) + : searchParams.get('type') || 'github'; // Import language context for translations const { messages } = useLanguage(); @@ -287,16 +283,15 @@ export default function RepoWikiPage() { } try { - const url = new URL(repoUrl); - const hostname = url.hostname; + const detectedType = detectRepositoryType(repoUrl); - if (hostname === 'github.com' || hostname.includes('github')) { + if (detectedType === 'github') { // GitHub URL format: https://github.com/owner/repo/blob/branch/path return `${repoUrl}/blob/${defaultBranch}/${filePath}`; - } else if (hostname === 'gitlab.com' || hostname.includes('gitlab')) { + } else if (detectedType === 'gitlab') { // GitLab URL format: https://gitlab.com/owner/repo/-/blob/branch/path return `${repoUrl}/-/blob/${defaultBranch}/${filePath}`; - } else if (hostname === 'bitbucket.org' || hostname.includes('bitbucket')) { + } else if (detectedType === 'bitbucket') { // Bitbucket URL format: https://bitbucket.org/owner/repo/src/branch/path return `${repoUrl}/src/${defaultBranch}/${filePath}`; } diff --git a/src/app/page.tsx b/src/app/page.tsx index 9e05a2ef9..a8491d817 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -8,7 +8,7 @@ import ThemeToggle from '@/components/theme-toggle'; import Mermaid from '../components/Mermaid'; import ConfigurationModal from '@/components/ConfigurationModal'; import ProcessedProjects from '@/components/ProcessedProjects'; -import { extractUrlPath, extractUrlDomain } from '@/utils/urlDecoder'; +import { extractUrlPath, detectRepositoryType } from '@/utils/urlDecoder'; import { useProcessedProjects } from '@/hooks/useProcessedProjects'; import { useLanguage } from '@/contexts/LanguageContext'; @@ -204,17 +204,8 @@ export default function Home() { owner = 'local'; } else if (customGitRegex.test(input)) { - // Detect repository type based on domain - const domain = extractUrlDomain(input); - if (domain?.includes('github.com')) { - type = 'github'; - } else if (domain?.includes('gitlab.com') || domain?.includes('gitlab.')) { - type = 'gitlab'; - } else if (domain?.includes('bitbucket.org') || domain?.includes('bitbucket.')) { - type = 'bitbucket'; - } else { - type = 'web'; // fallback for other git hosting services - } + // Detect repository type using configurable detector + type = detectRepositoryType(input); fullPath = extractUrlPath(input)?.replace(/\.git$/, ''); const parts = fullPath?.split('/') ?? []; diff --git a/src/config/repository-providers.json b/src/config/repository-providers.json new file mode 100644 index 000000000..46a4e5bfd --- /dev/null +++ b/src/config/repository-providers.json @@ -0,0 +1,30 @@ +{ + "providers": [ + { + "type": "github", + "name": "GitHub", + "patterns": [ + "*github.com*" + ], + "description": "GitHub.com public and enterprise instances" + }, + { + "type": "gitlab", + "name": "GitLab", + "patterns": [ + "*gitlab.*" + ], + "description": "GitLab. and self-hosted instances" + }, + { + "type": "bitbucket", + "name": "Bitbucket", + "patterns": [ + "*bitbucket.*" + ], + "description": "Bitbucket cloud and server instances" + } + ], + "fallback": "github", + "comment": "Configuration instructions: patterns supports wildcard matching, where * represents any character. Simply add your private domain deployment domain name to the corresponding patterns array." +} \ No newline at end of file diff --git a/src/utils/urlDecoder.tsx b/src/utils/urlDecoder.tsx index 8423e758b..0938619c9 100644 --- a/src/utils/urlDecoder.tsx +++ b/src/utils/urlDecoder.tsx @@ -1,3 +1,5 @@ +import repositoryConfig from '../config/repository-providers.json'; + export function extractUrlDomain(input: string): string | null { try { const normalizedInput = input.startsWith('http') ? input : `https://${input}`; @@ -16,4 +18,51 @@ export function extractUrlPath(input: string): string | null { } catch { return null; // Not a valid URL } +} + +export function extractUrlHostname(input: string): string | null { + try { + const normalizedInput = input.startsWith('http') ? input : `https://${input}`; + const url = new URL(normalizedInput); + return url.hostname; + } catch { + return null; + } +} + +/** + * Detect repository type from URL using simple pattern matching + * @param url Repository URL + * @returns Repository type (github/gitlab/bitbucket/web) + */ +export function detectRepositoryType(url: string): string { + const hostname = extractUrlHostname(url); + if (!hostname) return 'web'; + + const config = repositoryConfig as { providers: Array<{ type: string; patterns: string[] }>; fallback: string }; + + // Simple pattern matching - check if hostname contains any pattern + for (const provider of config.providers) { + for (const pattern of provider.patterns) { + if (pattern.includes('*')) { + // Handle wildcards by converting to simple contains/starts/ends checks + const cleanPattern = pattern.replace(/\*/g, ''); + if (pattern.startsWith('*') && pattern.endsWith('*')) { + // *pattern* - contains + if (hostname.includes(cleanPattern)) return provider.type; + } else if (pattern.startsWith('*')) { + // *pattern - ends with + if (hostname.endsWith(cleanPattern)) return provider.type; + } else if (pattern.endsWith('*')) { + // pattern* - starts with + if (hostname.startsWith(cleanPattern)) return provider.type; + } + } else { + // Exact match + if (hostname === pattern) return provider.type; + } + } + } + + return config.fallback; } \ No newline at end of file