collections.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /**
  2. * Collections configuration management
  3. *
  4. * This module manages the YAML-based collection configuration at ~/.config/qmd/index.yml.
  5. * Collections define which directories to index and their associated contexts.
  6. */
  7. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
  8. import { join } from "path";
  9. import { homedir } from "os";
  10. import YAML from "yaml";
  11. // ============================================================================
  12. // Types
  13. // ============================================================================
  14. /**
  15. * Context definitions for a collection
  16. * Key is path prefix (e.g., "/", "/2024", "/Board of Directors")
  17. * Value is the context description
  18. */
  19. export type ContextMap = Record<string, string>;
  20. /**
  21. * A single collection configuration
  22. */
  23. export interface Collection {
  24. path: string; // Absolute path to index
  25. pattern: string; // Glob pattern (e.g., "**/*.md")
  26. context?: ContextMap; // Optional context definitions
  27. update?: string; // Optional bash command to run during qmd update
  28. }
  29. /**
  30. * The complete configuration file structure
  31. */
  32. export interface CollectionConfig {
  33. global_context?: string; // Context applied to all collections
  34. collections: Record<string, Collection>; // Collection name -> config
  35. }
  36. /**
  37. * Collection with its name (for return values)
  38. */
  39. export interface NamedCollection extends Collection {
  40. name: string;
  41. }
  42. // ============================================================================
  43. // Configuration paths
  44. // ============================================================================
  45. function getConfigDir(): string {
  46. // Allow override via QMD_CONFIG_DIR for testing
  47. if (process.env.QMD_CONFIG_DIR) {
  48. return process.env.QMD_CONFIG_DIR;
  49. }
  50. return join(homedir(), ".config", "qmd");
  51. }
  52. function getConfigFilePath(): string {
  53. return join(getConfigDir(), "index.yml");
  54. }
  55. /**
  56. * Ensure config directory exists
  57. */
  58. function ensureConfigDir(): void {
  59. const configDir = getConfigDir();
  60. if (!existsSync(configDir)) {
  61. mkdirSync(configDir, { recursive: true });
  62. }
  63. }
  64. // ============================================================================
  65. // Core functions
  66. // ============================================================================
  67. /**
  68. * Load configuration from ~/.config/qmd/index.yml
  69. * Returns empty config if file doesn't exist
  70. */
  71. export function loadConfig(): CollectionConfig {
  72. const configPath = getConfigFilePath();
  73. if (!existsSync(configPath)) {
  74. return { collections: {} };
  75. }
  76. try {
  77. const content = readFileSync(configPath, "utf-8");
  78. const config = YAML.parse(content) as CollectionConfig;
  79. // Ensure collections object exists
  80. if (!config.collections) {
  81. config.collections = {};
  82. }
  83. return config;
  84. } catch (error) {
  85. throw new Error(`Failed to parse ${configPath}: ${error}`);
  86. }
  87. }
  88. /**
  89. * Save configuration to ~/.config/qmd/index.yml
  90. */
  91. export function saveConfig(config: CollectionConfig): void {
  92. ensureConfigDir();
  93. const configPath = getConfigFilePath();
  94. try {
  95. const yaml = YAML.stringify(config, {
  96. indent: 2,
  97. lineWidth: 0, // Don't wrap lines
  98. });
  99. writeFileSync(configPath, yaml, "utf-8");
  100. } catch (error) {
  101. throw new Error(`Failed to write ${configPath}: ${error}`);
  102. }
  103. }
  104. /**
  105. * Get a specific collection by name
  106. * Returns null if not found
  107. */
  108. export function getCollection(name: string): NamedCollection | null {
  109. const config = loadConfig();
  110. const collection = config.collections[name];
  111. if (!collection) {
  112. return null;
  113. }
  114. return { name, ...collection };
  115. }
  116. /**
  117. * List all collections
  118. */
  119. export function listCollections(): NamedCollection[] {
  120. const config = loadConfig();
  121. return Object.entries(config.collections).map(([name, collection]) => ({
  122. name,
  123. ...collection,
  124. }));
  125. }
  126. /**
  127. * Add or update a collection
  128. */
  129. export function addCollection(
  130. name: string,
  131. path: string,
  132. pattern: string = "**/*.md"
  133. ): void {
  134. const config = loadConfig();
  135. config.collections[name] = {
  136. path,
  137. pattern,
  138. context: config.collections[name]?.context, // Preserve existing context
  139. };
  140. saveConfig(config);
  141. }
  142. /**
  143. * Remove a collection
  144. */
  145. export function removeCollection(name: string): boolean {
  146. const config = loadConfig();
  147. if (!config.collections[name]) {
  148. return false;
  149. }
  150. delete config.collections[name];
  151. saveConfig(config);
  152. return true;
  153. }
  154. /**
  155. * Rename a collection
  156. */
  157. export function renameCollection(oldName: string, newName: string): boolean {
  158. const config = loadConfig();
  159. if (!config.collections[oldName]) {
  160. return false;
  161. }
  162. if (config.collections[newName]) {
  163. throw new Error(`Collection '${newName}' already exists`);
  164. }
  165. config.collections[newName] = config.collections[oldName];
  166. delete config.collections[oldName];
  167. saveConfig(config);
  168. return true;
  169. }
  170. // ============================================================================
  171. // Context management
  172. // ============================================================================
  173. /**
  174. * Get global context
  175. */
  176. export function getGlobalContext(): string | undefined {
  177. const config = loadConfig();
  178. return config.global_context;
  179. }
  180. /**
  181. * Set global context
  182. */
  183. export function setGlobalContext(context: string | undefined): void {
  184. const config = loadConfig();
  185. config.global_context = context;
  186. saveConfig(config);
  187. }
  188. /**
  189. * Get all contexts for a collection
  190. */
  191. export function getContexts(collectionName: string): ContextMap | undefined {
  192. const collection = getCollection(collectionName);
  193. return collection?.context;
  194. }
  195. /**
  196. * Add or update a context for a specific path in a collection
  197. */
  198. export function addContext(
  199. collectionName: string,
  200. pathPrefix: string,
  201. contextText: string
  202. ): boolean {
  203. const config = loadConfig();
  204. const collection = config.collections[collectionName];
  205. if (!collection) {
  206. return false;
  207. }
  208. if (!collection.context) {
  209. collection.context = {};
  210. }
  211. collection.context[pathPrefix] = contextText;
  212. saveConfig(config);
  213. return true;
  214. }
  215. /**
  216. * Remove a context from a collection
  217. */
  218. export function removeContext(
  219. collectionName: string,
  220. pathPrefix: string
  221. ): boolean {
  222. const config = loadConfig();
  223. const collection = config.collections[collectionName];
  224. if (!collection?.context?.[pathPrefix]) {
  225. return false;
  226. }
  227. delete collection.context[pathPrefix];
  228. // Remove empty context object
  229. if (Object.keys(collection.context).length === 0) {
  230. delete collection.context;
  231. }
  232. saveConfig(config);
  233. return true;
  234. }
  235. /**
  236. * List all contexts across all collections
  237. */
  238. export function listAllContexts(): Array<{
  239. collection: string;
  240. path: string;
  241. context: string;
  242. }> {
  243. const config = loadConfig();
  244. const results: Array<{ collection: string; path: string; context: string }> = [];
  245. // Add global context if present
  246. if (config.global_context) {
  247. results.push({
  248. collection: "*",
  249. path: "/",
  250. context: config.global_context,
  251. });
  252. }
  253. // Add collection contexts
  254. for (const [name, collection] of Object.entries(config.collections)) {
  255. if (collection.context) {
  256. for (const [path, context] of Object.entries(collection.context)) {
  257. results.push({
  258. collection: name,
  259. path,
  260. context,
  261. });
  262. }
  263. }
  264. }
  265. return results;
  266. }
  267. /**
  268. * Find best matching context for a given collection and path
  269. * Returns the most specific matching context (longest path prefix match)
  270. */
  271. export function findContextForPath(
  272. collectionName: string,
  273. filePath: string
  274. ): string | undefined {
  275. const config = loadConfig();
  276. const collection = config.collections[collectionName];
  277. if (!collection?.context) {
  278. return config.global_context;
  279. }
  280. // Find all matching prefixes
  281. const matches: Array<{ prefix: string; context: string }> = [];
  282. for (const [prefix, context] of Object.entries(collection.context)) {
  283. // Normalize paths for comparison
  284. const normalizedPath = filePath.startsWith("/") ? filePath : `/${filePath}`;
  285. const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
  286. if (normalizedPath.startsWith(normalizedPrefix)) {
  287. matches.push({ prefix: normalizedPrefix, context });
  288. }
  289. }
  290. // Return most specific match (longest prefix)
  291. if (matches.length > 0) {
  292. matches.sort((a, b) => b.prefix.length - a.prefix.length);
  293. return matches[0]!.context;
  294. }
  295. // Fallback to global context
  296. return config.global_context;
  297. }
  298. // ============================================================================
  299. // Utility functions
  300. // ============================================================================
  301. /**
  302. * Get the config file path (useful for error messages)
  303. */
  304. export function getConfigPath(): string {
  305. return getConfigFilePath();
  306. }
  307. /**
  308. * Check if config file exists
  309. */
  310. export function configExists(): boolean {
  311. return existsSync(getConfigFilePath());
  312. }
  313. /**
  314. * Validate a collection name
  315. * Collection names must be valid and not contain special characters
  316. */
  317. export function isValidCollectionName(name: string): boolean {
  318. // Allow alphanumeric, hyphens, underscores
  319. return /^[a-zA-Z0-9_-]+$/.test(name);
  320. }