top of page

BUILDING A PRODUCTION-READY GITHUB RAG SYSTEM

Nov 9
9 min read

Build Chapter 4: Classifying Files in a GitHub Repository

Part 1: Foundation and Repository Understanding   |   For engineers learning RAG   |   About 12 minutes to read, 25 to follow along


In Build Chapter 3 we created the domain models that represent repositories, files, eligibility decisions, and inventories. The next step is to work out what kind of file we have found. In this chapter we build a FileClassifier that recognizes Python, SQL, Markdown, YAML, JSON, configuration, shell, dependency, and plain-text files.


This chapter covers classification only. Deciding whether a file may enter the pipeline belongs to the file policy, which we build in Build Chapter 5.


What you will take away

•   A FileClassifier that turns a path into a FileType, using the filename first and the extension second.

•   Why requirements.txt and package.json need special handling, and why unknown files are not errors.

•   A small script that checks the classifier, and a clear view of what it does not handle yet.


Prerequisites: Build Chapter 3 completed

Series code: Link

For technical leaders: the 60-second version

•    The decision. Identify what each file is before choosing how to process it, and keep that step separate from the decision about whether to process it at all.

•    The cost. A small, rule-based component and a list of filenames and extensions to maintain. No model or file reading is needed.

•    The risk it reduces. Treating every file as generic text, which produces poor chunks, and mixing security rules into classification logic, which makes both harder to audit.

•    Questions to ask your team. What happens to a file type we do not recognize? Can we explain why a file was labelled the way it was? Are exclusion rules kept apart from classification rules?

1. What we will build


We create one file, update one, and add a check script:

src\github_rag\inventory

├── init.py       updated: exports FileClassifier
└── classifier.py     new: the FileClassifier class

tests\check_classifier.py    new: a small script that checks the classifier

2. Why file classification is needed


A repository holds many kinds of files, and they cannot all be processed the same way:

main.py   queries.sql   README.md   config.yaml   settings.json
pyproject.toml   requirements.txt   deploy.sh   Dockerfile   notes.txt   logo.png

File kind

What a later parser should preserve

Python

Classes and functions.

SQL

Statements and CTEs.

Markdown

The heading hierarchy.

YAML and JSON

The configuration structure.

Shell scripts

Commands and logical blocks.

Dependency files

Package declarations.

Before choosing a parser, the application needs to know which category each file belongs to. The classifier performs this transformation:

README.md           ->  FileClassifier  ->  FileType.MARKDOWN
monthly_summary.sql ->  FileClassifier  ->  FileType.SQL

3. Classification is not eligibility


Classification answers: what type of file is this? Eligibility answers: should this file be processed? These decisions must stay separate, as we saw in Build Chapter 3.

File

Classifier says

Policy may say

.venv\Lib\site-packages\example.py

PYTHON

EXCLUDED_DIRECTORY

archive\old_query.sql

SQL

EXCLUDED_DIRECTORY, if archive is excluded

The classifier identifies the category. The file policy decides whether to process the file. So the classifier should hold no security exclusions, file-size limits, or directory rules.


4. Classification strategy


We classify with two checks, in this order:

1.    Check whether the filename has a special meaning.

2.    If not, classify by extension.


The order matters. The file requirements.txt has the extension .txt, so an extension-only classifier would call it FileType.TEXT. But its name tells us it declares dependencies, so the right answer is FileType.DEPENDENCY.

Input path
   |
   v
Normalize the filename to lowercase
   |
   v
Is it a known special filename?
   |-- Yes --> return the mapped file type
   |
   '-- No --> normalize the extension
                  |
                  v
              Is the extension recognized?
                  |-- Yes --> return the mapped file type
                  '-- No  --> return FileType.UNKNOWN

5. Why we use Path


The classifier accepts a str or a Path and converts the input to a Path internally. Python's pathlib module provides object-oriented paths and ways to inspect their parts [1]:

from pathlib import Path

path = Path("src/service.py")
print(path.name)      # service.py
print(path.suffix)    # .py

This is clearer than splitting path strings by hand, and it avoids hardcoding separators such as \ or /. One caution: Path follows the system you run on. Give the classifier paths from your own operating system. On Linux or macOS, a Windows-style string such as C:\proj\requirements.txt is read as one long filename, so the special-filename check misses it.


6. Step 1: Create FileClassifier


Create src\github_rag\inventory\classifier.py:

"""Classification of repository files by filename and extension."""
 
from pathlib import Path
from github_rag.domain import FileType
 
class FileClassifier:

    """Classifies repository files into supported file categories."""

    FILENAMETYPES: dict[str, FileType] = {
        "requirements.txt": FileType.DEPENDENCY,
        "requirements-dev.txt": FileType.DEPENDENCY,
        "pyproject.toml": FileType.DEPENDENCY,
        "poetry.lock": FileType.DEPENDENCY,
        "uv.lock": FileType.DEPENDENCY,
        "package.json": FileType.DEPENDENCY,
        "package-lock.json": FileType.DEPENDENCY,
        "dockerfile": FileType.CONFIGURATION,
        "makefile": FileType.CONFIGURATION,
    }
 
    EXTENSIONTYPES: dict[str, FileType] = {
        ".py": FileType.PYTHON,
        ".sql": FileType.SQL,
        ".md": FileType.MARKDOWN,
        ".markdown": FileType.MARKDOWN,
        ".yaml": FileType.YAML,
        ".yml": FileType.YAML,
        ".json": FileType.JSON,
        ".toml": FileType.CONFIGURATION,
        ".ini": FileType.CONFIGURATION,
        ".cfg": FileType.CONFIGURATION,
        ".conf": FileType.CONFIGURATION,
        ".txt": FileType.TEXT,
        ".sh": FileType.SHELL,
        ".bash": FileType.SHELL,
        ".bat": FileType.SHELL,
        ".cmd": FileType.SHELL,
        ".ps1": FileType.SHELL,
    }

    def classify(self, file_path: str | Path) -> FileType:

        """Return the file type identified from a path."""

        path = Path(file_path)
        normalized_filename = path.name.lower()
        filename_type = self._FILENAME_TYPES.get(
            normalized_filename,
        )
        if filename_type is not None:
            return filename_type
        normalized_extension = path.suffix.lower()
 
        return self._EXTENSION_TYPES.get(
            normalized_extension,
            FileType.UNKNOWN,
        )

Check your underscores. Names such as FILENAMETYPES and EXTENSIONTYPES start with an underscore, and the filenames in this chapter use double underscores (__init__.py, all). Word processors and chat tools sometimes strip or format them. If you paste code and see an error such as NameError, compare the underscores first.

 

7. Understanding the class


FileClassifier has one responsibility: to determine the FileType of a repository path. It does not open or read the file, check its size or directory, decide eligibility, parse it, or hash it. Those jobs belong to other components, and keeping the classifier narrow makes it easy to test and reuse.


The two mappings


FILENAMETYPES maps specially recognized filenames to file types, with the lowercase filename as the key. EXTENSIONTYPES maps extensions, including the leading period, to file types. Related extensions share a type: .yaml and .yml are both YAML, and .md and .markdown are both Markdown.

The leading underscore is a Python convention for internal use. It is not a security feature. It tells callers to use classifier.classify(...) instead of reading or changing the mappings directly.


Why the filename check comes first

Some files cannot be classified well by extension alone:


File

Extension

Extension-only result

Preferred result

requirements.txt

.txt

TEXT

DEPENDENCY

pyproject.toml

.toml

CONFIGURATION

DEPENDENCY

package.json

.json

JSON

DEPENDENCY

For this project, pyproject.toml mainly describes the Python project and its dependencies. In each case the specific filename tells us more than the generic extension.


How classify() works

•   Accepts a `str` or `Path`, and always returns a FileType, so callers get a supported enum member and never an arbitrary string.

•   Converts the input with `Path(file_path)`. Converting a Path again is safe.

•   Lowercases the filename. For README.MD, path.name is README.MD and .lower() gives readme.md, so uppercase and lowercase names behave the same.

•   Looks up the filename with `.get()`, which returns None when the name is not in the mapping. A recognized name is returned at once, so requirements.txt never falls through to the generic .txt rule.

•   Lowercases the extension with path.suffix.lower(), so .PY matches .py. A file with no extension, such as LICENSE, has the suffix "".

•   Falls back to `FileType.UNKNOWN` when the extension is not in the mapping.


8. Why unknown files are not errors


A repository can contain formats the pipeline does not understand, such as logo.png, archive.zip, diagram.drawio, database.sqlite, or compiled.dll. Finding one does not mean discovery has failed. The classifier returns FileType.UNKNOWN, and the file policy can later mark the file as UNSUPPORTED_EXTENSION. This separation lets repository scanning continue safely.


9. Step 2: Export FileClassifier


Update src\github_rag\inventory\__init__.py:

"""Repository inventory generation components."""
from github_rag.inventory.classifier import FileClassifier

all = [
    "FileClassifier",
]

Without the export, callers write from github_rag.inventory.classifier import FileClassifier. With it, they write from github_rag.inventory import FileClassifier. Both work, and the package-level import gives the inventory package a simple public interface.


10. Step 3: Test the classifier


Run these from the project root. First, the basic extensions:

uv run python -c "from github_rag.inventory import FileClassifier; classifier = FileClassifier(); print(classifier.classify('main.py').value); print(classifier.classify('query.sql').value); print(classifier.classify('README.md').value)"
 
Expected output:
python
sql
markdown

Configuration and data files:

uv run python -c "from github_rag.inventory import FileClassifier; classifier = FileClassifier(); print(classifier.classify('config.yaml').value); print(classifier.classify('settings.json').value); print(classifier.classify('application.toml').value)"
 
Expected output:
yaml
json
configuration

Special filenames. This confirms the filename check runs before the extension check:

uv run python -c "from github_rag.inventory import FileClassifier; classifier = FileClassifier(); print(classifier.classify('requirements.txt').value); print(classifier.classify('pyproject.toml').value); print(classifier.classify('package.json').value)"
 
Expected output:
dependency
dependency
dependency

Without the filename check, these three files would have been classified as text, configuration, and json.

Uppercase names and extensions:

uv run python -c "from github_rag.inventory import FileClassifier; classifier = FileClassifier(); print(classifier.classify('SERVICE.PY').value); print(classifier.classify('QUERY.SQL').value); print(classifier.classify('README.MD').value)"
 
Expected output:
python
sql
markdown

Unknown files:

uv run python -c "from github_rag.inventory import FileClassifier; classifier = FileClassifier(); print(classifier.classify('logo.png').value); print(classifier.classify('archive.zip').value); print(classifier.classify('LICENSE').value)"
 
Expected output:
unknown
unknown
unknown

These are not errors. The current classifier simply does not recognize them. An extensionless document such as LICENSE could be classified on its own later if it becomes important to retrieval.


11. Step 4: Run a complete classification check


Create tests\check_classifier.py. It classifies nine sample files and prints each result:

"""Manual check of FileClassifier. Run it from the project root."""
from github_rag.inventory import FileClassifier

classifier = FileClassifier()
files = [
    "main.py",
    "query.sql",
    "README.md",
    "config.yaml",
    "settings.json",
    "pyproject.toml",
    "deploy.sh",
    "notes.txt",
    "logo.png",
]
for file_path in files:
    file_type = classifier.classify(file_path)
    print(f"{file_path}: {file_type.value}")

Run it:

uv run python tests\check_classifier.py

Expected output:
main.py: python
query.sql: sql
README.md: markdown
config.yaml: yaml
settings.json: json
pyproject.toml: dependency
deploy.sh: shell
notes.txt: text
logo.png: unknown

12. What the classifier does not handle yet


A rule-based classifier only knows the names and extensions we list. Run this to see three honest misses:

uv run python -c "from github_rag.inventory import FileClassifier; classifier = FileClassifier(); print(classifier.classify('requirements-test.txt').value); print(classifier.classify('.env').value); print(classifier.classify('notebook.ipynb').value)"

Expected output:
text
unknown
unknown

Case

Result today

Why it matters

requirements-test.txt

TEXT

Only the listed requirements names are special. Other variants fall back to the extension.

.env

UNKNOWN

A dot file has no extension in Python's eyes. This is safe, because the file policy excludes .env by name, so it never depends on its type.

notebook.ipynb

UNKNOWN

Notebooks are common in data science repositories. Support would need a new file type and a notebook-aware parser.

Dockerfile.dev, .gitignore

UNKNOWN

Name variants and dot files are not in the mappings.

None of these is a bug in the code above. They are the boundaries of a simple design. We keep the classifier small now and extend the mappings when a real repository needs it.


Classification is not a promise to index. The lock files in the mapping, such as uv.lock and package-lock.json, are labelled as dependency files, but they are large and rarely useful to answer questions. Whether they enter the index is a policy decision for the next chapter.


13. Step 5: Run and verify


Run these checks from the project root. Use them as the checkpoint for this chapter.

uv run python tests\check_classifier.py
uv run python -m compileall -f src
tree src\github_rag /f

Expected:

•   The first command prints the nine lines shown in section 11.

•   The syntax check lists src\github_rag\inventory\__init__.py and classifier.py as compiled, with no SyntaxError. The -f option forces a recompile. Without it, Python skips files it has already compiled and prints nothing for them.

•   The tree should match this:

src\github_rag
│   init.py
│   main.py
│
├───connectors
│       init.py
│
├───core
│       init.py
│       config.py
│       exceptions.py
│       logging.py
│
├───domain
│       init.py
│       enums.py
│       models.py
│
└───inventory
        init.py
        classifier.py

On macOS or Linux, use forward slashes in the paths (tests/check_classifier.py) and tree src/github_rag for the listing. The uv run python -c commands are the same on every system.


14. Why the mappings live inside the classifier


The filename and extension mappings are classification knowledge. The line ".py": FileType.PYTHON defines what a .py file means. That is different from ingestion policy such as "exclude .exe and .dll", which is a configurable decision.

Kind of rule

Where it belongs

What a file is (classification mappings)

FileClassifier

Excluded and supported extensions, excluded directories and filenames

The file-policy YAML, next chapter

We should not hardcode excluded directories, filenames, or extensions in the classifier. Those values will be centralized in YAML.

The early data flow now looks like this. The inventory service will later combine the type with the file's size, path, eligibility, and content hash:

README.md -> FileClassifier.classify() -> FileType.MARKDOWN -> RepositoryFile.file_type

15. Common issues


Symptom

Likely cause

Fix

A Python file is returned as unknown

The filename lacks the .py extension. The classifier does not read file contents.

Check the name, for example service.py.

requirements.txt is returned as text

The extension check runs before the filename check, or the path is a Windows-style string on Linux or macOS.

Keep the filename check first, and pass paths from your own operating system.

Uppercase extensions are not recognized

The .lower() call is missing.

Use path.suffix.lower() so that .PY matches .py.

cannot import name 'FileType'

Build Chapter 3 is incomplete.

Run uv run python -c "from github_rag.domain import FileType; print(FileType.PYTHON.value)" and expect python.

cannot import name 'FileClassifier'

inventory\__init__.py was not updated, or its underscores are wrong.

It must contain the FileClassifier import, and the file name needs double underscores.

NameError or AttributeError after pasting code

Underscores were lost in FILENAMETYPES, init or all.

Compare every underscore with the code in this chapter.


Conclusion and next chapter


FileClassifier gives the pipeline a consistent way to describe repository files. It uses special filenames when they say more than the extension, falls back to a normalized extension for ordinary files, and handles unknown files safely instead of stopping the scan. Most importantly, classification stays independent of eligibility: knowing that a file contains Python, SQL, or Markdown does not mean it should enter the RAG pipeline.

Next, Build Chapter 5: Building Configurable File Security Policies. It covers:

•   Why files must be filtered before extraction

•   FilePolicyConfig, FileEligibilityResult, and FilePolicy

•   Excluded directories, filenames, and extensions

•   Supported extensions and the maximum file size

•   Empty-file and unreadable-file checks

•   Loading policy values from YAML

 

About SNPaul Infotech

We help engineering and data teams design, evaluate, and secure retrieval and GenAI systems like this one. If you are weighing RAG for your own repositories or documents, get in touch: www.snpaulinfotech.com


References

Comments


bottom of page