Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/content/5.add-ons/2.services/2.git.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ A hub installs a shared instance with `initHub({ services: [createGitService(opt
|--------|------|-------------|
| `cwd` | `string` | Repository directory to operate on. Defaults to the context's `cwd`; the repo root is discovered once (`rev-parse --show-toplevel`) and memoized. |

You can pass a path from `status` directly to `diff`, `log`, `readFile`, `stage`, or `unstage`.
The service treats each file or directory name literally, including brackets in names like `pages/[id].tsx`.
For example, when `cwd` is `packages/app`, `README.md` selects the README at the repository root.
Both `packages/app/README.md` and `./README.md` select the package README.
Pass `.` to `stage` or `unstage` to select the working directory and its contents.

## RPC functions

Registered under `devframes:service:git:*`. Reads are `query`; writes are `action`. Write ops are **always exposed**; authorization is the host's connection-trust boundary. The service defines no `dump`/`snapshot`; a devframe bakes what it needs via `snapshotRpc`.
Expand Down
96 changes: 96 additions & 0 deletions services/git/src/git.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
import { isAbsolute, sep } from 'node:path'
import process from 'node:process'
import { promisify } from 'node:util'

Expand All @@ -10,6 +12,97 @@ export const RECORD = '\x1E'

const MAX_BUFFER = 1024 * 1024 * 64

const CWD_RELATIVE = sep === '\\'
? /^\.{1,2}(?:[/\\]|$)/
: /^\.{1,2}(?:\/|$)/

function isRootPath(path: string): boolean {
return !!path && !CWD_RELATIVE.test(path) && !isAbsolute(path)
}

// Git resolves these paths against the directory where its process starts.
const GIT_PATH_SETTINGS = [
'GIT_DIR',
'GIT_WORK_TREE',
'GIT_INDEX_FILE',
'GIT_COMMON_DIR',
'GIT_OBJECT_DIRECTORY',
'GIT_GRAFT_FILE',
'GIT_SHALLOW_FILE',
'GIT_CONFIG',
'GIT_CONFIG_GLOBAL',
'GIT_CONFIG_SYSTEM',
]

function needsOriginalCwd(): boolean {
return GIT_PATH_SETTINGS.some((key) => {
const value = process.env[key]
return value && !isAbsolute(value)
}) || !!process.env.GIT_ALTERNATE_OBJECT_DIRECTORIES || !!process.env.GIT_CONFIG_PARAMETERS
}

interface FileSelection {
cwd: string
paths: string[]
rootDiff: boolean
gitDir?: string
}

/** Select the same repository and preserve Git's native interpretation of literal file paths. */
export async function fileSelection(cwd: string, root: string, paths: string[]): Promise<FileSelection> {
if (!paths.length || cwd === root)
return { cwd, paths, rootDiff: false }
const rootCount = paths.filter(isRootPath).length
if (!rootCount)
return { cwd, paths, rootDiff: false }
const cwdCount = paths.filter(path => CWD_RELATIVE.test(path)).length
let fromRoot = !needsOriginalCwd()
let selected = paths
if (cwdCount || !fromRoot) {
// --show-cdup contains only ../ components. The worktree prefix can itself contain newlines.
const { stdout } = await runGit(cwd, ['rev-parse', '--show-cdup', '--show-prefix'])
const end = stdout.indexOf('\n')
const toRoot = stdout.slice(0, end)
const toCwd = stdout.slice(end + 1, -1)
fromRoot = fromRoot && cwdCount * Buffer.byteLength(toCwd) < rootCount * Buffer.byteLength(toRoot)
selected = paths.map((path) => {
if (fromRoot) {
return CWD_RELATIVE.test(path)
? toCwd + path
: path
}
return isRootPath(path)
? toRoot + path
: path
})
}
if (!fromRoot)
return { cwd, paths: selected, rootDiff: true }
// Two Git directories can share one working tree. Use the Git directory discovered by the service.
const { stdout } = await runGit(cwd, ['rev-parse', '--absolute-git-dir'])
return {
cwd: root,
paths: selected,
rootDiff: true,
gitDir: stdout.replace(/\n$/, ''),
}
}

export function fileArgs(command: string[], selection: FileSelection): string[] {
if (!selection.paths.length)
return command
const repo = selection.gitDir
? [`--git-dir=${selection.gitDir}`, `--work-tree=${selection.cwd}`]
: []
return [
'--literal-pathspecs',
...repo,
...command,
'--',
...selection.paths,
]
}

export interface GitRunResult {
stdout: string
stderr: string
Expand All @@ -20,13 +113,16 @@ export interface GitRunResult {
* tolerate failure (e.g. "no upstream configured") should use {@link tryGit}.
*/
export async function runGit(cwd: string, args: string[]): Promise<GitRunResult> {
// Inherited glob and case-folding modes conflict with the service's exact file selections.
const selectingFiles = args[0] === '--literal-pathspecs'
const { stdout, stderr } = await execFileAsync('git', args, {
cwd,
maxBuffer: MAX_BUFFER,
windowsHide: true,
/** Force plain, locale-independent output so parsers stay stable. */
env: {
...process.env,
...(selectingFiles && { GIT_GLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' }),
GIT_PAGER: 'cat',
GIT_OPTIONAL_LOCKS: '0',
LC_ALL: 'C',
Expand Down
60 changes: 25 additions & 35 deletions services/git/src/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import type {
Tag,
} from './types'
import {
fileArgs,
fileSelection,
gitErrorMessage,
isSafeRevision,
RECORD,
Expand Down Expand Up @@ -387,6 +389,15 @@ export function createGitOps(cwd: string): GitServiceApi {
return result
}

async function updateIndex(command: string[], paths: string[]): Promise<GitStatus> {
const root = await resolveRoot()
if (root && paths.length > 0) {
const selection = await fileSelection(cwd, root, paths)
await runGit(selection.cwd, fileArgs(command, selection))
}
return status()
}

async function readCommit(hash: string, includePatch: boolean): Promise<CommitDetail> {
if (!isSafeRevision(hash))
return { ...EMPTY_DETAIL, isRepo: true }
Expand Down Expand Up @@ -508,13 +519,9 @@ export function createGitOps(cwd: string): GitServiceApi {
}
command.push('--end-of-options', ref)
}
// Pathspec after `--`: everything past it is treated as a path, never
// an option, so client paths need no dash guard here.
const paths = (args.paths ?? []).map(p => p.trim()).filter(Boolean)
if (paths.length > 0)
command.push('--', ...paths)

const raw = await tryGit(cwd, command)
const paths = (args.paths ?? []).filter(Boolean)
const selection = await fileSelection(cwd, root, paths)
const raw = await tryGit(selection.cwd, fileArgs(command, selection))
const commits = raw
? parseLog(raw)
: []
Expand All @@ -537,7 +544,7 @@ export function createGitOps(cwd: string): GitServiceApi {
},

async readFile(args) {
const path = (args?.path ?? '').trim()
const path = args?.path ?? ''
const ref = args?.ref?.trim() || 'HEAD'
const root = await resolveRoot()
const base: GitFile = {
Expand Down Expand Up @@ -596,25 +603,21 @@ export function createGitOps(cwd: string): GitServiceApi {
const base = staged
? ['diff', '--cached']
: ['diff']
const scope = path
? ['--', path]
: []
const numstatRaw = await tryGit(cwd, [
...base,
'--numstat',
...scope,
])
const selection = await fileSelection(cwd, root, path
? [path]
: [])
if (selection.rootDiff)
base.push('--no-relative')
const summary = fileArgs([...base, '--numstat'], selection)
const numstatRaw = await tryGit(selection.cwd, summary)
const files = numstatRaw
? parseNumstat(numstatRaw)
: []

let patch: string | null = null
let truncated = false
if (path) {
const { stdout } = await runGit(cwd, [
...base,
...scope,
])
const { stdout } = await runGit(selection.cwd, fileArgs(base, selection))
;({ patch, truncated } = clipPatch(stdout))
}

Expand Down Expand Up @@ -685,21 +688,8 @@ export function createGitOps(cwd: string): GitServiceApi {
return { isRepo: true, tags }
},

async stage(args) {
const paths = args?.paths ?? []
const root = await resolveRoot()
if (root && paths.length > 0)
await runGit(cwd, ['add', '--', ...paths])
return status()
},

async unstage(args) {
const paths = args?.paths ?? []
const root = await resolveRoot()
if (root && paths.length > 0)
await runGit(cwd, ['restore', '--staged', '--', ...paths])
return status()
},
stage: args => updateIndex(['add'], args?.paths ?? []),
unstage: args => updateIndex(['restore', '--staged'], args?.paths ?? []),

async commit(args) {
const message = (args?.message ?? '').trim()
Expand Down
10 changes: 5 additions & 5 deletions services/git/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export interface LogArgs {
skip?: number
/** Optional ref/branch to read history from (default: current HEAD). */
ref?: string
/** Restrict history to commits that touched these repo-relative path(s). */
/** Limit history to these files or directories. Paths start at the repo root, or at the service cwd with `./`. */
paths?: string[]
}

Expand Down Expand Up @@ -112,7 +112,7 @@ export interface GitTags {
}

export interface ReadFileArgs {
/** Repo-relative path to the file. */
/** File path from the repo root, or from the service cwd with `./`. */
path: string
/** Commit-ish to read the file from (default: current HEAD). */
ref?: string
Expand Down Expand Up @@ -155,7 +155,7 @@ export interface GitDiff {
}

export interface DiffArgs {
/** Limit the diff to a single path; omit for the whole tree. */
/** File path from the repo root, or from the service cwd with `./`. Omit for the whole tree. */
path?: string
/** Diff the index against HEAD instead of the working tree. */
staged?: boolean
Expand Down Expand Up @@ -206,12 +206,12 @@ export interface ShowArgs {
}

export interface StageArgs {
/** Paths to stage (`git add`). */
/** Paths to stage from the repo root. Use `./` or `.` for the service cwd. */
paths: string[]
}

export interface UnstageArgs {
/** Paths to unstage (`git restore --staged`). */
/** Paths to unstage from the repo root. Use `./` or `.` for the service cwd. */
paths: string[]
}

Expand Down
41 changes: 40 additions & 1 deletion services/git/test/_repo.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { dirname, join } from 'node:path'
import process from 'node:process'

export interface TempRepo {
Expand Down Expand Up @@ -120,6 +120,45 @@ export function createPathRepo(): TempRepo {
}
}

/** Give each file its own commit and a distinguishable working-tree edit. */
export function createEditedRepo(files: [string, string][], relativeDiff = false): TempRepo {
const repo = createTempDir()
git(repo.dir, ['init', '-b', 'main'])
git(repo.dir, [
'config',
'diff.relative',
String(relativeDiff),
])
for (const [file, label] of files) {
mkdirSync(dirname(join(repo.dir, file)), { recursive: true })
write(repo.dir, file, `${label} committed\n`)
git(repo.dir, [
'--literal-pathspecs',
'add',
'--',
file,
])
git(repo.dir, ['commit', '-m', `add ${label}`])
write(repo.dir, file, `${label} edited\n`)
}
return repo
}

/** Both Git directories inspect the outer worktree but have distinct history and indexes. */
export function createSharedWorktreeRepo(): TempRepo {
const repo = createEditedRepo([
['README.md', 'outer'],
])
const nested = join(repo.dir, 'packages/app')
mkdirSync(nested, { recursive: true })
git(nested, ['init', '-b', 'inner'])
git(nested, ['config', 'core.worktree', repo.dir])
git(nested, ['add', '--', '../../README.md'])
git(nested, ['commit', '-m', 'inner README'])
write(repo.dir, 'README.md', 'inner change\n')
return repo
}

/** Create an empty (non-git) temp directory. */
export function createTempDir(): TempRepo {
const dir = mkdtempSync(join(tmpdir(), 'devframe-git-bare-'))
Expand Down
Loading
Loading