Skip to content
Merged
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
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
node_modules
dist
.docs
.DS_Store
*.tgz
*.log
pnpm-debug.log*
npm-debug.log*
yarn-debug.log*
.docs
docs.config.json
docs.lock
coverage
TODO.md
.docs/
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ pnpm.
- Test: `pnpm test`
- Typecheck: `pnpm typecheck`

## Testing expectations

- Add or update tests for behavior changes and bug fixes.
- Prefer extending existing test coverage in `tests/` before adding new files.

## Cache layout

- Materialized sources live at `.docs/<id>/`.
Expand Down
14 changes: 13 additions & 1 deletion src/add.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { access, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

import {
DEFAULT_CACHE_DIR,
DEFAULT_CONFIG,
type DocsCacheConfig,
resolveConfigPath,
stripDefaultConfigValues,
validateConfig,
writeConfig,
} from "./config";
import { ensureGitignoreEntry } from "./gitignore";
import { resolveTargetDir } from "./paths";
import { resolveRepoInput } from "./resolve-repo";
import { assertSafeSourceId } from "./source-id";
Expand Down Expand Up @@ -68,16 +69,19 @@ export const addSources = async (params: {
let config = DEFAULT_CONFIG;
let rawConfig: DocsCacheConfig | null = null;
let rawPackage: Record<string, unknown> | null = null;
let hadDocsCacheConfig = false;
if (await exists(resolvedPath)) {
if (target.mode === "package") {
const pkg = await loadPackageConfig(resolvedPath);
rawPackage = pkg.parsed;
rawConfig = pkg.config;
config = rawConfig ?? DEFAULT_CONFIG;
hadDocsCacheConfig = Boolean(rawConfig);
} else {
const raw = await readFile(resolvedPath, "utf8");
rawConfig = JSON.parse(raw.toString());
config = validateConfig(rawConfig);
hadDocsCacheConfig = true;
}
}

Expand Down Expand Up @@ -138,11 +142,19 @@ export const addSources = async (params: {
} else {
await writeConfig(resolvedPath, nextConfig);
}
const gitignoreResult = !hadDocsCacheConfig
? await ensureGitignoreEntry(
path.dirname(resolvedPath),
rawConfig?.cacheDir ?? DEFAULT_CACHE_DIR,
)
: null;

return {
configPath: resolvedPath,
sources: newSources,
skipped,
created: true,
gitignoreUpdated: gitignoreResult?.updated ?? false,
gitignorePath: gitignoreResult?.gitignorePath ?? null,
};
};
10 changes: 10 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ const runCommand = async (
ui.line(
`${symbols.info} Updated ${pc.gray(path.relative(process.cwd(), result.configPath) || "docs.config.json")}`,
);
if (result.gitignoreUpdated && result.gitignorePath) {
ui.line(
`${symbols.info} Updated ${pc.gray(ui.path(result.gitignorePath))}`,
);
}
}
return;
}
Expand Down Expand Up @@ -297,6 +302,11 @@ const runCommand = async (
ui.line(
`${symbols.success} Wrote ${pc.gray(ui.path(result.configPath))}`,
);
if (result.gitignoreUpdated && result.gitignorePath) {
ui.line(
`${symbols.info} Updated ${pc.gray(ui.path(result.gitignorePath))}`,
);
}
}
return;
}
Expand Down
92 changes: 92 additions & 0 deletions src/gitignore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { access, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { toPosixPath } from "./paths";

const exists = async (target: string) => {
try {
await access(target);
return true;
} catch {
return false;
}
};

const normalizeEntry = (value: string) => {
const trimmed = value.trim();
if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("!")) {
return "";
}
let normalized = trimmed.replace(/^\//, "");
normalized = normalized.replace(/^\.\//, "");
normalized = normalized.replace(/\/+$/, "");
return toPosixPath(normalized);
};

const resolveGitignoreEntry = (rootDir: string, cacheDir: string) => {
const resolved = path.isAbsolute(cacheDir)
? path.resolve(cacheDir)
: path.resolve(rootDir, cacheDir);
const relative = path.relative(rootDir, resolved);
const isOutside =
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative);
if (isOutside) {
return null;
}
return relative.length === 0 ? "." : relative;
};

export const getGitignoreStatus = async (rootDir: string, cacheDir: string) => {
const gitignorePath = path.resolve(rootDir, ".gitignore");
const entry = resolveGitignoreEntry(rootDir, cacheDir);
if (!entry) {
return { gitignorePath, entry: null, hasEntry: false };
}
const normalizedEntry = normalizeEntry(entry);
if (!normalizedEntry) {
return { gitignorePath, entry: null, hasEntry: false };
}
let contents = "";
if (await exists(gitignorePath)) {
contents = await readFile(gitignorePath, "utf8");
}
const lines = contents.split(/\r?\n/);
const existing = new Set(
lines.map((line) => normalizeEntry(line)).filter(Boolean),
);
return {
gitignorePath,
entry: `${normalizedEntry}/`,
hasEntry: existing.has(normalizedEntry),
};
};

export const ensureGitignoreEntry = async (
rootDir: string,
cacheDir: string,
) => {
const status = await getGitignoreStatus(rootDir, cacheDir);
if (!status.entry) {
return { updated: false, gitignorePath: status.gitignorePath, entry: null };
}
if (status.hasEntry) {
return {
updated: false,
gitignorePath: status.gitignorePath,
entry: status.entry,
};
}
let contents = "";
if (await exists(status.gitignorePath)) {
contents = await readFile(status.gitignorePath, "utf8");
}
const prefix = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
const next = `${contents}${prefix}${status.entry}\n`;
await writeFile(status.gitignorePath, next, "utf8");
return {
updated: true,
gitignorePath: status.gitignorePath,
entry: status.entry,
};
};
44 changes: 38 additions & 6 deletions src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
stripDefaultConfigValues,
writeConfig,
} from "./config";
import { ensureGitignoreEntry, getGitignoreStatus } from "./gitignore";

type InitOptions = {
cacheDirOverride?: string;
Expand Down Expand Up @@ -91,6 +92,7 @@ export const initConfig = async (
if (isCancel(cacheDirAnswer)) {
throw new Error("Init cancelled.");
}
const cacheDirValue = cacheDirAnswer || DEFAULT_CACHE_DIR;
const indexAnswer = await confirm({
message:
"Generate index.json (summary of cached sources + paths for tools)",
Expand All @@ -99,15 +101,29 @@ export const initConfig = async (
if (isCancel(indexAnswer)) {
throw new Error("Init cancelled.");
}
const gitignoreStatus = await getGitignoreStatus(cwd, cacheDirValue);
let gitignoreAnswer = false;
if (gitignoreStatus.entry && !gitignoreStatus.hasEntry) {
const reply = await confirm({
message: "Add cache directory to .gitignore",
initialValue: true,
});
if (isCancel(reply)) {
throw new Error("Init cancelled.");
}
gitignoreAnswer = reply;
}

const answers = {
configPath,
cacheDir: cacheDirAnswer,
index: indexAnswer,
gitignore: gitignoreAnswer,
} as {
configPath: string;
cacheDir: string;
index: boolean;
gitignore: boolean;
};

const resolvedConfigPath = path.resolve(cwd, answers.configPath);
Expand All @@ -124,9 +140,9 @@ export const initConfig = async (
"https://raw.githubusercontent.com/fbosch/docs-cache/main/docs.config.schema.json",
sources: [],
};
const cacheDirValue = answers.cacheDir || DEFAULT_CACHE_DIR;
if (cacheDirValue !== DEFAULT_CACHE_DIR) {
baseConfig.cacheDir = cacheDirValue;
const resolvedCacheDir = answers.cacheDir || DEFAULT_CACHE_DIR;
if (resolvedCacheDir !== DEFAULT_CACHE_DIR) {
baseConfig.cacheDir = resolvedCacheDir;
}
if (answers.index) {
baseConfig.index = true;
Expand All @@ -137,9 +153,17 @@ export const initConfig = async (
`${JSON.stringify(pkg, null, 2)}\n`,
"utf8",
);
const gitignoreResult = answers.gitignore
? await ensureGitignoreEntry(
path.dirname(resolvedConfigPath),
resolvedCacheDir,
)
: null;
return {
configPath: resolvedConfigPath,
created: true,
gitignoreUpdated: gitignoreResult?.updated ?? false,
gitignorePath: gitignoreResult?.gitignorePath ?? null,
};
}
if (await exists(resolvedConfigPath)) {
Expand All @@ -150,17 +174,25 @@ export const initConfig = async (
"https://raw.githubusercontent.com/fbosch/docs-cache/main/docs.config.schema.json",
sources: [],
};
const cacheDirValue = answers.cacheDir || DEFAULT_CACHE_DIR;
if (cacheDirValue !== DEFAULT_CACHE_DIR) {
config.cacheDir = cacheDirValue;
const resolvedCacheDir = answers.cacheDir || DEFAULT_CACHE_DIR;
if (resolvedCacheDir !== DEFAULT_CACHE_DIR) {
config.cacheDir = resolvedCacheDir;
}
if (answers.index) {
config.index = true;
}

await writeConfig(resolvedConfigPath, config);
const gitignoreResult = answers.gitignore
? await ensureGitignoreEntry(
path.dirname(resolvedConfigPath),
resolvedCacheDir,
)
: null;
return {
configPath: resolvedConfigPath,
created: true,
gitignoreUpdated: gitignoreResult?.updated ?? false,
gitignorePath: gitignoreResult?.gitignorePath ?? null,
};
};
18 changes: 18 additions & 0 deletions tests/cli-add.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,21 @@ test("add writes package.json without default fields", async () => {
assert.equal(pkg["docs-cache"].defaults, undefined);
assert.equal(pkg["docs-cache"].targetMode, undefined);
});

test("add writes .gitignore when initializing config", async () => {
const tmpRoot = path.join(tmpdir(), `docs-cache-add-gitignore-${Date.now()}`);
await mkdir(tmpRoot, { recursive: true });
const configPath = path.join(tmpRoot, "docs.config.json");

await execFileAsync("node", [
"bin/docs-cache.mjs",
"add",
"--offline",
"https://github.com/fbosch/docs-cache.git",
"--config",
configPath,
]);

const raw = await readFile(path.join(tmpRoot, ".gitignore"), "utf8");
assert.match(raw, /^\.docs\/$/m);
});
Loading
Loading