Skip to content
Closed
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
102 changes: 102 additions & 0 deletions .github/workflows/msys-git-path-repro.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
name: MSYS Git Path Repro

# End-to-end reproduction of the MSYS/Cygwin Git path bug on Windows.
# See https://github.com/facebook/docusaurus/issues/11920
#
# Under Git Bash / MSYS2 / Cygwin, `git rev-parse --show-toplevel` prints an
# MSYS-style path like `/c/Users/.../site`. Unfixed `getGitRepoRoot` passes that
# straight to `fs.realpath.native`, which resolves it against the current drive
# root and duplicates the drive letter into `C:\c\Users\...` (ENOENT).
#
# This job runs the real `getGitRepoRoot` from inside an MSYS2 shell so CI can
# prove the failure without the fix, and the pass once the fix lands.

on:
workflow_dispatch:
pull_request:
branches:
- main
- docusaurus-v**
paths:
- packages/docusaurus-utils/src/vcs/gitUtils.ts
- admin/scripts/msys-git-path-repro/**
- .github/workflows/msys-git-path-repro.yml

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

permissions:
contents: read

jobs:
msys-repro:
name: MSYS Git Path Repro
timeout-minutes: 30
runs-on: windows-latest
steps:
- name: Support longpaths
run: git config --system core.longpaths true

- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

- name: Install pnpm
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9

- name: Use Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: '24.14'
cache: pnpm

- name: Installation
run: pnpm install --frozen-lockfile || pnpm install --frozen-lockfile || pnpm install --frozen-lockfile

# Provide the MSYS2 build of Git. path-type inherit keeps the native
# Windows PATH (so node/pnpm stay reachable) while MSYS2 bin is prepended,
# so `git` resolves to the MSYS build inside this shell.
- name: Setup MSYS2
uses: msys2/setup-msys2@66cd2cce69caa17b53920067426061ca1de3a884 # v2.32.0
with:
msystem: MSYS
path-type: inherit
install: git

- name: Show toolchain (MSYS2 shell)
shell: msys2 {0}
run: |
echo "uname: $(uname -a)"
echo "git on PATH: $(command -v git)"
git --version
echo "node on PATH: $(command -v node)"
node -e "console.log('node platform:', process.platform, 'version:', process.version)"

# Create a real git repo on the C: drive and run the repro from the MSYS2
# shell so getGitRepoRoot's internal `git rev-parse --show-toplevel`
# returns a `/c/...` MSYS path.
- name: Create git repo and run repro
shell: msys2 {0}
run: |
set -euo pipefail
REPO_DIR="/c/msys-repro-site"
rm -rf "$REPO_DIR"
mkdir -p "$REPO_DIR"
cd "$REPO_DIR"
git init -q
git config user.email repro@example.com
git config user.name Repro
echo "# repro" > README.md
git add README.md
git commit -q -m "initial commit"
echo "git rev-parse --show-toplevel => $(git rev-parse --show-toplevel)"

# Native Windows Node needs native Windows paths for the script and
# cwd. The git that getGitRepoRoot shells out to is still the MSYS
# git on PATH, so it keeps returning the `/c/...` MSYS path.
WORKSPACE_UNIX="$(cygpath -u "${GITHUB_WORKSPACE}")"
REPO_DIR_WIN="$(cygpath -w "$REPO_DIR")"
SCRIPT_WIN="$(cygpath -w "${WORKSPACE_UNIX}/admin/scripts/msys-git-path-repro/repro.mjs")"
echo "repo dir (win) : ${REPO_DIR_WIN}"
echo "script (win) : ${SCRIPT_WIN}"
node "${SCRIPT_WIN}" "${REPO_DIR_WIN}"
Comment on lines +78 to +102

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please reproduce the bug using docusaurus build, not an artificial repro script

167 changes: 167 additions & 0 deletions admin/scripts/msys-git-path-repro/repro.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/**

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't want to have this kind of repro file

The original issue reported the bug while running docusaurus build

Please remove this file and make sure docusaurus build actually fails the build under MSYS

You are even stealing code from someone else's PR:
https://github.com/facebook/docusaurus/pull/12067/changes#diff-74d42521dbbadfcfa9876bacdc56b9a6105b61125b7cc88e6f2a7d3ff6ca8694

This code is wrong, and stealing code from someone else is wrong too

* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/*
* Standalone CI reproduction for the MSYS/Cygwin Git path bug.
* See https://github.com/facebook/docusaurus/issues/11920
*
* Run this on a Windows runner from inside an MSYS2 / Git Bash shell, where
* `git` is the MSYS build of Git. In that environment,
* `git rev-parse --show-toplevel` prints an MSYS-style path such as
* `/c/Users/runner/work/.../repo` instead of the native `C:\...\repo`.
*
* It exercises the REAL `getGitRepoRoot` from the compiled package output and
* asserts the returned value is a valid native Windows path that exists and is
* not corrupted by a duplicated drive segment (the symptom of the bug).
*
* In the same run it also computes the OLD, unfixed behaviour,
* `fs.realpath.native(stdout)` on the raw MSYS path, and asserts that it is
* broken — so a green run documents both the bug trigger and the fix.
*/

import path from 'path';
import fs from 'fs';
import {execFileSync} from 'child_process';
import {createRequire} from 'module';
import {fileURLToPath} from 'url';
import {promisify} from 'util';

const require = createRequire(import.meta.url);
const here = path.dirname(fileURLToPath(import.meta.url));

// Async equivalents of sync fs helpers (repo lint bans sync fs methods).
const realpathNative = promisify(fs.realpath.native);
async function pathExists(p) {
try {
await fs.promises.access(p);
return true;
} catch {
return false;
}
}

// Compiled package output (`lib`), produced by `pnpm build:packages` /
// postinstall. Require the built module directly because getGitRepoRoot is not
// part of the package's public index.
const libRoot = path.resolve(
here,
'..',
'..',
'..',
'packages',
'docusaurus-utils',
'lib',
);

const {getGitRepoRoot} = require(path.join(libRoot, 'vcs', 'gitUtils.js'));

const DUPLICATED_DRIVE_RE = /^[a-z]:[\\/][a-z](?:[\\/]|$)/i;
const MSYS_PATH_RE = /^\/[a-z](?:\/|$)/i;

async function main() {
const repoDir = process.argv[2];
if (!repoDir) {
throw new Error('Usage: node repro.mjs <repoDir>');
}

console.log('===== MSYS / Cygwin Git path reproduction =====');
console.log(`process.platform : ${process.platform}`);
console.log(`repo dir (cwd) : ${repoDir}`);

// 1. Show exactly what the MSYS git prints. This is the trigger condition.
const rawToplevel = execFileSync('git', ['rev-parse', '--show-toplevel'], {
cwd: repoDir,
encoding: 'utf8',
}).trim();
console.log(`git --show-toplevel : ${rawToplevel}`);

const looksLikeMsysPath = MSYS_PATH_RE.test(rawToplevel);
console.log(`looks like /c/... path : ${looksLikeMsysPath}`);
if (!looksLikeMsysPath) {
throw new Error(
`Expected git to return an MSYS-style /c/... path but got: ${rawToplevel}\n` +
'This run is not exercising the MSYS code path, so it proves nothing. ' +
'Make sure git is the MSYS2 / Git Bash build and the shell is msys2.',
);
}

// 2. Compute the OLD, unfixed behaviour: fs.realpath.native on the raw MSYS
// path. This is what getGitRepoRoot did before the fix.
let unfixedResult = null;
let unfixedError = null;
try {
unfixedResult = await realpathNative(rawToplevel);
} catch (err) {
unfixedError = err.message;
}
console.log('----- unfixed behaviour: fs.realpath.native(rawStdout) -----');
console.log(` result : ${unfixedResult ?? '(threw)'}`);
console.log(` error : ${unfixedError ?? '(none)'}`);

const unfixedIsBroken =
unfixedError !== null ||
unfixedResult === null ||
DUPLICATED_DRIVE_RE.test(unfixedResult) ||
!(await pathExists(unfixedResult));
console.log(` unfixed is broken : ${unfixedIsBroken}`);

// The bug must actually reproduce, otherwise the run proves nothing.
if (!unfixedIsBroken) {
throw new Error(
'The unfixed behaviour did NOT reproduce the bug. fs.realpath.native ' +
'on the raw MSYS path was expected to fail or produce a ' +
'duplicated-drive path that does not exist.',
);
}

// 3. Run the REAL getGitRepoRoot (the integration point under test).
const repoRoot = await getGitRepoRoot(repoDir);
console.log('----- getGitRepoRoot(repoDir) -----');
console.log(` returned : ${repoRoot}`);

const repoRootIsNative = /^[a-z]:[\\/]/i.test(repoRoot);
const repoRootHasDuplicatedDrive = DUPLICATED_DRIVE_RE.test(repoRoot);
const repoRootExists = await pathExists(repoRoot);
console.log(` is native C:\\ path : ${repoRootIsNative}`);
console.log(` has duplicated drive : ${repoRootHasDuplicatedDrive}`);
console.log(` path exists on disk : ${repoRootExists}`);

const errors = [];
if (!repoRootIsNative) {
errors.push(
`getGitRepoRoot did not return a native Windows path: ${repoRoot}`,
);
}
if (repoRootHasDuplicatedDrive) {
errors.push(`getGitRepoRoot returned a duplicated-drive path: ${repoRoot}`);
}
if (!repoRootExists) {
errors.push(
`getGitRepoRoot returned a path that does not exist: ${repoRoot}`,
);
}

if (errors.length > 0) {
console.error('\n===== REPRO RESULT: FAIL =====');
for (const error of errors) {
console.error(` - ${error}`);
}
process.exit(1);
}

console.log('\n===== REPRO RESULT: PASS =====');
console.log(
'The MSYS path triggered the drive duplication in the unfixed code, and ' +
'getGitRepoRoot resolved it to a correct existing native path.',
);
}

main().catch((err) => {
console.error('\n===== REPRO RESULT: FAIL =====');
console.error(err);
process.exit(1);
});
30 changes: 30 additions & 0 deletions packages/docusaurus-utils/src/vcs/__tests__/gitUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
getGitLastUpdate,
getGitCreation,
getGitRepoRoot,
gitPosixDrivePathToWindows,
getGitSuperProjectRoot,
getGitSubmodulePaths,
getGitAllRepoRoots,
Expand Down Expand Up @@ -454,6 +455,35 @@ describe('getGitRepoRoot', () => {
});
});

describe('gitPosixDrivePathToWindows', () => {
it('converts Git-Bash / MSYS / Cygwin drive paths to native Windows paths', () => {
// See https://github.com/facebook/docusaurus/issues/11920
expect(gitPosixDrivePathToWindows('/p/projets/my-repo')).toBe(
'P:\\projets\\my-repo',
);
expect(gitPosixDrivePathToWindows('/c/Users/me/website')).toBe(
'C:\\Users\\me\\website',
);
});

it('handles a drive root with no remaining segments', () => {
expect(gitPosixDrivePathToWindows('/d/')).toBe('D:\\');
});

it('leaves native Windows paths unchanged', () => {
expect(gitPosixDrivePathToWindows('C:/already/windows')).toBe(
'C:/already/windows',
);
});

it('leaves non-drive-mount POSIX paths unchanged', () => {
expect(gitPosixDrivePathToWindows('/home/user/repo')).toBe(
'/home/user/repo',
);
expect(gitPosixDrivePathToWindows('/usr/local/lib')).toBe('/usr/local/lib');
});
});

describe('submodules APIs', () => {
async function initTestRepo() {
const superproject = await createGitRepoEmpty();
Expand Down
25 changes: 23 additions & 2 deletions packages/docusaurus-utils/src/vcs/gitUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,27 @@ export async function isGitInsideWorktree(cwd: string): Promise<boolean> {
}
}

// Git (via Git Bash / MSYS2 / Cygwin on Windows) can report POSIX-style drive
// paths such as `/c/Users/me/repo` instead of `C:\Users\me\repo`. Node would
// interpret the leading `/c/` as drive-relative and resolve it to `C:\c\...`,
// which breaks `fs.realpath` with an ENOENT. Convert these to native Windows
// paths first. Exported for testing; callers gate on `process.platform`.
// See https://github.com/facebook/docusaurus/issues/11920
export function gitPosixDrivePathToWindows(gitPath: string): string {
const posixDriveMatch = /^\/(?<drive>[a-z])\/(?<rest>.*)$/i.exec(gitPath);
if (!posixDriveMatch?.groups) {
return gitPath;
}
const {drive = '', rest = ''} = posixDriveMatch.groups;
return path.win32.join(`${drive.toUpperCase()}:\\`, rest);
}

function toNativeGitPath(gitPath: string): string {
return process.platform === 'win32'
? gitPosixDrivePathToWindows(gitPath)
: gitPath;
}

export async function getGitRepoRoot(cwd: string): Promise<string> {
const createErrorMessageBase = () => {
return `Couldn't find the git repository root directory
Expand Down Expand Up @@ -303,7 +324,7 @@ The command returned exit code ${logger.code(result.exitCode)}: ${logger.subdue(
);
}

return fs.realpath.native(result.stdout.trim());
return fs.realpath.native(toNativeGitPath(result.stdout.trim()));
}

// A Git "superproject" is a Git repository that contains submodules
Expand Down Expand Up @@ -347,7 +368,7 @@ The command returned exit code ${logger.code(result.exitCode)}: ${logger.subdue(
// this command only works when inside submodules
// otherwise it doesn't return anything when we are inside the main repo
if (output) {
return fs.realpath.native(output);
return fs.realpath.native(toNativeGitPath(output));
}
return getGitRepoRoot(cwd);
}
Expand Down
2 changes: 2 additions & 0 deletions project-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ mkdocs
mkdown
Moesif
moesif
MSYS
Nabors
Nakagawa
nand
Expand Down Expand Up @@ -226,6 +227,7 @@ printfn
producthunt
Profilo
profilo
projets
protobuffet
PRPL
Pyltsyn
Expand Down
Loading