Skip to content

内存导入处理器

¥Memory Import Processor

内存导入处理器是一项功能,允许您通过使用从其他文件导入内容来模块化您的 GEMINI.md 文件@file.md句法。

¥The Memory Import Processor is a feature that allows you to modularize your GEMINI.md files by importing content from other files using the @file.md syntax.

概述

¥Overview

此功能可让您将大型 GEMINI.md 文件分解为更小、更易于管理的组件,这些组件可在不同的上下文中重复使用。导入处理器支持相对路径和绝对路径,并内置安全功能,可防止循环导入并确保文件访问安全。

¥This feature enables you to break down large GEMINI.md files into smaller, more manageable components that can be reused across different contexts. The import processor supports both relative and absolute paths, with built-in safety features to prevent circular imports and ensure file access security.

句法

¥Syntax

使用@符号后跟要导入的文件的路径:

¥Use the @ symbol followed by the path to the file you want to import:

# Main GEMINI.md file

This is the main content.

@./components/instructions.md

More content here.

@./shared/configuration.md

支持的路径格式

¥Supported Path Formats

相对路径

¥Relative Paths

  • @./file.md- 从同一目录导入

    ¥@./file.md - Import from the same directory

  • @../file.md- 从父目录导入

    ¥@../file.md - Import from parent directory

  • @./components/file.md- 从子目录导入

    ¥@./components/file.md - Import from subdirectory

绝对路径

¥Absolute Paths

  • @/absolute/path/to/file.md- 使用绝对路径导入

    ¥@/absolute/path/to/file.md - Import using absolute path

示例

¥Examples

基本导入

¥Basic Import

# My GEMINI.md

Welcome to my project!

@./getting-started.md

## Features

@./features/overview.md

嵌套导入

¥Nested Imports

导入的文件本身可以包含导入,从而创建嵌套结构:

¥The imported files can themselves contain imports, creating a nested structure:

# main.md

@./header.md
@./content.md
@./footer.md
# header.md

# Project Header

@./shared/title.md

安全功能

¥Safety Features

循环导入检测

¥Circular Import Detection

处理器自动检测并防止循环导入:

¥The processor automatically detects and prevents circular imports:

# file-a.md

@./file-b.md

# file-b.md

@./file-a.md <!-- This will be detected and prevented -->

文件访问安全

¥File Access Security

validateImportPath功能确保只允许从指定目录导入,防止访问允许范围之外的敏感文件。

¥The validateImportPath function ensures that imports are only allowed from specified directories, preventing access to sensitive files outside the allowed scope.

最大导入深度

¥Maximum Import Depth

为了防止无限递归,有一个可配置的最大导入深度(默认值:5 级)。

¥To prevent infinite recursion, there's a configurable maximum import depth (default: 5 levels).

错误处理

¥Error Handling

丢失文件

¥Missing Files

如果引用的文件不存在,导入将会失败,并在输出中显示错误注释。

¥If a referenced file doesn't exist, the import will fail gracefully with an error comment in the output.

文件访问错误

¥File Access Errors

权限问题或其他文件系统错误可以通过适当的错误消息得到妥善处理。

¥Permission issues or other file system errors are handled gracefully with appropriate error messages.

代码区域检测

¥Code Region Detection

导入处理器使用marked用于检测代码块和内联代码跨度的库,确保@这些区域内的导入将被正确忽略。这为嵌套代码块和复杂的 Markdown 结构提供了强大的处理能力。

¥The import processor uses the marked library to detect code blocks and inline code spans, ensuring that @ imports inside these regions are properly ignored. This provides robust handling of nested code blocks and complex Markdown structures.

导入树状结构

¥Import Tree Structure

处理器返回一个导入树,显示导入文件的层次结构,类似于 Claude 的/memory功能。通过显示已读取的文件及其导入关系,该功能可帮助用户调试其 GEMINI.md 文件的问题。

¥The processor returns an import tree that shows the hierarchy of imported files, similar to Claude's /memory feature. This helps users debug problems with their GEMINI.md files by showing which files were read and their import relationships.

树结构示例:

¥Example tree structure:

Memory Files
 L project: GEMINI.md
            L a.md
              L b.md
                L c.md
              L d.md
                L e.md
                  L f.md
            L included.md

该树保留了文件导入的顺序,并显示完整的导入链以供调试。

¥The tree preserves the order that files were imported and shows the complete import chain for debugging purposes.

与克劳德·科德的比较/memory(claude.md) 方法

¥Comparison to Claude Code's /memory (claude.md) Approach

克劳德·科德/memory功能(如claude.md) 通过连接所有包含的文件生成一个扁平的线性文档,并始终用清晰的注释和路径名标记文件边界。它没有明确显示导入的层次结构,但 LLM 会接收所有文件内容和路径,这足以在需要时重建层次结构。

¥Claude Code's /memory feature (as seen in claude.md) produces a flat, linear document by concatenating all included files, always marking file boundaries with clear comments and path names. It does not explicitly present the import hierarchy, but the LLM receives all file contents and paths, which is sufficient for reconstructing the hierarchy if needed.

注意:导入树主要用于开发过程中的清晰度,与 LLM 消耗的相关性有限。

¥Note: The import tree is mainly for clarity during development and has limited relevance to LLM consumption.

API 参考

¥API Reference

processImports(content, basePath, debugMode?, importState?)

¥processImports(content, basePath, debugMode?, importState?)

处理 GEMINI.md 内容中的导入语句。

¥Processes import statements in GEMINI.md content.

参数:

¥Parameters:

  • content(字符串):要处理导入的内容

    ¥content (string): The content to process for imports

  • basePath(字符串): 当前文件所在的目录路径

    ¥basePath (string): The directory path where the current file is located

  • debugMode(布尔值,可选): 是否启用调试日志记录(默认值:false)

    ¥debugMode (boolean, optional): Whether to enable debug logging (default: false)

  • importState(ImportState,可选):用于防止循环导入的状态跟踪

    ¥importState (ImportState, optional): State tracking for circular import prevention

返回:承诺- 包含已处理内容和导入树的对象

¥Returns: Promise - Object containing processed content and import tree

ProcessImportsResult

¥ProcessImportsResult

interface ProcessImportsResult {
  content: string; // The processed content with imports resolved
  importTree: MemoryFile; // Tree structure showing the import hierarchy
}

MemoryFile

¥MemoryFile

interface MemoryFile {
  path: string; // The file path
  imports?: MemoryFile[]; // Direct imports, in the order they were imported
}

validateImportPath(importPath, basePath, allowedDirectories)

¥validateImportPath(importPath, basePath, allowedDirectories)

验证导入路径以确保它们是安全的并且在允许的目录内。

¥Validates import paths to ensure they are safe and within allowed directories.

参数:

¥Parameters:

  • importPath(字符串): 要验证的导入路径

    ¥importPath (string): The import path to validate

  • basePath(字符串):解析相对路径的基目录

    ¥basePath (string): The base directory for resolving relative paths

  • allowedDirectories(string[]): 允许的目录路径数组

    ¥allowedDirectories (string[]): Array of allowed directory paths

返回:boolean - 导入路径是否有效

¥Returns: boolean - Whether the import path is valid

findProjectRoot(startDir)

¥findProjectRoot(startDir)

通过搜索找到项目根目录.git从给定的起始目录向上查找目录。实现为异步使用非阻塞文件系统 API 的功能来避免阻塞 Node.js 事件循环。

¥Finds the project root by searching for a .git directory upwards from the given start directory. Implemented as an async function using non-blocking file system APIs to avoid blocking the Node.js event loop.

参数:

¥Parameters:

  • startDir(字符串):开始搜索的目录

    ¥startDir (string): The directory to start searching from

返回:承诺- 项目根目录(如果没有,则为启动目录).git已找到)

¥Returns: Promise - The project root directory (or the start directory if no .git is found)

最佳实践

¥Best Practices

  1. 使用描述性文件名对于进口部件

    ¥Use descriptive file names for imported components

  2. 保持浅层导入- 避免深度嵌套的导入链

    ¥Keep imports shallow - avoid deeply nested import chains

  3. 记录你的结构- 保持导入文件的清晰层次结构

    ¥Document your structure - maintain a clear hierarchy of imported files

  4. 测试你的导入- 确保所有引用的文件都存在且可访问

    ¥Test your imports - ensure all referenced files exist and are accessible

  5. 使用相对路径为了获得更好的可移植性

    ¥Use relative paths when possible for better portability

故障排除

¥Troubleshooting

常见问题

¥Common Issues

  1. 导入不起作用:检查文件是否存在,路径是否正确

    ¥Import not working: Check that the file exists and the path is correct

  2. 循环导入警告:检查导入结构是否存在循环引用

    ¥Circular import warnings: Review your import structure for circular references

  3. 权限错误:确保文件可读且位于允许的目录内

    ¥Permission errors: Ensure the files are readable and within allowed directories

  4. 路径解析问题:如果相对路径无法正确解析,请使用绝对路径

    ¥Path resolution issues: Use absolute paths if relative paths aren't resolving correctly

调试模式

¥Debug Mode

启用调试模式以查看导入过程的详细日志:

¥Enable debug mode to see detailed logging of the import process:

const result = await processImports(content, basePath, true);