Skip to main content

khora_editor/
util.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Utility helpers for the editor application.
16
17/// Read the current git branch name from a project's `.git/HEAD`.
18///
19/// Returns `Some(branch_name)` if the project is a git repository on a
20/// regular branch, `None` if the project isn't tracked or HEAD is detached.
21/// Cheap (single fs read of a small file) — safe to call once at startup.
22pub fn read_git_branch(project_root: &std::path::Path) -> Option<String> {
23    let head_path = project_root.join(".git").join("HEAD");
24    let head = std::fs::read_to_string(head_path).ok()?;
25    let line = head.lines().next()?;
26    // Format: `ref: refs/heads/<branch>` or a raw SHA when detached.
27    line.strip_prefix("ref: refs/heads/").map(|s| s.to_owned())
28}