binary-collections 2.0.7 → 2.0.8

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 (150) hide show
  1. package/bin/dir-tree.cmd +7 -0
  2. package/bin/git-diff +4 -0
  3. package/bin/git-diff.cmd +5 -2
  4. package/bin/{git-fix-encoding → git-fix} +1 -4
  5. package/bin/git-fix.cmd +7 -0
  6. package/bin/nodekill +0 -0
  7. package/bin/nodekill.ps1 +0 -0
  8. package/bin/{submodule → submodule.txt} +0 -0
  9. package/lib/binary-collections-config.cjs +14 -0
  10. package/lib/binary-collections-config.d.mts +18 -0
  11. package/lib/binary-collections-config.d.ts +16 -0
  12. package/lib/binary-collections-config.js +39 -0
  13. package/lib/binary-collections-config.mjs +6 -0
  14. package/lib/binary-collections.cjs +105 -0
  15. package/lib/binary-collections.d.cts +2 -0
  16. package/lib/binary-collections.d.mts +121 -0
  17. package/lib/binary-collections.d.ts +121 -0
  18. package/lib/binary-collections.mjs +108 -0
  19. package/lib/chunk-4BYBVEYC.mjs +30 -0
  20. package/lib/{chunk-FB6YIQYR.mjs → chunk-AASHBCRW.mjs} +17 -2
  21. package/lib/chunk-APBWENF6.mjs +135 -0
  22. package/lib/{chunk-4LEXWIIF.mjs → chunk-DPKAJKFO.mjs} +2 -4
  23. package/lib/chunk-EGSSKVDH.mjs +66 -0
  24. package/lib/{chunk-3LOB2P54.mjs → chunk-G3THLIDT.mjs} +3 -5
  25. package/lib/chunk-JGR2NW6D.mjs +187 -0
  26. package/lib/chunk-ONIBBBQ3.mjs +108 -0
  27. package/lib/chunk-SH3L6HHV.mjs +27 -0
  28. package/lib/chunk-VVEZVNIV.mjs +81 -0
  29. package/lib/{chunk-JL32QDSH.mjs → chunk-W3ENOM53.mjs} +2 -4
  30. package/lib/chunk-YV7DO3YV.mjs +48 -0
  31. package/lib/{chunk-BSD5CIRU.mjs → chunk-YX5U7XDR.mjs} +11 -5
  32. package/lib/chunk-ZYAQRPUL.mjs +28 -0
  33. package/lib/clean-github-actions-caches.cjs +162 -0
  34. package/lib/clean-github-actions-caches.d.cts +1 -0
  35. package/lib/clean-github-actions-caches.d.mts +169 -0
  36. package/lib/clean-github-actions-caches.d.ts +169 -0
  37. package/lib/clean-github-actions-caches.mjs +132 -0
  38. package/lib/del-gradle.cjs +87 -3
  39. package/lib/del-gradle.js +1 -1
  40. package/lib/del-gradle.mjs +4 -6
  41. package/lib/del-node-modules.cjs +86 -2
  42. package/lib/del-node-modules.mjs +3 -5
  43. package/lib/del-ps.cjs +89 -5
  44. package/lib/del-ps.js +2 -2
  45. package/lib/del-ps.mjs +6 -8
  46. package/lib/del-yarn-caches.cjs +86 -2
  47. package/lib/del-yarn-caches.mjs +3 -5
  48. package/lib/find-node-modules-cli.cjs +8 -0
  49. package/lib/find-node-modules-cli.mjs +2 -3
  50. package/lib/find-node-modules.cjs +8 -0
  51. package/lib/find-node-modules.d.mts +3 -0
  52. package/lib/find-node-modules.d.ts +3 -0
  53. package/lib/find-node-modules.js +12 -0
  54. package/lib/find-node-modules.mjs +2 -3
  55. package/lib/git/gitattributes.cjs +171 -0
  56. package/lib/git/gitattributes.d.mts +35 -0
  57. package/lib/git/gitattributes.d.ts +33 -0
  58. package/lib/git/gitattributes.js +223 -0
  59. package/lib/git/gitattributes.mjs +6 -0
  60. package/lib/git/line-endings.cjs +74 -0
  61. package/lib/git/line-endings.d.cts +7 -0
  62. package/lib/git/line-endings.d.mts +83 -0
  63. package/lib/git/line-endings.d.ts +83 -0
  64. package/lib/git/line-endings.mjs +8 -0
  65. package/lib/git/normalize.cjs +42 -0
  66. package/lib/git/normalize.d.cts +6 -0
  67. package/lib/git/normalize.d.mts +43 -0
  68. package/lib/git/normalize.d.ts +43 -0
  69. package/lib/git/normalize.mjs +6 -0
  70. package/lib/git/permissions.cjs +15 -0
  71. package/lib/git/permissions.d.cts +6 -0
  72. package/lib/git/permissions.d.mts +17 -0
  73. package/lib/git/permissions.d.ts +17 -0
  74. package/lib/git/permissions.mjs +7 -0
  75. package/lib/git/pull-strategy.cjs +13 -0
  76. package/lib/git/pull-strategy.d.cts +5 -0
  77. package/lib/git/pull-strategy.d.mts +15 -0
  78. package/lib/git/pull-strategy.d.ts +15 -0
  79. package/lib/git/pull-strategy.mjs +7 -0
  80. package/lib/git/user-config.cjs +100 -0
  81. package/lib/git/user-config.d.cts +10 -0
  82. package/lib/git/user-config.d.mts +105 -0
  83. package/lib/git/user-config.d.ts +105 -0
  84. package/lib/git/user-config.mjs +8 -0
  85. package/lib/git/utils.cjs +70 -0
  86. package/lib/git/utils.d.cts +20 -0
  87. package/lib/git/utils.d.mts +69 -0
  88. package/lib/git/utils.d.ts +69 -0
  89. package/lib/git/utils.mjs +6 -0
  90. package/lib/git-diff.cjs +23 -24
  91. package/lib/git-diff.d.mts +25 -28
  92. package/lib/git-diff.d.ts +25 -28
  93. package/lib/git-diff.mjs +32 -27
  94. package/lib/git-fix.cjs +129 -0
  95. package/lib/git-fix.d.cts +2 -0
  96. package/lib/git-fix.d.mts +141 -0
  97. package/lib/git-fix.d.ts +141 -0
  98. package/lib/git-fix.mjs +151 -0
  99. package/lib/git-purge.cjs +86 -2
  100. package/lib/git-purge.mjs +3 -5
  101. package/lib/index.cjs +8 -0
  102. package/lib/index.mjs +3 -5
  103. package/lib/npm-run-series.cjs +140 -1
  104. package/lib/npm-run-series.js +2 -1
  105. package/lib/npm-run-series.mjs +7 -5
  106. package/lib/package-resolutions-updater.cjs +274 -0
  107. package/lib/package-resolutions-updater.d.mts +1 -0
  108. package/lib/package-resolutions-updater.d.ts +326 -0
  109. package/lib/package-resolutions-updater.mjs +316 -0
  110. package/lib/print-directory-tree.cjs +241 -0
  111. package/lib/print-directory-tree.d.cts +1 -0
  112. package/lib/print-directory-tree.d.mts +234 -0
  113. package/lib/print-directory-tree.d.ts +234 -0
  114. package/lib/print-directory-tree.mjs +182 -0
  115. package/lib/ps/connected-domain.mjs +2 -3
  116. package/lib/ps/index.cjs +3 -3
  117. package/lib/ps/index.d.mjs +1 -2
  118. package/lib/ps/index.js +6 -3
  119. package/lib/ps/index.mjs +9 -11
  120. package/lib/ps/isWin.mjs +2 -3
  121. package/lib/ps/table-parser.mjs +3 -4
  122. package/lib/submodule-install.cjs +13 -31
  123. package/lib/submodule-install.d.mts +12 -32
  124. package/lib/submodule-install.d.ts +12 -32
  125. package/lib/submodule-install.mjs +16 -25
  126. package/lib/utils.cjs +86 -2
  127. package/lib/utils.d.mts +29 -9
  128. package/lib/utils.d.ts +28 -8
  129. package/lib/utils.js +139 -8
  130. package/lib/utils.mjs +2 -3
  131. package/lib/yarn-reinstall.cjs +9 -7
  132. package/lib/yarn-reinstall.d.mts +12 -8
  133. package/lib/yarn-reinstall.d.ts +12 -8
  134. package/lib/yarn-reinstall.mjs +14 -10
  135. package/package.json +109 -80
  136. package/readme.md +74 -11
  137. package/src/package-resolutions-updater.mjs +325 -0
  138. package/src/print-directory-tree.cjs +234 -0
  139. package/src/ps/index.js +4 -3
  140. package/src/yarn-reinstall.cjs +49 -0
  141. package/test-project/package.json +16 -0
  142. package/tmp/test-repo/package.json +7 -0
  143. package/bin/git-fix-encoding.cmd +0 -6
  144. package/lib/chunk-OKYLF2MU.mjs +0 -53
  145. package/lib/chunk-VXZQNLPU.mjs +0 -23
  146. package/lib/package-resolutions.cjs +0 -28
  147. package/lib/package-resolutions.d.mts +0 -25
  148. package/lib/package-resolutions.d.ts +0 -25
  149. package/lib/package-resolutions.mjs +0 -31
  150. /package/bin/{submodule-install → submodule-install.txt} +0 -0
@@ -0,0 +1,48 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import {
3
+ __commonJS,
4
+ __require,
5
+ init_esm_shims
6
+ } from "./chunk-AASHBCRW.mjs";
7
+
8
+ // src/git/normalize.cjs
9
+ var require_normalize = __commonJS({
10
+ "src/git/normalize.cjs"(exports, module) {
11
+ init_esm_shims();
12
+ var { execSync } = __require("child_process");
13
+ function normalizeLineEndings() {
14
+ console.log("\n=== Normalizing Existing Files ===");
15
+ try {
16
+ const result = execSync("git ls-files", { encoding: "utf-8", stdio: "pipe" });
17
+ if (!result.trim()) {
18
+ console.log("[i] No tracked files to normalize");
19
+ return;
20
+ }
21
+ console.log("[i] Refreshing index to detect line ending changes...");
22
+ execSync("git add --renormalize .", { stdio: "pipe" });
23
+ try {
24
+ const statusResult = execSync("git status --porcelain", { encoding: "utf-8", stdio: "pipe" });
25
+ if (statusResult.trim()) {
26
+ console.log("[\u2713] Line endings normalized for tracked files");
27
+ console.log("[i] Files with updated line endings are now staged");
28
+ console.log("[i] Run 'git status' to see the changes");
29
+ } else {
30
+ console.log("[\u2713] All files already have correct line endings");
31
+ }
32
+ } catch {
33
+ console.log("[\u2713] Line ending normalization completed");
34
+ }
35
+ } catch (error) {
36
+ console.error("[\u2717] Failed to normalize line endings");
37
+ console.error(`Error: ${error.message}`);
38
+ }
39
+ }
40
+ module.exports = {
41
+ normalizeLineEndings
42
+ };
43
+ }
44
+ });
45
+
46
+ export {
47
+ require_normalize
48
+ };
@@ -1,11 +1,9 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import {
3
- init_esm_shims
4
- } from "./chunk-VXZQNLPU.mjs";
5
2
  import {
6
3
  __commonJS,
7
- __require
8
- } from "./chunk-FB6YIQYR.mjs";
4
+ __require,
5
+ init_esm_shims
6
+ } from "./chunk-AASHBCRW.mjs";
9
7
 
10
8
  // src/find-node-modules.js
11
9
  var require_find_node_modules = __commonJS({
@@ -43,7 +41,15 @@ var require_find_node_modules = __commonJS({
43
41
  });
44
42
  });
45
43
  }
44
+ if (typeof module !== "undefined" && __require.main === module) {
45
+ findNodeModules(null, console.log).then((dirs) => {
46
+ console.log(`Found ${dirs.length} node_modules directories.`);
47
+ }).catch((err) => {
48
+ console.error("Error finding node_modules directories:", err);
49
+ });
50
+ }
46
51
  module.exports = findNodeModules;
52
+ module.exports.default = findNodeModules;
47
53
  }
48
54
  });
49
55
 
@@ -0,0 +1,28 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import {
3
+ require_utils
4
+ } from "./chunk-EGSSKVDH.mjs";
5
+ import {
6
+ __commonJS,
7
+ init_esm_shims
8
+ } from "./chunk-AASHBCRW.mjs";
9
+
10
+ // src/git/permissions.cjs
11
+ var require_permissions = __commonJS({
12
+ "src/git/permissions.cjs"(exports, module) {
13
+ init_esm_shims();
14
+ var { runGitCommand } = require_utils();
15
+ function ignoreFilePermissions() {
16
+ console.log("\n=== Configuring File Permissions ===");
17
+ runGitCommand(["config", "core.filemode", "false"], "Ignore file permission changes");
18
+ runGitCommand(["config", "diff.ignoreSubmodules", "dirty"], "Ignore submodule permission changes");
19
+ }
20
+ module.exports = {
21
+ ignoreFilePermissions
22
+ };
23
+ }
24
+ });
25
+
26
+ export {
27
+ require_permissions
28
+ };
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ const axios = require("axios");
12
+ const { parseGitRemotes } = require("./utils");
13
+ const path = require("upath");
14
+ const fs = require("fs");
15
+ const projectDir = process.cwd();
16
+ const envPath = path.join(projectDir, ".env");
17
+ // Load the .env file using dotenv
18
+ if (fs.existsSync(envPath)) {
19
+ require("dotenv").config({ path: envPath });
20
+ }
21
+ else {
22
+ console.warn(`.env file not found at ${envPath}`);
23
+ }
24
+ // delete caches leaving single last cache based on creation date
25
+ const ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
26
+ if (!ACCESS_TOKEN) {
27
+ throw new Error("Access token is not provided. Please set ACCESS_TOKEN or GITHUB_TOKEN in your environment variables.");
28
+ }
29
+ /**
30
+ * Deletes a GitHub Actions cache.
31
+ * @param {string} GH_REPO - The GitHub repository in the format "owner/repo".
32
+ * @param {string} cacheId - The ID of the cache to delete.
33
+ * @returns {Promise} - A promise that resolves on success and rejects on error.
34
+ */
35
+ function deleteGitHubActionsCache(GH_REPO, cacheId) {
36
+ return new Promise((resolve, reject) => {
37
+ const url = `https://api.github.com/repos/${GH_REPO}/actions/caches/${cacheId}`;
38
+ const token = ACCESS_TOKEN;
39
+ if (!token) {
40
+ return reject(new Error("Access token is not provided"));
41
+ }
42
+ axios
43
+ .delete(url, {
44
+ headers: {
45
+ Authorization: `token ${token}`,
46
+ Accept: "application/vnd.github.v3+json"
47
+ }
48
+ })
49
+ .then((response) => {
50
+ console.log(`Cache (${cacheId}) deleted successfully`, response.data);
51
+ resolve(response.data); // Resolve with the response data
52
+ })
53
+ .catch((error) => {
54
+ var _a;
55
+ console.error("Error deleting cache:", ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) || error.message || "Unknown error");
56
+ reject(error); // Reject with the error
57
+ });
58
+ });
59
+ }
60
+ /**
61
+ * list github actions caches
62
+ * @param {string} GH_REPO
63
+ * @returns {Promise<Record<string, Record<string, any>[]>>}
64
+ */
65
+ function get_caches(GH_REPO) {
66
+ const url = `https://api.github.com/repos/${GH_REPO}/actions/caches`;
67
+ return new Promise((resolve, reject) => {
68
+ axios
69
+ .get(url, {
70
+ headers: {
71
+ Accept: "application/vnd.github.v3+json",
72
+ Authorization: `token ${ACCESS_TOKEN}`
73
+ }
74
+ })
75
+ .then((response) => {
76
+ /**
77
+ * @type {Record<string, any>[]}
78
+ */
79
+ const data = response.data.actions_caches;
80
+ // resolve(response.data);
81
+ /**
82
+ * extract the prefix from the key
83
+ * @param {string} key
84
+ * @returns
85
+ */
86
+ const getPrefix = (key) => {
87
+ const split = key.split(/[-_]/);
88
+ if (split.length == 3) {
89
+ return `${split[0]}-${split[1]}`;
90
+ }
91
+ else if (split.length > 3) {
92
+ return `${split[0]}-${split[1]}-${split[2]}`;
93
+ }
94
+ return split[0];
95
+ };
96
+ // Group by prefix
97
+ const grouped = data.reduce(
98
+ /**
99
+ * @param {Record<string, Record<string, any>[]>} acc
100
+ * @param {Record<string, any>} item
101
+ * @returns {Record<string, Record<string, any>[]>}
102
+ */
103
+ (acc, item) => {
104
+ const prefix = getPrefix(item.key);
105
+ if (!acc[prefix]) {
106
+ acc[prefix] = [];
107
+ }
108
+ acc[prefix].push(item);
109
+ return acc;
110
+ }, {});
111
+ // Convert the grouped object into an array of arrays
112
+ // const result = Object.values(grouped);
113
+ resolve(grouped);
114
+ })
115
+ .catch((error) => {
116
+ console.error("Error fetching data:", error);
117
+ reject(error); // Reject the promise with the error
118
+ });
119
+ });
120
+ }
121
+ /**
122
+ * Deletes old GitHub Actions caches for the current repository (origin remote),
123
+ * keeping only the most recent cache for each prefix (based on creation date).
124
+ * Retrieves caches, groups by prefix, sorts by creation date, and deletes all but the latest.
125
+ */
126
+ (() => __awaiter(void 0, void 0, void 0, function* () {
127
+ try {
128
+ const remotes = yield parseGitRemotes();
129
+ const GH_REPO = remotes.origin;
130
+ const caches = yield get_caches(GH_REPO);
131
+ for (const key in caches) {
132
+ if (Object.hasOwnProperty.call(caches, key)) {
133
+ const items = caches[key]
134
+ .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
135
+ .map((item) => (Object.assign(Object.assign({}, item), { human_readable_date: new Date(item.created_at).toLocaleString() })));
136
+ if (items.length > 1) {
137
+ const ids = items.map((o) => o.id);
138
+ ids.shift(); // keep the most recent cache
139
+ if (ids.length > 0) {
140
+ for (const id of ids) {
141
+ try {
142
+ yield deleteGitHubActionsCache(GH_REPO, id);
143
+ }
144
+ catch (err) {
145
+ console.error(`Error deleting cache ${id}:`, err);
146
+ }
147
+ }
148
+ }
149
+ else {
150
+ console.log(`cache prefix ${key} no cache left`);
151
+ }
152
+ }
153
+ else {
154
+ console.log(`cache prefix ${key} only have 1 cache`);
155
+ }
156
+ }
157
+ }
158
+ }
159
+ catch (e) {
160
+ console.error(`Error: ${e}`);
161
+ }
162
+ }))();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,169 @@
1
+ const axios = require("axios");
2
+ const { parseGitRemotes } = require("./utils");
3
+ const path = require("upath");
4
+ const fs = require("fs");
5
+ const projectDir = process.cwd();
6
+ const envPath = path.join(projectDir, ".env");
7
+
8
+ // Load the .env file using dotenv
9
+ if (fs.existsSync(envPath)) {
10
+ require("dotenv").config({ path: envPath });
11
+ } else {
12
+ console.warn(`.env file not found at ${envPath}`);
13
+ }
14
+
15
+ // delete caches leaving single last cache based on creation date
16
+
17
+ const ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
18
+
19
+ if (!ACCESS_TOKEN) {
20
+ throw new Error(
21
+ "Access token is not provided. Please set ACCESS_TOKEN or GITHUB_TOKEN in your environment variables."
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Deletes a GitHub Actions cache.
27
+ * @param {string} GH_REPO - The GitHub repository in the format "owner/repo".
28
+ * @param {string} cacheId - The ID of the cache to delete.
29
+ * @returns {Promise} - A promise that resolves on success and rejects on error.
30
+ */
31
+ function deleteGitHubActionsCache(GH_REPO, cacheId) {
32
+ return new Promise((resolve, reject) => {
33
+ const url = `https://api.github.com/repos/${GH_REPO}/actions/caches/${cacheId}`;
34
+ const token = ACCESS_TOKEN;
35
+
36
+ if (!token) {
37
+ return reject(new Error("Access token is not provided"));
38
+ }
39
+
40
+ axios
41
+ .delete(url, {
42
+ headers: {
43
+ Authorization: `token ${token}`,
44
+ Accept: "application/vnd.github.v3+json"
45
+ }
46
+ })
47
+ .then((response) => {
48
+ console.log(`Cache (${cacheId}) deleted successfully`, response.data);
49
+ resolve(response.data); // Resolve with the response data
50
+ })
51
+ .catch((error) => {
52
+ console.error("Error deleting cache:", error.response?.data || error.message || "Unknown error");
53
+ reject(error); // Reject with the error
54
+ });
55
+ });
56
+ }
57
+
58
+ /**
59
+ * list github actions caches
60
+ * @param {string} GH_REPO
61
+ * @returns {Promise<Record<string, Record<string, any>[]>>}
62
+ */
63
+ function get_caches(GH_REPO) {
64
+ const url = `https://api.github.com/repos/${GH_REPO}/actions/caches`;
65
+
66
+ return new Promise((resolve, reject) => {
67
+ axios
68
+ .get(url, {
69
+ headers: {
70
+ Accept: "application/vnd.github.v3+json",
71
+ Authorization: `token ${ACCESS_TOKEN}`
72
+ }
73
+ })
74
+ .then((response) => {
75
+ /**
76
+ * @type {Record<string, any>[]}
77
+ */
78
+ const data = response.data.actions_caches;
79
+ // resolve(response.data);
80
+ /**
81
+ * extract the prefix from the key
82
+ * @param {string} key
83
+ * @returns
84
+ */
85
+ const getPrefix = (key) => {
86
+ const split = key.split(/[-_]/);
87
+ if (split.length == 3) {
88
+ return `${split[0]}-${split[1]}`;
89
+ } else if (split.length > 3) {
90
+ return `${split[0]}-${split[1]}-${split[2]}`;
91
+ }
92
+ return split[0];
93
+ };
94
+
95
+ // Group by prefix
96
+ const grouped = data.reduce(
97
+ /**
98
+ * @param {Record<string, Record<string, any>[]>} acc
99
+ * @param {Record<string, any>} item
100
+ * @returns {Record<string, Record<string, any>[]>}
101
+ */
102
+ (acc, item) => {
103
+ const prefix = getPrefix(item.key);
104
+
105
+ if (!acc[prefix]) {
106
+ acc[prefix] = [];
107
+ }
108
+
109
+ acc[prefix].push(item);
110
+
111
+ return acc;
112
+ },
113
+ {}
114
+ );
115
+
116
+ // Convert the grouped object into an array of arrays
117
+ // const result = Object.values(grouped);
118
+ resolve(grouped);
119
+ })
120
+ .catch((error) => {
121
+ console.error("Error fetching data:", error);
122
+ reject(error); // Reject the promise with the error
123
+ });
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Deletes old GitHub Actions caches for the current repository (origin remote),
129
+ * keeping only the most recent cache for each prefix (based on creation date).
130
+ * Retrieves caches, groups by prefix, sorts by creation date, and deletes all but the latest.
131
+ */
132
+ (async () => {
133
+ try {
134
+ const remotes = await parseGitRemotes();
135
+ const GH_REPO = remotes.origin;
136
+ const caches = await get_caches(GH_REPO);
137
+
138
+ for (const key in caches) {
139
+ if (Object.hasOwnProperty.call(caches, key)) {
140
+ const items = caches[key]
141
+ .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
142
+ .map((item) => ({
143
+ ...item,
144
+ human_readable_date: new Date(item.created_at).toLocaleString()
145
+ }));
146
+
147
+ if (items.length > 1) {
148
+ const ids = items.map((o) => o.id);
149
+ ids.shift(); // keep the most recent cache
150
+ if (ids.length > 0) {
151
+ for (const id of ids) {
152
+ try {
153
+ await deleteGitHubActionsCache(GH_REPO, id);
154
+ } catch (err) {
155
+ console.error(`Error deleting cache ${id}:`, err);
156
+ }
157
+ }
158
+ } else {
159
+ console.log(`cache prefix ${key} no cache left`);
160
+ }
161
+ } else {
162
+ console.log(`cache prefix ${key} only have 1 cache`);
163
+ }
164
+ }
165
+ }
166
+ } catch (e) {
167
+ console.error(`Error: ${e}`);
168
+ }
169
+ })();
@@ -0,0 +1,169 @@
1
+ const axios = require("axios");
2
+ const { parseGitRemotes } = require("./utils");
3
+ const path = require("upath");
4
+ const fs = require("fs");
5
+ const projectDir = process.cwd();
6
+ const envPath = path.join(projectDir, ".env");
7
+
8
+ // Load the .env file using dotenv
9
+ if (fs.existsSync(envPath)) {
10
+ require("dotenv").config({ path: envPath });
11
+ } else {
12
+ console.warn(`.env file not found at ${envPath}`);
13
+ }
14
+
15
+ // delete caches leaving single last cache based on creation date
16
+
17
+ const ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
18
+
19
+ if (!ACCESS_TOKEN) {
20
+ throw new Error(
21
+ "Access token is not provided. Please set ACCESS_TOKEN or GITHUB_TOKEN in your environment variables."
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Deletes a GitHub Actions cache.
27
+ * @param {string} GH_REPO - The GitHub repository in the format "owner/repo".
28
+ * @param {string} cacheId - The ID of the cache to delete.
29
+ * @returns {Promise} - A promise that resolves on success and rejects on error.
30
+ */
31
+ function deleteGitHubActionsCache(GH_REPO, cacheId) {
32
+ return new Promise((resolve, reject) => {
33
+ const url = `https://api.github.com/repos/${GH_REPO}/actions/caches/${cacheId}`;
34
+ const token = ACCESS_TOKEN;
35
+
36
+ if (!token) {
37
+ return reject(new Error("Access token is not provided"));
38
+ }
39
+
40
+ axios
41
+ .delete(url, {
42
+ headers: {
43
+ Authorization: `token ${token}`,
44
+ Accept: "application/vnd.github.v3+json"
45
+ }
46
+ })
47
+ .then((response) => {
48
+ console.log(`Cache (${cacheId}) deleted successfully`, response.data);
49
+ resolve(response.data); // Resolve with the response data
50
+ })
51
+ .catch((error) => {
52
+ console.error("Error deleting cache:", error.response?.data || error.message || "Unknown error");
53
+ reject(error); // Reject with the error
54
+ });
55
+ });
56
+ }
57
+
58
+ /**
59
+ * list github actions caches
60
+ * @param {string} GH_REPO
61
+ * @returns {Promise<Record<string, Record<string, any>[]>>}
62
+ */
63
+ function get_caches(GH_REPO) {
64
+ const url = `https://api.github.com/repos/${GH_REPO}/actions/caches`;
65
+
66
+ return new Promise((resolve, reject) => {
67
+ axios
68
+ .get(url, {
69
+ headers: {
70
+ Accept: "application/vnd.github.v3+json",
71
+ Authorization: `token ${ACCESS_TOKEN}`
72
+ }
73
+ })
74
+ .then((response) => {
75
+ /**
76
+ * @type {Record<string, any>[]}
77
+ */
78
+ const data = response.data.actions_caches;
79
+ // resolve(response.data);
80
+ /**
81
+ * extract the prefix from the key
82
+ * @param {string} key
83
+ * @returns
84
+ */
85
+ const getPrefix = (key) => {
86
+ const split = key.split(/[-_]/);
87
+ if (split.length == 3) {
88
+ return `${split[0]}-${split[1]}`;
89
+ } else if (split.length > 3) {
90
+ return `${split[0]}-${split[1]}-${split[2]}`;
91
+ }
92
+ return split[0];
93
+ };
94
+
95
+ // Group by prefix
96
+ const grouped = data.reduce(
97
+ /**
98
+ * @param {Record<string, Record<string, any>[]>} acc
99
+ * @param {Record<string, any>} item
100
+ * @returns {Record<string, Record<string, any>[]>}
101
+ */
102
+ (acc, item) => {
103
+ const prefix = getPrefix(item.key);
104
+
105
+ if (!acc[prefix]) {
106
+ acc[prefix] = [];
107
+ }
108
+
109
+ acc[prefix].push(item);
110
+
111
+ return acc;
112
+ },
113
+ {}
114
+ );
115
+
116
+ // Convert the grouped object into an array of arrays
117
+ // const result = Object.values(grouped);
118
+ resolve(grouped);
119
+ })
120
+ .catch((error) => {
121
+ console.error("Error fetching data:", error);
122
+ reject(error); // Reject the promise with the error
123
+ });
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Deletes old GitHub Actions caches for the current repository (origin remote),
129
+ * keeping only the most recent cache for each prefix (based on creation date).
130
+ * Retrieves caches, groups by prefix, sorts by creation date, and deletes all but the latest.
131
+ */
132
+ (async () => {
133
+ try {
134
+ const remotes = await parseGitRemotes();
135
+ const GH_REPO = remotes.origin;
136
+ const caches = await get_caches(GH_REPO);
137
+
138
+ for (const key in caches) {
139
+ if (Object.hasOwnProperty.call(caches, key)) {
140
+ const items = caches[key]
141
+ .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
142
+ .map((item) => ({
143
+ ...item,
144
+ human_readable_date: new Date(item.created_at).toLocaleString()
145
+ }));
146
+
147
+ if (items.length > 1) {
148
+ const ids = items.map((o) => o.id);
149
+ ids.shift(); // keep the most recent cache
150
+ if (ids.length > 0) {
151
+ for (const id of ids) {
152
+ try {
153
+ await deleteGitHubActionsCache(GH_REPO, id);
154
+ } catch (err) {
155
+ console.error(`Error deleting cache ${id}:`, err);
156
+ }
157
+ }
158
+ } else {
159
+ console.log(`cache prefix ${key} no cache left`);
160
+ }
161
+ } else {
162
+ console.log(`cache prefix ${key} only have 1 cache`);
163
+ }
164
+ }
165
+ }
166
+ } catch (e) {
167
+ console.error(`Error: ${e}`);
168
+ }
169
+ })();