@fluado/enmetu 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +99 -10
  2. package/dist/adapters/git/gitFacade.d.ts +8 -0
  3. package/dist/adapters/git/gitFacade.js +34 -1
  4. package/dist/adapters/git/gitLocatorFacade.js +6 -3
  5. package/dist/adapters/git/gitProcessAdapter.js +1 -48
  6. package/dist/adapters/host/hostMessageWriterAdapter.d.ts +23 -0
  7. package/dist/adapters/host/hostMessageWriterAdapter.js +76 -0
  8. package/dist/adapters/process/processGroup.d.ts +18 -0
  9. package/dist/adapters/process/processGroup.js +52 -0
  10. package/dist/adapters/process/shellMessageCommandAdapter.d.ts +24 -0
  11. package/dist/adapters/process/shellMessageCommandAdapter.js +102 -0
  12. package/dist/adapters/watch/watcherFor.d.ts +22 -0
  13. package/dist/adapters/watch/watcherFor.js +29 -0
  14. package/dist/cli/commands/hookCommand.d.ts +3 -1
  15. package/dist/cli/commands/hookCommand.js +15 -7
  16. package/dist/cli/commands/runCommand.d.ts +10 -2
  17. package/dist/cli/commands/runCommand.js +51 -5
  18. package/dist/cli/exitCodes.js +0 -1
  19. package/dist/cli.js +2 -0
  20. package/dist/commit/commitLocalChangesController.d.ts +28 -7
  21. package/dist/commit/commitLocalChangesController.js +135 -27
  22. package/dist/contracts/ICommitMessageCommand.d.ts +32 -0
  23. package/dist/contracts/ICommitMessageCommand.js +1 -0
  24. package/dist/contracts/IGitConfigReader.d.ts +4 -1
  25. package/dist/contracts/IGitReader.d.ts +5 -0
  26. package/dist/contracts/IHostMessageWriter.d.ts +28 -0
  27. package/dist/contracts/IHostMessageWriter.js +1 -0
  28. package/dist/contracts/IRepositoryLocator.d.ts +5 -1
  29. package/dist/contracts/config.d.ts +44 -5
  30. package/dist/contracts/errors.d.ts +7 -3
  31. package/dist/contracts/errors.js +5 -1
  32. package/dist/contracts/library.d.ts +30 -0
  33. package/dist/contracts/logCodes.d.ts +1 -1
  34. package/dist/contracts/runtime.d.ts +4 -0
  35. package/dist/contracts/syncTypes.d.ts +3 -3
  36. package/dist/contracts/syncTypes.js +1 -1
  37. package/dist/core/commit/commitMemory.js +1 -1
  38. package/dist/core/commit/commitMessage.d.ts +27 -0
  39. package/dist/core/commit/commitMessage.js +61 -0
  40. package/dist/core/config/parseConfig.d.ts +9 -3
  41. package/dist/core/config/parseConfig.js +186 -60
  42. package/dist/core/git/porcelain.d.ts +9 -1
  43. package/dist/core/git/porcelain.js +27 -3
  44. package/dist/core/status/statusHeadline.js +1 -1
  45. package/dist/enmetuInstances.d.ts +7 -4
  46. package/dist/enmetuInstances.js +53 -15
  47. package/dist/hooks/preCommitHookInstaller.js +10 -0
  48. package/dist/index.d.ts +1 -1
  49. package/dist/index.js +2 -0
  50. package/dist/library/enmetuLibrary.d.ts +2 -1
  51. package/dist/library/enmetuLibrary.js +5 -2
  52. package/dist/quarantine/pathQuarantine.d.ts +10 -0
  53. package/dist/quarantine/pathQuarantine.js +44 -2
  54. package/dist/sync/syncCycleController.d.ts +1 -1
  55. package/dist/sync/syncCycleController.js +2 -2
  56. package/dist/sync/syncCycleRunner.js +1 -1
  57. package/package.json +1 -1
@@ -0,0 +1,29 @@
1
+ import { FsWatchAdapter, nodeWatch } from './fsWatchAdapter.js';
2
+ /** Why no file watch starts under Node on Linux (design 14.20, Decision 137). */
3
+ export const NODE_LINUX_WATCH_OFF = 'file watching is off under Node on Linux, where its recursive watch can end the process (nodejs/node#66791)';
4
+ /**
5
+ * Null Object: a watcher that never starts and says so at once, so the
6
+ * daemon takes its existing path for a lost watch, one WATCHER_FAILED line,
7
+ * then the poll (Decision 21).
8
+ */
9
+ export class PollOnlyWatcher {
10
+ reason;
11
+ constructor(reason) {
12
+ this.reason = reason;
13
+ }
14
+ start(listener) {
15
+ listener.onFailure(this.reason);
16
+ }
17
+ close() { }
18
+ }
19
+ /**
20
+ * The watcher for a runtime, chosen at the composition root (design 14.20):
21
+ * Node's recursive fs.watch on Linux throws ENOTDIR, EACCES or ELOOP inside
22
+ * its own event handler from 24.22.0 on, where no error listener sees it, so
23
+ * Node on Linux polls; Bun, and Node on every other platform, watch.
24
+ */
25
+ export function watcherFor(root, runtime) {
26
+ return runtime.platform === 'linux' && runtime.engine === 'node'
27
+ ? new PollOnlyWatcher(NODE_LINUX_WATCH_OFF)
28
+ : new FsWatchAdapter(root, nodeWatch);
29
+ }
@@ -20,8 +20,10 @@ export interface HookCommandResult {
20
20
  /**
21
21
  * Controller:
22
22
  * 1. locator.locate(startDir); anything but found: notice, exit 0 (the hook fails open).
23
- * 2. parseConfig of <root>/enmetu.config.json; a ConfigError prints a notice and
23
+ * 2. parseConfig of <root>/enmetu.config.json with git config over it, as the
24
+ * daemon reads it (design 14.18); a ConfigError prints a notice and
24
25
  * applies the defaults, so a broken config never blocks the commit that fixes it.
26
+ * Unknown keys are ignored without a word: the daemon names them at start (design 14.17).
25
27
  * 3. preCommitCheckController with the config's skipJsonCheck.
26
28
  * 4. Violations: print the refusal of design 1.18 to stderr, exit 1. None: print nothing, exit 0.
27
29
  */
@@ -7,8 +7,10 @@ const HOOK_CYCLE_ID = 'hook';
7
7
  /**
8
8
  * Controller:
9
9
  * 1. locator.locate(startDir); anything but found: notice, exit 0 (the hook fails open).
10
- * 2. parseConfig of <root>/enmetu.config.json; a ConfigError prints a notice and
10
+ * 2. parseConfig of <root>/enmetu.config.json with git config over it, as the
11
+ * daemon reads it (design 14.18); a ConfigError prints a notice and
11
12
  * applies the defaults, so a broken config never blocks the commit that fixes it.
13
+ * Unknown keys are ignored without a word: the daemon names them at start (design 14.17).
12
14
  * 3. preCommitCheckController with the config's skipJsonCheck.
13
15
  * 4. Violations: print the refusal of design 1.18 to stderr, exit 1. None: print nothing, exit 0.
14
16
  */
@@ -20,10 +22,11 @@ export async function hookCommand(input, deps) {
20
22
  return { exitCode: EXIT.OK };
21
23
  }
22
24
  const { paths } = location;
23
- // --- Step 2: the config at the root; defaults when it is broken ---
24
- const config = await configForCheck(paths.root, deps);
25
+ const git = deps.openGit(paths);
26
+ // --- Step 2: the config at the root and git config; defaults when it is broken ---
27
+ const config = await configForCheck(paths.root, git, deps);
25
28
  // --- Step 3: the shared content rules over the staged blobs (D11) ---
26
- const { violations } = await preCommitCheckController({ cycleId: HOOK_CYCLE_ID }, { git: deps.openGit(paths), skipJsonCheck: config.skipJsonCheck });
29
+ const { violations } = await preCommitCheckController({ cycleId: HOOK_CYCLE_ID }, { git, skipJsonCheck: config.skipJsonCheck });
27
30
  // --- Step 4: the refusal, or silence ---
28
31
  if (violations.length === 0) {
29
32
  return { exitCode: EXIT.OK };
@@ -55,15 +58,20 @@ async function locateOrReason(startDir, deps) {
55
58
  };
56
59
  }
57
60
  }
58
- async function configForCheck(root, deps) {
61
+ async function configForCheck(root, git, deps) {
62
+ const text = await deps.fs.readText(join(root, CONFIG_FILE_NAME));
63
+ const gitEntries = await git.enmetuEntries();
59
64
  try {
60
- return parseConfig(await deps.fs.readText(join(root, CONFIG_FILE_NAME)));
65
+ return parseConfig(text, gitEntries).config;
61
66
  }
62
67
  catch (error) {
63
68
  if (!(error instanceof ConfigError)) {
64
69
  throw error;
65
70
  }
66
- deps.stderr.write(`enmetu: ignoring ${CONFIG_FILE_NAME} (${error.code}: ${error.message}); using the defaults for this check\n`);
71
+ const source = error.gitScope === null
72
+ ? CONFIG_FILE_NAME
73
+ : `git config enmetu.${error.key ?? ''} (${error.gitScope})`;
74
+ deps.stderr.write(`enmetu: ignoring ${source} (${error.code}: ${error.message}); using the defaults for this check\n`);
67
75
  return DEFAULT_CONFIG;
68
76
  }
69
77
  }
@@ -1,4 +1,4 @@
1
- import type { EnmetuConfig } from '../../contracts/config.js';
1
+ import type { EnmetuConfig, GitConfigEntry } from '../../contracts/config.js';
2
2
  import { type ExitCode } from '../../contracts/exitCode.js';
3
3
  import type { IDaemon } from '../../contracts/IDaemon.js';
4
4
  import type { IFileSystem } from '../../contracts/IFileSystem.js';
@@ -11,6 +11,8 @@ export interface RunCommandInput {
11
11
  export interface RunCommandDeps {
12
12
  readonly locator: IRepositoryLocator;
13
13
  readonly fs: IFileSystem;
14
+ /** Every enmetu.* entry of git config for the resolved repository (design 14.18). */
15
+ readonly readGitConfig: (paths: RepositoryPaths) => Promise<readonly GitConfigEntry[]>;
14
16
  readonly logger: ILogger;
15
17
  /** Composition-root closure; builds the daemon for the resolved repository. */
16
18
  readonly createDaemon: (paths: RepositoryPaths, config: EnmetuConfig) => IDaemon;
@@ -27,7 +29,13 @@ export declare const MIN_GIT_VERSION: {
27
29
  * Controller:
28
30
  * 1. locator.locate(startDir): not a repository, bare, or PATH_UNSUPPORTED log NOT_ELIGIBLE, exit 5.
29
31
  * 2. Git older than 2.38: NOT_ELIGIBLE (GIT_TOO_OLD), exit 5.
30
- * 3. parseConfig of <root>/enmetu.config.json: ConfigError logs CONFIG_INVALID, exit 2.
32
+ * 3. parseConfig of <root>/enmetu.config.json and readGitConfig(paths), git
33
+ * config overriding the file (design 14.18): ConfigError logs
34
+ * CONFIG_INVALID naming the file or the git config key and scope, exit 2;
35
+ * each unknown key of the file, each key of the file only git config may
36
+ * set and each unknown enmetu.* key of git config logs CONFIG_KEY_IGNORED
37
+ * once and is ignored (design 14.17); each setting git config set logs
38
+ * CONFIG_FROM_GIT with its scope.
31
39
  * 4. createDaemon(paths, config).run(), its exit code returned.
32
40
  */
33
41
  export declare function runCommand(input: RunCommandInput, deps: RunCommandDeps): Promise<RunCommandResult>;
@@ -8,7 +8,13 @@ export const MIN_GIT_VERSION = { major: 2, minor: 38 };
8
8
  * Controller:
9
9
  * 1. locator.locate(startDir): not a repository, bare, or PATH_UNSUPPORTED log NOT_ELIGIBLE, exit 5.
10
10
  * 2. Git older than 2.38: NOT_ELIGIBLE (GIT_TOO_OLD), exit 5.
11
- * 3. parseConfig of <root>/enmetu.config.json: ConfigError logs CONFIG_INVALID, exit 2.
11
+ * 3. parseConfig of <root>/enmetu.config.json and readGitConfig(paths), git
12
+ * config overriding the file (design 14.18): ConfigError logs
13
+ * CONFIG_INVALID naming the file or the git config key and scope, exit 2;
14
+ * each unknown key of the file, each key of the file only git config may
15
+ * set and each unknown enmetu.* key of git config logs CONFIG_KEY_IGNORED
16
+ * once and is ignored (design 14.17); each setting git config set logs
17
+ * CONFIG_FROM_GIT with its scope.
12
18
  * 4. createDaemon(paths, config).run(), its exit code returned.
13
19
  */
14
20
  export async function runCommand(input, deps) {
@@ -34,26 +40,66 @@ export async function runCommand(input, deps) {
34
40
  if (olderThanMinimum(version)) {
35
41
  return notEligible(deps, 'GIT_TOO_OLD', `git ${version.major}.${version.minor}.${version.patch} is older than ${MIN_GIT_VERSION.major}.${MIN_GIT_VERSION.minor}`);
36
42
  }
37
- // --- Step 3: the config at the resolved root, defaults when absent ---
43
+ // --- Step 3: the config at the resolved root, then git config over it ---
38
44
  const configPath = join(paths.root, CONFIG_FILE_NAME);
39
- let config;
45
+ let parsed;
40
46
  try {
41
- config = parseConfig(await deps.fs.readText(configPath));
47
+ parsed = parseConfig(await deps.fs.readText(configPath), await deps.readGitConfig(paths));
42
48
  }
43
49
  catch (error) {
44
50
  if (!(error instanceof ConfigError)) {
45
51
  throw error;
46
52
  }
53
+ const source = error.gitScope === null
54
+ ? configPath
55
+ : `git config enmetu.${error.key ?? ''} (${error.gitScope})`;
47
56
  deps.logger.log({
48
57
  level: 'ERROR',
49
58
  code: 'CONFIG_INVALID',
50
- message: `${configPath}: ${error.code}: ${error.message}`,
59
+ message: `${source}: ${error.code}: ${error.message}`,
51
60
  });
52
61
  return { exitCode: EXIT.USAGE };
53
62
  }
63
+ logConfigSources(parsed, deps.logger);
64
+ const { config } = parsed;
54
65
  // --- Step 4: the daemon for this repository ---
55
66
  return { exitCode: await deps.createDaemon(paths, config).run() };
56
67
  }
68
+ /**
69
+ * Step 3's lines, before the daemon starts: what was ignored, then every
70
+ * setting git config set, so nobody wonders why one clone behaves differently.
71
+ */
72
+ function logConfigSources(parsed, logger) {
73
+ // A key only a newer enmetu knows must not stop this one (design 14.17).
74
+ for (const key of parsed.unknownKeys) {
75
+ logger.log({
76
+ level: 'WARN',
77
+ code: 'CONFIG_KEY_IGNORED',
78
+ message: `${CONFIG_FILE_NAME}: unknown setting "${key}", ignored`,
79
+ });
80
+ }
81
+ for (const key of parsed.gitOnlyKeysInFile) {
82
+ logger.log({
83
+ level: 'WARN',
84
+ code: 'CONFIG_KEY_IGNORED',
85
+ message: `${CONFIG_FILE_NAME}: ${key} is read from git config only, ignored`,
86
+ });
87
+ }
88
+ for (const { key, scope } of parsed.unknownGitKeys) {
89
+ logger.log({
90
+ level: 'WARN',
91
+ code: 'CONFIG_KEY_IGNORED',
92
+ message: `git config (${scope}): unknown setting "${key}", ignored`,
93
+ });
94
+ }
95
+ for (const { key, scope, shown } of parsed.fromGit) {
96
+ logger.log({
97
+ level: 'INFO',
98
+ code: 'CONFIG_FROM_GIT',
99
+ message: `${key} ${shown} (git config, ${scope})`,
100
+ });
101
+ }
102
+ }
57
103
  function olderThanMinimum(version) {
58
104
  return (version.major < MIN_GIT_VERSION.major ||
59
105
  (version.major === MIN_GIT_VERSION.major &&
@@ -4,7 +4,6 @@ import { EXIT } from '../contracts/exitCode.js';
4
4
  const EXIT_CODE_BY_ERROR = {
5
5
  USAGE: EXIT.USAGE,
6
6
  CONFIG_INVALID_JSON: EXIT.USAGE,
7
- CONFIG_UNKNOWN_KEY: EXIT.USAGE,
8
7
  CONFIG_INVALID_VALUE: EXIT.USAGE,
9
8
  HALTED: EXIT.HALTED,
10
9
  LOCK_HELD: EXIT.LOCKED,
package/dist/cli.js CHANGED
@@ -26,6 +26,8 @@ const runtime = {
26
26
  // an empty path, finds no CLI there and lets commits through (fail open).
27
27
  cliPath: process.argv[1] ?? '',
28
28
  version: packageVersion(),
29
+ platform: process.platform,
30
+ engine: process.versions.bun === undefined ? 'node' : 'bun',
29
31
  stdout: process.stdout,
30
32
  stderr: process.stderr,
31
33
  };
@@ -1,14 +1,17 @@
1
- import type { StagedSelectionMode } from '../contracts/config.js';
2
1
  import type { IClock } from '../contracts/IClock.js';
2
+ import type { ICommitMessageCommand } from '../contracts/ICommitMessageCommand.js';
3
3
  import type { IFileSystem } from '../contracts/IFileSystem.js';
4
4
  import type { IGitCommitter, IGitHookRunner } from '../contracts/IGitCommitter.js';
5
5
  import type { IGitIndexLock } from '../contracts/IGitIndexLock.js';
6
6
  import type { IGitReader } from '../contracts/IGitReader.js';
7
7
  import type { IGitWriter } from '../contracts/IGitWriter.js';
8
+ import type { IHostMessageWriter } from '../contracts/IHostMessageWriter.js';
8
9
  import type { ILogger } from '../contracts/ILogger.js';
9
10
  import type { CommitMemory, WaitReason } from '../contracts/syncTypes.js';
10
11
  /** An unchanged tree a hook rejected is offered to the hooks again after this long (design 12.7). */
11
12
  export declare const HOOK_RETRY_MS = 600000;
13
+ /** commitMessageCommand reads at most this much of the patch on stdin (design 14.18). */
14
+ export declare const MESSAGE_PATCH_CAP_BYTES = 65536;
12
15
  export interface CommitLocalChangesInput {
13
16
  readonly cycleId: string;
14
17
  readonly memory: CommitMemory;
@@ -32,9 +35,11 @@ export interface CommitIndexGit {
32
35
  }
33
36
  export interface CommitSettings {
34
37
  readonly commitSubject: string;
38
+ /** null: the message is commitSubject alone (design 14.18). */
39
+ readonly commitMessageCommand: string | null;
35
40
  readonly skipJsonCheck: readonly string[];
36
- readonly stagedSelection: StagedSelectionMode;
37
- readonly stagedSelectionMaxWaitMs: number | null;
41
+ /** How long a partial staging holds the commit back; 0 commits at once (design 14.17). */
42
+ readonly partialStagingWaitMs: number;
38
43
  readonly commitHooks: boolean;
39
44
  /** <gitDir>/index, copied to seed the commit index with its stat data. */
40
45
  readonly realIndex: string;
@@ -50,6 +55,10 @@ export interface CommitLocalChangesDeps {
50
55
  /** Hooks on the real index: post-commit and post-index-change run after the branch moved. */
51
56
  readonly realHooks: IGitHookRunner;
52
57
  readonly indexLock: IGitIndexLock;
58
+ /** Runs commitMessageCommand; called only when it is set (design 14.18). */
59
+ readonly messageCommand: ICommitMessageCommand;
60
+ /** The host program's writer (library option commitMessage); null for the CLI (design 14.19). */
61
+ readonly hostMessage: IHostMessageWriter | null;
53
62
  readonly fs: IFileSystem;
54
63
  readonly logger: ILogger;
55
64
  /** NullLogger from the root: the residue build must not log EXCLUDED a second time. */
@@ -93,9 +102,10 @@ export type CommitLocalChanges = (input: CommitLocalChangesInput) => Promise<Com
93
102
  * differs and memory.lastMove is set, repairStaleIndexController first
94
103
  * (Decision 98): moved, repaired or reverted (Decision 108) forgets lastMove; repaired reads
95
104
  * before and the verdict again, so a stale index is never taken for a
96
- * person's selection. "wait"
97
- * without a reached cap returns waiting PARTIAL_SELECTION_STAGED; a reached
98
- * cap logs SELECTION_WAIT_ENDED and goes on; "commit" goes on.
105
+ * person's selection. While less than partialStagingWaitMs has passed
106
+ * since memory.partialStagingSince (the first cycle that saw the staging)
107
+ * it returns waiting PARTIAL_SELECTION_STAGED; once it has passed it logs
108
+ * SELECTION_WAIT_ENDED and goes on; 0 goes on at once (design 14.17).
99
109
  * 2. Build: parent = git.headCommit(); fs.copy(realIndex, commit index);
100
110
  * committer.seedFrom(parent); stageGuardedChanges on the commit index.
101
111
  * Nothing staged returns nothing.
@@ -105,9 +115,20 @@ export type CommitLocalChanges = (input: CommitLocalChangesInput) => Promise<Com
105
115
  * 4. commitHooks: pre-commit on the commit index (rejected, timed out or
106
116
  * killed: HOOK_REJECTED, waiting, rejection remembered); then re-stage and
107
117
  * write the tree again, so a formatter's rewrite is in this commit. The
108
- * message is commitSubject plus a newline, with or without hooks; the
109
118
  * message hooks do not run (Decision 80). The re-stage logs through
110
119
  * residueLogger: its EXCLUDED lines repeat the first build's.
120
+ * 4b. The message (design 14.18, 14.19), before index.lock, so no writer
121
+ * ever holds up a person's git. The command's message: when
122
+ * commitMessageCommand is set, messageCommand runs with
123
+ * git.patch(parent, tree, MESSAGE_PATCH_CAP_BYTES) on stdin and
124
+ * messageFromText turns its stdout into the message; a failed patch, a
125
+ * failed command or output messageFromText refuses log one
126
+ * MESSAGE_COMMAND_FAILED line and give none. Without hostMessage: the
127
+ * command's message, else commitSubject plus a newline. With hostMessage:
128
+ * its write decides, given a runCommand that yields the command's message,
129
+ * run at most once however often it is called; declined is commitSubject;
130
+ * failed, or text messageFromText refuses, logs MESSAGE_WRITER_FAILED and
131
+ * is commitSubject.
111
132
  * 5. commit = committer.commitTree({ tree, parent, message, sign: gitBoolean(commit.gpgSign) }).
112
133
  * 6. Critical section: indexLock.acquire(commit) (false: busy);
113
134
  * 6.1 repositoryState() with an operation: release, paused; HEAD naming
@@ -1,10 +1,12 @@
1
1
  import { EnmetuError, GitCommandError } from '../contracts/errors.js';
2
2
  import { withLastMove } from '../core/commit/commitMemory.js';
3
- import { gitBoolean } from '../core/commit/commitMessage.js';
3
+ import { gitBoolean, messageFromText } from '../core/commit/commitMessage.js';
4
4
  import { repairStaleIndexController } from './repairStaleIndexController.js';
5
5
  import { stageGuardedChanges } from './stageGuardedChanges.js';
6
6
  /** An unchanged tree a hook rejected is offered to the hooks again after this long (design 12.7). */
7
7
  export const HOOK_RETRY_MS = 600000;
8
+ /** commitMessageCommand reads at most this much of the patch on stdin (design 14.18). */
9
+ export const MESSAGE_PATCH_CAP_BYTES = 65536;
8
10
  /**
9
11
  * Controller: enmetu's commit without touching the person's index (design
10
12
  * 12.7, Decisions 72 to 74, 80, 81).
@@ -15,9 +17,10 @@ export const HOOK_RETRY_MS = 600000;
15
17
  * differs and memory.lastMove is set, repairStaleIndexController first
16
18
  * (Decision 98): moved, repaired or reverted (Decision 108) forgets lastMove; repaired reads
17
19
  * before and the verdict again, so a stale index is never taken for a
18
- * person's selection. "wait"
19
- * without a reached cap returns waiting PARTIAL_SELECTION_STAGED; a reached
20
- * cap logs SELECTION_WAIT_ENDED and goes on; "commit" goes on.
20
+ * person's selection. While less than partialStagingWaitMs has passed
21
+ * since memory.partialStagingSince (the first cycle that saw the staging)
22
+ * it returns waiting PARTIAL_SELECTION_STAGED; once it has passed it logs
23
+ * SELECTION_WAIT_ENDED and goes on; 0 goes on at once (design 14.17).
21
24
  * 2. Build: parent = git.headCommit(); fs.copy(realIndex, commit index);
22
25
  * committer.seedFrom(parent); stageGuardedChanges on the commit index.
23
26
  * Nothing staged returns nothing.
@@ -27,9 +30,20 @@ export const HOOK_RETRY_MS = 600000;
27
30
  * 4. commitHooks: pre-commit on the commit index (rejected, timed out or
28
31
  * killed: HOOK_REJECTED, waiting, rejection remembered); then re-stage and
29
32
  * write the tree again, so a formatter's rewrite is in this commit. The
30
- * message is commitSubject plus a newline, with or without hooks; the
31
33
  * message hooks do not run (Decision 80). The re-stage logs through
32
34
  * residueLogger: its EXCLUDED lines repeat the first build's.
35
+ * 4b. The message (design 14.18, 14.19), before index.lock, so no writer
36
+ * ever holds up a person's git. The command's message: when
37
+ * commitMessageCommand is set, messageCommand runs with
38
+ * git.patch(parent, tree, MESSAGE_PATCH_CAP_BYTES) on stdin and
39
+ * messageFromText turns its stdout into the message; a failed patch, a
40
+ * failed command or output messageFromText refuses log one
41
+ * MESSAGE_COMMAND_FAILED line and give none. Without hostMessage: the
42
+ * command's message, else commitSubject plus a newline. With hostMessage:
43
+ * its write decides, given a runCommand that yields the command's message,
44
+ * run at most once however often it is called; declined is commitSubject;
45
+ * failed, or text messageFromText refuses, logs MESSAGE_WRITER_FAILED and
46
+ * is commitSubject.
33
47
  * 5. commit = committer.commitTree({ tree, parent, message, sign: gitBoolean(commit.gpgSign) }).
34
48
  * 6. Critical section: indexLock.acquire(commit) (false: busy);
35
49
  * 6.1 repositoryState() with an operation: release, paused; HEAD naming
@@ -73,24 +87,22 @@ export async function commitLocalChangesController(input, deps) {
73
87
  }
74
88
  }
75
89
  let since = null;
76
- if (staged) {
77
- if (settings.stagedSelection === 'wait') {
78
- since = memory.stagedSelectionSince ?? now;
79
- const cap = settings.stagedSelectionMaxWaitMs;
80
- if (cap === null || now - since < cap) {
81
- return {
82
- kind: 'waiting',
83
- reason: 'PARTIAL_SELECTION_STAGED',
84
- memory: rememberSince(memory, since),
85
- };
86
- }
87
- deps.logger.log({
88
- level: 'WARN',
89
- code: 'SELECTION_WAIT_ENDED',
90
- message: `a staged selection waited ${cap} ms, the configured cap; committing everything, the selection included`,
91
- cycleId,
92
- });
90
+ const wait = settings.partialStagingWaitMs;
91
+ if (staged && wait > 0) {
92
+ since = memory.partialStagingSince ?? now;
93
+ if (now - since < wait) {
94
+ return {
95
+ kind: 'waiting',
96
+ reason: 'PARTIAL_SELECTION_STAGED',
97
+ memory: rememberSince(memory, since),
98
+ };
93
99
  }
100
+ deps.logger.log({
101
+ level: 'WARN',
102
+ code: 'SELECTION_WAIT_ENDED',
103
+ message: `a staged selection waited ${wait} ms, the configured cap; committing everything, the selection included`,
104
+ cycleId,
105
+ });
94
106
  }
95
107
  const unchanged = rememberSince(memory, since);
96
108
  // --- Step 2: build on the commit index, seeded from HEAD ---
@@ -131,7 +143,7 @@ export async function commitLocalChangesController(input, deps) {
131
143
  kind: 'waiting',
132
144
  reason: 'COMMIT_HOOK_REJECTED',
133
145
  memory: {
134
- stagedSelectionSince: since,
146
+ partialStagingSince: since,
135
147
  rejection: { tree, at: now },
136
148
  residueTree: memory.residueTree,
137
149
  lastMove: memory.lastMove,
@@ -149,12 +161,15 @@ export async function commitLocalChangesController(input, deps) {
149
161
  }
150
162
  tree = await deps.commitIndex.committer.writeTree();
151
163
  }
164
+ // --- Step 4b: the message, outside the lock ---
165
+ const message = await commitMessage(parent, tree, cycleId, deps);
152
166
  // --- Step 5: the commit object; HEAD is its only parent, never MERGE_HEAD ---
153
- // The subject is the whole message: no path ever reaches it (D1).
167
+ // enmetu itself puts no path into the message (D1); a person's
168
+ // commitMessageCommand may (design 14.18).
154
169
  const commit = await deps.commitIndex.committer.commitTree({
155
170
  tree,
156
171
  parent,
157
- message: `${settings.commitSubject}\n`,
172
+ message,
158
173
  sign: gitBoolean(await deps.git.configValue('commit.gpgSign')),
159
174
  });
160
175
  // --- Step 6: critical section under git's own index.lock ---
@@ -178,7 +193,7 @@ export async function commitLocalChangesController(input, deps) {
178
193
  return {
179
194
  kind: 'committed',
180
195
  memory: {
181
- stagedSelectionSince: null,
196
+ partialStagingSince: null,
182
197
  rejection: null,
183
198
  residueTree,
184
199
  lastMove: { from: parent, to: commit },
@@ -213,6 +228,99 @@ async function runPostCommitHooks(commit, tree, cycleId, deps) {
213
228
  const residue = await deps.commitIndex.committer.writeTree();
214
229
  return residue === tree ? null : residue;
215
230
  }
231
+ /**
232
+ * Step 4b (design 14.18, 14.19): the message. Without a host writer, the
233
+ * person's commitMessageCommand's, else commitSubject. With one, the
234
+ * writer's: it decides, and the person's command runs only when the writer
235
+ * asks for it, at most once. Messages are optional and cosmetic, so nothing
236
+ * about them ever stops a commit: every failure falls back to commitSubject
237
+ * with one line.
238
+ */
239
+ async function commitMessage(parent, tree, cycleId, deps) {
240
+ const subjectOnly = `${deps.settings.commitSubject}\n`;
241
+ if (deps.hostMessage === null) {
242
+ return (await commandMessage(parent, tree, cycleId, deps)) ?? subjectOnly;
243
+ }
244
+ let command = null;
245
+ const run = await deps.hostMessage.write({
246
+ parent,
247
+ tree,
248
+ runCommand: () => {
249
+ command ??= commandMessage(parent, tree, cycleId, deps);
250
+ return command;
251
+ },
252
+ });
253
+ if (run.kind === 'declined') {
254
+ return subjectOnly;
255
+ }
256
+ let failure;
257
+ if (run.kind === 'failed') {
258
+ failure = run.detail;
259
+ }
260
+ else {
261
+ const parsed = messageFromText(run.text);
262
+ if (parsed.kind === 'message') {
263
+ return parsed.message;
264
+ }
265
+ failure = `returned ${parsed.reason}`;
266
+ }
267
+ deps.logger.log({
268
+ level: 'WARN',
269
+ code: 'MESSAGE_WRITER_FAILED',
270
+ message: `the host program's commitMessage ${failure}; committing with commitSubject`,
271
+ cycleId,
272
+ });
273
+ return subjectOnly;
274
+ }
275
+ /**
276
+ * commitMessageCommand on the patch from the parent to the tree (design
277
+ * 14.18, Decision 131): its message, or null when the setting is unset or
278
+ * anything failed, a failure logged once as MESSAGE_COMMAND_FAILED naming
279
+ * what comes instead: commitSubject, or the host writer's own message.
280
+ */
281
+ async function commandMessage(parent, tree, cycleId, deps) {
282
+ const { commitMessageCommand } = deps.settings;
283
+ if (commitMessageCommand === null) {
284
+ return null;
285
+ }
286
+ let failure;
287
+ try {
288
+ const stdin = await deps.git.patch(parent, tree, MESSAGE_PATCH_CAP_BYTES);
289
+ const run = await deps.messageCommand.run({
290
+ command: commitMessageCommand,
291
+ stdin,
292
+ parent,
293
+ tree,
294
+ });
295
+ if (run.kind === 'failed') {
296
+ failure = run.detail;
297
+ }
298
+ else {
299
+ const parsed = messageFromText(run.stdout);
300
+ if (parsed.kind === 'message') {
301
+ return parsed.message;
302
+ }
303
+ failure = `printed ${parsed.reason}`;
304
+ }
305
+ }
306
+ catch (error) {
307
+ if (!(error instanceof GitCommandError)) {
308
+ throw error;
309
+ }
310
+ failure = `got no patch (${error.message})`;
311
+ }
312
+ // With a host writer the fallback is the writer's, not commitSubject.
313
+ const next = deps.hostMessage === null
314
+ ? 'committing with commitSubject'
315
+ : "the host program's commitMessage writes the message";
316
+ deps.logger.log({
317
+ level: 'WARN',
318
+ code: 'MESSAGE_COMMAND_FAILED',
319
+ message: `commitMessageCommand ${failure}; ${next}`,
320
+ cycleId,
321
+ });
322
+ return null;
323
+ }
216
324
  /**
217
325
  * Step 2 of the chain: copy the real index (git's stat data and skip-worktree
218
326
  * bits, so add -A does not re-hash every file), seed it with the commit's
@@ -347,7 +455,7 @@ async function rollBack(branchRef, commit, parent, cycleId, deps) {
347
455
  }
348
456
  function rememberSince(memory, since) {
349
457
  return {
350
- stagedSelectionSince: since,
458
+ partialStagingSince: since,
351
459
  rejection: memory.rejection,
352
460
  residueTree: memory.residueTree,
353
461
  lastMove: memory.lastMove,
@@ -0,0 +1,32 @@
1
+ export interface CommitMessageCommandInput {
2
+ /** commitMessageCommand, run by the shell in the repository root. */
3
+ readonly command: string;
4
+ /** Written to the command's stdin, then stdin is closed. */
5
+ readonly stdin: Buffer;
6
+ /** The commit's parent, as ENMETU_PARENT. */
7
+ readonly parent: string;
8
+ /** The commit's tree, as ENMETU_TREE. */
9
+ readonly tree: string;
10
+ }
11
+ export type CommitMessageCommandRun =
12
+ /** Exit code 0; stdout up to the output cap. */
13
+ {
14
+ readonly kind: 'printed';
15
+ readonly stdout: string;
16
+ }
17
+ /**
18
+ * Not started, a non-zero exit, a signal, the time limit, or a stop
19
+ * request; detail says which, with the first line of stderr when there is one.
20
+ */
21
+ | {
22
+ readonly kind: 'failed';
23
+ readonly detail: string;
24
+ };
25
+ /**
26
+ * Runs commitMessageCommand for one commit (design 14.18): a shell command
27
+ * leading its own process group, ended with the whole group at the time
28
+ * limit or a stop request. Never throws.
29
+ */
30
+ export interface ICommitMessageCommand {
31
+ run(input: CommitMessageCommandInput): Promise<CommitMessageCommandRun>;
32
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,8 @@
1
- /** The one git question the hook installer needs; it cannot write configuration through it. */
1
+ import type { GitConfigEntry } from './config.js';
2
+ /** The git config questions enmetu asks; it cannot write configuration through it. */
2
3
  export interface IGitConfigReader {
3
4
  /** null when unset at every scope. */
4
5
  configValue(key: string): Promise<string | null>;
6
+ /** Every enmetu.* entry at every scope, in git's reading order; none set: empty (design 14.18). */
7
+ enmetuEntries(): Promise<readonly GitConfigEntry[]>;
5
8
  }
@@ -78,4 +78,9 @@ export interface IGitReader extends IGitConfigReader {
78
78
  mergeBase(left: string, right: string): Promise<string | null>;
79
79
  /** Root-relative paths that differ between two commits, a rename being a delete plus an add, in git's order. */
80
80
  changedPaths(from: string, to: string): Promise<readonly string[]>;
81
+ /**
82
+ * `git diff-tree -p` from a commit to a tree, without colour, external
83
+ * diffs or textconv; the first maxBytes bytes, the rest dropped (design 14.18).
84
+ */
85
+ patch(from: string, toTree: string, maxBytes: number): Promise<Buffer>;
81
86
  }
@@ -0,0 +1,28 @@
1
+ export interface HostMessageInput {
2
+ readonly parent: string;
3
+ readonly tree: string;
4
+ /** The person's command for this change, its message or null; see CommitChange.runCommand. */
5
+ readonly runCommand: () => Promise<string | null>;
6
+ }
7
+ export type HostMessageRun =
8
+ /** The writer returned text; enmetu still checks that it holds a subject. */
9
+ {
10
+ readonly kind: 'wrote';
11
+ readonly text: string;
12
+ }
13
+ /** The writer returned null: commitSubject, nothing logged. */
14
+ | {
15
+ readonly kind: 'declined';
16
+ }
17
+ /** A throw, the time limit, a stop request or a value that is neither text nor null. */
18
+ | {
19
+ readonly kind: 'failed';
20
+ readonly detail: string;
21
+ };
22
+ /**
23
+ * The host program's commit message writer (EnmetuStartOptions.commitMessage)
24
+ * with its time limit, behind one call that never throws (design 14.19).
25
+ */
26
+ export interface IHostMessageWriter {
27
+ write(input: HostMessageInput): Promise<HostMessageRun>;
28
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -3,7 +3,11 @@ export interface RepositoryPaths {
3
3
  readonly root: string;
4
4
  /** Per worktree; state files live under it. */
5
5
  readonly gitDir: string;
6
- /** Effective hooks directory (honours core.hooksPath). */
6
+ /**
7
+ * The repository's own hooks directory, <git common dir>/hooks, whatever
8
+ * core.hooksPath says; git runs hooks from it only while core.hooksPath is
9
+ * unset, which is also the only case the installer writes there (design 14.17).
10
+ */
7
11
  readonly hooksDir: string;
8
12
  /** <gitDir>/enmetu */
9
13
  readonly stateDir: string;