@mark1russell7/conventions 0.37.0 → 0.37.2

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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawnSync } from "node:child_process";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
4
4
  import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
5
5
  import { createHash } from "node:crypto";
6
6
  import { parseAllDocuments } from "yaml";
@@ -12,7 +12,7 @@ const RULE_FIELDS = [
12
12
  "generated",
13
13
  "reason"
14
14
  ];
15
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16
16
  const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
17
17
  /** This function gives the options of a rule with their defaults. */
18
18
  function defaultOptions(rule) {
@@ -32,18 +32,18 @@ function parseConfig(value, rules) {
32
32
  options: defaultOptions(rule)
33
33
  };
34
34
  if (value === void 0) return { rules: result };
35
- if (!isObject(value)) throw new Error("The field conventions of package.json must be an object.");
35
+ if (!isObject$1(value)) throw new Error("The field conventions of package.json must be an object.");
36
36
  const unknown = Object.keys(value).filter((key) => key !== "packages" && key !== "rules" && key !== "$comment");
37
37
  if (unknown.length > 0) throw new Error(`conventions has unknown fields: ${unknown.join(", ")}.`);
38
38
  const packages = value["packages"];
39
39
  if (packages !== void 0 && !isStrings(packages)) throw new Error("conventions.packages must be an array of globs.");
40
40
  const rulesValue = value["rules"] ?? {};
41
- if (!isObject(rulesValue)) throw new Error("conventions.rules must be an object, with a rule id for each key.");
41
+ if (!isObject$1(rulesValue)) throw new Error("conventions.rules must be an object, with a rule id for each key.");
42
42
  for (const [id, entry] of Object.entries(rulesValue)) {
43
43
  const rule = byId.get(id);
44
44
  if (rule === void 0) throw new Error(`conventions.rules has an unknown rule: ${id}. The rules are: ${[...byId.keys()].join(", ")}.`);
45
45
  const where = `conventions.rules["${id}"]`;
46
- if (!isObject(entry)) throw new Error(`${where} must be an object, for example { "off": "<reason>" }.`);
46
+ if (!isObject$1(entry)) throw new Error(`${where} must be an object, for example { "off": "<reason>" }.`);
47
47
  const off = entry["off"];
48
48
  if (off !== void 0 && (typeof off !== "string" || off.trim() === "")) throw new Error(`${where}.off must be the reason why the rule is off, as text.`);
49
49
  const ignore = entry["ignore"] ?? [];
@@ -9432,12 +9432,280 @@ const noBuildOutput = {
9432
9432
  }));
9433
9433
  }
9434
9434
  };
9435
+ // src/private-names.ts
9436
+ /**
9437
+ * The private name list: a JSON file outside of the public repositories, with the names of private projects. The file
9438
+ * `schema/private-names.schema.json` tells its form. This module parses the list and finds its names in a line or in a
9439
+ * path. It has no input or output.
9440
+ *
9441
+ * A result tells the place of a name by its index in the list, for example `name 3 of the private name list`. A result
9442
+ * does not show the text, the id, the project or a pattern, because the id of a name is the private name.
9443
+ */
9444
+ /** The name of the private name list in a break and in an error. A break does not show the path of the file. */
9445
+ const PRIVATE_NAME_LIST = "the private name list";
9446
+ /**
9447
+ * This error tells that a private name list is not valid. Its reason names a field by the index of its entry, and
9448
+ * does not show a value of the list.
9449
+ */
9450
+ var PrivateNameListError = class extends Error {
9451
+ /** The reason, for example `name 3 of the private name list: the field seeds has no text`. */
9452
+ reason;
9453
+ constructor(reason) {
9454
+ super(`The private name list is not valid: ${reason}.`);
9455
+ this.name = "PrivateNameListError";
9456
+ this.reason = reason;
9457
+ }
9458
+ };
9459
+ /** The compiled names, by entry. The parse fills it, and a list of another source gets its entries on the first use. */
9460
+ const compiled = /* @__PURE__ */ new WeakMap();
9461
+ /** The form of a word: letters, digits, `_` and `-`. So the word is a literal in a regular expression. */
9462
+ const WORD = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
9463
+ /** The form of a word of `commonAfter`: lower-case letters. The check compares it with the next word in lower case. */
9464
+ const AFTER = /^[a-z]+$/;
9465
+ /** This function gives the compiled regular expressions of a name. */
9466
+ function compiledOf(rule) {
9467
+ const known = compiled.get(rule);
9468
+ if (known !== void 0) return known;
9469
+ const made = {
9470
+ patterns: rule.patterns.map((source) => new RegExp(source)),
9471
+ ...rule.word === void 0 || rule.word === "" ? {} : { word: new RegExp(`\\b${rule.word}\\b`, "g") }
9472
+ };
9473
+ compiled.set(rule, made);
9474
+ return made;
9475
+ }
9476
+ /** This function tells if a value is a list of texts that are not empty. */
9477
+ const isTexts = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item !== "");
9478
+ /** This function tells if a value is an object that is not a list. */
9479
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9480
+ /** This function gives the first field of `entry` that `known` does not have, or undefined. */
9481
+ const unknownField = (entry, known) => Object.keys(entry).find((key) => !known.includes(key));
9482
+ /** This function gives a name of the list after a check of its fields. The error names the entry by its index. */
9483
+ function nameOf(entry, at) {
9484
+ const fail = (reason) => {
9485
+ throw new PrivateNameListError(`${at}: ${reason}`);
9486
+ };
9487
+ if (!isObject(entry)) return fail("the entry is not an object");
9488
+ if (unknownField(entry, [
9489
+ "id",
9490
+ "project",
9491
+ "seeds",
9492
+ "patterns",
9493
+ "word",
9494
+ "commonAfter"
9495
+ ]) !== void 0) fail("the entry has a field that the schema does not have");
9496
+ const { id, project, seeds, patterns, word, commonAfter } = entry;
9497
+ if (typeof id !== "string" || id === "") fail("the field id is not a text");
9498
+ if (typeof project !== "string" || project === "") fail("the field project is not a text");
9499
+ if (!isTexts(seeds) || seeds.length === 0) fail("the field seeds is not a list of one or more texts");
9500
+ if (!isTexts(patterns)) fail("the field patterns is not a list of texts");
9501
+ if (word !== void 0 && (typeof word !== "string" || !WORD.test(word))) fail("the field word is not one word of letters, digits, _ and -");
9502
+ if (commonAfter !== void 0 && (!Array.isArray(commonAfter) || !commonAfter.every((item) => typeof item === "string" && AFTER.test(item)))) fail("the field commonAfter is not a list of lower-case words");
9503
+ if (commonAfter !== void 0 && word === void 0) fail("the field commonAfter has no field word");
9504
+ const rule = {
9505
+ id,
9506
+ project,
9507
+ seeds,
9508
+ patterns,
9509
+ ...word === void 0 ? {} : { word },
9510
+ ...commonAfter === void 0 ? {} : { commonAfter }
9511
+ };
9512
+ rule.patterns.forEach((source, index) => {
9513
+ try {
9514
+ new RegExp(source);
9515
+ } catch {
9516
+ fail(`pattern ${String(index + 1)} is not a valid regular expression`);
9517
+ }
9518
+ });
9519
+ compiledOf(rule);
9520
+ return rule;
9521
+ }
9522
+ /** This function gives an entry of the list `allow` after a check of its fields. */
9523
+ function allowedOf(entry, at, ids) {
9524
+ const fail = (reason) => {
9525
+ throw new PrivateNameListError(`${at}: ${reason}`);
9526
+ };
9527
+ if (!isObject(entry)) return fail("the entry is not an object");
9528
+ if (unknownField(entry, [
9529
+ "repo",
9530
+ "path",
9531
+ "name",
9532
+ "why"
9533
+ ]) !== void 0) fail("the entry has a field that the schema does not have");
9534
+ const { repo, path, name, why } = entry;
9535
+ if (typeof repo !== "string" || repo === "") fail("the field repo is not a text");
9536
+ if (typeof path !== "string" || path === "") fail("the field path is not a text");
9537
+ if (typeof why !== "string" || why === "") fail("the field why is not a text");
9538
+ if (name !== void 0 && (typeof name !== "string" || !ids.has(name))) fail("the field name is not the id of a name of the list");
9539
+ return {
9540
+ repo,
9541
+ path,
9542
+ why,
9543
+ ...name === void 0 ? {} : { name }
9544
+ };
9545
+ }
9546
+ /**
9547
+ * This function parses the text of a private name list, and checks it against the schema. It also checks each regular
9548
+ * expression and the ids. It throws a `PrivateNameListError` when the text is not valid. The error shows no value of the text.
9549
+ */
9550
+ function parsePrivateNames(text) {
9551
+ let data;
9552
+ try {
9553
+ data = JSON.parse(text);
9554
+ } catch {
9555
+ throw new PrivateNameListError("the text is not valid JSON");
9556
+ }
9557
+ if (!isObject(data)) throw new PrivateNameListError("the text is not a JSON object");
9558
+ if (unknownField(data, [
9559
+ "$schema",
9560
+ "$comment",
9561
+ "names",
9562
+ "allow"
9563
+ ]) !== void 0) throw new PrivateNameListError("the object has a field that the schema does not have");
9564
+ if (data["$comment"] !== void 0 && typeof data["$comment"] !== "string") throw new PrivateNameListError("the field $comment is not a text");
9565
+ const names = data["names"];
9566
+ const allow = data["allow"] ?? [];
9567
+ if (!Array.isArray(names)) throw new PrivateNameListError("the field names is not a list");
9568
+ if (!Array.isArray(allow)) throw new PrivateNameListError("the field allow is not a list");
9569
+ const rules = names.map((entry, index) => nameOf(entry, `name ${String(index + 1)} of ${PRIVATE_NAME_LIST}`));
9570
+ const ids = /* @__PURE__ */ new Set();
9571
+ rules.forEach((rule, index) => {
9572
+ if (ids.has(rule.id)) throw new PrivateNameListError(`name ${String(index + 1)} of ${PRIVATE_NAME_LIST}: the id is also the id of an earlier name`);
9573
+ ids.add(rule.id);
9574
+ });
9575
+ return {
9576
+ names: rules,
9577
+ allow: allow.map((entry, index) => allowedOf(entry, `allow entry ${String(index + 1)} of ${PRIVATE_NAME_LIST}`, ids))
9578
+ };
9579
+ }
9580
+ /** The words before a name in code: a declaration, a type or an operator. */
9581
+ const CODE_BEFORE = /\b(class|interface|type|new|extends|implements|const|let|enum|struct|typeof|instanceof|as)\s+$/;
9582
+ /** A line of code that imports or exports names. */
9583
+ const CODE_LINE = /^\s*(import|export)\b/;
9584
+ /** The words before a common noun: an article or a count. */
9585
+ const COUNT_BEFORE = /\b(a|an|any|each|every|one|our|this|your)\s+$/i;
9586
+ /** A word with a capital letter before the word: a title, or a name of more words. */
9587
+ const TITLE_BEFORE = /[A-Z][\w-]*\s+$/;
9588
+ /** The words with a capital letter that start a sentence part, not a title. */
9589
+ const WORD_BEFORE = /\b(And|By|For|From|In|Of|See|To|With)\s+$/;
9590
+ /**
9591
+ * This function tells if the word of `rule` at `index` of `line` is a common word or code, and not the name of the
9592
+ * project. Code is a type, a key or a part of a path. A common word comes after an article, in a title or before a noun.
9593
+ */
9594
+ function isCommonUse(line, index, rule) {
9595
+ const word = rule.word ?? "";
9596
+ const before = line.slice(0, index);
9597
+ const after = line.slice(index + word.length);
9598
+ if (/^\s*[\]>{};]/.test(after) || /["[]$/.test(before) || /=>\s*$/.test(before)) return true;
9599
+ if (/^[<([{]/.test(after) || /^\.\w/.test(after) || after.startsWith("::") || /^:\s*[{[(]/.test(after)) return true;
9600
+ if (/^[-/]/.test(after) || /[-/]$/.test(before)) return true;
9601
+ if (/[<.]$/.test(before)) return true;
9602
+ if (CODE_BEFORE.test(before) || CODE_LINE.test(line)) return true;
9603
+ if (/[`'"]$/.test(before) && /^[`'"]/.test(after)) return true;
9604
+ if (/[\w)\]?]:\s*$/.test(before) && /^\s*([,;)=|&>]|$)/.test(after)) return true;
9605
+ if (COUNT_BEFORE.test(before)) return true;
9606
+ if (TITLE_BEFORE.test(before) && !WORD_BEFORE.test(before)) return true;
9607
+ const next = /^\s+([A-Za-z]+)/.exec(after)?.[1];
9608
+ if (next === void 0) return false;
9609
+ return /^[A-Z][a-z]/.test(next) || (rule.commonAfter ?? []).includes(next.toLowerCase());
9610
+ }
9611
+ /**
9612
+ * This function gives the first name of `names` in `line`, or undefined. For each name in sequence, a pattern match is
9613
+ * a hit. A match of the word is a hit when `isCommonUse` is false. It does not use the seeds or the list `allow`.
9614
+ */
9615
+ function firstNameMatch(line, names) {
9616
+ for (let at = 0; at < names.length; at++) {
9617
+ const hit = nameMatch(line, names, at);
9618
+ if (hit !== void 0) return hit;
9619
+ }
9620
+ }
9621
+ /**
9622
+ * This function gives each name of `names` in `line`, in the sequence of the list. Each name gives one hit at most: its
9623
+ * first pattern match, or else its first word match that is not a common use.
9624
+ */
9625
+ function nameMatches(line, names) {
9626
+ const hits = [];
9627
+ for (let at = 0; at < names.length; at++) {
9628
+ const hit = nameMatch(line, names, at);
9629
+ if (hit !== void 0) hits.push(hit);
9630
+ }
9631
+ return hits;
9632
+ }
9633
+ /** This function gives the hit of the name at position `at` of `names` in `line`, or undefined. */
9634
+ function nameMatch(line, names, at) {
9635
+ const rule = names[at];
9636
+ if (rule === void 0) return void 0;
9637
+ const { patterns, word } = compiledOf(rule);
9638
+ for (const pattern of patterns) {
9639
+ const found = pattern.exec(line);
9640
+ if (found !== null) return {
9641
+ name: at + 1,
9642
+ rule,
9643
+ index: found.index
9644
+ };
9645
+ }
9646
+ if (word === void 0) return void 0;
9647
+ for (const found of line.matchAll(word)) if (!isCommonUse(line, found.index, rule)) return {
9648
+ name: at + 1,
9649
+ rule,
9650
+ index: found.index
9651
+ };
9652
+ }
9653
+ /** This function gives the name part of a repository: `name` for `owner/name`, in lower case. */
9654
+ const repoName = (repo) => (repo.split("/").at(-1) ?? repo).toLowerCase();
9655
+ /**
9656
+ * This function tells if the list `allow` permits the name `id` in the file `path` of the repository `repo`. An entry
9657
+ * with the repository `name` or `owner/name` matches the repository `owner/name`. Case of a repository is not significant.
9658
+ */
9659
+ function isAllowedHit(allow, repo, path, id) {
9660
+ const full = repo.toLowerCase();
9661
+ return allow.some((entry) => {
9662
+ const named = entry.repo.toLowerCase();
9663
+ return (named.includes("/") ? named === full : named === repoName(repo)) && entry.path === path && (entry.name === void 0 || entry.name === id);
9664
+ });
9665
+ }
9666
+ /**
9667
+ * This function gives each name of the list in one line of a file or of a message, in the sequence of the list. The line
9668
+ * must have a seed of the list. Each name gives one hit at most. A permitted hit at the place does not count.
9669
+ */
9670
+ function lineNameHits(list, line, place = {}) {
9671
+ if (!list.names.some((rule) => rule.seeds.some((seed) => line.includes(seed)))) return [];
9672
+ const { repo, path } = place;
9673
+ const hits = nameMatches(line, list.names);
9674
+ if (repo === void 0 || path === void 0) return hits;
9675
+ return hits.filter((hit) => !isAllowedHit(list.allow, repo, path, hit.rule.id));
9676
+ }
9677
+ /**
9678
+ * This function gives the first name of the list in one line of a file or of a message, or undefined. It is the first
9679
+ * hit of `lineNameHits`, so a permitted hit does not hide a hit of another name.
9680
+ */
9681
+ function lineNameHit(list, line, place = {}) {
9682
+ return lineNameHits(list, line, place)[0];
9683
+ }
9684
+ /**
9685
+ * This function gives the first name of the list whose pattern matches a path of a file, or undefined. Only the patterns
9686
+ * apply, because a path has no sentence. The seeds and the list `allow` do not apply.
9687
+ */
9688
+ function pathNameHit(list, path) {
9689
+ for (let at = 0; at < list.names.length; at++) {
9690
+ const rule = list.names[at];
9691
+ if (rule === void 0) continue;
9692
+ const found = compiledOf(rule).patterns.map((pattern) => pattern.exec(path)).find((match) => match !== null);
9693
+ if (found !== void 0 && found !== null) return {
9694
+ name: at + 1,
9695
+ rule,
9696
+ index: found.index
9697
+ };
9698
+ }
9699
+ }
9435
9700
  // src/rules/no-local-paths.ts
9436
9701
  /**
9437
9702
  * The rule `no-local-paths`: no tracked file names the home folder of a user of a computer. The commit messages of a
9438
9703
  * change and the title and the body of its pull request do not name one either. The same is true for each private
9439
9704
  * pattern of the environment variable `CONVENTIONS_PRIVATE_PATTERNS`. A break of a private pattern does not show the
9440
9705
  * text or the pattern, because a public log must not name them.
9706
+ *
9707
+ * The module also has the core of the command `conventions pre-push`. The core has the setting of the private name list,
9708
+ * the private patterns and the breaks of one text.
9441
9709
  */
9442
9710
  /** The extensions of files that are not text. The rule does not read them. */
9443
9711
  const BINARY = new Set(".png .jpg .jpeg .gif .webp .avif .ico .bmp .tiff .pdf .zip .gz .tgz .bz2 .xz .7z .tar .woff .woff2 .ttf .otf .eot .mp3 .mp4 .webm .mov .wav .ogg .wasm .node .exe .dll .so .dylib .bin .db .sqlite .duckdb".split(" "));
@@ -9472,13 +9740,128 @@ const HOME_PATTERNS = [
9472
9740
  ];
9473
9741
  /** The name of the environment variable of the private patterns. */
9474
9742
  const PRIVATE_PATTERNS_VARIABLE = "CONVENTIONS_PRIVATE_PATTERNS";
9475
- /** This function gives the private patterns of the environment variable, with the line of each (from 1). */
9476
- function privatePatterns(env) {
9477
- return (env["CONVENTIONS_PRIVATE_PATTERNS"] ?? "").split("\n").map((source, index) => ({
9743
+ /** The name of the environment variable of the path of the private name list. */
9744
+ const PRIVATE_NAMES_FILE_VARIABLE = "CONVENTIONS_PRIVATE_NAMES_FILE";
9745
+ /** The key of the git configuration of the path of the private name list. */
9746
+ const PRIVATE_NAMES_FILE_CONFIG = "conventions.privateNamesFile";
9747
+ /** This function gives the regular expression of a pattern, or undefined when the pattern is not valid. */
9748
+ function compilePattern(source) {
9749
+ try {
9750
+ return new RegExp(source, "g");
9751
+ } catch {
9752
+ return;
9753
+ }
9754
+ }
9755
+ /** This function compiles the patterns of a check. A private pattern that is not valid has no matcher. */
9756
+ function compile(privates, options) {
9757
+ const extra = (options.patterns ?? []).map((source) => ({ regex: new RegExp(source, "g") }));
9758
+ for (const pattern of privates.patterns ?? []) {
9759
+ const regex = compilePattern(pattern.source);
9760
+ if (regex !== void 0) extra.push({
9761
+ regex,
9762
+ secret: pattern
9763
+ });
9764
+ }
9765
+ return {
9766
+ ...privates.names === void 0 ? {} : { names: privates.names },
9767
+ extra,
9768
+ allowed: new Set([...DEFAULT_ALLOWED, ...options.allow ?? []].map((name) => name.toLowerCase())),
9769
+ homes: options.homes !== false
9770
+ };
9771
+ }
9772
+ /** This function gives the breaks of one text with compiled patterns. */
9773
+ function textBreaks(name, text, matchers, options) {
9774
+ const breaks = [];
9775
+ const first = options.firstLine ?? 1;
9776
+ const lines = text.split(/\r?\n/);
9777
+ for (let index = 0; index < lines.length; index++) {
9778
+ const line = lines[index] ?? "";
9779
+ const at = first + index;
9780
+ const isReason = options.rootPackage === true && /^\s*"(?:reason|off)"\s*:/.test(line);
9781
+ if (matchers.homes && !isReason) for (const pattern of HOME_PATTERNS) for (const match of line.matchAll(pattern)) {
9782
+ const user = match.groups?.["user"] ?? "";
9783
+ if (user.length < 2 || matchers.allowed.has(user.toLowerCase())) continue;
9784
+ breaks.push({
9785
+ file: name,
9786
+ line: at,
9787
+ message: `The text "${match[0]}" is the home folder of a user.`
9788
+ });
9789
+ }
9790
+ if (matchers.names !== void 0) {
9791
+ const place = {
9792
+ ...options.repo === void 0 ? {} : { repo: options.repo },
9793
+ ...options.path === void 0 ? {} : { path: options.path }
9794
+ };
9795
+ const hit = options.isPath === true ? pathNameHit(matchers.names, line) : lineNameHit(matchers.names, line, place);
9796
+ if (hit !== void 0) breaks.push({
9797
+ file: name,
9798
+ line: at,
9799
+ message: `A text names name ${String(hit.name)} of ${PRIVATE_NAME_LIST}.`,
9800
+ fix: "Remove the text. The check does not show the text, because the name is private."
9801
+ });
9802
+ }
9803
+ for (const matcher of matchers.extra) {
9804
+ if (options.rootPackage === true && matcher.secret === void 0 && line.trim().replace(/,$/, "") === JSON.stringify(matcher.regex.source)) continue;
9805
+ for (const match of line.matchAll(matcher.regex)) breaks.push(matcher.secret === void 0 ? {
9806
+ file: name,
9807
+ line: at,
9808
+ message: `The text "${match[0]}" matches the pattern ${matcher.regex.source}.`,
9809
+ fix: "Remove the text."
9810
+ } : {
9811
+ file: name,
9812
+ line: at,
9813
+ message: `A text matches the private pattern on line ${String(matcher.secret.line)} of ${matcher.secret.label}.`,
9814
+ fix: "Remove the text. The check does not show the text, because the pattern is private."
9815
+ });
9816
+ }
9817
+ }
9818
+ return breaks;
9819
+ }
9820
+ /** This function gives the patterns of the lines of `text`, with the line of each (from 1). It skips empty lines. */
9821
+ function patternLines(text, label) {
9822
+ return text.split("\n").map((source, index) => ({
9478
9823
  source: source.trim(),
9479
- line: index + 1
9824
+ line: index + 1,
9825
+ label
9480
9826
  })).filter((pattern) => pattern.source !== "");
9481
9827
  }
9828
+ /** This function gives the private patterns of the environment variable, with the line of each (from 1). */
9829
+ function privatePatterns(env) {
9830
+ return patternLines(env["CONVENTIONS_PRIVATE_PATTERNS"] ?? "", PRIVATE_PATTERNS_VARIABLE);
9831
+ }
9832
+ /**
9833
+ * This function gives the path of the private name list: the environment variable `CONVENTIONS_PRIVATE_NAMES_FILE`,
9834
+ * else the git configuration `conventions.privateNamesFile`. It gives undefined when neither has a value.
9835
+ */
9836
+ function privateNamesFile(env, git) {
9837
+ const fromEnv = env["CONVENTIONS_PRIVATE_NAMES_FILE"]?.trim() ?? "";
9838
+ if (fromEnv !== "") return fromEnv;
9839
+ const fromGit = git([
9840
+ "config",
9841
+ "--type=path",
9842
+ "--get",
9843
+ "conventions.privateNamesFile"
9844
+ ])?.trim() ?? "";
9845
+ return fromGit === "" ? void 0 : fromGit;
9846
+ }
9847
+ /** This function gives a break for each private pattern that is not a valid regular expression. A break does not show the pattern. */
9848
+ function invalidPatternBreaks(patterns) {
9849
+ return patterns.filter((pattern) => compilePattern(pattern.source) === void 0).map((pattern) => ({
9850
+ file: pattern.label,
9851
+ line: pattern.line,
9852
+ message: `Line ${String(pattern.line)} of ${pattern.label} is not a valid regular expression.`,
9853
+ fix: "Correct the regular expression. The check does not show the pattern, because it is private."
9854
+ }));
9855
+ }
9856
+ /**
9857
+ * This function gives the breaks of one text: a file, a commit message or the body of a pull request. Each break has the
9858
+ * file `name`. A break of a private source does not show the text, the name or the pattern. A line has one break or no
9859
+ * break of the private name list. The breaks of home folders use `HOME_PATTERNS` and the permitted names. A private pattern
9860
+ * that is not valid gives no break here: refer to `invalidPatternBreaks`.
9861
+ */
9862
+ function privateTextBreaks(name, text, privates, options = {}) {
9863
+ return textBreaks(name, text, compile(privates, options), options);
9864
+ }
9482
9865
  /**
9483
9866
  * This function gives the texts of the change that are not files. They are each commit message of a pull request (or of the
9484
9867
  * range of `--base`). They are also the title and the body of the pull request, from the event file of GitHub Actions.
@@ -9564,41 +9947,16 @@ const noLocalPaths = {
9564
9947
  check(context, options) {
9565
9948
  const files = context.gitFiles();
9566
9949
  if (files === void 0) return { skipped: "the root is not in a git repository" };
9567
- const allowed = new Set([...DEFAULT_ALLOWED, ...Array.isArray(options["allow"]) ? options["allow"] : []].map((name) => name.toLowerCase()));
9568
- const extra = [...(Array.isArray(options["patterns"]) ? options["patterns"] : []).map((source) => ({ regex: new RegExp(source, "g") })), ...privatePatterns(context.env).map((pattern) => ({
9569
- regex: new RegExp(pattern.source, "g"),
9570
- privateLine: pattern.line
9571
- }))];
9572
- const rootFile = context.rootPackage.file;
9573
- const breaks = [];
9574
- /** This function adds the breaks of the extra patterns on one line. A break of a private pattern shows no text. */
9575
- const extraBreaks = (file, line, at, isRootFile) => {
9576
- for (const pattern of extra) {
9577
- if (isRootFile && pattern.privateLine === void 0 && line.trim().replace(/,$/, "") === JSON.stringify(pattern.regex.source)) continue;
9578
- for (const match of line.matchAll(pattern.regex)) breaks.push(pattern.privateLine === void 0 ? {
9579
- file,
9580
- line: at,
9581
- message: `The text "${match[0]}" matches the pattern ${pattern.regex.source}.`,
9582
- fix: "Remove the text."
9583
- } : {
9584
- file,
9585
- line: at,
9586
- message: `A text matches the private pattern on line ${String(pattern.privateLine)} of ${PRIVATE_PATTERNS_VARIABLE}.`,
9587
- fix: "Remove the text. The check does not show the text, because the pattern is private."
9588
- });
9589
- }
9950
+ const settings = {
9951
+ allow: Array.isArray(options["allow"]) ? [...options["allow"]] : [],
9952
+ patterns: Array.isArray(options["patterns"]) ? [...options["patterns"]] : []
9590
9953
  };
9591
- /** This function adds the breaks of the home folders on one line. */
9592
- const homeBreaks = (file, line, at) => {
9593
- for (const pattern of HOME_PATTERNS) for (const match of line.matchAll(pattern)) {
9594
- const user = match.groups?.["user"] ?? "";
9595
- if (user.length < 2 || allowed.has(user.toLowerCase())) continue;
9596
- breaks.push({
9597
- file,
9598
- line: at,
9599
- message: `The text "${match[0]}" is the home folder of a user.`
9600
- });
9601
- }
9954
+ const privates = privatePatterns(context.env);
9955
+ const matchers = compile({ patterns: privates }, settings);
9956
+ const rootFile = context.rootPackage.file;
9957
+ const breaks = invalidPatternBreaks(privates);
9958
+ const add = (items) => {
9959
+ for (const item of items) breaks.push(item);
9602
9960
  };
9603
9961
  for (const file of files) {
9604
9962
  if (BINARY.has(extname(file).toLowerCase())) continue;
@@ -9611,20 +9969,9 @@ const noLocalPaths = {
9611
9969
  continue;
9612
9970
  }
9613
9971
  if (text.includes("\0")) continue;
9614
- const lines = text.split(/\r?\n/);
9615
- for (let index = 0; index < lines.length; index++) {
9616
- const line = lines[index] ?? "";
9617
- if (!(file === rootFile && /^\s*"(?:reason|off)"\s*:/.test(line))) homeBreaks(file, line, index + 1);
9618
- extraBreaks(file, line, index + 1, file === rootFile);
9619
- }
9620
- }
9621
- for (const change of changeTexts(context)) {
9622
- const lines = change.text.split(/\r?\n/);
9623
- for (let index = 0; index < lines.length; index++) {
9624
- homeBreaks(change.name, lines[index] ?? "", index + 1);
9625
- extraBreaks(change.name, lines[index] ?? "", index + 1, false);
9626
- }
9972
+ add(textBreaks(file, text, matchers, { rootPackage: file === rootFile }));
9627
9973
  }
9974
+ for (const change of changeTexts(context)) add(textBreaks(change.name, change.text, matchers, {}));
9628
9975
  return breaks;
9629
9976
  }
9630
9977
  };
@@ -13166,10 +13513,409 @@ const RULES = [
13166
13513
  pagesAfterRelease,
13167
13514
  sharedDocs
13168
13515
  ];
13516
+ // src/pre-push.ts
13517
+ /**
13518
+ * The commands `conventions pre-push` and `conventions hook install`. The hook `pre-push` of git starts the first
13519
+ * command before each push. It examines the new commits of the push with the private name list, which is outside
13520
+ * of the public repositories. The second command writes that hook.
13521
+ */
13522
+ /** The line of `conventions pre-push` when no setting names a private name list and no environment variable has a pattern. */
13523
+ const NO_READ_LINE = `conventions pre-push: No read: no private name list. Set ${PRIVATE_NAMES_FILE_VARIABLE} or the git config ${PRIVATE_NAMES_FILE_CONFIG}.`;
13524
+ /** A sha of no commit: git gives it for a ref that the push deletes, or for a ref that the remote does not have. */
13525
+ const ZERO = /^0+$/;
13526
+ /** The form of a sha of a commit. */
13527
+ const SHA = /^[0-9a-f]{40,64}$/;
13528
+ /**
13529
+ * This function reads the settings of the rule `no-local-paths` in the root `package.json`: the state, the permitted names
13530
+ * and the globs of `ignore` and `generated`. They apply only to the home folders. A private pattern always counts.
13531
+ */
13532
+ function homeSettings(root, readFile) {
13533
+ try {
13534
+ const config = parseConfig(JSON.parse(readFile(join(root, "package.json")))["conventions"], RULES).rules["no-local-paths"];
13535
+ if (config === void 0) return {
13536
+ on: true,
13537
+ allow: [],
13538
+ ignore: []
13539
+ };
13540
+ const allow = config.options["allow"];
13541
+ return {
13542
+ on: config.off === void 0,
13543
+ allow: Array.isArray(allow) ? [...allow] : [],
13544
+ ignore: [...config.ignore, ...config.generated ?? []]
13545
+ };
13546
+ } catch {
13547
+ return {
13548
+ on: true,
13549
+ allow: [],
13550
+ ignore: []
13551
+ };
13552
+ }
13553
+ }
13554
+ /** This function gives the text of a path in a header of a patch, without the quotes of git. */
13555
+ function unquote(path) {
13556
+ if (!path.startsWith("\"") || !path.endsWith("\"")) return path;
13557
+ const bytes = [];
13558
+ const body = path.slice(1, -1);
13559
+ const escapes = {
13560
+ a: 7,
13561
+ b: 8,
13562
+ t: 9,
13563
+ n: 10,
13564
+ v: 11,
13565
+ f: 12,
13566
+ r: 13,
13567
+ "\"": 34,
13568
+ "\\": 92
13569
+ };
13570
+ for (let index = 0; index < body.length; index++) {
13571
+ if (body.charAt(index) !== "\\") {
13572
+ const char = String.fromCodePoint(body.codePointAt(index) ?? 0);
13573
+ bytes.push(...Buffer.from(char, "utf8"));
13574
+ index += char.length - 1;
13575
+ continue;
13576
+ }
13577
+ const octal = /^[0-7]{3}/.exec(body.slice(index + 1));
13578
+ if (octal !== null) {
13579
+ bytes.push(parseInt(octal[0], 8));
13580
+ index += 3;
13581
+ continue;
13582
+ }
13583
+ const next = body.charAt(index + 1);
13584
+ bytes.push(escapes[next] ?? next.charCodeAt(0));
13585
+ index += 1;
13586
+ }
13587
+ return Buffer.from(bytes).toString("utf8");
13588
+ }
13589
+ /**
13590
+ * This function gives the added lines of a patch of `git show --unified=0`, in runs of lines that follow each other.
13591
+ * It reads the counts of each hunk, so an added line that starts with `+++` is a line, not a header. It also reads the
13592
+ * combined patch of a merge commit, with one column of marks for each parent.
13593
+ */
13594
+ function addedRuns(patch) {
13595
+ const runs = [];
13596
+ let file;
13597
+ let columns = 1;
13598
+ let parentLeft = [];
13599
+ let resultLeft = 0;
13600
+ let next = 0;
13601
+ for (const raw of patch.split("\n")) {
13602
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
13603
+ if (line.startsWith("\\")) continue;
13604
+ if (resultLeft > 0 || parentLeft.some((count) => count > 0)) {
13605
+ const marks = line.slice(0, columns);
13606
+ const removed = marks.includes("-");
13607
+ for (let column = 0; column < columns; column++) {
13608
+ const mark = marks.charAt(column);
13609
+ if (mark === "-" || !removed && mark === " ") parentLeft[column] = (parentLeft[column] ?? 0) - 1;
13610
+ }
13611
+ if (removed) continue;
13612
+ resultLeft -= 1;
13613
+ if (marks.includes("+") && file !== void 0) {
13614
+ const text = line.slice(columns);
13615
+ const last = runs.at(-1);
13616
+ if (last !== void 0 && last.file === file && last.first + last.lines.length === next) last.lines.push(text);
13617
+ else runs.push({
13618
+ file,
13619
+ first: next,
13620
+ lines: [text]
13621
+ });
13622
+ }
13623
+ next += 1;
13624
+ continue;
13625
+ }
13626
+ if (line.startsWith("diff ")) {
13627
+ file = void 0;
13628
+ continue;
13629
+ }
13630
+ if (line.startsWith("+++ ")) {
13631
+ const path = unquote(line.slice(4));
13632
+ file = path === "/dev/null" ? void 0 : path.replace(/^b\//, "");
13633
+ continue;
13634
+ }
13635
+ const hunk = /^(@{2,}) ((?:-\d+(?:,\d+)? )+)\+(\d+)(?:,(\d+))? \1/.exec(line);
13636
+ if (hunk === null) continue;
13637
+ columns = (hunk[1] ?? "@@").length - 1;
13638
+ parentLeft = (hunk[2] ?? "").trim().split(" ").map((range) => {
13639
+ const count = /^-\d+(?:,(\d+))?$/.exec(range)?.[1];
13640
+ return count === void 0 ? 1 : Number(count);
13641
+ });
13642
+ next = Number(hunk[3]);
13643
+ resultLeft = hunk[4] === void 0 ? 1 : Number(hunk[4]);
13644
+ }
13645
+ return runs;
13646
+ }
13647
+ /** This function gives the place of a break as `file:line`. */
13648
+ const placeOf$1 = (item) => item.line === void 0 ? item.file : `${item.file}:${String(item.line)}`;
13649
+ /** This function examines one commit: its message, the paths that it adds or changes, and each line that it adds. */
13650
+ function readCommit(sha, privates, home, repo, git) {
13651
+ const short = sha.slice(0, 12);
13652
+ const message = git([
13653
+ "show",
13654
+ "-s",
13655
+ "--format=%B",
13656
+ sha
13657
+ ]);
13658
+ const names = git([
13659
+ "show",
13660
+ "--format=",
13661
+ "--name-only",
13662
+ "--diff-filter=AMRC",
13663
+ "-z",
13664
+ "--no-ext-diff",
13665
+ sha
13666
+ ]);
13667
+ const patch = git([
13668
+ "-c",
13669
+ "core.quotePath=false",
13670
+ "show",
13671
+ "--format=",
13672
+ "--no-color",
13673
+ "--unified=0",
13674
+ "--no-ext-diff",
13675
+ "--no-textconv",
13676
+ "--src-prefix=a/",
13677
+ "--dst-prefix=b/",
13678
+ sha
13679
+ ]);
13680
+ if (message === void 0 || names === void 0 || patch === void 0) return void 0;
13681
+ const breaks = [];
13682
+ const add = (items) => {
13683
+ for (const item of items) breaks.push(item);
13684
+ };
13685
+ const text = message.replace(/\s+$/, "");
13686
+ add(privateTextBreaks(`commit ${short} message`, text, privates, {
13687
+ allow: home.allow,
13688
+ homes: home.on
13689
+ }));
13690
+ let lines = text === "" ? 0 : text.split(/\r?\n/).length;
13691
+ const runs = addedRuns(patch);
13692
+ const paths = names.replace(/^\n+/, "").split("\0").filter((path) => path !== "");
13693
+ for (const run of runs) if (!paths.includes(run.file)) paths.push(run.file);
13694
+ const shown = /* @__PURE__ */ new Map();
13695
+ paths.forEach((path, index) => {
13696
+ const homes = home.on && !matchesAny(path, home.ignore);
13697
+ const found = privateTextBreaks(`commit ${short} path ${String(index + 1)}`, path, privates, {
13698
+ allow: home.allow,
13699
+ homes,
13700
+ isPath: true
13701
+ });
13702
+ lines += 1;
13703
+ shown.set(path, found.length > 0 ? `commit ${short} path ${String(index + 1)}` : `commit ${short} ${path}`);
13704
+ for (const item of found) breaks.push({
13705
+ file: item.file,
13706
+ message: item.message.replace(/^A text /, "The path "),
13707
+ ...item.fix === void 0 ? {} : { fix: item.fix }
13708
+ });
13709
+ });
13710
+ for (const run of runs) {
13711
+ const homes = home.on && !matchesAny(run.file, home.ignore);
13712
+ const place = {
13713
+ ...repo === void 0 ? {} : { repo },
13714
+ path: run.file
13715
+ };
13716
+ add(privateTextBreaks(shown.get(run.file) ?? `commit ${short} ${run.file}`, run.lines.join("\n"), privates, {
13717
+ allow: home.allow,
13718
+ homes,
13719
+ firstLine: run.first,
13720
+ rootPackage: run.file === "package.json",
13721
+ ...place
13722
+ }));
13723
+ lines += run.lines.length;
13724
+ }
13725
+ return {
13726
+ breaks,
13727
+ lines
13728
+ };
13729
+ }
13730
+ /** This function gives the reason of a read that failed, in words. */
13731
+ function readReason(error) {
13732
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
13733
+ if (code === "ENOENT") return "the file does not exist";
13734
+ if (code === "EISDIR") return "the path is a folder";
13735
+ if (code === "EACCES" || code === "EPERM") return "the file has no read permission";
13736
+ return error instanceof Error ? error.message : String(error);
13737
+ }
13738
+ /**
13739
+ * This function gives the repository `owner/name` of the push: from the URL of the hook, else from `git remote get-url`.
13740
+ * It gives undefined when neither URL is a URL of a GitHub repository.
13741
+ */
13742
+ function repoOfPush(options) {
13743
+ return (options.url === void 0 ? void 0 : repositoryOfRemote(options.url)) ?? repositoryOfRemote(options.git([
13744
+ "remote",
13745
+ "get-url",
13746
+ options.remote
13747
+ ]) ?? "");
13748
+ }
13749
+ /**
13750
+ * This function is the command `conventions pre-push`. It examines each new commit of the push: its message, the paths
13751
+ * that it adds or changes, and each line that it adds. It writes the breaks to `stderr`, and gives the exit code: 1 on a
13752
+ * break, 0 on a pass. With no private name list and no private pattern, it writes the line `NO_READ_LINE` and gives 0.
13753
+ */
13754
+ function prePush(options, io) {
13755
+ const readFile = options.readFile ?? ((path) => readFileSync(path, "utf8"));
13756
+ const file = privateNamesFile(options.env, options.git);
13757
+ const patterns = privatePatterns(options.env);
13758
+ if (file === void 0 && patterns.length === 0) {
13759
+ io.stderr(`${NO_READ_LINE}\n`);
13760
+ return 0;
13761
+ }
13762
+ let names;
13763
+ if (file !== void 0) {
13764
+ const source = (options.env["CONVENTIONS_PRIVATE_NAMES_FILE"]?.trim() ?? "") !== "" ? PRIVATE_NAMES_FILE_VARIABLE : `the git config ${PRIVATE_NAMES_FILE_CONFIG}`;
13765
+ let text;
13766
+ try {
13767
+ text = readFile(resolve(options.root, file));
13768
+ } catch (error) {
13769
+ io.stderr(`conventions pre-push: Cannot read the private name list that ${source} names: ${readReason(error)}. Correct the setting or the file. The push stops.\n`);
13770
+ return 1;
13771
+ }
13772
+ try {
13773
+ names = parsePrivateNames(text);
13774
+ } catch (error) {
13775
+ const reason = error instanceof PrivateNameListError ? error.reason : "the parse failed";
13776
+ io.stderr(`conventions pre-push: The private name list that ${source} names is not valid: ${reason}. Correct the file. The push stops.\n`);
13777
+ return 1;
13778
+ }
13779
+ }
13780
+ const privates = {
13781
+ ...names === void 0 ? {} : { names },
13782
+ patterns
13783
+ };
13784
+ const repo = names === void 0 || names.allow.length === 0 ? void 0 : repoOfPush(options);
13785
+ const home = homeSettings(options.root, readFile);
13786
+ const breaks = invalidPatternBreaks(patterns);
13787
+ const commits = /* @__PURE__ */ new Set();
13788
+ for (const line of options.input.split(/\r?\n/)) {
13789
+ if (line.trim() === "") continue;
13790
+ const [localRef, localSha, , remoteSha] = line.trim().split(/\s+/);
13791
+ if (localSha === void 0 || remoteSha === void 0 || !SHA.test(localSha) || !SHA.test(remoteSha)) {
13792
+ io.stderr(`conventions pre-push: The input line "${line.trim()}" does not have the form <local ref> <local sha> <remote ref> <remote sha>. The push stops.\n`);
13793
+ return 1;
13794
+ }
13795
+ if (ZERO.test(localSha)) continue;
13796
+ const others = [
13797
+ "rev-list",
13798
+ localSha,
13799
+ "--not",
13800
+ `--remotes=${options.remote}`
13801
+ ];
13802
+ const listed = ZERO.test(remoteSha) ? options.git(others) : options.git([
13803
+ "rev-list",
13804
+ localSha,
13805
+ `^${remoteSha}`
13806
+ ]) ?? options.git(others);
13807
+ if (listed === void 0) {
13808
+ io.stderr(`conventions pre-push: git cannot list the new commits of ${localRef ?? localSha}. The push stops.\n`);
13809
+ return 1;
13810
+ }
13811
+ for (const sha of listed.split(/\r?\n/)) if (SHA.test(sha.trim())) commits.add(sha.trim());
13812
+ }
13813
+ let lines = 0;
13814
+ for (const sha of commits) {
13815
+ const read = readCommit(sha, privates, home, repo, options.git);
13816
+ if (read === void 0) {
13817
+ io.stderr(`conventions pre-push: git cannot show the commit ${sha.slice(0, 12)}. The push stops.\n`);
13818
+ return 1;
13819
+ }
13820
+ for (const item of read.breaks) breaks.push(item);
13821
+ lines += read.lines;
13822
+ }
13823
+ if (breaks.length === 0) {
13824
+ io.stderr(`conventions pre-push: ${String(commits.size)} commits, ${String(lines)} lines read, 0 breaks.\n`);
13825
+ return 0;
13826
+ }
13827
+ const out = [`conventions pre-push: ${String(commits.size)} commits, ${String(lines)} lines read, ${String(breaks.length)} breaks. The push stops.`];
13828
+ for (const item of breaks) {
13829
+ out.push(` ${placeOf$1(item)} ${item.message}`);
13830
+ if (item.fix !== void 0) out.push(` fix: ${item.fix}`);
13831
+ }
13832
+ out.push("Change the commits (git commit --amend, or git rebase), and push again.");
13833
+ io.stderr(`${out.join("\n")}\n`);
13834
+ return 1;
13835
+ }
13836
+ /** The marker line of the hook that `conventions hook install` writes. The command rewrites only a hook with this line. */
13837
+ const HOOK_MARKER = "# conventions hook: pre-push";
13838
+ /** The first version of the package with the command `conventions pre-push`. */
13839
+ const FIRST_PRE_PUSH_VERSION = "0.37.1";
13840
+ /** This function gives the version of this package, from its package.json, or FIRST_PRE_PUSH_VERSION when it cannot read it. */
13841
+ function ownVersion() {
13842
+ try {
13843
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
13844
+ return typeof version === "string" && /^\d+\.\d+\.\d+/.test(version) ? version : FIRST_PRE_PUSH_VERSION;
13845
+ } catch {
13846
+ return FIRST_PRE_PUSH_VERSION;
13847
+ }
13848
+ }
13849
+ /**
13850
+ * The text of the hook `pre-push` that `conventions hook install` writes: a POSIX shell script.
13851
+ *
13852
+ * Git keeps one hooks folder for all worktrees of a repository, but each worktree has its own node_modules. A worktree
13853
+ * of an older branch can have a conventions with no pre-push command (before 0.37.1). Then the hook starts the
13854
+ * version that wrote it, with pnpm dlx. The hook stays closed: when no conventions can start, the push stops.
13855
+ */
13856
+ const PRE_PUSH_HOOK = `#!/bin/sh
13857
+ ${HOOK_MARKER}
13858
+ # The command "conventions hook install" wrote this file, and each install writes it again.
13859
+ # The hook examines the new commits of each push with the private name list.
13860
+ # All worktrees use this file. A worktree with a conventions older than ${FIRST_PRE_PUSH_VERSION} has no pre-push command,
13861
+ # so then the hook starts the version that wrote it.
13862
+ root="$(git rev-parse --show-toplevel)" || exit 1
13863
+ bin="$root/node_modules/.bin/conventions"
13864
+ pkg="$root/node_modules/@mark1russell7/conventions/package.json"
13865
+ if [ -x "$bin" ] && node -e 'let v;try{v=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).version}catch{process.exit(1)}const a=String(v).split("-")[0].split(".").map(Number),b=process.argv[2].split(".").map(Number);for(let i=0;i<3;i++)if(a[i]!==b[i])process.exit(a[i]>b[i]?0:1);process.exit(0)' "$pkg" ${FIRST_PRE_PUSH_VERSION} 2>/dev/null; then
13866
+ exec "$bin" pre-push "$@"
13867
+ fi
13868
+ exec pnpm dlx @mark1russell7/conventions@${ownVersion()} pre-push "$@"
13869
+ `;
13870
+ /** This function tells if the environment is a CI run. */
13871
+ const isCi = (env) => ["true", "1"].includes((env["CI"] ?? "").toLowerCase()) || env["GITHUB_ACTIONS"] === "true";
13872
+ /**
13873
+ * This function is the command `conventions hook install`. It writes the hook `pre-push` into the hooks folder of git,
13874
+ * so it uses the folder of `core.hooksPath` and works in a worktree. It keeps a hook that does not have `HOOK_MARKER`, and writes a warning.
13875
+ * In CI or outside a git repository, it writes one line and does nothing.
13876
+ */
13877
+ function installHook(options, io) {
13878
+ if (isCi(options.env)) {
13879
+ io.stdout("conventions hook install: CI has no push hook, so the command does nothing.\n");
13880
+ return 0;
13881
+ }
13882
+ const hooks = options.git([
13883
+ "rev-parse",
13884
+ "--git-path",
13885
+ "hooks"
13886
+ ])?.trim() ?? "";
13887
+ if (hooks === "") {
13888
+ io.stdout("conventions hook install: The folder is not in a git repository, so the command does nothing.\n");
13889
+ return 0;
13890
+ }
13891
+ const dir = resolve(options.cwd, hooks);
13892
+ const file = join(dir, "pre-push");
13893
+ const shown = `${hooks.replace(/[\\/]+$/, "")}/pre-push`;
13894
+ const before = existsSync(file) ? readFileSync(file, "utf8") : void 0;
13895
+ if (before !== void 0 && !before.includes("# conventions hook: pre-push")) {
13896
+ io.stderr(`conventions hook install: warning: ${shown} exists and conventions did not write it. The command keeps it. Add the line 'conventions pre-push "$@"' to it, or remove it and install again.\n`);
13897
+ return 0;
13898
+ }
13899
+ if (before === PRE_PUSH_HOOK) {
13900
+ io.stdout(`conventions hook install: ${shown} is current.\n`);
13901
+ return 0;
13902
+ }
13903
+ try {
13904
+ mkdirSync(dir, { recursive: true });
13905
+ writeFileSync(file, PRE_PUSH_HOOK, { mode: 493 });
13906
+ chmodSync(file, 493);
13907
+ } catch (error) {
13908
+ io.stderr(`conventions hook install: Cannot write ${shown}: ${error instanceof Error ? error.message : String(error)}\n`);
13909
+ return 1;
13910
+ }
13911
+ io.stdout(`conventions hook install: ${before === void 0 ? "wrote" : "updated"} ${shown}.\n`);
13912
+ return 0;
13913
+ }
13169
13914
  // src/run.ts
13170
13915
  /**
13171
13916
  * The commands `check`, `fix` and `--list` of the bin `conventions`, as functions. `runChecks` starts the
13172
13917
  * rules, `runFix` writes the edits of the breaks, and `runCli` reads the arguments and writes the result.
13918
+ * The commands `pre-push` and `hook install` are in `pre-push.ts`.
13173
13919
  */
13174
13920
  /** This function reads a `package.json` file. */
13175
13921
  function readPackage(root, dir) {
@@ -13435,12 +14181,21 @@ const USAGE = `Usage: conventions check [options]
13435
14181
  conventions fix [options]
13436
14182
  conventions --list
13437
14183
  conventions map [words] [--markdown | --json] [--overlay <file>]
14184
+ conventions pre-push <remote> [<url>]
14185
+ conventions hook install
13438
14186
 
13439
14187
  check Start each rule. Exit code 1 when a rule has a break.
13440
14188
  fix Write the fixes of the breaks that have one, and check again. Exit code 1 when a break stays.
13441
14189
  --list Show each rule: why, fix, options, state and the audit rows that it comes from.
13442
14190
  map Show the home package of each area of code, or of the areas that match the words.
13443
14191
  --markdown writes the table with the rule, and --overlay adds the homes of a JSON file.
14192
+ pre-push The git hook pre-push starts it. It reads the refs of the push on the standard input, and
14193
+ examines each new commit with the private name list: the message, the paths and the added
14194
+ lines. Exit code 1 on a break. The list is the JSON file of CONVENTIONS_PRIVATE_NAMES_FILE, else
14195
+ of the git config conventions.privateNamesFile. CONVENTIONS_PRIVATE_PATTERNS adds one regular
14196
+ expression on each line. With neither, it writes a "No read" line and gives 0.
14197
+ hook install Write the hook pre-push into the hooks folder of git. It keeps a hook that it did not write.
14198
+ In CI, or outside a git repository, it does nothing.
13444
14199
 
13445
14200
  --root <folder> The root of the repository. The default is the current folder.
13446
14201
  --rule <id> Only this rule. Use it again for more rules.
@@ -13486,6 +14241,8 @@ var UsageError = class extends Error {};
13486
14241
  /** This function starts the bin with the arguments `args`, and gives its exit code. */
13487
14242
  function runCli(args, io) {
13488
14243
  if (args[0] === "map") return runMap(args.slice(1), io);
14244
+ if (args[0] === "pre-push") return runPrePush(args.slice(1), io);
14245
+ if (args[0] === "hook") return runHook(args.slice(1), io);
13489
14246
  let check = false;
13490
14247
  let fix = false;
13491
14248
  let list = false;
@@ -13600,6 +14357,37 @@ function runMap(args, io) {
13600
14357
  else io.stdout(mapText(found));
13601
14358
  return 0;
13602
14359
  }
13603
- export { pagesAfterRelease as $, prPathFilters as $t, HOME_TIMEOUT_MS as A, mapText as At, publishedMinor as B, SHARED_CI as Bt, configsOfScript as C, parseConfig as Cn, messageOf as Ct, isSourcePath as D, MAP_RULE as Dt, testsRequired as E, HOMES as Et, roadmapParses as F, runCalls as Ft, UNSHIPPED_FILES as G, SECURITY_SCAN_INPUTS as Gt, reachOf as H, callsSharedCi as Ht, requiredScripts as I, serviceRunMain as It, unreleasedChangeRule as J, securityOneJob as Jt, npmLookup as K, SECURITY_TIMEOUT_MINUTES as Kt, releaseFiles as L, hasTests as Lt, githubFetch as M, readOverlay as Mt, sharedDocsRule as N, HOME_EXPORTS as Nt, pathsOf as O, findHomes as Ot, roadmapOfLine as P, SERVICE_PACKAGE as Pt, pinnedGitDeps as Q, gateTrigger as Qt, lockedVersions as R, tsconfigTest as Rt, typedScripts as S, defaultOptions as Sn, homePackage as St, typedFiles as T, signaturesOf as Tt, NPM_REGISTRY as U, sharedCi as Ut, publishedMinorRule as V, SHARED_WORKFLOWS as Vt, SHIPPED_FIELDS as W, SECURITY_SCAN_COMMIT as Wt, isGitSpecifier as X, ACTIONS_COMMIT as Xt, pipeFails as Y, withOneJob as Yt, isPinned as Z, convertGate as Zt, setVersions as _, specifiersOf as _n, licenseFile as _t, listRules as a, DEPENDENCY_FIELDS as an, pagesCalls as at, TRAIN_SCOPES as b, packageFolders as bn, repositoryIsPublic as bt, runCli as c, hasFile as cn, DEFAULT_ALLOWED as ct, RULES as d, lineOf as dn, noBuildOutput as dt, summaryName as en, repositoryOfRemote as et, workspaceProtocol as f, matchesAny as fn, REAL_COMPARE as ft, namedVersions as g, runGit as gn, authorOf as gt, yamlFaults as h, replaceLine as hn, LICENSE_TEXTS as ht, formatResult as i, cuePreset as in, PAGES_WORKFLOWS as it, blockHash as j, mergeHomes as jt, sourceMain as k, mapMarkdown as kt, runFix as l, inFolder as ln, HOME_PATTERNS as lt, workflowParses as m, readJsonc as mn, mainCheck as mt, annotations as n, readWorkflow as nn, scheduleMinute as nt, readConfig as o, cleanPath as on, pagesSite as ot, GITHUB_YAML as p, parseJsonc as pn, hasImportMetaMain as pt, unreleasedChange as q, securityCallers as qt, createContext as r, STRICT_OPTIONS as rn, pushMainOnly as rt, runChecks as s, codePackages as sn, apiReportScript as st, USAGE as t, gateAfterCancel as tn, runnerBudget as tt, summaryMarkdown as u, keyLine as un, noLocalPaths as ut, versionTitle as v, globFolders as vn, licenseFileOf as vt, scriptsOf as w, repoOf as wt, trustPolicy as x, workspaceGlobs as xn, declaredName as xt, IGNORE_AFTER as y, globToRegExp as yn, mitText as yt, minorOf as z, SHARED_ACTIONS as zt };
14360
+ /** The command `pre-push`: the arguments of the git hook, the remote and its URL. */
14361
+ function runPrePush(args, io) {
14362
+ const remote = args[0];
14363
+ if (remote === void 0 || remote.startsWith("-") || args.length > 2) {
14364
+ io.stderr(`conventions: The command pre-push takes the name of the remote and, after it, its URL.\n\n${USAGE}`);
14365
+ return 2;
14366
+ }
14367
+ const top = runGit(io.cwd, ["rev-parse", "--show-toplevel"])?.trim() ?? "";
14368
+ const root = top === "" ? io.cwd : top;
14369
+ const url = args[1];
14370
+ return prePush({
14371
+ remote,
14372
+ ...url === void 0 ? {} : { url },
14373
+ input: io.stdin ?? "",
14374
+ env: io.env,
14375
+ root,
14376
+ git: (gitArgs) => runGit(root, gitArgs)
14377
+ }, io);
14378
+ }
14379
+ /** The command `hook install`: it writes the git hook pre-push. */
14380
+ function runHook(args, io) {
14381
+ if (args.length !== 1 || args[0] !== "install") {
14382
+ io.stderr(`conventions: The command hook takes one argument: install.\n\n${USAGE}`);
14383
+ return 2;
14384
+ }
14385
+ return installHook({
14386
+ cwd: io.cwd,
14387
+ env: io.env,
14388
+ git: (gitArgs) => runGit(io.cwd, gitArgs)
14389
+ }, io);
14390
+ }
14391
+ export { unreleasedChangeRule as $, mergeHomes as $t, typedFiles as A, hasFile as An, nameMatches as At, roadmapParses as B, globFolders as Bn, licenseFileOf as Bt, versionTitle as C, gateAfterCancel as Cn, PRIVATE_NAME_LIST as Ct, typedScripts as D, DEPENDENCY_FIELDS as Dn, isCommonUse as Dt, trustPolicy as E, cuePreset as En, isAllowedHit as Et, HOME_TIMEOUT_MS as F, parseJsonc as Fn, hasImportMetaMain as Ft, publishedMinor as G, parseConfig as Gn, messageOf as Gt, releaseFiles as H, packageFolders as Hn, repositoryIsPublic as Ht, blockHash as I, readJsonc as In, mainCheck as It, NPM_REGISTRY as J, HOMES as Jt, publishedMinorRule as K, repoOf as Kt, githubFetch as L, replaceLine as Ln, LICENSE_TEXTS as Lt, isSourcePath as M, keyLine as Mn, pathNameHit as Mt, pathsOf as N, lineOf as Nn, noBuildOutput as Nt, configsOfScript as O, cleanPath as On, lineNameHit as Ot, sourceMain as P, matchesAny as Pn, REAL_COMPARE as Pt, unreleasedChange as Q, mapText as Qt, sharedDocsRule as R, runGit as Rn, authorOf as Rt, setVersions as S, summaryName as Sn, privateTextBreaks as St, TRAIN_SCOPES as T, STRICT_OPTIONS as Tn, firstNameMatch as Tt, lockedVersions as U, workspaceGlobs as Un, declaredName as Ut, requiredScripts as V, globToRegExp as Vn, mitText as Vt, minorOf as W, defaultOptions as Wn, homePackage as Wt, UNSHIPPED_FILES as X, findHomes as Xt, SHIPPED_FIELDS as Y, MAP_RULE as Yt, npmLookup as Z, mapMarkdown as Zt, workspaceProtocol as _, withOneJob as _n, PRIVATE_PATTERNS_VARIABLE as _t, listRules as a, hasTests as an, repositoryOfRemote as at, yamlFaults as b, gateTrigger as bn, privateNamesFile as bt, runCli as c, SHARED_CI as cn, pushMainOnly as ct, HOOK_MARKER as d, sharedCi as dn, pagesSite as dt, readOverlay as en, pipeFails as et, NO_READ_LINE as f, SECURITY_SCAN_COMMIT as fn, apiReportScript as ft, RULES as g, securityOneJob as gn, PRIVATE_NAMES_FILE_VARIABLE as gt, prePush as h, securityCallers as hn, PRIVATE_NAMES_FILE_CONFIG as ht, formatResult as i, serviceRunMain as in, pagesAfterRelease as it, testsRequired as j, inFolder as jn, parsePrivateNames as jt, scriptsOf as k, codePackages as kn, lineNameHits as kt, runFix as l, SHARED_WORKFLOWS as ln, PAGES_WORKFLOWS as lt, installHook as m, SECURITY_TIMEOUT_MINUTES as mn, HOME_PATTERNS as mt, annotations as n, SERVICE_PACKAGE as nn, isPinned as nt, readConfig as o, tsconfigTest as on, runnerBudget as ot, PRE_PUSH_HOOK as p, SECURITY_SCAN_INPUTS as pn, DEFAULT_ALLOWED as pt, reachOf as q, signaturesOf as qt, createContext as r, runCalls as rn, pinnedGitDeps as rt, runChecks as s, SHARED_ACTIONS as sn, scheduleMinute as st, USAGE as t, HOME_EXPORTS as tn, isGitSpecifier as tt, summaryMarkdown as u, callsSharedCi as un, pagesCalls as ut, GITHUB_YAML as v, ACTIONS_COMMIT as vn, invalidPatternBreaks as vt, IGNORE_AFTER as w, readWorkflow as wn, PrivateNameListError as wt, namedVersions as x, prPathFilters as xn, privatePatterns as xt, workflowParses as y, convertGate as yn, noLocalPaths as yt, roadmapOfLine as z, specifiersOf as zn, licenseFile as zt };
13604
14392
 
13605
- //# sourceMappingURL=run-DWyPhbeH.js.map
14393
+ //# sourceMappingURL=run-_3JdUrzy.js.map