Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: match linked-folder paths against .gitignore runs, not rule by rule (#15949)
Daniel Hand0cc1942f79a
diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.pyindex 72fce2258c6..1b1b54d3322 100644--- a/studio/backend/core/rag/folder_sync.py+++ b/studio/backend/core/rag/folder_sync.py@@ -1084,14 +1084,17 @@ def _scan(found: dict[str, dict] = {}mount_points = _mount_points()root_identities = frozenset({identity}) if identity[1] not in (None, 0) else frozenset()- pending = [(root, frozenset({_path_key(root)}), root_identities, 0, ())]+ pending = [(root, frozenset({_path_key(root)}), root_identities, 0, (), None)]# Collect past the cap so the kept set is the sorted first FOLDER_MAX_FILES, stable across scans.hard_cap = config.FOLDER_MAX_FILES * 2 if config.FOLDER_MAX_FILES else 0while pending:- directory, ancestor_paths, ancestor_identities, depth, rules = pending.pop()+ directory, ancestor_paths, ancestor_identities, depth, rules, matcher = pending.pop()directory_rel = os.path.relpath(directory, root).replace(os.sep, "/")directory_rel = "" if directory_rel == "." else directory_rel- rules = (*rules, *_read_gitignore(directory, directory_rel))+ own_rules = _read_gitignore(directory, directory_rel)+ if own_rules:+ rules = (*rules, *own_rules)+ matcher = gitignore.Matcher(rules)with os.scandir(directory) as entries:for entry in entries:full = entry.path@@ -1102,7 +1105,7 @@ def _scan(if _is_ignored_scan_dir(entry.name, full):excluded.add(rel)continue- if rules and gitignore.is_ignored(rel, True, rules):+ if matcher and matcher.is_ignored(rel, True):skipped["gitignored"] += 1excluded.add(rel)continue@@ -1143,6 +1146,7 @@ def _scan(child_identities,depth + 1,rules,+ matcher,))continue@@ -1153,7 +1157,7 @@ def _scan(ext = os.path.splitext(entry.name)[1].lower()if ext not in config.UPLOAD_EXTS:continue- if rules and gitignore.is_ignored(rel, False, rules):+ if matcher and matcher.is_ignored(rel, False):skipped["gitignored"] += 1excluded.add(rel)continuediff --git a/studio/backend/core/rag/gitignore.py b/studio/backend/core/rag/gitignore.pyindex 26eac250d12..ab388fe5877 100644--- a/studio/backend/core/rag/gitignore.py+++ b/studio/backend/core/rag/gitignore.py@@ -130,6 +130,53 @@ def parse(text: str, base: str) -> list[Rule]:return rules+class Matcher:+ """``is_ignored`` compiled once: one regex per run of same-``negate`` rules; last matching run wins."""++ __slots__ = ("_dir_plan", "_file_plan")++ def __init__(self, rules: "tuple[Rule, ...] | list[Rule]"):+ self._dir_plan = _plan(rules)+ self._file_plan = _plan([rule for rule in rules if not rule.dir_only])++ def is_ignored(self, rel: str, is_dir: bool) -> bool:+ for negate, matcher in self._dir_plan if is_dir else self._file_plan:+ if isinstance(matcher, Rule):+ if matcher.base:+ prefix = matcher.base + "/"+ if not rel.startswith(prefix) or not matcher.regex.match(rel[len(prefix) :]):+ continue+ elif not matcher.regex.match(rel):+ continue+ elif not matcher.match(rel):+ continue+ return not negate+ return False+++def _plan(rules) -> "tuple[tuple[bool, re.Pattern[str] | Rule], ...]":+ runs: list[tuple[bool, list]] = []+ for rule in rules:+ if rule.regex.groupindex:+ # Named groups (the atomic "*" emulation) would clash inside one regex: kept alone.+ runs.append((rule.negate, [rule]))+ continue+ body = rule.regex.pattern[1:]+ alternative = re.escape(rule.base + "/") + body if rule.base else body+ if runs and runs[-1][0] == rule.negate and isinstance(runs[-1][1][0], str):+ runs[-1][1].append(alternative)+ else:+ runs.append((rule.negate, [alternative]))+ plan = []+ for negate, members in reversed(runs):+ if isinstance(members[0], str):+ body = "(?:" + ")|(?:".join(members) + ")"+ plan.append((negate, re.compile(f"^(?:{body})", re.DOTALL)))+ else:+ plan.append((negate, members[0]))+ return tuple(plan)++def is_ignored(rel: str, is_dir: bool, rules: tuple[Rule, ...]) -> bool:"""Whether `rel` (posix, relative to the scan root) is ignored; the last matching rule wins."""ignored = Falsediff --git a/studio/backend/tests/test_rag_gitignore_matcher.py b/studio/backend/tests/test_rag_gitignore_matcher.pynew file mode 100644index 00000000000..9e6ca7737fa--- /dev/null+++ b/studio/backend/tests/test_rag_gitignore_matcher.py@@ -0,0 +1,174 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The compiled .gitignore Matcher agrees with rule-by-rule matching."""++from __future__ import annotations++import random+import re+from pathlib import Path++import pytest++from core.rag import folder_sync, gitignore++_ATOMS = [+ "a",+ "b",+ "foo",+ "x.py",+ "*.py",+ "build",+ "*",+ "**",+ "?",+ "[ab]",+ "[!a]",+ "[^b]",+ "[]a]",+ "[a-c]",+ "\\*",+ "\\ ",+ "/",+ "\\!",+ "\\#",+ "#c",+ "!",+ " ",+ "\\",+ "[",+ "(?P<g0>",+ ")",+ "$",+ "^",+ ".",+ "\n",+]+_PATH_ATOMS = ["a", "b", "foo", "x.py", "build", "ab", "*", "(?P<g0>", "$", "é", "\n"]+++def _rules(rng: random.Random) -> tuple[gitignore.Rule, ...]:+ rules: list[gitignore.Rule] = []+ for _ in range(rng.randint(1, 4)):+ base = rng.choice(["", "", "a", "foo/bar", "a.b", "x*y"])+ text = "\n".join(+ "".join(rng.choice(_ATOMS) for _ in range(rng.randint(1, 5)))+ for _ in range(rng.randint(0, 30))+ )+ rules += gitignore.parse(text, base)+ return tuple(rules)+++def _path(rng: random.Random, rules) -> str:+ rel = "/".join(+ "".join(rng.choice(_PATH_ATOMS) for _ in range(rng.randint(1, 2)))+ for _ in range(rng.randint(1, 5))+ )+ if rules and rng.random() < 0.3 and rng.choice(rules).base:+ rel = rng.choice(rules).base + "/" + rel+ return rel+++def test_matcher_agrees_with_rule_by_rule_matching():+ rng = random.Random(0)+ checked = ignored = 0+ for _ in range(400):+ rules = _rules(rng)+ matcher = gitignore.Matcher(rules)+ for _ in range(40):+ rel, is_dir = _path(rng, rules), rng.random() < 0.5+ expected = gitignore.is_ignored(rel, is_dir, rules)+ assert matcher.is_ignored(rel, is_dir) is expected, (rel, is_dir)+ checked += 1+ ignored += expected+ assert 0.1 < ignored / checked < 0.9+++ "rules, rel, is_dir",+ [+ ("*.md\n!keep.md", "keep.md", False),+ ("*.md\n!keep.md", "drop.md", False),+ ("generated/", "generated", True),+ ("generated/", "generated", False),+ ("*a*b\n*.log", "xaab", False),+ ("a*b*c\n!acbc", "acbc", False),+ ("logs/**\n!logs/keep/\nlogs/keep/*.tmp", "logs/keep/x.tmp", False),+ ("logs/**\n!logs/keep/", "logs/keep", True),+ ("x\n", "x\n", False),+ ],+)+def test_matcher_keeps_last_rule_wins(rules, rel, is_dir):+ for base in ("", "sub"):+ parsed = tuple(gitignore.parse(rules, base))+ target = f"{base}/{rel}" if base else rel+ assert gitignore.Matcher(parsed).is_ignored(target, is_dir) is gitignore.is_ignored(+ target, is_dir, parsed+ )+++def test_adjacent_rules_share_one_regex():+ text = "\n".join(f"*.ext{i}" for i in range(100)) + "\n!keep.ext1\ncache/\n*.tmp\n"+ matcher = gitignore.Matcher(tuple(gitignore.parse(text, "")))+ # Files skip the directory-only cache/; directories run it together with *.tmp.+ assert len(matcher._file_plan) == 3+ assert len(matcher._dir_plan) == 3+ assert all(isinstance(m, re.Pattern) for _, m in matcher._file_plan)+++def test_a_rule_with_named_groups_keeps_its_own_regex():+ parsed = tuple(gitignore.parse("*a*b\n*c*d\n", ""))+ assert all(rule.regex.groupindex for rule in parsed)+ matcher = gitignore.Matcher(parsed)+ assert len(matcher._file_plan) == 2+ assert matcher.is_ignored("xaab", False) and matcher.is_ignored("q/ccd", False)+ assert not matcher.is_ignored("xaa/b", False)+++def _write(+ root: Path,+ rel: str,+ text: str = "words",+) -> None:+ path = root / rel+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text(text, encoding = "utf-8")+++def test_scan_matches_through_one_matcher_per_gitignore(linkable_temp_base, tmp_path, monkeypatch):+ source = linkable_temp_base / f"scan-{tmp_path.name}"+ source.mkdir(parents = True)+ _write(source, ".gitignore", "*.log\ngenerated/\n!important.log\n")+ _write(source, "notes.md")+ _write(source, "debug.log")+ _write(source, "important.log")+ _write(source, "generated/out.md")+ _write(source, "pkg/.gitignore", "local.md\n")+ _write(source, "pkg/local.md")+ _write(source, "pkg/kept.md")+ _write(source, "pkg/deep/more.md")+ _write(source, "local.md")+ built = []+ real_matcher = gitignore.Matcher++ def counting_matcher(rules):+ built.append(len(rules))+ return real_matcher(rules)++ def per_rule(*_args, **_kwargs):+ raise AssertionError("the scan matched rule by rule")++ monkeypatch.setattr(gitignore, "Matcher", counting_matcher)+ monkeypatch.setattr(gitignore, "is_ignored", per_rule)+ report: dict[str, int] = {}+ found, _ = folder_sync._scan(str(source), report = report)+ assert set(found) == {+ "notes.md",+ "important.log",+ "pkg/kept.md",+ "pkg/deep/more.md",+ "local.md",+ }+ assert report["gitignored"] == 3+ assert sorted(built) == [3, 4]