preferences.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
  2. import { dirname, join } from 'node:path';
  3. import { randomUUID } from 'node:crypto';
  4. export class ReviewPreferencesService {
  5. readonly rulesPath: string;
  6. constructor(dataDir: string) {
  7. this.rulesPath = join(dataDir, 'review-rules', 'global.md');
  8. }
  9. async get(): Promise<string> {
  10. try {
  11. return await readFile(this.rulesPath, 'utf8');
  12. } catch (error) {
  13. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return '';
  14. throw error;
  15. }
  16. }
  17. async update(rules: string): Promise<string> {
  18. if (!rules.trim()) {
  19. await rm(this.rulesPath, { force: true });
  20. return '';
  21. }
  22. const parent = dirname(this.rulesPath);
  23. await mkdir(parent, { recursive: true });
  24. const temporaryPath = join(parent, `.global.md.${randomUUID()}.tmp`);
  25. try {
  26. await writeFile(temporaryPath, rules, { encoding: 'utf8', mode: 0o600 });
  27. await rename(temporaryPath, this.rulesPath);
  28. } finally {
  29. await rm(temporaryPath, { force: true });
  30. }
  31. return rules;
  32. }
  33. }