UNPKG

146 kBJavaScriptView Raw
1"use strict";
2var __create = Object.create;
3var __defProp = Object.defineProperty;
4var __defProps = Object.defineProperties;
5var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7var __getOwnPropNames = Object.getOwnPropertyNames;
8var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9var __getProtoOf = Object.getPrototypeOf;
10var __hasOwnProp = Object.prototype.hasOwnProperty;
11var __propIsEnum = Object.prototype.propertyIsEnumerable;
12var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13var __spreadValues = (a, b) => {
14 for (var prop in b || (b = {}))
15 if (__hasOwnProp.call(b, prop))
16 __defNormalProp(a, prop, b[prop]);
17 if (__getOwnPropSymbols)
18 for (var prop of __getOwnPropSymbols(b)) {
19 if (__propIsEnum.call(b, prop))
20 __defNormalProp(a, prop, b[prop]);
21 }
22 return a;
23};
24var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25var __esm = (fn, res) => function __init() {
26 return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
27};
28var __commonJS = (cb, mod) => function __require() {
29 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
30};
31var __export = (target, all) => {
32 for (var name in all)
33 __defProp(target, name, { get: all[name], enumerable: true });
34};
35var __copyProps = (to, from, except, desc) => {
36 if (from && typeof from === "object" || typeof from === "function") {
37 for (let key of __getOwnPropNames(from))
38 if (!__hasOwnProp.call(to, key) && key !== except)
39 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
40 }
41 return to;
42};
43var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
44 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
45 mod
46));
47var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48var __async = (__this, __arguments, generator) => {
49 return new Promise((resolve, reject) => {
50 var fulfilled = (value) => {
51 try {
52 step(generator.next(value));
53 } catch (e) {
54 reject(e);
55 }
56 };
57 var rejected = (value) => {
58 try {
59 step(generator.throw(value));
60 } catch (e) {
61 reject(e);
62 }
63 };
64 var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
65 step((generator = generator.apply(__this, __arguments)).next());
66 });
67};
68
69// src/lib/errors/git-error.ts
70var GitError;
71var init_git_error = __esm({
72 "src/lib/errors/git-error.ts"() {
73 "use strict";
74 GitError = class extends Error {
75 constructor(task, message) {
76 super(message);
77 this.task = task;
78 Object.setPrototypeOf(this, new.target.prototype);
79 }
80 };
81 }
82});
83
84// src/lib/errors/git-response-error.ts
85var GitResponseError;
86var init_git_response_error = __esm({
87 "src/lib/errors/git-response-error.ts"() {
88 "use strict";
89 init_git_error();
90 GitResponseError = class extends GitError {
91 constructor(git, message) {
92 super(void 0, message || String(git));
93 this.git = git;
94 }
95 };
96 }
97});
98
99// src/lib/args/pathspec.ts
100function pathspec(...paths) {
101 const key = new String(paths);
102 cache.set(key, paths);
103 return key;
104}
105function isPathSpec(path) {
106 return path instanceof String && cache.has(path);
107}
108function toPaths(pathSpec) {
109 return cache.get(pathSpec) || [];
110}
111var cache;
112var init_pathspec = __esm({
113 "src/lib/args/pathspec.ts"() {
114 "use strict";
115 cache = /* @__PURE__ */ new WeakMap();
116 }
117});
118
119// src/lib/errors/git-construct-error.ts
120var GitConstructError;
121var init_git_construct_error = __esm({
122 "src/lib/errors/git-construct-error.ts"() {
123 "use strict";
124 init_git_error();
125 GitConstructError = class extends GitError {
126 constructor(config, message) {
127 super(void 0, message);
128 this.config = config;
129 }
130 };
131 }
132});
133
134// src/lib/errors/git-plugin-error.ts
135var GitPluginError;
136var init_git_plugin_error = __esm({
137 "src/lib/errors/git-plugin-error.ts"() {
138 "use strict";
139 init_git_error();
140 GitPluginError = class extends GitError {
141 constructor(task, plugin, message) {
142 super(task, message);
143 this.task = task;
144 this.plugin = plugin;
145 Object.setPrototypeOf(this, new.target.prototype);
146 }
147 };
148 }
149});
150
151// src/lib/errors/task-configuration-error.ts
152var TaskConfigurationError;
153var init_task_configuration_error = __esm({
154 "src/lib/errors/task-configuration-error.ts"() {
155 "use strict";
156 init_git_error();
157 TaskConfigurationError = class extends GitError {
158 constructor(message) {
159 super(void 0, message);
160 }
161 };
162 }
163});
164
165// src/lib/utils/util.ts
166function asFunction(source) {
167 return typeof source === "function" ? source : NOOP;
168}
169function isUserFunction(source) {
170 return typeof source === "function" && source !== NOOP;
171}
172function splitOn(input, char) {
173 const index = input.indexOf(char);
174 if (index <= 0) {
175 return [input, ""];
176 }
177 return [input.substr(0, index), input.substr(index + 1)];
178}
179function first(input, offset = 0) {
180 return isArrayLike(input) && input.length > offset ? input[offset] : void 0;
181}
182function last(input, offset = 0) {
183 if (isArrayLike(input) && input.length > offset) {
184 return input[input.length - 1 - offset];
185 }
186}
187function isArrayLike(input) {
188 return !!(input && typeof input.length === "number");
189}
190function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") {
191 return input.split(separator).reduce((output, line) => {
192 const lineContent = trimmed2 ? line.trim() : line;
193 if (lineContent) {
194 output.push(lineContent);
195 }
196 return output;
197 }, []);
198}
199function forEachLineWithContent(input, callback) {
200 return toLinesWithContent(input, true).map((line) => callback(line));
201}
202function folderExists(path) {
203 return (0, import_file_exists.exists)(path, import_file_exists.FOLDER);
204}
205function append(target, item) {
206 if (Array.isArray(target)) {
207 if (!target.includes(item)) {
208 target.push(item);
209 }
210 } else {
211 target.add(item);
212 }
213 return item;
214}
215function including(target, item) {
216 if (Array.isArray(target) && !target.includes(item)) {
217 target.push(item);
218 }
219 return target;
220}
221function remove(target, item) {
222 if (Array.isArray(target)) {
223 const index = target.indexOf(item);
224 if (index >= 0) {
225 target.splice(index, 1);
226 }
227 } else {
228 target.delete(item);
229 }
230 return item;
231}
232function asArray(source) {
233 return Array.isArray(source) ? source : [source];
234}
235function asCamelCase(str) {
236 return str.replace(/[\s-]+(.)/g, (_all, chr) => {
237 return chr.toUpperCase();
238 });
239}
240function asStringArray(source) {
241 return asArray(source).map(String);
242}
243function asNumber(source, onNaN = 0) {
244 if (source == null) {
245 return onNaN;
246 }
247 const num = parseInt(source, 10);
248 return isNaN(num) ? onNaN : num;
249}
250function prefixedArray(input, prefix) {
251 const output = [];
252 for (let i = 0, max = input.length; i < max; i++) {
253 output.push(prefix, input[i]);
254 }
255 return output;
256}
257function bufferToString(input) {
258 return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8");
259}
260function pick(source, properties) {
261 return Object.assign(
262 {},
263 ...properties.map((property) => property in source ? { [property]: source[property] } : {})
264 );
265}
266function delay(duration = 0) {
267 return new Promise((done) => setTimeout(done, duration));
268}
269function orVoid(input) {
270 if (input === false) {
271 return void 0;
272 }
273 return input;
274}
275var import_file_exists, NULL, NOOP, objectToString;
276var init_util = __esm({
277 "src/lib/utils/util.ts"() {
278 "use strict";
279 import_file_exists = require("@kwsites/file-exists");
280 NULL = "\0";
281 NOOP = () => {
282 };
283 objectToString = Object.prototype.toString.call.bind(Object.prototype.toString);
284 }
285});
286
287// src/lib/utils/argument-filters.ts
288function filterType(input, filter, def) {
289 if (filter(input)) {
290 return input;
291 }
292 return arguments.length > 2 ? def : void 0;
293}
294function filterPrimitives(input, omit) {
295 const type = isPathSpec(input) ? "string" : typeof input;
296 return /number|string|boolean/.test(type) && (!omit || !omit.includes(type));
297}
298function filterPlainObject(input) {
299 return !!input && objectToString(input) === "[object Object]";
300}
301function filterFunction(input) {
302 return typeof input === "function";
303}
304var filterArray, filterString, filterStringArray, filterStringOrStringArray, filterHasLength;
305var init_argument_filters = __esm({
306 "src/lib/utils/argument-filters.ts"() {
307 "use strict";
308 init_util();
309 init_pathspec();
310 filterArray = (input) => {
311 return Array.isArray(input);
312 };
313 filterString = (input) => {
314 return typeof input === "string";
315 };
316 filterStringArray = (input) => {
317 return Array.isArray(input) && input.every(filterString);
318 };
319 filterStringOrStringArray = (input) => {
320 return filterString(input) || Array.isArray(input) && input.every(filterString);
321 };
322 filterHasLength = (input) => {
323 if (input == null || "number|boolean|function".includes(typeof input)) {
324 return false;
325 }
326 return Array.isArray(input) || typeof input === "string" || typeof input.length === "number";
327 };
328 }
329});
330
331// src/lib/utils/exit-codes.ts
332var ExitCodes;
333var init_exit_codes = __esm({
334 "src/lib/utils/exit-codes.ts"() {
335 "use strict";
336 ExitCodes = /* @__PURE__ */ ((ExitCodes2) => {
337 ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS";
338 ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR";
339 ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND";
340 ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN";
341 return ExitCodes2;
342 })(ExitCodes || {});
343 }
344});
345
346// src/lib/utils/git-output-streams.ts
347var GitOutputStreams;
348var init_git_output_streams = __esm({
349 "src/lib/utils/git-output-streams.ts"() {
350 "use strict";
351 GitOutputStreams = class {
352 constructor(stdOut, stdErr) {
353 this.stdOut = stdOut;
354 this.stdErr = stdErr;
355 }
356 asStrings() {
357 return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8"));
358 }
359 };
360 }
361});
362
363// src/lib/utils/line-parser.ts
364var LineParser, RemoteLineParser;
365var init_line_parser = __esm({
366 "src/lib/utils/line-parser.ts"() {
367 "use strict";
368 LineParser = class {
369 constructor(regExp, useMatches) {
370 this.matches = [];
371 this.parse = (line, target) => {
372 this.resetMatches();
373 if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) {
374 return false;
375 }
376 return this.useMatches(target, this.prepareMatches()) !== false;
377 };
378 this._regExp = Array.isArray(regExp) ? regExp : [regExp];
379 if (useMatches) {
380 this.useMatches = useMatches;
381 }
382 }
383 useMatches(target, match) {
384 throw new Error(`LineParser:useMatches not implemented`);
385 }
386 resetMatches() {
387 this.matches.length = 0;
388 }
389 prepareMatches() {
390 return this.matches;
391 }
392 addMatch(reg, index, line) {
393 const matched = line && reg.exec(line);
394 if (matched) {
395 this.pushMatch(index, matched);
396 }
397 return !!matched;
398 }
399 pushMatch(_index, matched) {
400 this.matches.push(...matched.slice(1));
401 }
402 };
403 RemoteLineParser = class extends LineParser {
404 addMatch(reg, index, line) {
405 return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line);
406 }
407 pushMatch(index, matched) {
408 if (index > 0 || matched.length > 1) {
409 super.pushMatch(index, matched);
410 }
411 }
412 };
413 }
414});
415
416// src/lib/utils/simple-git-options.ts
417function createInstanceConfig(...options) {
418 const baseDir = process.cwd();
419 const config = Object.assign(
420 __spreadValues({ baseDir }, defaultOptions),
421 ...options.filter((o) => typeof o === "object" && o)
422 );
423 config.baseDir = config.baseDir || baseDir;
424 config.trimmed = config.trimmed === true;
425 return config;
426}
427var defaultOptions;
428var init_simple_git_options = __esm({
429 "src/lib/utils/simple-git-options.ts"() {
430 "use strict";
431 defaultOptions = {
432 binary: "git",
433 maxConcurrentProcesses: 5,
434 config: [],
435 trimmed: false
436 };
437 }
438});
439
440// src/lib/utils/task-options.ts
441function appendTaskOptions(options, commands = []) {
442 if (!filterPlainObject(options)) {
443 return commands;
444 }
445 return Object.keys(options).reduce((commands2, key) => {
446 const value = options[key];
447 if (isPathSpec(value)) {
448 commands2.push(value);
449 } else if (filterPrimitives(value, ["boolean"])) {
450 commands2.push(key + "=" + value);
451 } else {
452 commands2.push(key);
453 }
454 return commands2;
455 }, commands);
456}
457function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) {
458 const command = [];
459 for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) {
460 if ("string|number".includes(typeof args[i])) {
461 command.push(String(args[i]));
462 }
463 }
464 appendTaskOptions(trailingOptionsArgument(args), command);
465 if (!objectOnly) {
466 command.push(...trailingArrayArgument(args));
467 }
468 return command;
469}
470function trailingArrayArgument(args) {
471 const hasTrailingCallback = typeof last(args) === "function";
472 return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []);
473}
474function trailingOptionsArgument(args) {
475 const hasTrailingCallback = filterFunction(last(args));
476 return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject);
477}
478function trailingFunctionArgument(args, includeNoop = true) {
479 const callback = asFunction(last(args));
480 return includeNoop || isUserFunction(callback) ? callback : void 0;
481}
482var init_task_options = __esm({
483 "src/lib/utils/task-options.ts"() {
484 "use strict";
485 init_argument_filters();
486 init_util();
487 init_pathspec();
488 }
489});
490
491// src/lib/utils/task-parser.ts
492function callTaskParser(parser4, streams) {
493 return parser4(streams.stdOut, streams.stdErr);
494}
495function parseStringResponse(result, parsers12, texts, trim = true) {
496 asArray(texts).forEach((text) => {
497 for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) {
498 const line = (offset = 0) => {
499 if (i + offset >= max) {
500 return;
501 }
502 return lines[i + offset];
503 };
504 parsers12.some(({ parse }) => parse(line, result));
505 }
506 });
507 return result;
508}
509var init_task_parser = __esm({
510 "src/lib/utils/task-parser.ts"() {
511 "use strict";
512 init_util();
513 }
514});
515
516// src/lib/utils/index.ts
517var utils_exports = {};
518__export(utils_exports, {
519 ExitCodes: () => ExitCodes,
520 GitOutputStreams: () => GitOutputStreams,
521 LineParser: () => LineParser,
522 NOOP: () => NOOP,
523 NULL: () => NULL,
524 RemoteLineParser: () => RemoteLineParser,
525 append: () => append,
526 appendTaskOptions: () => appendTaskOptions,
527 asArray: () => asArray,
528 asCamelCase: () => asCamelCase,
529 asFunction: () => asFunction,
530 asNumber: () => asNumber,
531 asStringArray: () => asStringArray,
532 bufferToString: () => bufferToString,
533 callTaskParser: () => callTaskParser,
534 createInstanceConfig: () => createInstanceConfig,
535 delay: () => delay,
536 filterArray: () => filterArray,
537 filterFunction: () => filterFunction,
538 filterHasLength: () => filterHasLength,
539 filterPlainObject: () => filterPlainObject,
540 filterPrimitives: () => filterPrimitives,
541 filterString: () => filterString,
542 filterStringArray: () => filterStringArray,
543 filterStringOrStringArray: () => filterStringOrStringArray,
544 filterType: () => filterType,
545 first: () => first,
546 folderExists: () => folderExists,
547 forEachLineWithContent: () => forEachLineWithContent,
548 getTrailingOptions: () => getTrailingOptions,
549 including: () => including,
550 isUserFunction: () => isUserFunction,
551 last: () => last,
552 objectToString: () => objectToString,
553 orVoid: () => orVoid,
554 parseStringResponse: () => parseStringResponse,
555 pick: () => pick,
556 prefixedArray: () => prefixedArray,
557 remove: () => remove,
558 splitOn: () => splitOn,
559 toLinesWithContent: () => toLinesWithContent,
560 trailingFunctionArgument: () => trailingFunctionArgument,
561 trailingOptionsArgument: () => trailingOptionsArgument
562});
563var init_utils = __esm({
564 "src/lib/utils/index.ts"() {
565 "use strict";
566 init_argument_filters();
567 init_exit_codes();
568 init_git_output_streams();
569 init_line_parser();
570 init_simple_git_options();
571 init_task_options();
572 init_task_parser();
573 init_util();
574 }
575});
576
577// src/lib/tasks/check-is-repo.ts
578var check_is_repo_exports = {};
579__export(check_is_repo_exports, {
580 CheckRepoActions: () => CheckRepoActions,
581 checkIsBareRepoTask: () => checkIsBareRepoTask,
582 checkIsRepoRootTask: () => checkIsRepoRootTask,
583 checkIsRepoTask: () => checkIsRepoTask
584});
585function checkIsRepoTask(action) {
586 switch (action) {
587 case "bare" /* BARE */:
588 return checkIsBareRepoTask();
589 case "root" /* IS_REPO_ROOT */:
590 return checkIsRepoRootTask();
591 }
592 const commands = ["rev-parse", "--is-inside-work-tree"];
593 return {
594 commands,
595 format: "utf-8",
596 onError,
597 parser
598 };
599}
600function checkIsRepoRootTask() {
601 const commands = ["rev-parse", "--git-dir"];
602 return {
603 commands,
604 format: "utf-8",
605 onError,
606 parser(path) {
607 return /^\.(git)?$/.test(path.trim());
608 }
609 };
610}
611function checkIsBareRepoTask() {
612 const commands = ["rev-parse", "--is-bare-repository"];
613 return {
614 commands,
615 format: "utf-8",
616 onError,
617 parser
618 };
619}
620function isNotRepoMessage(error) {
621 return /(Not a git repository|Kein Git-Repository)/i.test(String(error));
622}
623var CheckRepoActions, onError, parser;
624var init_check_is_repo = __esm({
625 "src/lib/tasks/check-is-repo.ts"() {
626 "use strict";
627 init_utils();
628 CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => {
629 CheckRepoActions2["BARE"] = "bare";
630 CheckRepoActions2["IN_TREE"] = "tree";
631 CheckRepoActions2["IS_REPO_ROOT"] = "root";
632 return CheckRepoActions2;
633 })(CheckRepoActions || {});
634 onError = ({ exitCode }, error, done, fail) => {
635 if (exitCode === 128 /* UNCLEAN */ && isNotRepoMessage(error)) {
636 return done(Buffer.from("false"));
637 }
638 fail(error);
639 };
640 parser = (text) => {
641 return text.trim() === "true";
642 };
643 }
644});
645
646// src/lib/responses/CleanSummary.ts
647function cleanSummaryParser(dryRun, text) {
648 const summary = new CleanResponse(dryRun);
649 const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp;
650 toLinesWithContent(text).forEach((line) => {
651 const removed = line.replace(regexp, "");
652 summary.paths.push(removed);
653 (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed);
654 });
655 return summary;
656}
657var CleanResponse, removalRegexp, dryRunRemovalRegexp, isFolderRegexp;
658var init_CleanSummary = __esm({
659 "src/lib/responses/CleanSummary.ts"() {
660 "use strict";
661 init_utils();
662 CleanResponse = class {
663 constructor(dryRun) {
664 this.dryRun = dryRun;
665 this.paths = [];
666 this.files = [];
667 this.folders = [];
668 }
669 };
670 removalRegexp = /^[a-z]+\s*/i;
671 dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i;
672 isFolderRegexp = /\/$/;
673 }
674});
675
676// src/lib/tasks/task.ts
677var task_exports = {};
678__export(task_exports, {
679 EMPTY_COMMANDS: () => EMPTY_COMMANDS,
680 adhocExecTask: () => adhocExecTask,
681 configurationErrorTask: () => configurationErrorTask,
682 isBufferTask: () => isBufferTask,
683 isEmptyTask: () => isEmptyTask,
684 straightThroughBufferTask: () => straightThroughBufferTask,
685 straightThroughStringTask: () => straightThroughStringTask
686});
687function adhocExecTask(parser4) {
688 return {
689 commands: EMPTY_COMMANDS,
690 format: "empty",
691 parser: parser4
692 };
693}
694function configurationErrorTask(error) {
695 return {
696 commands: EMPTY_COMMANDS,
697 format: "empty",
698 parser() {
699 throw typeof error === "string" ? new TaskConfigurationError(error) : error;
700 }
701 };
702}
703function straightThroughStringTask(commands, trimmed2 = false) {
704 return {
705 commands,
706 format: "utf-8",
707 parser(text) {
708 return trimmed2 ? String(text).trim() : text;
709 }
710 };
711}
712function straightThroughBufferTask(commands) {
713 return {
714 commands,
715 format: "buffer",
716 parser(buffer) {
717 return buffer;
718 }
719 };
720}
721function isBufferTask(task) {
722 return task.format === "buffer";
723}
724function isEmptyTask(task) {
725 return task.format === "empty" || !task.commands.length;
726}
727var EMPTY_COMMANDS;
728var init_task = __esm({
729 "src/lib/tasks/task.ts"() {
730 "use strict";
731 init_task_configuration_error();
732 EMPTY_COMMANDS = [];
733 }
734});
735
736// src/lib/tasks/clean.ts
737var clean_exports = {};
738__export(clean_exports, {
739 CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE,
740 CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED,
741 CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION,
742 CleanOptions: () => CleanOptions,
743 cleanTask: () => cleanTask,
744 cleanWithOptionsTask: () => cleanWithOptionsTask,
745 isCleanOptionsArray: () => isCleanOptionsArray
746});
747function cleanWithOptionsTask(mode, customArgs) {
748 const { cleanMode, options, valid } = getCleanOptions(mode);
749 if (!cleanMode) {
750 return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED);
751 }
752 if (!valid.options) {
753 return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode));
754 }
755 options.push(...customArgs);
756 if (options.some(isInteractiveMode)) {
757 return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE);
758 }
759 return cleanTask(cleanMode, options);
760}
761function cleanTask(mode, customArgs) {
762 const commands = ["clean", `-${mode}`, ...customArgs];
763 return {
764 commands,
765 format: "utf-8",
766 parser(text) {
767 return cleanSummaryParser(mode === "n" /* DRY_RUN */, text);
768 }
769 };
770}
771function isCleanOptionsArray(input) {
772 return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test));
773}
774function getCleanOptions(input) {
775 let cleanMode;
776 let options = [];
777 let valid = { cleanMode: false, options: true };
778 input.replace(/[^a-z]i/g, "").split("").forEach((char) => {
779 if (isCleanMode(char)) {
780 cleanMode = char;
781 valid.cleanMode = true;
782 } else {
783 valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`);
784 }
785 });
786 return {
787 cleanMode,
788 options,
789 valid
790 };
791}
792function isCleanMode(cleanMode) {
793 return cleanMode === "f" /* FORCE */ || cleanMode === "n" /* DRY_RUN */;
794}
795function isKnownOption(option) {
796 return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1));
797}
798function isInteractiveMode(option) {
799 if (/^-[^\-]/.test(option)) {
800 return option.indexOf("i") > 0;
801 }
802 return option === "--interactive";
803}
804var CONFIG_ERROR_INTERACTIVE_MODE, CONFIG_ERROR_MODE_REQUIRED, CONFIG_ERROR_UNKNOWN_OPTION, CleanOptions, CleanOptionValues;
805var init_clean = __esm({
806 "src/lib/tasks/clean.ts"() {
807 "use strict";
808 init_CleanSummary();
809 init_utils();
810 init_task();
811 CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported";
812 CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required';
813 CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: ";
814 CleanOptions = /* @__PURE__ */ ((CleanOptions2) => {
815 CleanOptions2["DRY_RUN"] = "n";
816 CleanOptions2["FORCE"] = "f";
817 CleanOptions2["IGNORED_INCLUDED"] = "x";
818 CleanOptions2["IGNORED_ONLY"] = "X";
819 CleanOptions2["EXCLUDING"] = "e";
820 CleanOptions2["QUIET"] = "q";
821 CleanOptions2["RECURSIVE"] = "d";
822 return CleanOptions2;
823 })(CleanOptions || {});
824 CleanOptionValues = /* @__PURE__ */ new Set([
825 "i",
826 ...asStringArray(Object.values(CleanOptions))
827 ]);
828 }
829});
830
831// src/lib/responses/ConfigList.ts
832function configListParser(text) {
833 const config = new ConfigList();
834 for (const item of configParser(text)) {
835 config.addValue(item.file, String(item.key), item.value);
836 }
837 return config;
838}
839function configGetParser(text, key) {
840 let value = null;
841 const values = [];
842 const scopes = /* @__PURE__ */ new Map();
843 for (const item of configParser(text, key)) {
844 if (item.key !== key) {
845 continue;
846 }
847 values.push(value = item.value);
848 if (!scopes.has(item.file)) {
849 scopes.set(item.file, []);
850 }
851 scopes.get(item.file).push(value);
852 }
853 return {
854 key,
855 paths: Array.from(scopes.keys()),
856 scopes,
857 value,
858 values
859 };
860}
861function configFilePath(filePath) {
862 return filePath.replace(/^(file):/, "");
863}
864function* configParser(text, requestedKey = null) {
865 const lines = text.split("\0");
866 for (let i = 0, max = lines.length - 1; i < max; ) {
867 const file = configFilePath(lines[i++]);
868 let value = lines[i++];
869 let key = requestedKey;
870 if (value.includes("\n")) {
871 const line = splitOn(value, "\n");
872 key = line[0];
873 value = line[1];
874 }
875 yield { file, key, value };
876 }
877}
878var ConfigList;
879var init_ConfigList = __esm({
880 "src/lib/responses/ConfigList.ts"() {
881 "use strict";
882 init_utils();
883 ConfigList = class {
884 constructor() {
885 this.files = [];
886 this.values = /* @__PURE__ */ Object.create(null);
887 }
888 get all() {
889 if (!this._all) {
890 this._all = this.files.reduce((all, file) => {
891 return Object.assign(all, this.values[file]);
892 }, {});
893 }
894 return this._all;
895 }
896 addFile(file) {
897 if (!(file in this.values)) {
898 const latest = last(this.files);
899 this.values[file] = latest ? Object.create(this.values[latest]) : {};
900 this.files.push(file);
901 }
902 return this.values[file];
903 }
904 addValue(file, key, value) {
905 const values = this.addFile(file);
906 if (!values.hasOwnProperty(key)) {
907 values[key] = value;
908 } else if (Array.isArray(values[key])) {
909 values[key].push(value);
910 } else {
911 values[key] = [values[key], value];
912 }
913 this._all = void 0;
914 }
915 };
916 }
917});
918
919// src/lib/tasks/config.ts
920function asConfigScope(scope, fallback) {
921 if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) {
922 return scope;
923 }
924 return fallback;
925}
926function addConfigTask(key, value, append2, scope) {
927 const commands = ["config", `--${scope}`];
928 if (append2) {
929 commands.push("--add");
930 }
931 commands.push(key, value);
932 return {
933 commands,
934 format: "utf-8",
935 parser(text) {
936 return text;
937 }
938 };
939}
940function getConfigTask(key, scope) {
941 const commands = ["config", "--null", "--show-origin", "--get-all", key];
942 if (scope) {
943 commands.splice(1, 0, `--${scope}`);
944 }
945 return {
946 commands,
947 format: "utf-8",
948 parser(text) {
949 return configGetParser(text, key);
950 }
951 };
952}
953function listConfigTask(scope) {
954 const commands = ["config", "--list", "--show-origin", "--null"];
955 if (scope) {
956 commands.push(`--${scope}`);
957 }
958 return {
959 commands,
960 format: "utf-8",
961 parser(text) {
962 return configListParser(text);
963 }
964 };
965}
966function config_default() {
967 return {
968 addConfig(key, value, ...rest) {
969 return this._runTask(
970 addConfigTask(
971 key,
972 value,
973 rest[0] === true,
974 asConfigScope(rest[1], "local" /* local */)
975 ),
976 trailingFunctionArgument(arguments)
977 );
978 },
979 getConfig(key, scope) {
980 return this._runTask(
981 getConfigTask(key, asConfigScope(scope, void 0)),
982 trailingFunctionArgument(arguments)
983 );
984 },
985 listConfig(...rest) {
986 return this._runTask(
987 listConfigTask(asConfigScope(rest[0], void 0)),
988 trailingFunctionArgument(arguments)
989 );
990 }
991 };
992}
993var GitConfigScope;
994var init_config = __esm({
995 "src/lib/tasks/config.ts"() {
996 "use strict";
997 init_ConfigList();
998 init_utils();
999 GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => {
1000 GitConfigScope2["system"] = "system";
1001 GitConfigScope2["global"] = "global";
1002 GitConfigScope2["local"] = "local";
1003 GitConfigScope2["worktree"] = "worktree";
1004 return GitConfigScope2;
1005 })(GitConfigScope || {});
1006 }
1007});
1008
1009// src/lib/tasks/diff-name-status.ts
1010function isDiffNameStatus(input) {
1011 return diffNameStatus.has(input);
1012}
1013var DiffNameStatus, diffNameStatus;
1014var init_diff_name_status = __esm({
1015 "src/lib/tasks/diff-name-status.ts"() {
1016 "use strict";
1017 DiffNameStatus = /* @__PURE__ */ ((DiffNameStatus2) => {
1018 DiffNameStatus2["ADDED"] = "A";
1019 DiffNameStatus2["COPIED"] = "C";
1020 DiffNameStatus2["DELETED"] = "D";
1021 DiffNameStatus2["MODIFIED"] = "M";
1022 DiffNameStatus2["RENAMED"] = "R";
1023 DiffNameStatus2["CHANGED"] = "T";
1024 DiffNameStatus2["UNMERGED"] = "U";
1025 DiffNameStatus2["UNKNOWN"] = "X";
1026 DiffNameStatus2["BROKEN"] = "B";
1027 return DiffNameStatus2;
1028 })(DiffNameStatus || {});
1029 diffNameStatus = new Set(Object.values(DiffNameStatus));
1030 }
1031});
1032
1033// src/lib/tasks/grep.ts
1034function grepQueryBuilder(...params) {
1035 return new GrepQuery().param(...params);
1036}
1037function parseGrep(grep) {
1038 const paths = /* @__PURE__ */ new Set();
1039 const results = {};
1040 forEachLineWithContent(grep, (input) => {
1041 const [path, line, preview] = input.split(NULL);
1042 paths.add(path);
1043 (results[path] = results[path] || []).push({
1044 line: asNumber(line),
1045 path,
1046 preview
1047 });
1048 });
1049 return {
1050 paths,
1051 results
1052 };
1053}
1054function grep_default() {
1055 return {
1056 grep(searchTerm) {
1057 const then = trailingFunctionArgument(arguments);
1058 const options = getTrailingOptions(arguments);
1059 for (const option of disallowedOptions) {
1060 if (options.includes(option)) {
1061 return this._runTask(
1062 configurationErrorTask(`git.grep: use of "${option}" is not supported.`),
1063 then
1064 );
1065 }
1066 }
1067 if (typeof searchTerm === "string") {
1068 searchTerm = grepQueryBuilder().param(searchTerm);
1069 }
1070 const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm];
1071 return this._runTask(
1072 {
1073 commands,
1074 format: "utf-8",
1075 parser(stdOut) {
1076 return parseGrep(stdOut);
1077 }
1078 },
1079 then
1080 );
1081 }
1082 };
1083}
1084var disallowedOptions, Query, _a, GrepQuery;
1085var init_grep = __esm({
1086 "src/lib/tasks/grep.ts"() {
1087 "use strict";
1088 init_utils();
1089 init_task();
1090 disallowedOptions = ["-h"];
1091 Query = Symbol("grepQuery");
1092 GrepQuery = class {
1093 constructor() {
1094 this[_a] = [];
1095 }
1096 *[(_a = Query, Symbol.iterator)]() {
1097 for (const query of this[Query]) {
1098 yield query;
1099 }
1100 }
1101 and(...and) {
1102 and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")");
1103 return this;
1104 }
1105 param(...param) {
1106 this[Query].push(...prefixedArray(param, "-e"));
1107 return this;
1108 }
1109 };
1110 }
1111});
1112
1113// src/lib/tasks/reset.ts
1114var reset_exports = {};
1115__export(reset_exports, {
1116 ResetMode: () => ResetMode,
1117 getResetMode: () => getResetMode,
1118 resetTask: () => resetTask
1119});
1120function resetTask(mode, customArgs) {
1121 const commands = ["reset"];
1122 if (isValidResetMode(mode)) {
1123 commands.push(`--${mode}`);
1124 }
1125 commands.push(...customArgs);
1126 return straightThroughStringTask(commands);
1127}
1128function getResetMode(mode) {
1129 if (isValidResetMode(mode)) {
1130 return mode;
1131 }
1132 switch (typeof mode) {
1133 case "string":
1134 case "undefined":
1135 return "soft" /* SOFT */;
1136 }
1137 return;
1138}
1139function isValidResetMode(mode) {
1140 return ResetModes.includes(mode);
1141}
1142var ResetMode, ResetModes;
1143var init_reset = __esm({
1144 "src/lib/tasks/reset.ts"() {
1145 "use strict";
1146 init_task();
1147 ResetMode = /* @__PURE__ */ ((ResetMode2) => {
1148 ResetMode2["MIXED"] = "mixed";
1149 ResetMode2["SOFT"] = "soft";
1150 ResetMode2["HARD"] = "hard";
1151 ResetMode2["MERGE"] = "merge";
1152 ResetMode2["KEEP"] = "keep";
1153 return ResetMode2;
1154 })(ResetMode || {});
1155 ResetModes = Array.from(Object.values(ResetMode));
1156 }
1157});
1158
1159// src/lib/api.ts
1160var api_exports = {};
1161__export(api_exports, {
1162 CheckRepoActions: () => CheckRepoActions,
1163 CleanOptions: () => CleanOptions,
1164 DiffNameStatus: () => DiffNameStatus,
1165 GitConfigScope: () => GitConfigScope,
1166 GitConstructError: () => GitConstructError,
1167 GitError: () => GitError,
1168 GitPluginError: () => GitPluginError,
1169 GitResponseError: () => GitResponseError,
1170 ResetMode: () => ResetMode,
1171 TaskConfigurationError: () => TaskConfigurationError,
1172 grepQueryBuilder: () => grepQueryBuilder,
1173 pathspec: () => pathspec
1174});
1175var init_api = __esm({
1176 "src/lib/api.ts"() {
1177 "use strict";
1178 init_pathspec();
1179 init_git_construct_error();
1180 init_git_error();
1181 init_git_plugin_error();
1182 init_git_response_error();
1183 init_task_configuration_error();
1184 init_check_is_repo();
1185 init_clean();
1186 init_config();
1187 init_diff_name_status();
1188 init_grep();
1189 init_reset();
1190 }
1191});
1192
1193// src/lib/plugins/abort-plugin.ts
1194function abortPlugin(signal) {
1195 if (!signal) {
1196 return;
1197 }
1198 const onSpawnAfter = {
1199 type: "spawn.after",
1200 action(_data, context) {
1201 function kill() {
1202 context.kill(new GitPluginError(void 0, "abort", "Abort signal received"));
1203 }
1204 signal.addEventListener("abort", kill);
1205 context.spawned.on("close", () => signal.removeEventListener("abort", kill));
1206 }
1207 };
1208 const onSpawnBefore = {
1209 type: "spawn.before",
1210 action(_data, context) {
1211 if (signal.aborted) {
1212 context.kill(new GitPluginError(void 0, "abort", "Abort already signaled"));
1213 }
1214 }
1215 };
1216 return [onSpawnBefore, onSpawnAfter];
1217}
1218var init_abort_plugin = __esm({
1219 "src/lib/plugins/abort-plugin.ts"() {
1220 "use strict";
1221 init_git_plugin_error();
1222 }
1223});
1224
1225// src/lib/plugins/block-unsafe-operations-plugin.ts
1226function isConfigSwitch(arg) {
1227 return typeof arg === "string" && arg.trim().toLowerCase() === "-c";
1228}
1229function preventProtocolOverride(arg, next) {
1230 if (!isConfigSwitch(arg)) {
1231 return;
1232 }
1233 if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) {
1234 return;
1235 }
1236 throw new GitPluginError(
1237 void 0,
1238 "unsafe",
1239 "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol"
1240 );
1241}
1242function preventUploadPack(arg, method) {
1243 if (/^\s*--(upload|receive)-pack/.test(arg)) {
1244 throw new GitPluginError(
1245 void 0,
1246 "unsafe",
1247 `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`
1248 );
1249 }
1250 if (method === "clone" && /^\s*-u\b/.test(arg)) {
1251 throw new GitPluginError(
1252 void 0,
1253 "unsafe",
1254 `Use of clone with option -u is not permitted without enabling allowUnsafePack`
1255 );
1256 }
1257 if (method === "push" && /^\s*--exec\b/.test(arg)) {
1258 throw new GitPluginError(
1259 void 0,
1260 "unsafe",
1261 `Use of push with option --exec is not permitted without enabling allowUnsafePack`
1262 );
1263 }
1264}
1265function blockUnsafeOperationsPlugin({
1266 allowUnsafeProtocolOverride = false,
1267 allowUnsafePack = false
1268} = {}) {
1269 return {
1270 type: "spawn.args",
1271 action(args, context) {
1272 args.forEach((current, index) => {
1273 const next = index < args.length ? args[index + 1] : "";
1274 allowUnsafeProtocolOverride || preventProtocolOverride(current, next);
1275 allowUnsafePack || preventUploadPack(current, context.method);
1276 });
1277 return args;
1278 }
1279 };
1280}
1281var init_block_unsafe_operations_plugin = __esm({
1282 "src/lib/plugins/block-unsafe-operations-plugin.ts"() {
1283 "use strict";
1284 init_git_plugin_error();
1285 }
1286});
1287
1288// src/lib/plugins/command-config-prefixing-plugin.ts
1289function commandConfigPrefixingPlugin(configuration) {
1290 const prefix = prefixedArray(configuration, "-c");
1291 return {
1292 type: "spawn.args",
1293 action(data) {
1294 return [...prefix, ...data];
1295 }
1296 };
1297}
1298var init_command_config_prefixing_plugin = __esm({
1299 "src/lib/plugins/command-config-prefixing-plugin.ts"() {
1300 "use strict";
1301 init_utils();
1302 }
1303});
1304
1305// src/lib/plugins/completion-detection.plugin.ts
1306function completionDetectionPlugin({
1307 onClose = true,
1308 onExit = 50
1309} = {}) {
1310 function createEvents() {
1311 let exitCode = -1;
1312 const events = {
1313 close: (0, import_promise_deferred.deferred)(),
1314 closeTimeout: (0, import_promise_deferred.deferred)(),
1315 exit: (0, import_promise_deferred.deferred)(),
1316 exitTimeout: (0, import_promise_deferred.deferred)()
1317 };
1318 const result = Promise.race([
1319 onClose === false ? never : events.closeTimeout.promise,
1320 onExit === false ? never : events.exitTimeout.promise
1321 ]);
1322 configureTimeout(onClose, events.close, events.closeTimeout);
1323 configureTimeout(onExit, events.exit, events.exitTimeout);
1324 return {
1325 close(code) {
1326 exitCode = code;
1327 events.close.done();
1328 },
1329 exit(code) {
1330 exitCode = code;
1331 events.exit.done();
1332 },
1333 get exitCode() {
1334 return exitCode;
1335 },
1336 result
1337 };
1338 }
1339 function configureTimeout(flag, event, timeout) {
1340 if (flag === false) {
1341 return;
1342 }
1343 (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done);
1344 }
1345 return {
1346 type: "spawn.after",
1347 action(_0, _1) {
1348 return __async(this, arguments, function* (_data, { spawned, close }) {
1349 var _a3, _b;
1350 const events = createEvents();
1351 let deferClose = true;
1352 let quickClose = () => void (deferClose = false);
1353 (_a3 = spawned.stdout) == null ? void 0 : _a3.on("data", quickClose);
1354 (_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose);
1355 spawned.on("error", quickClose);
1356 spawned.on("close", (code) => events.close(code));
1357 spawned.on("exit", (code) => events.exit(code));
1358 try {
1359 yield events.result;
1360 if (deferClose) {
1361 yield delay(50);
1362 }
1363 close(events.exitCode);
1364 } catch (err) {
1365 close(events.exitCode, err);
1366 }
1367 });
1368 }
1369 };
1370}
1371var import_promise_deferred, never;
1372var init_completion_detection_plugin = __esm({
1373 "src/lib/plugins/completion-detection.plugin.ts"() {
1374 "use strict";
1375 import_promise_deferred = require("@kwsites/promise-deferred");
1376 init_utils();
1377 never = (0, import_promise_deferred.deferred)().promise;
1378 }
1379});
1380
1381// src/lib/plugins/custom-binary.plugin.ts
1382function isBadArgument(arg) {
1383 return !arg || !/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(arg);
1384}
1385function toBinaryConfig(input, allowUnsafe) {
1386 if (input.length < 1 || input.length > 2) {
1387 throw new GitPluginError(void 0, "binary", WRONG_NUMBER_ERR);
1388 }
1389 const isBad = input.some(isBadArgument);
1390 if (isBad) {
1391 if (allowUnsafe) {
1392 console.warn(WRONG_CHARS_ERR);
1393 } else {
1394 throw new GitPluginError(void 0, "binary", WRONG_CHARS_ERR);
1395 }
1396 }
1397 const [binary, prefix] = input;
1398 return {
1399 binary,
1400 prefix
1401 };
1402}
1403function customBinaryPlugin(plugins, input = ["git"], allowUnsafe = false) {
1404 let config = toBinaryConfig(asArray(input), allowUnsafe);
1405 plugins.on("binary", (input2) => {
1406 config = toBinaryConfig(asArray(input2), allowUnsafe);
1407 });
1408 plugins.append("spawn.binary", () => {
1409 return config.binary;
1410 });
1411 plugins.append("spawn.args", (data) => {
1412 return config.prefix ? [config.prefix, ...data] : data;
1413 });
1414}
1415var WRONG_NUMBER_ERR, WRONG_CHARS_ERR;
1416var init_custom_binary_plugin = __esm({
1417 "src/lib/plugins/custom-binary.plugin.ts"() {
1418 "use strict";
1419 init_git_plugin_error();
1420 init_utils();
1421 WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`;
1422 WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`;
1423 }
1424});
1425
1426// src/lib/plugins/error-detection.plugin.ts
1427function isTaskError(result) {
1428 return !!(result.exitCode && result.stdErr.length);
1429}
1430function getErrorMessage(result) {
1431 return Buffer.concat([...result.stdOut, ...result.stdErr]);
1432}
1433function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) {
1434 return (error, result) => {
1435 if (!overwrite && error || !isError(result)) {
1436 return error;
1437 }
1438 return errorMessage(result);
1439 };
1440}
1441function errorDetectionPlugin(config) {
1442 return {
1443 type: "task.error",
1444 action(data, context) {
1445 const error = config(data.error, {
1446 stdErr: context.stdErr,
1447 stdOut: context.stdOut,
1448 exitCode: context.exitCode
1449 });
1450 if (Buffer.isBuffer(error)) {
1451 return { error: new GitError(void 0, error.toString("utf-8")) };
1452 }
1453 return {
1454 error
1455 };
1456 }
1457 };
1458}
1459var init_error_detection_plugin = __esm({
1460 "src/lib/plugins/error-detection.plugin.ts"() {
1461 "use strict";
1462 init_git_error();
1463 }
1464});
1465
1466// src/lib/plugins/plugin-store.ts
1467var import_node_events, PluginStore;
1468var init_plugin_store = __esm({
1469 "src/lib/plugins/plugin-store.ts"() {
1470 "use strict";
1471 import_node_events = require("node:events");
1472 init_utils();
1473 PluginStore = class {
1474 constructor() {
1475 this.plugins = /* @__PURE__ */ new Set();
1476 this.events = new import_node_events.EventEmitter();
1477 }
1478 on(type, listener) {
1479 this.events.on(type, listener);
1480 }
1481 reconfigure(type, data) {
1482 this.events.emit(type, data);
1483 }
1484 append(type, action) {
1485 const plugin = append(this.plugins, { type, action });
1486 return () => this.plugins.delete(plugin);
1487 }
1488 add(plugin) {
1489 const plugins = [];
1490 asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2)));
1491 return () => {
1492 plugins.forEach((plugin2) => this.plugins.delete(plugin2));
1493 };
1494 }
1495 exec(type, data, context) {
1496 let output = data;
1497 const contextual = Object.freeze(Object.create(context));
1498 for (const plugin of this.plugins) {
1499 if (plugin.type === type) {
1500 output = plugin.action(output, contextual);
1501 }
1502 }
1503 return output;
1504 }
1505 };
1506 }
1507});
1508
1509// src/lib/plugins/progress-monitor-plugin.ts
1510function progressMonitorPlugin(progress) {
1511 const progressCommand = "--progress";
1512 const progressMethods = ["checkout", "clone", "fetch", "pull", "push"];
1513 const onProgress = {
1514 type: "spawn.after",
1515 action(_data, context) {
1516 var _a2;
1517 if (!context.commands.includes(progressCommand)) {
1518 return;
1519 }
1520 (_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => {
1521 const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8"));
1522 if (!message) {
1523 return;
1524 }
1525 progress({
1526 method: context.method,
1527 stage: progressEventStage(message[1]),
1528 progress: asNumber(message[2]),
1529 processed: asNumber(message[3]),
1530 total: asNumber(message[4])
1531 });
1532 });
1533 }
1534 };
1535 const onArgs = {
1536 type: "spawn.args",
1537 action(args, context) {
1538 if (!progressMethods.includes(context.method)) {
1539 return args;
1540 }
1541 return including(args, progressCommand);
1542 }
1543 };
1544 return [onArgs, onProgress];
1545}
1546function progressEventStage(input) {
1547 return String(input.toLowerCase().split(" ", 1)) || "unknown";
1548}
1549var init_progress_monitor_plugin = __esm({
1550 "src/lib/plugins/progress-monitor-plugin.ts"() {
1551 "use strict";
1552 init_utils();
1553 }
1554});
1555
1556// src/lib/plugins/simple-git-plugin.ts
1557var init_simple_git_plugin = __esm({
1558 "src/lib/plugins/simple-git-plugin.ts"() {
1559 "use strict";
1560 }
1561});
1562
1563// src/lib/plugins/spawn-options-plugin.ts
1564function spawnOptionsPlugin(spawnOptions) {
1565 const options = pick(spawnOptions, ["uid", "gid"]);
1566 return {
1567 type: "spawn.options",
1568 action(data) {
1569 return __spreadValues(__spreadValues({}, options), data);
1570 }
1571 };
1572}
1573var init_spawn_options_plugin = __esm({
1574 "src/lib/plugins/spawn-options-plugin.ts"() {
1575 "use strict";
1576 init_utils();
1577 }
1578});
1579
1580// src/lib/plugins/timout-plugin.ts
1581function timeoutPlugin({
1582 block,
1583 stdErr = true,
1584 stdOut = true
1585}) {
1586 if (block > 0) {
1587 return {
1588 type: "spawn.after",
1589 action(_data, context) {
1590 var _a2, _b;
1591 let timeout;
1592 function wait() {
1593 timeout && clearTimeout(timeout);
1594 timeout = setTimeout(kill, block);
1595 }
1596 function stop() {
1597 var _a3, _b2;
1598 (_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait);
1599 (_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait);
1600 context.spawned.off("exit", stop);
1601 context.spawned.off("close", stop);
1602 timeout && clearTimeout(timeout);
1603 }
1604 function kill() {
1605 stop();
1606 context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`));
1607 }
1608 stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait));
1609 stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait));
1610 context.spawned.on("exit", stop);
1611 context.spawned.on("close", stop);
1612 wait();
1613 }
1614 };
1615 }
1616}
1617var init_timout_plugin = __esm({
1618 "src/lib/plugins/timout-plugin.ts"() {
1619 "use strict";
1620 init_git_plugin_error();
1621 }
1622});
1623
1624// src/lib/plugins/index.ts
1625var init_plugins = __esm({
1626 "src/lib/plugins/index.ts"() {
1627 "use strict";
1628 init_abort_plugin();
1629 init_block_unsafe_operations_plugin();
1630 init_command_config_prefixing_plugin();
1631 init_completion_detection_plugin();
1632 init_custom_binary_plugin();
1633 init_error_detection_plugin();
1634 init_plugin_store();
1635 init_progress_monitor_plugin();
1636 init_simple_git_plugin();
1637 init_spawn_options_plugin();
1638 init_timout_plugin();
1639 }
1640});
1641
1642// src/lib/plugins/suffix-paths.plugin.ts
1643function suffixPathsPlugin() {
1644 return {
1645 type: "spawn.args",
1646 action(data) {
1647 const prefix = [];
1648 let suffix;
1649 function append2(args) {
1650 (suffix = suffix || []).push(...args);
1651 }
1652 for (let i = 0; i < data.length; i++) {
1653 const param = data[i];
1654 if (isPathSpec(param)) {
1655 append2(toPaths(param));
1656 continue;
1657 }
1658 if (param === "--") {
1659 append2(
1660 data.slice(i + 1).flatMap((item) => isPathSpec(item) && toPaths(item) || item)
1661 );
1662 break;
1663 }
1664 prefix.push(param);
1665 }
1666 return !suffix ? prefix : [...prefix, "--", ...suffix.map(String)];
1667 }
1668 };
1669}
1670var init_suffix_paths_plugin = __esm({
1671 "src/lib/plugins/suffix-paths.plugin.ts"() {
1672 "use strict";
1673 init_pathspec();
1674 }
1675});
1676
1677// src/lib/git-logger.ts
1678function createLog() {
1679 return (0, import_debug.default)("simple-git");
1680}
1681function prefixedLogger(to, prefix, forward) {
1682 if (!prefix || !String(prefix).replace(/\s*/, "")) {
1683 return !forward ? to : (message, ...args) => {
1684 to(message, ...args);
1685 forward(message, ...args);
1686 };
1687 }
1688 return (message, ...args) => {
1689 to(`%s ${message}`, prefix, ...args);
1690 if (forward) {
1691 forward(message, ...args);
1692 }
1693 };
1694}
1695function childLoggerName(name, childDebugger, { namespace: parentNamespace }) {
1696 if (typeof name === "string") {
1697 return name;
1698 }
1699 const childNamespace = childDebugger && childDebugger.namespace || "";
1700 if (childNamespace.startsWith(parentNamespace)) {
1701 return childNamespace.substr(parentNamespace.length + 1);
1702 }
1703 return childNamespace || parentNamespace;
1704}
1705function createLogger(label, verbose, initialStep, infoDebugger = createLog()) {
1706 const labelPrefix = label && `[${label}]` || "";
1707 const spawned = [];
1708 const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose;
1709 const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger);
1710 return step(initialStep);
1711 function sibling(name, initial) {
1712 return append(
1713 spawned,
1714 createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger)
1715 );
1716 }
1717 function step(phase) {
1718 const stepPrefix = phase && `[${phase}]` || "";
1719 const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
1720 const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2);
1721 return Object.assign(debugDebugger ? debug2 : info, {
1722 label,
1723 sibling,
1724 info,
1725 step
1726 });
1727 }
1728}
1729var import_debug;
1730var init_git_logger = __esm({
1731 "src/lib/git-logger.ts"() {
1732 "use strict";
1733 import_debug = __toESM(require("debug"));
1734 init_utils();
1735 import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-");
1736 import_debug.default.formatters.B = (value) => {
1737 if (Buffer.isBuffer(value)) {
1738 return value.toString("utf8");
1739 }
1740 return objectToString(value);
1741 };
1742 }
1743});
1744
1745// src/lib/runners/tasks-pending-queue.ts
1746var _TasksPendingQueue, TasksPendingQueue;
1747var init_tasks_pending_queue = __esm({
1748 "src/lib/runners/tasks-pending-queue.ts"() {
1749 "use strict";
1750 init_git_error();
1751 init_git_logger();
1752 _TasksPendingQueue = class {
1753 constructor(logLabel = "GitExecutor") {
1754 this.logLabel = logLabel;
1755 this._queue = /* @__PURE__ */ new Map();
1756 }
1757 withProgress(task) {
1758 return this._queue.get(task);
1759 }
1760 createProgress(task) {
1761 const name = _TasksPendingQueue.getName(task.commands[0]);
1762 const logger = createLogger(this.logLabel, name);
1763 return {
1764 task,
1765 logger,
1766 name
1767 };
1768 }
1769 push(task) {
1770 const progress = this.createProgress(task);
1771 progress.logger("Adding task to the queue, commands = %o", task.commands);
1772 this._queue.set(task, progress);
1773 return progress;
1774 }
1775 fatal(err) {
1776 for (const [task, { logger }] of Array.from(this._queue.entries())) {
1777 if (task === err.task) {
1778 logger.info(`Failed %o`, err);
1779 logger(
1780 `Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`
1781 );
1782 } else {
1783 logger.info(
1784 `A fatal exception occurred in a previous task, the queue has been purged: %o`,
1785 err.message
1786 );
1787 }
1788 this.complete(task);
1789 }
1790 if (this._queue.size !== 0) {
1791 throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`);
1792 }
1793 }
1794 complete(task) {
1795 const progress = this.withProgress(task);
1796 if (progress) {
1797 this._queue.delete(task);
1798 }
1799 }
1800 attempt(task) {
1801 const progress = this.withProgress(task);
1802 if (!progress) {
1803 throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task");
1804 }
1805 progress.logger("Starting task");
1806 return progress;
1807 }
1808 static getName(name = "empty") {
1809 return `task:${name}:${++_TasksPendingQueue.counter}`;
1810 }
1811 };
1812 TasksPendingQueue = _TasksPendingQueue;
1813 TasksPendingQueue.counter = 0;
1814 }
1815});
1816
1817// src/lib/runners/git-executor-chain.ts
1818function pluginContext(task, commands) {
1819 return {
1820 method: first(task.commands) || "",
1821 commands
1822 };
1823}
1824function onErrorReceived(target, logger) {
1825 return (err) => {
1826 logger(`[ERROR] child process exception %o`, err);
1827 target.push(Buffer.from(String(err.stack), "ascii"));
1828 };
1829}
1830function onDataReceived(target, name, logger, output) {
1831 return (buffer) => {
1832 logger(`%s received %L bytes`, name, buffer);
1833 output(`%B`, buffer);
1834 target.push(buffer);
1835 };
1836}
1837var import_child_process, GitExecutorChain;
1838var init_git_executor_chain = __esm({
1839 "src/lib/runners/git-executor-chain.ts"() {
1840 "use strict";
1841 import_child_process = require("child_process");
1842 init_git_error();
1843 init_task();
1844 init_utils();
1845 init_tasks_pending_queue();
1846 GitExecutorChain = class {
1847 constructor(_executor, _scheduler, _plugins) {
1848 this._executor = _executor;
1849 this._scheduler = _scheduler;
1850 this._plugins = _plugins;
1851 this._chain = Promise.resolve();
1852 this._queue = new TasksPendingQueue();
1853 }
1854 get cwd() {
1855 return this._cwd || this._executor.cwd;
1856 }
1857 set cwd(cwd) {
1858 this._cwd = cwd;
1859 }
1860 get env() {
1861 return this._executor.env;
1862 }
1863 get outputHandler() {
1864 return this._executor.outputHandler;
1865 }
1866 chain() {
1867 return this;
1868 }
1869 push(task) {
1870 this._queue.push(task);
1871 return this._chain = this._chain.then(() => this.attemptTask(task));
1872 }
1873 attemptTask(task) {
1874 return __async(this, null, function* () {
1875 const onScheduleComplete = yield this._scheduler.next();
1876 const onQueueComplete = () => this._queue.complete(task);
1877 try {
1878 const { logger } = this._queue.attempt(task);
1879 return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger);
1880 } catch (e) {
1881 throw this.onFatalException(task, e);
1882 } finally {
1883 onQueueComplete();
1884 onScheduleComplete();
1885 }
1886 });
1887 }
1888 onFatalException(task, e) {
1889 const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e));
1890 this._chain = Promise.resolve();
1891 this._queue.fatal(gitError);
1892 return gitError;
1893 }
1894 attemptRemoteTask(task, logger) {
1895 return __async(this, null, function* () {
1896 const binary = this._plugins.exec("spawn.binary", "", pluginContext(task, task.commands));
1897 const args = this._plugins.exec(
1898 "spawn.args",
1899 [...task.commands],
1900 pluginContext(task, task.commands)
1901 );
1902 const raw = yield this.gitResponse(
1903 task,
1904 binary,
1905 args,
1906 this.outputHandler,
1907 logger.step("SPAWN")
1908 );
1909 const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE"));
1910 logger(`passing response to task's parser as a %s`, task.format);
1911 if (isBufferTask(task)) {
1912 return callTaskParser(task.parser, outputStreams);
1913 }
1914 return callTaskParser(task.parser, outputStreams.asStrings());
1915 });
1916 }
1917 attemptEmptyTask(task, logger) {
1918 return __async(this, null, function* () {
1919 logger(`empty task bypassing child process to call to task's parser`);
1920 return task.parser(this);
1921 });
1922 }
1923 handleTaskData(task, args, result, logger) {
1924 const { exitCode, rejection, stdOut, stdErr } = result;
1925 return new Promise((done, fail) => {
1926 logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode);
1927 const { error } = this._plugins.exec(
1928 "task.error",
1929 { error: rejection },
1930 __spreadValues(__spreadValues({}, pluginContext(task, args)), result)
1931 );
1932 if (error && task.onError) {
1933 logger.info(`exitCode=%s handling with custom error handler`);
1934 return task.onError(
1935 result,
1936 error,
1937 (newStdOut) => {
1938 logger.info(`custom error handler treated as success`);
1939 logger(`custom error returned a %s`, objectToString(newStdOut));
1940 done(
1941 new GitOutputStreams(
1942 Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut,
1943 Buffer.concat(stdErr)
1944 )
1945 );
1946 },
1947 fail
1948 );
1949 }
1950 if (error) {
1951 logger.info(
1952 `handling as error: exitCode=%s stdErr=%s rejection=%o`,
1953 exitCode,
1954 stdErr.length,
1955 rejection
1956 );
1957 return fail(error);
1958 }
1959 logger.info(`retrieving task output complete`);
1960 done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));
1961 });
1962 }
1963 gitResponse(task, command, args, outputHandler, logger) {
1964 return __async(this, null, function* () {
1965 const outputLogger = logger.sibling("output");
1966 const spawnOptions = this._plugins.exec(
1967 "spawn.options",
1968 {
1969 cwd: this.cwd,
1970 env: this.env,
1971 windowsHide: true
1972 },
1973 pluginContext(task, task.commands)
1974 );
1975 return new Promise((done) => {
1976 const stdOut = [];
1977 const stdErr = [];
1978 logger.info(`%s %o`, command, args);
1979 logger("%O", spawnOptions);
1980 let rejection = this._beforeSpawn(task, args);
1981 if (rejection) {
1982 return done({
1983 stdOut,
1984 stdErr,
1985 exitCode: 9901,
1986 rejection
1987 });
1988 }
1989 this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), {
1990 kill(reason) {
1991 rejection = reason || rejection;
1992 }
1993 }));
1994 const spawned = (0, import_child_process.spawn)(command, args, spawnOptions);
1995 spawned.stdout.on(
1996 "data",
1997 onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut"))
1998 );
1999 spawned.stderr.on(
2000 "data",
2001 onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr"))
2002 );
2003 spawned.on("error", onErrorReceived(stdErr, logger));
2004 if (outputHandler) {
2005 logger(`Passing child process stdOut/stdErr to custom outputHandler`);
2006 outputHandler(command, spawned.stdout, spawned.stderr, [...args]);
2007 }
2008 this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), {
2009 spawned,
2010 close(exitCode, reason) {
2011 done({
2012 stdOut,
2013 stdErr,
2014 exitCode,
2015 rejection: rejection || reason
2016 });
2017 },
2018 kill(reason) {
2019 if (spawned.killed) {
2020 return;
2021 }
2022 rejection = reason;
2023 spawned.kill("SIGINT");
2024 }
2025 }));
2026 });
2027 });
2028 }
2029 _beforeSpawn(task, args) {
2030 let rejection;
2031 this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), {
2032 kill(reason) {
2033 rejection = reason || rejection;
2034 }
2035 }));
2036 return rejection;
2037 }
2038 };
2039 }
2040});
2041
2042// src/lib/runners/git-executor.ts
2043var git_executor_exports = {};
2044__export(git_executor_exports, {
2045 GitExecutor: () => GitExecutor
2046});
2047var GitExecutor;
2048var init_git_executor = __esm({
2049 "src/lib/runners/git-executor.ts"() {
2050 "use strict";
2051 init_git_executor_chain();
2052 GitExecutor = class {
2053 constructor(cwd, _scheduler, _plugins) {
2054 this.cwd = cwd;
2055 this._scheduler = _scheduler;
2056 this._plugins = _plugins;
2057 this._chain = new GitExecutorChain(this, this._scheduler, this._plugins);
2058 }
2059 chain() {
2060 return new GitExecutorChain(this, this._scheduler, this._plugins);
2061 }
2062 push(task) {
2063 return this._chain.push(task);
2064 }
2065 };
2066 }
2067});
2068
2069// src/lib/task-callback.ts
2070function taskCallback(task, response, callback = NOOP) {
2071 const onSuccess = (data) => {
2072 callback(null, data);
2073 };
2074 const onError2 = (err) => {
2075 if ((err == null ? void 0 : err.task) === task) {
2076 callback(
2077 err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err,
2078 void 0
2079 );
2080 }
2081 };
2082 response.then(onSuccess, onError2);
2083}
2084function addDeprecationNoticeToError(err) {
2085 let log = (name) => {
2086 console.warn(
2087 `simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`
2088 );
2089 log = NOOP;
2090 };
2091 return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {}));
2092 function descriptorReducer(all, name) {
2093 if (name in err) {
2094 return all;
2095 }
2096 all[name] = {
2097 enumerable: false,
2098 configurable: false,
2099 get() {
2100 log(name);
2101 return err.git[name];
2102 }
2103 };
2104 return all;
2105 }
2106}
2107var init_task_callback = __esm({
2108 "src/lib/task-callback.ts"() {
2109 "use strict";
2110 init_git_response_error();
2111 init_utils();
2112 }
2113});
2114
2115// src/lib/tasks/change-working-directory.ts
2116function changeWorkingDirectoryTask(directory, root) {
2117 return adhocExecTask((instance) => {
2118 if (!folderExists(directory)) {
2119 throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`);
2120 }
2121 return (root || instance).cwd = directory;
2122 });
2123}
2124var init_change_working_directory = __esm({
2125 "src/lib/tasks/change-working-directory.ts"() {
2126 "use strict";
2127 init_utils();
2128 init_task();
2129 }
2130});
2131
2132// src/lib/tasks/checkout.ts
2133function checkoutTask(args) {
2134 const commands = ["checkout", ...args];
2135 if (commands[1] === "-b" && commands.includes("-B")) {
2136 commands[1] = remove(commands, "-B");
2137 }
2138 return straightThroughStringTask(commands);
2139}
2140function checkout_default() {
2141 return {
2142 checkout() {
2143 return this._runTask(
2144 checkoutTask(getTrailingOptions(arguments, 1)),
2145 trailingFunctionArgument(arguments)
2146 );
2147 },
2148 checkoutBranch(branchName, startPoint) {
2149 return this._runTask(
2150 checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]),
2151 trailingFunctionArgument(arguments)
2152 );
2153 },
2154 checkoutLocalBranch(branchName) {
2155 return this._runTask(
2156 checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]),
2157 trailingFunctionArgument(arguments)
2158 );
2159 }
2160 };
2161}
2162var init_checkout = __esm({
2163 "src/lib/tasks/checkout.ts"() {
2164 "use strict";
2165 init_utils();
2166 init_task();
2167 }
2168});
2169
2170// src/lib/tasks/count-objects.ts
2171function countObjectsResponse() {
2172 return {
2173 count: 0,
2174 garbage: 0,
2175 inPack: 0,
2176 packs: 0,
2177 prunePackable: 0,
2178 size: 0,
2179 sizeGarbage: 0,
2180 sizePack: 0
2181 };
2182}
2183function count_objects_default() {
2184 return {
2185 countObjects() {
2186 return this._runTask({
2187 commands: ["count-objects", "--verbose"],
2188 format: "utf-8",
2189 parser(stdOut) {
2190 return parseStringResponse(countObjectsResponse(), [parser2], stdOut);
2191 }
2192 });
2193 }
2194 };
2195}
2196var parser2;
2197var init_count_objects = __esm({
2198 "src/lib/tasks/count-objects.ts"() {
2199 "use strict";
2200 init_utils();
2201 parser2 = new LineParser(
2202 /([a-z-]+): (\d+)$/,
2203 (result, [key, value]) => {
2204 const property = asCamelCase(key);
2205 if (result.hasOwnProperty(property)) {
2206 result[property] = asNumber(value);
2207 }
2208 }
2209 );
2210 }
2211});
2212
2213// src/lib/parsers/parse-commit.ts
2214function parseCommitResult(stdOut) {
2215 const result = {
2216 author: null,
2217 branch: "",
2218 commit: "",
2219 root: false,
2220 summary: {
2221 changes: 0,
2222 insertions: 0,
2223 deletions: 0
2224 }
2225 };
2226 return parseStringResponse(result, parsers, stdOut);
2227}
2228var parsers;
2229var init_parse_commit = __esm({
2230 "src/lib/parsers/parse-commit.ts"() {
2231 "use strict";
2232 init_utils();
2233 parsers = [
2234 new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => {
2235 result.branch = branch;
2236 result.commit = commit;
2237 result.root = !!root;
2238 }),
2239 new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => {
2240 const parts = author.split("<");
2241 const email = parts.pop();
2242 if (!email || !email.includes("@")) {
2243 return;
2244 }
2245 result.author = {
2246 email: email.substr(0, email.length - 1),
2247 name: parts.join("<").trim()
2248 };
2249 }),
2250 new LineParser(
2251 /(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,
2252 (result, [changes, insertions, deletions]) => {
2253 result.summary.changes = parseInt(changes, 10) || 0;
2254 result.summary.insertions = parseInt(insertions, 10) || 0;
2255 result.summary.deletions = parseInt(deletions, 10) || 0;
2256 }
2257 ),
2258 new LineParser(
2259 /^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,
2260 (result, [changes, lines, direction]) => {
2261 result.summary.changes = parseInt(changes, 10) || 0;
2262 const count = parseInt(lines, 10) || 0;
2263 if (direction === "-") {
2264 result.summary.deletions = count;
2265 } else if (direction === "+") {
2266 result.summary.insertions = count;
2267 }
2268 }
2269 )
2270 ];
2271 }
2272});
2273
2274// src/lib/tasks/commit.ts
2275function commitTask(message, files, customArgs) {
2276 const commands = [
2277 "-c",
2278 "core.abbrev=40",
2279 "commit",
2280 ...prefixedArray(message, "-m"),
2281 ...files,
2282 ...customArgs
2283 ];
2284 return {
2285 commands,
2286 format: "utf-8",
2287 parser: parseCommitResult
2288 };
2289}
2290function commit_default() {
2291 return {
2292 commit(message, ...rest) {
2293 const next = trailingFunctionArgument(arguments);
2294 const task = rejectDeprecatedSignatures(message) || commitTask(
2295 asArray(message),
2296 asArray(filterType(rest[0], filterStringOrStringArray, [])),
2297 [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]
2298 );
2299 return this._runTask(task, next);
2300 }
2301 };
2302 function rejectDeprecatedSignatures(message) {
2303 return !filterStringOrStringArray(message) && configurationErrorTask(
2304 `git.commit: requires the commit message to be supplied as a string/string[]`
2305 );
2306 }
2307}
2308var init_commit = __esm({
2309 "src/lib/tasks/commit.ts"() {
2310 "use strict";
2311 init_parse_commit();
2312 init_utils();
2313 init_task();
2314 }
2315});
2316
2317// src/lib/tasks/first-commit.ts
2318function first_commit_default() {
2319 return {
2320 firstCommit() {
2321 return this._runTask(
2322 straightThroughStringTask(["rev-list", "--max-parents=0", "HEAD"], true),
2323 trailingFunctionArgument(arguments)
2324 );
2325 }
2326 };
2327}
2328var init_first_commit = __esm({
2329 "src/lib/tasks/first-commit.ts"() {
2330 "use strict";
2331 init_utils();
2332 init_task();
2333 }
2334});
2335
2336// src/lib/tasks/hash-object.ts
2337function hashObjectTask(filePath, write) {
2338 const commands = ["hash-object", filePath];
2339 if (write) {
2340 commands.push("-w");
2341 }
2342 return straightThroughStringTask(commands, true);
2343}
2344var init_hash_object = __esm({
2345 "src/lib/tasks/hash-object.ts"() {
2346 "use strict";
2347 init_task();
2348 }
2349});
2350
2351// src/lib/responses/InitSummary.ts
2352function parseInit(bare, path, text) {
2353 const response = String(text).trim();
2354 let result;
2355 if (result = initResponseRegex.exec(response)) {
2356 return new InitSummary(bare, path, false, result[1]);
2357 }
2358 if (result = reInitResponseRegex.exec(response)) {
2359 return new InitSummary(bare, path, true, result[1]);
2360 }
2361 let gitDir = "";
2362 const tokens = response.split(" ");
2363 while (tokens.length) {
2364 const token = tokens.shift();
2365 if (token === "in") {
2366 gitDir = tokens.join(" ");
2367 break;
2368 }
2369 }
2370 return new InitSummary(bare, path, /^re/i.test(response), gitDir);
2371}
2372var InitSummary, initResponseRegex, reInitResponseRegex;
2373var init_InitSummary = __esm({
2374 "src/lib/responses/InitSummary.ts"() {
2375 "use strict";
2376 InitSummary = class {
2377 constructor(bare, path, existing, gitDir) {
2378 this.bare = bare;
2379 this.path = path;
2380 this.existing = existing;
2381 this.gitDir = gitDir;
2382 }
2383 };
2384 initResponseRegex = /^Init.+ repository in (.+)$/;
2385 reInitResponseRegex = /^Rein.+ in (.+)$/;
2386 }
2387});
2388
2389// src/lib/tasks/init.ts
2390function hasBareCommand(command) {
2391 return command.includes(bareCommand);
2392}
2393function initTask(bare = false, path, customArgs) {
2394 const commands = ["init", ...customArgs];
2395 if (bare && !hasBareCommand(commands)) {
2396 commands.splice(1, 0, bareCommand);
2397 }
2398 return {
2399 commands,
2400 format: "utf-8",
2401 parser(text) {
2402 return parseInit(commands.includes("--bare"), path, text);
2403 }
2404 };
2405}
2406var bareCommand;
2407var init_init = __esm({
2408 "src/lib/tasks/init.ts"() {
2409 "use strict";
2410 init_InitSummary();
2411 bareCommand = "--bare";
2412 }
2413});
2414
2415// src/lib/args/log-format.ts
2416function logFormatFromCommand(customArgs) {
2417 for (let i = 0; i < customArgs.length; i++) {
2418 const format = logFormatRegex.exec(customArgs[i]);
2419 if (format) {
2420 return `--${format[1]}`;
2421 }
2422 }
2423 return "" /* NONE */;
2424}
2425function isLogFormat(customArg) {
2426 return logFormatRegex.test(customArg);
2427}
2428var logFormatRegex;
2429var init_log_format = __esm({
2430 "src/lib/args/log-format.ts"() {
2431 "use strict";
2432 logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/;
2433 }
2434});
2435
2436// src/lib/responses/DiffSummary.ts
2437var DiffSummary;
2438var init_DiffSummary = __esm({
2439 "src/lib/responses/DiffSummary.ts"() {
2440 "use strict";
2441 DiffSummary = class {
2442 constructor() {
2443 this.changed = 0;
2444 this.deletions = 0;
2445 this.insertions = 0;
2446 this.files = [];
2447 }
2448 };
2449 }
2450});
2451
2452// src/lib/parsers/parse-diff-summary.ts
2453function getDiffParser(format = "" /* NONE */) {
2454 const parser4 = diffSummaryParsers[format];
2455 return (stdOut) => parseStringResponse(new DiffSummary(), parser4, stdOut, false);
2456}
2457var statParser, numStatParser, nameOnlyParser, nameStatusParser, diffSummaryParsers;
2458var init_parse_diff_summary = __esm({
2459 "src/lib/parsers/parse-diff-summary.ts"() {
2460 "use strict";
2461 init_log_format();
2462 init_DiffSummary();
2463 init_diff_name_status();
2464 init_utils();
2465 statParser = [
2466 new LineParser(
2467 /^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,
2468 (result, [file, changes, alterations = ""]) => {
2469 result.files.push({
2470 file: file.trim(),
2471 changes: asNumber(changes),
2472 insertions: alterations.replace(/[^+]/g, "").length,
2473 deletions: alterations.replace(/[^-]/g, "").length,
2474 binary: false
2475 });
2476 }
2477 ),
2478 new LineParser(
2479 /^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,
2480 (result, [file, before, after]) => {
2481 result.files.push({
2482 file: file.trim(),
2483 before: asNumber(before),
2484 after: asNumber(after),
2485 binary: true
2486 });
2487 }
2488 ),
2489 new LineParser(
2490 /(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,
2491 (result, [changed, summary]) => {
2492 const inserted = /(\d+) i/.exec(summary);
2493 const deleted = /(\d+) d/.exec(summary);
2494 result.changed = asNumber(changed);
2495 result.insertions = asNumber(inserted == null ? void 0 : inserted[1]);
2496 result.deletions = asNumber(deleted == null ? void 0 : deleted[1]);
2497 }
2498 )
2499 ];
2500 numStatParser = [
2501 new LineParser(
2502 /(\d+)\t(\d+)\t(.+)$/,
2503 (result, [changesInsert, changesDelete, file]) => {
2504 const insertions = asNumber(changesInsert);
2505 const deletions = asNumber(changesDelete);
2506 result.changed++;
2507 result.insertions += insertions;
2508 result.deletions += deletions;
2509 result.files.push({
2510 file,
2511 changes: insertions + deletions,
2512 insertions,
2513 deletions,
2514 binary: false
2515 });
2516 }
2517 ),
2518 new LineParser(/-\t-\t(.+)$/, (result, [file]) => {
2519 result.changed++;
2520 result.files.push({
2521 file,
2522 after: 0,
2523 before: 0,
2524 binary: true
2525 });
2526 })
2527 ];
2528 nameOnlyParser = [
2529 new LineParser(/(.+)$/, (result, [file]) => {
2530 result.changed++;
2531 result.files.push({
2532 file,
2533 changes: 0,
2534 insertions: 0,
2535 deletions: 0,
2536 binary: false
2537 });
2538 })
2539 ];
2540 nameStatusParser = [
2541 new LineParser(
2542 /([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,
2543 (result, [status, similarity, from, _to, to]) => {
2544 result.changed++;
2545 result.files.push({
2546 file: to != null ? to : from,
2547 changes: 0,
2548 insertions: 0,
2549 deletions: 0,
2550 binary: false,
2551 status: orVoid(isDiffNameStatus(status) && status),
2552 from: orVoid(!!to && from !== to && from),
2553 similarity: asNumber(similarity)
2554 });
2555 }
2556 )
2557 ];
2558 diffSummaryParsers = {
2559 ["" /* NONE */]: statParser,
2560 ["--stat" /* STAT */]: statParser,
2561 ["--numstat" /* NUM_STAT */]: numStatParser,
2562 ["--name-status" /* NAME_STATUS */]: nameStatusParser,
2563 ["--name-only" /* NAME_ONLY */]: nameOnlyParser
2564 };
2565 }
2566});
2567
2568// src/lib/parsers/parse-list-log-summary.ts
2569function lineBuilder(tokens, fields) {
2570 return fields.reduce(
2571 (line, field, index) => {
2572 line[field] = tokens[index] || "";
2573 return line;
2574 },
2575 /* @__PURE__ */ Object.create({ diff: null })
2576 );
2577}
2578function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "" /* NONE */) {
2579 const parseDiffResult = getDiffParser(logFormat);
2580 return function(stdOut) {
2581 const all = toLinesWithContent(
2582 stdOut.trim(),
2583 false,
2584 START_BOUNDARY
2585 ).map(function(item) {
2586 const lineDetail = item.split(COMMIT_BOUNDARY);
2587 const listLogLine = lineBuilder(lineDetail[0].split(splitter), fields);
2588 if (lineDetail.length > 1 && !!lineDetail[1].trim()) {
2589 listLogLine.diff = parseDiffResult(lineDetail[1]);
2590 }
2591 return listLogLine;
2592 });
2593 return {
2594 all,
2595 latest: all.length && all[0] || null,
2596 total: all.length
2597 };
2598 };
2599}
2600var START_BOUNDARY, COMMIT_BOUNDARY, SPLITTER, defaultFieldNames;
2601var init_parse_list_log_summary = __esm({
2602 "src/lib/parsers/parse-list-log-summary.ts"() {
2603 "use strict";
2604 init_utils();
2605 init_parse_diff_summary();
2606 init_log_format();
2607 START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 ";
2608 COMMIT_BOUNDARY = " \xF2\xF2";
2609 SPLITTER = " \xF2 ";
2610 defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"];
2611 }
2612});
2613
2614// src/lib/tasks/diff.ts
2615var diff_exports = {};
2616__export(diff_exports, {
2617 diffSummaryTask: () => diffSummaryTask,
2618 validateLogFormatConfig: () => validateLogFormatConfig
2619});
2620function diffSummaryTask(customArgs) {
2621 let logFormat = logFormatFromCommand(customArgs);
2622 const commands = ["diff"];
2623 if (logFormat === "" /* NONE */) {
2624 logFormat = "--stat" /* STAT */;
2625 commands.push("--stat=4096");
2626 }
2627 commands.push(...customArgs);
2628 return validateLogFormatConfig(commands) || {
2629 commands,
2630 format: "utf-8",
2631 parser: getDiffParser(logFormat)
2632 };
2633}
2634function validateLogFormatConfig(customArgs) {
2635 const flags = customArgs.filter(isLogFormat);
2636 if (flags.length > 1) {
2637 return configurationErrorTask(
2638 `Summary flags are mutually exclusive - pick one of ${flags.join(",")}`
2639 );
2640 }
2641 if (flags.length && customArgs.includes("-z")) {
2642 return configurationErrorTask(
2643 `Summary flag ${flags} parsing is not compatible with null termination option '-z'`
2644 );
2645 }
2646}
2647var init_diff = __esm({
2648 "src/lib/tasks/diff.ts"() {
2649 "use strict";
2650 init_log_format();
2651 init_parse_diff_summary();
2652 init_task();
2653 }
2654});
2655
2656// src/lib/tasks/log.ts
2657function prettyFormat(format, splitter) {
2658 const fields = [];
2659 const formatStr = [];
2660 Object.keys(format).forEach((field) => {
2661 fields.push(field);
2662 formatStr.push(String(format[field]));
2663 });
2664 return [fields, formatStr.join(splitter)];
2665}
2666function userOptions(input) {
2667 return Object.keys(input).reduce((out, key) => {
2668 if (!(key in excludeOptions)) {
2669 out[key] = input[key];
2670 }
2671 return out;
2672 }, {});
2673}
2674function parseLogOptions(opt = {}, customArgs = []) {
2675 const splitter = filterType(opt.splitter, filterString, SPLITTER);
2676 const format = !filterPrimitives(opt.format) && opt.format ? opt.format : {
2677 hash: "%H",
2678 date: opt.strictDate === false ? "%ai" : "%aI",
2679 message: "%s",
2680 refs: "%D",
2681 body: opt.multiLine ? "%B" : "%b",
2682 author_name: opt.mailMap !== false ? "%aN" : "%an",
2683 author_email: opt.mailMap !== false ? "%aE" : "%ae"
2684 };
2685 const [fields, formatStr] = prettyFormat(format, splitter);
2686 const suffix = [];
2687 const command = [
2688 `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`,
2689 ...customArgs
2690 ];
2691 const maxCount = opt.n || opt["max-count"] || opt.maxCount;
2692 if (maxCount) {
2693 command.push(`--max-count=${maxCount}`);
2694 }
2695 if (opt.from || opt.to) {
2696 const rangeOperator = opt.symmetric !== false ? "..." : "..";
2697 suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`);
2698 }
2699 if (filterString(opt.file)) {
2700 command.push("--follow", pathspec(opt.file));
2701 }
2702 appendTaskOptions(userOptions(opt), command);
2703 return {
2704 fields,
2705 splitter,
2706 commands: [...command, ...suffix]
2707 };
2708}
2709function logTask(splitter, fields, customArgs) {
2710 const parser4 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs));
2711 return {
2712 commands: ["log", ...customArgs],
2713 format: "utf-8",
2714 parser: parser4
2715 };
2716}
2717function log_default() {
2718 return {
2719 log(...rest) {
2720 const next = trailingFunctionArgument(arguments);
2721 const options = parseLogOptions(
2722 trailingOptionsArgument(arguments),
2723 filterType(arguments[0], filterArray)
2724 );
2725 const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options);
2726 return this._runTask(task, next);
2727 }
2728 };
2729 function createLogTask(options) {
2730 return logTask(options.splitter, options.fields, options.commands);
2731 }
2732 function rejectDeprecatedSignatures(from, to) {
2733 return filterString(from) && filterString(to) && configurationErrorTask(
2734 `git.log(string, string) should be replaced with git.log({ from: string, to: string })`
2735 );
2736 }
2737}
2738var excludeOptions;
2739var init_log = __esm({
2740 "src/lib/tasks/log.ts"() {
2741 "use strict";
2742 init_log_format();
2743 init_pathspec();
2744 init_parse_list_log_summary();
2745 init_utils();
2746 init_task();
2747 init_diff();
2748 excludeOptions = /* @__PURE__ */ ((excludeOptions2) => {
2749 excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty";
2750 excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count";
2751 excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount";
2752 excludeOptions2[excludeOptions2["n"] = 3] = "n";
2753 excludeOptions2[excludeOptions2["file"] = 4] = "file";
2754 excludeOptions2[excludeOptions2["format"] = 5] = "format";
2755 excludeOptions2[excludeOptions2["from"] = 6] = "from";
2756 excludeOptions2[excludeOptions2["to"] = 7] = "to";
2757 excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter";
2758 excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric";
2759 excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap";
2760 excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine";
2761 excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate";
2762 return excludeOptions2;
2763 })(excludeOptions || {});
2764 }
2765});
2766
2767// src/lib/responses/MergeSummary.ts
2768var MergeSummaryConflict, MergeSummaryDetail;
2769var init_MergeSummary = __esm({
2770 "src/lib/responses/MergeSummary.ts"() {
2771 "use strict";
2772 MergeSummaryConflict = class {
2773 constructor(reason, file = null, meta) {
2774 this.reason = reason;
2775 this.file = file;
2776 this.meta = meta;
2777 }
2778 toString() {
2779 return `${this.file}:${this.reason}`;
2780 }
2781 };
2782 MergeSummaryDetail = class {
2783 constructor() {
2784 this.conflicts = [];
2785 this.merges = [];
2786 this.result = "success";
2787 }
2788 get failed() {
2789 return this.conflicts.length > 0;
2790 }
2791 get reason() {
2792 return this.result;
2793 }
2794 toString() {
2795 if (this.conflicts.length) {
2796 return `CONFLICTS: ${this.conflicts.join(", ")}`;
2797 }
2798 return "OK";
2799 }
2800 };
2801 }
2802});
2803
2804// src/lib/responses/PullSummary.ts
2805var PullSummary, PullFailedSummary;
2806var init_PullSummary = __esm({
2807 "src/lib/responses/PullSummary.ts"() {
2808 "use strict";
2809 PullSummary = class {
2810 constructor() {
2811 this.remoteMessages = {
2812 all: []
2813 };
2814 this.created = [];
2815 this.deleted = [];
2816 this.files = [];
2817 this.deletions = {};
2818 this.insertions = {};
2819 this.summary = {
2820 changes: 0,
2821 deletions: 0,
2822 insertions: 0
2823 };
2824 }
2825 };
2826 PullFailedSummary = class {
2827 constructor() {
2828 this.remote = "";
2829 this.hash = {
2830 local: "",
2831 remote: ""
2832 };
2833 this.branch = {
2834 local: "",
2835 remote: ""
2836 };
2837 this.message = "";
2838 }
2839 toString() {
2840 return this.message;
2841 }
2842 };
2843 }
2844});
2845
2846// src/lib/parsers/parse-remote-objects.ts
2847function objectEnumerationResult(remoteMessages) {
2848 return remoteMessages.objects = remoteMessages.objects || {
2849 compressing: 0,
2850 counting: 0,
2851 enumerating: 0,
2852 packReused: 0,
2853 reused: { count: 0, delta: 0 },
2854 total: { count: 0, delta: 0 }
2855 };
2856}
2857function asObjectCount(source) {
2858 const count = /^\s*(\d+)/.exec(source);
2859 const delta = /delta (\d+)/i.exec(source);
2860 return {
2861 count: asNumber(count && count[1] || "0"),
2862 delta: asNumber(delta && delta[1] || "0")
2863 };
2864}
2865var remoteMessagesObjectParsers;
2866var init_parse_remote_objects = __esm({
2867 "src/lib/parsers/parse-remote-objects.ts"() {
2868 "use strict";
2869 init_utils();
2870 remoteMessagesObjectParsers = [
2871 new RemoteLineParser(
2872 /^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,
2873 (result, [action, count]) => {
2874 const key = action.toLowerCase();
2875 const enumeration = objectEnumerationResult(result.remoteMessages);
2876 Object.assign(enumeration, { [key]: asNumber(count) });
2877 }
2878 ),
2879 new RemoteLineParser(
2880 /^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,
2881 (result, [action, count]) => {
2882 const key = action.toLowerCase();
2883 const enumeration = objectEnumerationResult(result.remoteMessages);
2884 Object.assign(enumeration, { [key]: asNumber(count) });
2885 }
2886 ),
2887 new RemoteLineParser(
2888 /total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,
2889 (result, [total, reused, packReused]) => {
2890 const objects = objectEnumerationResult(result.remoteMessages);
2891 objects.total = asObjectCount(total);
2892 objects.reused = asObjectCount(reused);
2893 objects.packReused = asNumber(packReused);
2894 }
2895 )
2896 ];
2897 }
2898});
2899
2900// src/lib/parsers/parse-remote-messages.ts
2901function parseRemoteMessages(_stdOut, stdErr) {
2902 return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr);
2903}
2904var parsers2, RemoteMessageSummary;
2905var init_parse_remote_messages = __esm({
2906 "src/lib/parsers/parse-remote-messages.ts"() {
2907 "use strict";
2908 init_utils();
2909 init_parse_remote_objects();
2910 parsers2 = [
2911 new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => {
2912 result.remoteMessages.all.push(text.trim());
2913 return false;
2914 }),
2915 ...remoteMessagesObjectParsers,
2916 new RemoteLineParser(
2917 [/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/],
2918 (result, [pullRequestUrl]) => {
2919 result.remoteMessages.pullRequestUrl = pullRequestUrl;
2920 }
2921 ),
2922 new RemoteLineParser(
2923 [/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/],
2924 (result, [count, summary, url]) => {
2925 result.remoteMessages.vulnerabilities = {
2926 count: asNumber(count),
2927 summary,
2928 url
2929 };
2930 }
2931 )
2932 ];
2933 RemoteMessageSummary = class {
2934 constructor() {
2935 this.all = [];
2936 }
2937 };
2938 }
2939});
2940
2941// src/lib/parsers/parse-pull.ts
2942function parsePullErrorResult(stdOut, stdErr) {
2943 const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]);
2944 return pullError.message && pullError;
2945}
2946var FILE_UPDATE_REGEX, SUMMARY_REGEX, ACTION_REGEX, parsers3, errorParsers, parsePullDetail, parsePullResult;
2947var init_parse_pull = __esm({
2948 "src/lib/parsers/parse-pull.ts"() {
2949 "use strict";
2950 init_PullSummary();
2951 init_utils();
2952 init_parse_remote_messages();
2953 FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/;
2954 SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/;
2955 ACTION_REGEX = /^(create|delete) mode \d+ (.+)/;
2956 parsers3 = [
2957 new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => {
2958 result.files.push(file);
2959 if (insertions) {
2960 result.insertions[file] = insertions.length;
2961 }
2962 if (deletions) {
2963 result.deletions[file] = deletions.length;
2964 }
2965 }),
2966 new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => {
2967 if (insertions !== void 0 || deletions !== void 0) {
2968 result.summary.changes = +changes || 0;
2969 result.summary.insertions = +insertions || 0;
2970 result.summary.deletions = +deletions || 0;
2971 return true;
2972 }
2973 return false;
2974 }),
2975 new LineParser(ACTION_REGEX, (result, [action, file]) => {
2976 append(result.files, file);
2977 append(action === "create" ? result.created : result.deleted, file);
2978 })
2979 ];
2980 errorParsers = [
2981 new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)),
2982 new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)),
2983 new LineParser(
2984 /([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,
2985 (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => {
2986 result.branch.local = branchLocal;
2987 result.hash.local = hashLocal;
2988 result.branch.remote = branchRemote;
2989 result.hash.remote = hashRemote;
2990 }
2991 )
2992 ];
2993 parsePullDetail = (stdOut, stdErr) => {
2994 return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]);
2995 };
2996 parsePullResult = (stdOut, stdErr) => {
2997 return Object.assign(
2998 new PullSummary(),
2999 parsePullDetail(stdOut, stdErr),
3000 parseRemoteMessages(stdOut, stdErr)
3001 );
3002 };
3003 }
3004});
3005
3006// src/lib/parsers/parse-merge.ts
3007var parsers4, parseMergeResult, parseMergeDetail;
3008var init_parse_merge = __esm({
3009 "src/lib/parsers/parse-merge.ts"() {
3010 "use strict";
3011 init_MergeSummary();
3012 init_utils();
3013 init_parse_pull();
3014 parsers4 = [
3015 new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => {
3016 summary.merges.push(autoMerge);
3017 }),
3018 new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => {
3019 summary.conflicts.push(new MergeSummaryConflict(reason, file));
3020 }),
3021 new LineParser(
3022 /^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,
3023 (summary, [reason, file, deleteRef]) => {
3024 summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef }));
3025 }
3026 ),
3027 new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => {
3028 summary.conflicts.push(new MergeSummaryConflict(reason, null));
3029 }),
3030 new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => {
3031 summary.result = result;
3032 })
3033 ];
3034 parseMergeResult = (stdOut, stdErr) => {
3035 return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr));
3036 };
3037 parseMergeDetail = (stdOut) => {
3038 return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut);
3039 };
3040 }
3041});
3042
3043// src/lib/tasks/merge.ts
3044function mergeTask(customArgs) {
3045 if (!customArgs.length) {
3046 return configurationErrorTask("Git.merge requires at least one option");
3047 }
3048 return {
3049 commands: ["merge", ...customArgs],
3050 format: "utf-8",
3051 parser(stdOut, stdErr) {
3052 const merge = parseMergeResult(stdOut, stdErr);
3053 if (merge.failed) {
3054 throw new GitResponseError(merge);
3055 }
3056 return merge;
3057 }
3058 };
3059}
3060var init_merge = __esm({
3061 "src/lib/tasks/merge.ts"() {
3062 "use strict";
3063 init_git_response_error();
3064 init_parse_merge();
3065 init_task();
3066 }
3067});
3068
3069// src/lib/parsers/parse-push.ts
3070function pushResultPushedItem(local, remote, status) {
3071 const deleted = status.includes("deleted");
3072 const tag = status.includes("tag") || /^refs\/tags/.test(local);
3073 const alreadyUpdated = !status.includes("new");
3074 return {
3075 deleted,
3076 tag,
3077 branch: !tag,
3078 new: !alreadyUpdated,
3079 alreadyUpdated,
3080 local,
3081 remote
3082 };
3083}
3084var parsers5, parsePushResult, parsePushDetail;
3085var init_parse_push = __esm({
3086 "src/lib/parsers/parse-push.ts"() {
3087 "use strict";
3088 init_utils();
3089 init_parse_remote_messages();
3090 parsers5 = [
3091 new LineParser(/^Pushing to (.+)$/, (result, [repo]) => {
3092 result.repo = repo;
3093 }),
3094 new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => {
3095 result.ref = __spreadProps(__spreadValues({}, result.ref || {}), {
3096 local
3097 });
3098 }),
3099 new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => {
3100 result.pushed.push(pushResultPushedItem(local, remote, type));
3101 }),
3102 new LineParser(
3103 /^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,
3104 (result, [local, remote, remoteName]) => {
3105 result.branch = __spreadProps(__spreadValues({}, result.branch || {}), {
3106 local,
3107 remote,
3108 remoteName
3109 });
3110 }
3111 ),
3112 new LineParser(
3113 /^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,
3114 (result, [local, remote, from, to]) => {
3115 result.update = {
3116 head: {
3117 local,
3118 remote
3119 },
3120 hash: {
3121 from,
3122 to
3123 }
3124 };
3125 }
3126 )
3127 ];
3128 parsePushResult = (stdOut, stdErr) => {
3129 const pushDetail = parsePushDetail(stdOut, stdErr);
3130 const responseDetail = parseRemoteMessages(stdOut, stdErr);
3131 return __spreadValues(__spreadValues({}, pushDetail), responseDetail);
3132 };
3133 parsePushDetail = (stdOut, stdErr) => {
3134 return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]);
3135 };
3136 }
3137});
3138
3139// src/lib/tasks/push.ts
3140var push_exports = {};
3141__export(push_exports, {
3142 pushTagsTask: () => pushTagsTask,
3143 pushTask: () => pushTask
3144});
3145function pushTagsTask(ref = {}, customArgs) {
3146 append(customArgs, "--tags");
3147 return pushTask(ref, customArgs);
3148}
3149function pushTask(ref = {}, customArgs) {
3150 const commands = ["push", ...customArgs];
3151 if (ref.branch) {
3152 commands.splice(1, 0, ref.branch);
3153 }
3154 if (ref.remote) {
3155 commands.splice(1, 0, ref.remote);
3156 }
3157 remove(commands, "-v");
3158 append(commands, "--verbose");
3159 append(commands, "--porcelain");
3160 return {
3161 commands,
3162 format: "utf-8",
3163 parser: parsePushResult
3164 };
3165}
3166var init_push = __esm({
3167 "src/lib/tasks/push.ts"() {
3168 "use strict";
3169 init_parse_push();
3170 init_utils();
3171 }
3172});
3173
3174// src/lib/tasks/show.ts
3175function show_default() {
3176 return {
3177 showBuffer() {
3178 const commands = ["show", ...getTrailingOptions(arguments, 1)];
3179 if (!commands.includes("--binary")) {
3180 commands.splice(1, 0, "--binary");
3181 }
3182 return this._runTask(
3183 straightThroughBufferTask(commands),
3184 trailingFunctionArgument(arguments)
3185 );
3186 },
3187 show() {
3188 const commands = ["show", ...getTrailingOptions(arguments, 1)];
3189 return this._runTask(
3190 straightThroughStringTask(commands),
3191 trailingFunctionArgument(arguments)
3192 );
3193 }
3194 };
3195}
3196var init_show = __esm({
3197 "src/lib/tasks/show.ts"() {
3198 "use strict";
3199 init_utils();
3200 init_task();
3201 }
3202});
3203
3204// src/lib/responses/FileStatusSummary.ts
3205var fromPathRegex, FileStatusSummary;
3206var init_FileStatusSummary = __esm({
3207 "src/lib/responses/FileStatusSummary.ts"() {
3208 "use strict";
3209 fromPathRegex = /^(.+)\0(.+)$/;
3210 FileStatusSummary = class {
3211 constructor(path, index, working_dir) {
3212 this.path = path;
3213 this.index = index;
3214 this.working_dir = working_dir;
3215 if (index === "R" || working_dir === "R") {
3216 const detail = fromPathRegex.exec(path) || [null, path, path];
3217 this.from = detail[2] || "";
3218 this.path = detail[1] || "";
3219 }
3220 }
3221 };
3222 }
3223});
3224
3225// src/lib/responses/StatusSummary.ts
3226function renamedFile(line) {
3227 const [to, from] = line.split(NULL);
3228 return {
3229 from: from || to,
3230 to
3231 };
3232}
3233function parser3(indexX, indexY, handler) {
3234 return [`${indexX}${indexY}`, handler];
3235}
3236function conflicts(indexX, ...indexY) {
3237 return indexY.map((y) => parser3(indexX, y, (result, file) => append(result.conflicted, file)));
3238}
3239function splitLine(result, lineStr) {
3240 const trimmed2 = lineStr.trim();
3241 switch (" ") {
3242 case trimmed2.charAt(2):
3243 return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3));
3244 case trimmed2.charAt(1):
3245 return data(" " /* NONE */, trimmed2.charAt(0), trimmed2.substr(2));
3246 default:
3247 return;
3248 }
3249 function data(index, workingDir, path) {
3250 const raw = `${index}${workingDir}`;
3251 const handler = parsers6.get(raw);
3252 if (handler) {
3253 handler(result, path);
3254 }
3255 if (raw !== "##" && raw !== "!!") {
3256 result.files.push(new FileStatusSummary(path, index, workingDir));
3257 }
3258 }
3259}
3260var StatusSummary, parsers6, parseStatusSummary;
3261var init_StatusSummary = __esm({
3262 "src/lib/responses/StatusSummary.ts"() {
3263 "use strict";
3264 init_utils();
3265 init_FileStatusSummary();
3266 StatusSummary = class {
3267 constructor() {
3268 this.not_added = [];
3269 this.conflicted = [];
3270 this.created = [];
3271 this.deleted = [];
3272 this.ignored = void 0;
3273 this.modified = [];
3274 this.renamed = [];
3275 this.files = [];
3276 this.staged = [];
3277 this.ahead = 0;
3278 this.behind = 0;
3279 this.current = null;
3280 this.tracking = null;
3281 this.detached = false;
3282 this.isClean = () => {
3283 return !this.files.length;
3284 };
3285 }
3286 };
3287 parsers6 = new Map([
3288 parser3(
3289 " " /* NONE */,
3290 "A" /* ADDED */,
3291 (result, file) => append(result.created, file)
3292 ),
3293 parser3(
3294 " " /* NONE */,
3295 "D" /* DELETED */,
3296 (result, file) => append(result.deleted, file)
3297 ),
3298 parser3(
3299 " " /* NONE */,
3300 "M" /* MODIFIED */,
3301 (result, file) => append(result.modified, file)
3302 ),
3303 parser3(
3304 "A" /* ADDED */,
3305 " " /* NONE */,
3306 (result, file) => append(result.created, file) && append(result.staged, file)
3307 ),
3308 parser3(
3309 "A" /* ADDED */,
3310 "M" /* MODIFIED */,
3311 (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file)
3312 ),
3313 parser3(
3314 "D" /* DELETED */,
3315 " " /* NONE */,
3316 (result, file) => append(result.deleted, file) && append(result.staged, file)
3317 ),
3318 parser3(
3319 "M" /* MODIFIED */,
3320 " " /* NONE */,
3321 (result, file) => append(result.modified, file) && append(result.staged, file)
3322 ),
3323 parser3(
3324 "M" /* MODIFIED */,
3325 "M" /* MODIFIED */,
3326 (result, file) => append(result.modified, file) && append(result.staged, file)
3327 ),
3328 parser3("R" /* RENAMED */, " " /* NONE */, (result, file) => {
3329 append(result.renamed, renamedFile(file));
3330 }),
3331 parser3("R" /* RENAMED */, "M" /* MODIFIED */, (result, file) => {
3332 const renamed = renamedFile(file);
3333 append(result.renamed, renamed);
3334 append(result.modified, renamed.to);
3335 }),
3336 parser3("!" /* IGNORED */, "!" /* IGNORED */, (_result, _file) => {
3337 append(_result.ignored = _result.ignored || [], _file);
3338 }),
3339 parser3(
3340 "?" /* UNTRACKED */,
3341 "?" /* UNTRACKED */,
3342 (result, file) => append(result.not_added, file)
3343 ),
3344 ...conflicts("A" /* ADDED */, "A" /* ADDED */, "U" /* UNMERGED */),
3345 ...conflicts(
3346 "D" /* DELETED */,
3347 "D" /* DELETED */,
3348 "U" /* UNMERGED */
3349 ),
3350 ...conflicts(
3351 "U" /* UNMERGED */,
3352 "A" /* ADDED */,
3353 "D" /* DELETED */,
3354 "U" /* UNMERGED */
3355 ),
3356 [
3357 "##",
3358 (result, line) => {
3359 const aheadReg = /ahead (\d+)/;
3360 const behindReg = /behind (\d+)/;
3361 const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/;
3362 const trackingReg = /\.{3}(\S*)/;
3363 const onEmptyBranchReg = /\son\s([\S]+)$/;
3364 let regexResult;
3365 regexResult = aheadReg.exec(line);
3366 result.ahead = regexResult && +regexResult[1] || 0;
3367 regexResult = behindReg.exec(line);
3368 result.behind = regexResult && +regexResult[1] || 0;
3369 regexResult = currentReg.exec(line);
3370 result.current = regexResult && regexResult[1];
3371 regexResult = trackingReg.exec(line);
3372 result.tracking = regexResult && regexResult[1];
3373 regexResult = onEmptyBranchReg.exec(line);
3374 result.current = regexResult && regexResult[1] || result.current;
3375 result.detached = /\(no branch\)/.test(line);
3376 }
3377 ]
3378 ]);
3379 parseStatusSummary = function(text) {
3380 const lines = text.split(NULL);
3381 const status = new StatusSummary();
3382 for (let i = 0, l = lines.length; i < l; ) {
3383 let line = lines[i++].trim();
3384 if (!line) {
3385 continue;
3386 }
3387 if (line.charAt(0) === "R" /* RENAMED */) {
3388 line += NULL + (lines[i++] || "");
3389 }
3390 splitLine(status, line);
3391 }
3392 return status;
3393 };
3394 }
3395});
3396
3397// src/lib/tasks/status.ts
3398function statusTask(customArgs) {
3399 const commands = [
3400 "status",
3401 "--porcelain",
3402 "-b",
3403 "-u",
3404 "--null",
3405 ...customArgs.filter((arg) => !ignoredOptions.includes(arg))
3406 ];
3407 return {
3408 format: "utf-8",
3409 commands,
3410 parser(text) {
3411 return parseStatusSummary(text);
3412 }
3413 };
3414}
3415var ignoredOptions;
3416var init_status = __esm({
3417 "src/lib/tasks/status.ts"() {
3418 "use strict";
3419 init_StatusSummary();
3420 ignoredOptions = ["--null", "-z"];
3421 }
3422});
3423
3424// src/lib/tasks/version.ts
3425function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) {
3426 return Object.defineProperty(
3427 {
3428 major,
3429 minor,
3430 patch,
3431 agent,
3432 installed
3433 },
3434 "toString",
3435 {
3436 value() {
3437 return `${this.major}.${this.minor}.${this.patch}`;
3438 },
3439 configurable: false,
3440 enumerable: false
3441 }
3442 );
3443}
3444function notInstalledResponse() {
3445 return versionResponse(0, 0, 0, "", false);
3446}
3447function version_default() {
3448 return {
3449 version() {
3450 return this._runTask({
3451 commands: ["--version"],
3452 format: "utf-8",
3453 parser: versionParser,
3454 onError(result, error, done, fail) {
3455 if (result.exitCode === -2 /* NOT_FOUND */) {
3456 return done(Buffer.from(NOT_INSTALLED));
3457 }
3458 fail(error);
3459 }
3460 });
3461 }
3462 };
3463}
3464function versionParser(stdOut) {
3465 if (stdOut === NOT_INSTALLED) {
3466 return notInstalledResponse();
3467 }
3468 return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut);
3469}
3470var NOT_INSTALLED, parsers7;
3471var init_version = __esm({
3472 "src/lib/tasks/version.ts"() {
3473 "use strict";
3474 init_utils();
3475 NOT_INSTALLED = "installed=false";
3476 parsers7 = [
3477 new LineParser(
3478 /version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,
3479 (result, [major, minor, patch, agent = ""]) => {
3480 Object.assign(
3481 result,
3482 versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent)
3483 );
3484 }
3485 ),
3486 new LineParser(
3487 /version (\d+)\.(\d+)\.(\D+)(.+)?$/,
3488 (result, [major, minor, patch, agent = ""]) => {
3489 Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent));
3490 }
3491 )
3492 ];
3493 }
3494});
3495
3496// src/lib/simple-git-api.ts
3497var simple_git_api_exports = {};
3498__export(simple_git_api_exports, {
3499 SimpleGitApi: () => SimpleGitApi
3500});
3501var SimpleGitApi;
3502var init_simple_git_api = __esm({
3503 "src/lib/simple-git-api.ts"() {
3504 "use strict";
3505 init_task_callback();
3506 init_change_working_directory();
3507 init_checkout();
3508 init_count_objects();
3509 init_commit();
3510 init_config();
3511 init_first_commit();
3512 init_grep();
3513 init_hash_object();
3514 init_init();
3515 init_log();
3516 init_merge();
3517 init_push();
3518 init_show();
3519 init_status();
3520 init_task();
3521 init_version();
3522 init_utils();
3523 SimpleGitApi = class {
3524 constructor(_executor) {
3525 this._executor = _executor;
3526 }
3527 _runTask(task, then) {
3528 const chain = this._executor.chain();
3529 const promise = chain.push(task);
3530 if (then) {
3531 taskCallback(task, promise, then);
3532 }
3533 return Object.create(this, {
3534 then: { value: promise.then.bind(promise) },
3535 catch: { value: promise.catch.bind(promise) },
3536 _executor: { value: chain }
3537 });
3538 }
3539 add(files) {
3540 return this._runTask(
3541 straightThroughStringTask(["add", ...asArray(files)]),
3542 trailingFunctionArgument(arguments)
3543 );
3544 }
3545 cwd(directory) {
3546 const next = trailingFunctionArgument(arguments);
3547 if (typeof directory === "string") {
3548 return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next);
3549 }
3550 if (typeof (directory == null ? void 0 : directory.path) === "string") {
3551 return this._runTask(
3552 changeWorkingDirectoryTask(
3553 directory.path,
3554 directory.root && this._executor || void 0
3555 ),
3556 next
3557 );
3558 }
3559 return this._runTask(
3560 configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"),
3561 next
3562 );
3563 }
3564 hashObject(path, write) {
3565 return this._runTask(
3566 hashObjectTask(path, write === true),
3567 trailingFunctionArgument(arguments)
3568 );
3569 }
3570 init(bare) {
3571 return this._runTask(
3572 initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)),
3573 trailingFunctionArgument(arguments)
3574 );
3575 }
3576 merge() {
3577 return this._runTask(
3578 mergeTask(getTrailingOptions(arguments)),
3579 trailingFunctionArgument(arguments)
3580 );
3581 }
3582 mergeFromTo(remote, branch) {
3583 if (!(filterString(remote) && filterString(branch))) {
3584 return this._runTask(
3585 configurationErrorTask(
3586 `Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`
3587 )
3588 );
3589 }
3590 return this._runTask(
3591 mergeTask([remote, branch, ...getTrailingOptions(arguments)]),
3592 trailingFunctionArgument(arguments, false)
3593 );
3594 }
3595 outputHandler(handler) {
3596 this._executor.outputHandler = handler;
3597 return this;
3598 }
3599 push() {
3600 const task = pushTask(
3601 {
3602 remote: filterType(arguments[0], filterString),
3603 branch: filterType(arguments[1], filterString)
3604 },
3605 getTrailingOptions(arguments)
3606 );
3607 return this._runTask(task, trailingFunctionArgument(arguments));
3608 }
3609 stash() {
3610 return this._runTask(
3611 straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]),
3612 trailingFunctionArgument(arguments)
3613 );
3614 }
3615 status() {
3616 return this._runTask(
3617 statusTask(getTrailingOptions(arguments)),
3618 trailingFunctionArgument(arguments)
3619 );
3620 }
3621 };
3622 Object.assign(
3623 SimpleGitApi.prototype,
3624 checkout_default(),
3625 commit_default(),
3626 config_default(),
3627 count_objects_default(),
3628 first_commit_default(),
3629 grep_default(),
3630 log_default(),
3631 show_default(),
3632 version_default()
3633 );
3634 }
3635});
3636
3637// src/lib/runners/scheduler.ts
3638var scheduler_exports = {};
3639__export(scheduler_exports, {
3640 Scheduler: () => Scheduler
3641});
3642var import_promise_deferred2, createScheduledTask, Scheduler;
3643var init_scheduler = __esm({
3644 "src/lib/runners/scheduler.ts"() {
3645 "use strict";
3646 init_utils();
3647 import_promise_deferred2 = require("@kwsites/promise-deferred");
3648 init_git_logger();
3649 createScheduledTask = (() => {
3650 let id = 0;
3651 return () => {
3652 id++;
3653 const { promise, done } = (0, import_promise_deferred2.createDeferred)();
3654 return {
3655 promise,
3656 done,
3657 id
3658 };
3659 };
3660 })();
3661 Scheduler = class {
3662 constructor(concurrency = 2) {
3663 this.concurrency = concurrency;
3664 this.logger = createLogger("", "scheduler");
3665 this.pending = [];
3666 this.running = [];
3667 this.logger(`Constructed, concurrency=%s`, concurrency);
3668 }
3669 schedule() {
3670 if (!this.pending.length || this.running.length >= this.concurrency) {
3671 this.logger(
3672 `Schedule attempt ignored, pending=%s running=%s concurrency=%s`,
3673 this.pending.length,
3674 this.running.length,
3675 this.concurrency
3676 );
3677 return;
3678 }
3679 const task = append(this.running, this.pending.shift());
3680 this.logger(`Attempting id=%s`, task.id);
3681 task.done(() => {
3682 this.logger(`Completing id=`, task.id);
3683 remove(this.running, task);
3684 this.schedule();
3685 });
3686 }
3687 next() {
3688 const { promise, id } = append(this.pending, createScheduledTask());
3689 this.logger(`Scheduling id=%s`, id);
3690 this.schedule();
3691 return promise;
3692 }
3693 };
3694 }
3695});
3696
3697// src/lib/tasks/apply-patch.ts
3698var apply_patch_exports = {};
3699__export(apply_patch_exports, {
3700 applyPatchTask: () => applyPatchTask
3701});
3702function applyPatchTask(patches, customArgs) {
3703 return straightThroughStringTask(["apply", ...customArgs, ...patches]);
3704}
3705var init_apply_patch = __esm({
3706 "src/lib/tasks/apply-patch.ts"() {
3707 "use strict";
3708 init_task();
3709 }
3710});
3711
3712// src/lib/responses/BranchDeleteSummary.ts
3713function branchDeletionSuccess(branch, hash) {
3714 return {
3715 branch,
3716 hash,
3717 success: true
3718 };
3719}
3720function branchDeletionFailure(branch) {
3721 return {
3722 branch,
3723 hash: null,
3724 success: false
3725 };
3726}
3727var BranchDeletionBatch;
3728var init_BranchDeleteSummary = __esm({
3729 "src/lib/responses/BranchDeleteSummary.ts"() {
3730 "use strict";
3731 BranchDeletionBatch = class {
3732 constructor() {
3733 this.all = [];
3734 this.branches = {};
3735 this.errors = [];
3736 }
3737 get success() {
3738 return !this.errors.length;
3739 }
3740 };
3741 }
3742});
3743
3744// src/lib/parsers/parse-branch-delete.ts
3745function hasBranchDeletionError(data, processExitCode) {
3746 return processExitCode === 1 /* ERROR */ && deleteErrorRegex.test(data);
3747}
3748var deleteSuccessRegex, deleteErrorRegex, parsers8, parseBranchDeletions;
3749var init_parse_branch_delete = __esm({
3750 "src/lib/parsers/parse-branch-delete.ts"() {
3751 "use strict";
3752 init_BranchDeleteSummary();
3753 init_utils();
3754 deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/;
3755 deleteErrorRegex = /^error[^']+'([^']+)'/m;
3756 parsers8 = [
3757 new LineParser(deleteSuccessRegex, (result, [branch, hash]) => {
3758 const deletion = branchDeletionSuccess(branch, hash);
3759 result.all.push(deletion);
3760 result.branches[branch] = deletion;
3761 }),
3762 new LineParser(deleteErrorRegex, (result, [branch]) => {
3763 const deletion = branchDeletionFailure(branch);
3764 result.errors.push(deletion);
3765 result.all.push(deletion);
3766 result.branches[branch] = deletion;
3767 })
3768 ];
3769 parseBranchDeletions = (stdOut, stdErr) => {
3770 return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]);
3771 };
3772 }
3773});
3774
3775// src/lib/responses/BranchSummary.ts
3776var BranchSummaryResult;
3777var init_BranchSummary = __esm({
3778 "src/lib/responses/BranchSummary.ts"() {
3779 "use strict";
3780 BranchSummaryResult = class {
3781 constructor() {
3782 this.all = [];
3783 this.branches = {};
3784 this.current = "";
3785 this.detached = false;
3786 }
3787 push(status, detached, name, commit, label) {
3788 if (status === "*" /* CURRENT */) {
3789 this.detached = detached;
3790 this.current = name;
3791 }
3792 this.all.push(name);
3793 this.branches[name] = {
3794 current: status === "*" /* CURRENT */,
3795 linkedWorkTree: status === "+" /* LINKED */,
3796 name,
3797 commit,
3798 label
3799 };
3800 }
3801 };
3802 }
3803});
3804
3805// src/lib/parsers/parse-branch.ts
3806function branchStatus(input) {
3807 return input ? input.charAt(0) : "";
3808}
3809function parseBranchSummary(stdOut) {
3810 return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut);
3811}
3812var parsers9;
3813var init_parse_branch = __esm({
3814 "src/lib/parsers/parse-branch.ts"() {
3815 "use strict";
3816 init_BranchSummary();
3817 init_utils();
3818 parsers9 = [
3819 new LineParser(
3820 /^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,
3821 (result, [current, name, commit, label]) => {
3822 result.push(branchStatus(current), true, name, commit, label);
3823 }
3824 ),
3825 new LineParser(
3826 new RegExp("^([*+]\\s)?(\\S+)\\s+([a-z0-9]+)\\s?(.*)$", "s"),
3827 (result, [current, name, commit, label]) => {
3828 result.push(branchStatus(current), false, name, commit, label);
3829 }
3830 )
3831 ];
3832 }
3833});
3834
3835// src/lib/tasks/branch.ts
3836var branch_exports = {};
3837__export(branch_exports, {
3838 branchLocalTask: () => branchLocalTask,
3839 branchTask: () => branchTask,
3840 containsDeleteBranchCommand: () => containsDeleteBranchCommand,
3841 deleteBranchTask: () => deleteBranchTask,
3842 deleteBranchesTask: () => deleteBranchesTask
3843});
3844function containsDeleteBranchCommand(commands) {
3845 const deleteCommands = ["-d", "-D", "--delete"];
3846 return commands.some((command) => deleteCommands.includes(command));
3847}
3848function branchTask(customArgs) {
3849 const isDelete = containsDeleteBranchCommand(customArgs);
3850 const commands = ["branch", ...customArgs];
3851 if (commands.length === 1) {
3852 commands.push("-a");
3853 }
3854 if (!commands.includes("-v")) {
3855 commands.splice(1, 0, "-v");
3856 }
3857 return {
3858 format: "utf-8",
3859 commands,
3860 parser(stdOut, stdErr) {
3861 if (isDelete) {
3862 return parseBranchDeletions(stdOut, stdErr).all[0];
3863 }
3864 return parseBranchSummary(stdOut);
3865 }
3866 };
3867}
3868function branchLocalTask() {
3869 const parser4 = parseBranchSummary;
3870 return {
3871 format: "utf-8",
3872 commands: ["branch", "-v"],
3873 parser: parser4
3874 };
3875}
3876function deleteBranchesTask(branches, forceDelete = false) {
3877 return {
3878 format: "utf-8",
3879 commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches],
3880 parser(stdOut, stdErr) {
3881 return parseBranchDeletions(stdOut, stdErr);
3882 },
3883 onError({ exitCode, stdOut }, error, done, fail) {
3884 if (!hasBranchDeletionError(String(error), exitCode)) {
3885 return fail(error);
3886 }
3887 done(stdOut);
3888 }
3889 };
3890}
3891function deleteBranchTask(branch, forceDelete = false) {
3892 const task = {
3893 format: "utf-8",
3894 commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch],
3895 parser(stdOut, stdErr) {
3896 return parseBranchDeletions(stdOut, stdErr).branches[branch];
3897 },
3898 onError({ exitCode, stdErr, stdOut }, error, _, fail) {
3899 if (!hasBranchDeletionError(String(error), exitCode)) {
3900 return fail(error);
3901 }
3902 throw new GitResponseError(
3903 task.parser(bufferToString(stdOut), bufferToString(stdErr)),
3904 String(error)
3905 );
3906 }
3907 };
3908 return task;
3909}
3910var init_branch = __esm({
3911 "src/lib/tasks/branch.ts"() {
3912 "use strict";
3913 init_git_response_error();
3914 init_parse_branch_delete();
3915 init_parse_branch();
3916 init_utils();
3917 }
3918});
3919
3920// src/lib/responses/CheckIgnore.ts
3921var parseCheckIgnore;
3922var init_CheckIgnore = __esm({
3923 "src/lib/responses/CheckIgnore.ts"() {
3924 "use strict";
3925 parseCheckIgnore = (text) => {
3926 return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file);
3927 };
3928 }
3929});
3930
3931// src/lib/tasks/check-ignore.ts
3932var check_ignore_exports = {};
3933__export(check_ignore_exports, {
3934 checkIgnoreTask: () => checkIgnoreTask
3935});
3936function checkIgnoreTask(paths) {
3937 return {
3938 commands: ["check-ignore", ...paths],
3939 format: "utf-8",
3940 parser: parseCheckIgnore
3941 };
3942}
3943var init_check_ignore = __esm({
3944 "src/lib/tasks/check-ignore.ts"() {
3945 "use strict";
3946 init_CheckIgnore();
3947 }
3948});
3949
3950// src/lib/tasks/clone.ts
3951var clone_exports = {};
3952__export(clone_exports, {
3953 cloneMirrorTask: () => cloneMirrorTask,
3954 cloneTask: () => cloneTask
3955});
3956function disallowedCommand(command) {
3957 return /^--upload-pack(=|$)/.test(command);
3958}
3959function cloneTask(repo, directory, customArgs) {
3960 const commands = ["clone", ...customArgs];
3961 filterString(repo) && commands.push(repo);
3962 filterString(directory) && commands.push(directory);
3963 const banned = commands.find(disallowedCommand);
3964 if (banned) {
3965 return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
3966 }
3967 return straightThroughStringTask(commands);
3968}
3969function cloneMirrorTask(repo, directory, customArgs) {
3970 append(customArgs, "--mirror");
3971 return cloneTask(repo, directory, customArgs);
3972}
3973var init_clone = __esm({
3974 "src/lib/tasks/clone.ts"() {
3975 "use strict";
3976 init_task();
3977 init_utils();
3978 }
3979});
3980
3981// src/lib/parsers/parse-fetch.ts
3982function parseFetchResult(stdOut, stdErr) {
3983 const result = {
3984 raw: stdOut,
3985 remote: null,
3986 branches: [],
3987 tags: [],
3988 updated: [],
3989 deleted: []
3990 };
3991 return parseStringResponse(result, parsers10, [stdOut, stdErr]);
3992}
3993var parsers10;
3994var init_parse_fetch = __esm({
3995 "src/lib/parsers/parse-fetch.ts"() {
3996 "use strict";
3997 init_utils();
3998 parsers10 = [
3999 new LineParser(/From (.+)$/, (result, [remote]) => {
4000 result.remote = remote;
4001 }),
4002 new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => {
4003 result.branches.push({
4004 name,
4005 tracking
4006 });
4007 }),
4008 new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => {
4009 result.tags.push({
4010 name,
4011 tracking
4012 });
4013 }),
4014 new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => {
4015 result.deleted.push({
4016 tracking
4017 });
4018 }),
4019 new LineParser(
4020 /\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,
4021 (result, [from, to, name, tracking]) => {
4022 result.updated.push({
4023 name,
4024 tracking,
4025 to,
4026 from
4027 });
4028 }
4029 )
4030 ];
4031 }
4032});
4033
4034// src/lib/tasks/fetch.ts
4035var fetch_exports = {};
4036__export(fetch_exports, {
4037 fetchTask: () => fetchTask
4038});
4039function disallowedCommand2(command) {
4040 return /^--upload-pack(=|$)/.test(command);
4041}
4042function fetchTask(remote, branch, customArgs) {
4043 const commands = ["fetch", ...customArgs];
4044 if (remote && branch) {
4045 commands.push(remote, branch);
4046 }
4047 const banned = commands.find(disallowedCommand2);
4048 if (banned) {
4049 return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
4050 }
4051 return {
4052 commands,
4053 format: "utf-8",
4054 parser: parseFetchResult
4055 };
4056}
4057var init_fetch = __esm({
4058 "src/lib/tasks/fetch.ts"() {
4059 "use strict";
4060 init_parse_fetch();
4061 init_task();
4062 }
4063});
4064
4065// src/lib/parsers/parse-move.ts
4066function parseMoveResult(stdOut) {
4067 return parseStringResponse({ moves: [] }, parsers11, stdOut);
4068}
4069var parsers11;
4070var init_parse_move = __esm({
4071 "src/lib/parsers/parse-move.ts"() {
4072 "use strict";
4073 init_utils();
4074 parsers11 = [
4075 new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => {
4076 result.moves.push({ from, to });
4077 })
4078 ];
4079 }
4080});
4081
4082// src/lib/tasks/move.ts
4083var move_exports = {};
4084__export(move_exports, {
4085 moveTask: () => moveTask
4086});
4087function moveTask(from, to) {
4088 return {
4089 commands: ["mv", "-v", ...asArray(from), to],
4090 format: "utf-8",
4091 parser: parseMoveResult
4092 };
4093}
4094var init_move = __esm({
4095 "src/lib/tasks/move.ts"() {
4096 "use strict";
4097 init_parse_move();
4098 init_utils();
4099 }
4100});
4101
4102// src/lib/tasks/pull.ts
4103var pull_exports = {};
4104__export(pull_exports, {
4105 pullTask: () => pullTask
4106});
4107function pullTask(remote, branch, customArgs) {
4108 const commands = ["pull", ...customArgs];
4109 if (remote && branch) {
4110 commands.splice(1, 0, remote, branch);
4111 }
4112 return {
4113 commands,
4114 format: "utf-8",
4115 parser(stdOut, stdErr) {
4116 return parsePullResult(stdOut, stdErr);
4117 },
4118 onError(result, _error, _done, fail) {
4119 const pullError = parsePullErrorResult(
4120 bufferToString(result.stdOut),
4121 bufferToString(result.stdErr)
4122 );
4123 if (pullError) {
4124 return fail(new GitResponseError(pullError));
4125 }
4126 fail(_error);
4127 }
4128 };
4129}
4130var init_pull = __esm({
4131 "src/lib/tasks/pull.ts"() {
4132 "use strict";
4133 init_git_response_error();
4134 init_parse_pull();
4135 init_utils();
4136 }
4137});
4138
4139// src/lib/responses/GetRemoteSummary.ts
4140function parseGetRemotes(text) {
4141 const remotes = {};
4142 forEach(text, ([name]) => remotes[name] = { name });
4143 return Object.values(remotes);
4144}
4145function parseGetRemotesVerbose(text) {
4146 const remotes = {};
4147 forEach(text, ([name, url, purpose]) => {
4148 if (!remotes.hasOwnProperty(name)) {
4149 remotes[name] = {
4150 name,
4151 refs: { fetch: "", push: "" }
4152 };
4153 }
4154 if (purpose && url) {
4155 remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url;
4156 }
4157 });
4158 return Object.values(remotes);
4159}
4160function forEach(text, handler) {
4161 forEachLineWithContent(text, (line) => handler(line.split(/\s+/)));
4162}
4163var init_GetRemoteSummary = __esm({
4164 "src/lib/responses/GetRemoteSummary.ts"() {
4165 "use strict";
4166 init_utils();
4167 }
4168});
4169
4170// src/lib/tasks/remote.ts
4171var remote_exports = {};
4172__export(remote_exports, {
4173 addRemoteTask: () => addRemoteTask,
4174 getRemotesTask: () => getRemotesTask,
4175 listRemotesTask: () => listRemotesTask,
4176 remoteTask: () => remoteTask,
4177 removeRemoteTask: () => removeRemoteTask
4178});
4179function addRemoteTask(remoteName, remoteRepo, customArgs) {
4180 return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]);
4181}
4182function getRemotesTask(verbose) {
4183 const commands = ["remote"];
4184 if (verbose) {
4185 commands.push("-v");
4186 }
4187 return {
4188 commands,
4189 format: "utf-8",
4190 parser: verbose ? parseGetRemotesVerbose : parseGetRemotes
4191 };
4192}
4193function listRemotesTask(customArgs) {
4194 const commands = [...customArgs];
4195 if (commands[0] !== "ls-remote") {
4196 commands.unshift("ls-remote");
4197 }
4198 return straightThroughStringTask(commands);
4199}
4200function remoteTask(customArgs) {
4201 const commands = [...customArgs];
4202 if (commands[0] !== "remote") {
4203 commands.unshift("remote");
4204 }
4205 return straightThroughStringTask(commands);
4206}
4207function removeRemoteTask(remoteName) {
4208 return straightThroughStringTask(["remote", "remove", remoteName]);
4209}
4210var init_remote = __esm({
4211 "src/lib/tasks/remote.ts"() {
4212 "use strict";
4213 init_GetRemoteSummary();
4214 init_task();
4215 }
4216});
4217
4218// src/lib/tasks/stash-list.ts
4219var stash_list_exports = {};
4220__export(stash_list_exports, {
4221 stashListTask: () => stashListTask
4222});
4223function stashListTask(opt = {}, customArgs) {
4224 const options = parseLogOptions(opt);
4225 const commands = ["stash", "list", ...options.commands, ...customArgs];
4226 const parser4 = createListLogSummaryParser(
4227 options.splitter,
4228 options.fields,
4229 logFormatFromCommand(commands)
4230 );
4231 return validateLogFormatConfig(commands) || {
4232 commands,
4233 format: "utf-8",
4234 parser: parser4
4235 };
4236}
4237var init_stash_list = __esm({
4238 "src/lib/tasks/stash-list.ts"() {
4239 "use strict";
4240 init_log_format();
4241 init_parse_list_log_summary();
4242 init_diff();
4243 init_log();
4244 }
4245});
4246
4247// src/lib/tasks/sub-module.ts
4248var sub_module_exports = {};
4249__export(sub_module_exports, {
4250 addSubModuleTask: () => addSubModuleTask,
4251 initSubModuleTask: () => initSubModuleTask,
4252 subModuleTask: () => subModuleTask,
4253 updateSubModuleTask: () => updateSubModuleTask
4254});
4255function addSubModuleTask(repo, path) {
4256 return subModuleTask(["add", repo, path]);
4257}
4258function initSubModuleTask(customArgs) {
4259 return subModuleTask(["init", ...customArgs]);
4260}
4261function subModuleTask(customArgs) {
4262 const commands = [...customArgs];
4263 if (commands[0] !== "submodule") {
4264 commands.unshift("submodule");
4265 }
4266 return straightThroughStringTask(commands);
4267}
4268function updateSubModuleTask(customArgs) {
4269 return subModuleTask(["update", ...customArgs]);
4270}
4271var init_sub_module = __esm({
4272 "src/lib/tasks/sub-module.ts"() {
4273 "use strict";
4274 init_task();
4275 }
4276});
4277
4278// src/lib/responses/TagList.ts
4279function singleSorted(a, b) {
4280 const aIsNum = isNaN(a);
4281 const bIsNum = isNaN(b);
4282 if (aIsNum !== bIsNum) {
4283 return aIsNum ? 1 : -1;
4284 }
4285 return aIsNum ? sorted(a, b) : 0;
4286}
4287function sorted(a, b) {
4288 return a === b ? 0 : a > b ? 1 : -1;
4289}
4290function trimmed(input) {
4291 return input.trim();
4292}
4293function toNumber(input) {
4294 if (typeof input === "string") {
4295 return parseInt(input.replace(/^\D+/g, ""), 10) || 0;
4296 }
4297 return 0;
4298}
4299var TagList, parseTagList;
4300var init_TagList = __esm({
4301 "src/lib/responses/TagList.ts"() {
4302 "use strict";
4303 TagList = class {
4304 constructor(all, latest) {
4305 this.all = all;
4306 this.latest = latest;
4307 }
4308 };
4309 parseTagList = function(data, customSort = false) {
4310 const tags = data.split("\n").map(trimmed).filter(Boolean);
4311 if (!customSort) {
4312 tags.sort(function(tagA, tagB) {
4313 const partsA = tagA.split(".");
4314 const partsB = tagB.split(".");
4315 if (partsA.length === 1 || partsB.length === 1) {
4316 return singleSorted(toNumber(partsA[0]), toNumber(partsB[0]));
4317 }
4318 for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) {
4319 const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i]));
4320 if (diff) {
4321 return diff;
4322 }
4323 }
4324 return 0;
4325 });
4326 }
4327 const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf(".") >= 0);
4328 return new TagList(tags, latest);
4329 };
4330 }
4331});
4332
4333// src/lib/tasks/tag.ts
4334var tag_exports = {};
4335__export(tag_exports, {
4336 addAnnotatedTagTask: () => addAnnotatedTagTask,
4337 addTagTask: () => addTagTask,
4338 tagListTask: () => tagListTask
4339});
4340function tagListTask(customArgs = []) {
4341 const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option));
4342 return {
4343 format: "utf-8",
4344 commands: ["tag", "-l", ...customArgs],
4345 parser(text) {
4346 return parseTagList(text, hasCustomSort);
4347 }
4348 };
4349}
4350function addTagTask(name) {
4351 return {
4352 format: "utf-8",
4353 commands: ["tag", name],
4354 parser() {
4355 return { name };
4356 }
4357 };
4358}
4359function addAnnotatedTagTask(name, tagMessage) {
4360 return {
4361 format: "utf-8",
4362 commands: ["tag", "-a", "-m", tagMessage, name],
4363 parser() {
4364 return { name };
4365 }
4366 };
4367}
4368var init_tag = __esm({
4369 "src/lib/tasks/tag.ts"() {
4370 "use strict";
4371 init_TagList();
4372 }
4373});
4374
4375// src/git.js
4376var require_git = __commonJS({
4377 "src/git.js"(exports2, module2) {
4378 "use strict";
4379 var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS(git_executor_exports));
4380 var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS(simple_git_api_exports));
4381 var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS(scheduler_exports));
4382 var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS(task_exports));
4383 var {
4384 asArray: asArray2,
4385 filterArray: filterArray2,
4386 filterPrimitives: filterPrimitives2,
4387 filterString: filterString2,
4388 filterStringOrStringArray: filterStringOrStringArray2,
4389 filterType: filterType2,
4390 getTrailingOptions: getTrailingOptions2,
4391 trailingFunctionArgument: trailingFunctionArgument2,
4392 trailingOptionsArgument: trailingOptionsArgument2
4393 } = (init_utils(), __toCommonJS(utils_exports));
4394 var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS(apply_patch_exports));
4395 var {
4396 branchTask: branchTask2,
4397 branchLocalTask: branchLocalTask2,
4398 deleteBranchesTask: deleteBranchesTask2,
4399 deleteBranchTask: deleteBranchTask2
4400 } = (init_branch(), __toCommonJS(branch_exports));
4401 var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS(check_ignore_exports));
4402 var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS(check_is_repo_exports));
4403 var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS(clone_exports));
4404 var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS(clean_exports));
4405 var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS(diff_exports));
4406 var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS(fetch_exports));
4407 var { moveTask: moveTask2 } = (init_move(), __toCommonJS(move_exports));
4408 var { pullTask: pullTask2 } = (init_pull(), __toCommonJS(pull_exports));
4409 var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS(push_exports));
4410 var {
4411 addRemoteTask: addRemoteTask2,
4412 getRemotesTask: getRemotesTask2,
4413 listRemotesTask: listRemotesTask2,
4414 remoteTask: remoteTask2,
4415 removeRemoteTask: removeRemoteTask2
4416 } = (init_remote(), __toCommonJS(remote_exports));
4417 var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS(reset_exports));
4418 var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS(stash_list_exports));
4419 var {
4420 addSubModuleTask: addSubModuleTask2,
4421 initSubModuleTask: initSubModuleTask2,
4422 subModuleTask: subModuleTask2,
4423 updateSubModuleTask: updateSubModuleTask2
4424 } = (init_sub_module(), __toCommonJS(sub_module_exports));
4425 var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS(tag_exports));
4426 var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS(task_exports));
4427 function Git2(options, plugins) {
4428 this._plugins = plugins;
4429 this._executor = new GitExecutor2(
4430 options.baseDir,
4431 new Scheduler2(options.maxConcurrentProcesses),
4432 plugins
4433 );
4434 this._trimmed = options.trimmed;
4435 }
4436 (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2;
4437 Git2.prototype.customBinary = function(command) {
4438 this._plugins.reconfigure("binary", command);
4439 return this;
4440 };
4441 Git2.prototype.env = function(name, value) {
4442 if (arguments.length === 1 && typeof name === "object") {
4443 this._executor.env = name;
4444 } else {
4445 (this._executor.env = this._executor.env || {})[name] = value;
4446 }
4447 return this;
4448 };
4449 Git2.prototype.stashList = function(options) {
4450 return this._runTask(
4451 stashListTask2(
4452 trailingOptionsArgument2(arguments) || {},
4453 filterArray2(options) && options || []
4454 ),
4455 trailingFunctionArgument2(arguments)
4456 );
4457 };
4458 function createCloneTask(api, task, repoPath, localPath) {
4459 if (typeof repoPath !== "string") {
4460 return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`);
4461 }
4462 return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments));
4463 }
4464 Git2.prototype.clone = function() {
4465 return this._runTask(
4466 createCloneTask("clone", cloneTask2, ...arguments),
4467 trailingFunctionArgument2(arguments)
4468 );
4469 };
4470 Git2.prototype.mirror = function() {
4471 return this._runTask(
4472 createCloneTask("mirror", cloneMirrorTask2, ...arguments),
4473 trailingFunctionArgument2(arguments)
4474 );
4475 };
4476 Git2.prototype.mv = function(from, to) {
4477 return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments));
4478 };
4479 Git2.prototype.checkoutLatestTag = function(then) {
4480 var git = this;
4481 return this.pull(function() {
4482 git.tags(function(err, tags) {
4483 git.checkout(tags.latest, then);
4484 });
4485 });
4486 };
4487 Git2.prototype.pull = function(remote, branch, options, then) {
4488 return this._runTask(
4489 pullTask2(
4490 filterType2(remote, filterString2),
4491 filterType2(branch, filterString2),
4492 getTrailingOptions2(arguments)
4493 ),
4494 trailingFunctionArgument2(arguments)
4495 );
4496 };
4497 Git2.prototype.fetch = function(remote, branch) {
4498 return this._runTask(
4499 fetchTask2(
4500 filterType2(remote, filterString2),
4501 filterType2(branch, filterString2),
4502 getTrailingOptions2(arguments)
4503 ),
4504 trailingFunctionArgument2(arguments)
4505 );
4506 };
4507 Git2.prototype.silent = function(silence) {
4508 console.warn(
4509 "simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"
4510 );
4511 return this;
4512 };
4513 Git2.prototype.tags = function(options, then) {
4514 return this._runTask(
4515 tagListTask2(getTrailingOptions2(arguments)),
4516 trailingFunctionArgument2(arguments)
4517 );
4518 };
4519 Git2.prototype.rebase = function() {
4520 return this._runTask(
4521 straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]),
4522 trailingFunctionArgument2(arguments)
4523 );
4524 };
4525 Git2.prototype.reset = function(mode) {
4526 return this._runTask(
4527 resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)),
4528 trailingFunctionArgument2(arguments)
4529 );
4530 };
4531 Git2.prototype.revert = function(commit) {
4532 const next = trailingFunctionArgument2(arguments);
4533 if (typeof commit !== "string") {
4534 return this._runTask(configurationErrorTask2("Commit must be a string"), next);
4535 }
4536 return this._runTask(
4537 straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]),
4538 next
4539 );
4540 };
4541 Git2.prototype.addTag = function(name) {
4542 const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name");
4543 return this._runTask(task, trailingFunctionArgument2(arguments));
4544 };
4545 Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) {
4546 return this._runTask(
4547 addAnnotatedTagTask2(tagName, tagMessage),
4548 trailingFunctionArgument2(arguments)
4549 );
4550 };
4551 Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) {
4552 return this._runTask(
4553 deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false),
4554 trailingFunctionArgument2(arguments)
4555 );
4556 };
4557 Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) {
4558 return this._runTask(
4559 deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false),
4560 trailingFunctionArgument2(arguments)
4561 );
4562 };
4563 Git2.prototype.branch = function(options, then) {
4564 return this._runTask(
4565 branchTask2(getTrailingOptions2(arguments)),
4566 trailingFunctionArgument2(arguments)
4567 );
4568 };
4569 Git2.prototype.branchLocal = function(then) {
4570 return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments));
4571 };
4572 Git2.prototype.raw = function(commands) {
4573 const createRestCommands = !Array.isArray(commands);
4574 const command = [].slice.call(createRestCommands ? arguments : commands, 0);
4575 for (let i = 0; i < command.length && createRestCommands; i++) {
4576 if (!filterPrimitives2(command[i])) {
4577 command.splice(i, command.length - i);
4578 break;
4579 }
4580 }
4581 command.push(...getTrailingOptions2(arguments, 0, true));
4582 var next = trailingFunctionArgument2(arguments);
4583 if (!command.length) {
4584 return this._runTask(
4585 configurationErrorTask2("Raw: must supply one or more command to execute"),
4586 next
4587 );
4588 }
4589 return this._runTask(straightThroughStringTask2(command, this._trimmed), next);
4590 };
4591 Git2.prototype.submoduleAdd = function(repo, path, then) {
4592 return this._runTask(addSubModuleTask2(repo, path), trailingFunctionArgument2(arguments));
4593 };
4594 Git2.prototype.submoduleUpdate = function(args, then) {
4595 return this._runTask(
4596 updateSubModuleTask2(getTrailingOptions2(arguments, true)),
4597 trailingFunctionArgument2(arguments)
4598 );
4599 };
4600 Git2.prototype.submoduleInit = function(args, then) {
4601 return this._runTask(
4602 initSubModuleTask2(getTrailingOptions2(arguments, true)),
4603 trailingFunctionArgument2(arguments)
4604 );
4605 };
4606 Git2.prototype.subModule = function(options, then) {
4607 return this._runTask(
4608 subModuleTask2(getTrailingOptions2(arguments)),
4609 trailingFunctionArgument2(arguments)
4610 );
4611 };
4612 Git2.prototype.listRemote = function() {
4613 return this._runTask(
4614 listRemotesTask2(getTrailingOptions2(arguments)),
4615 trailingFunctionArgument2(arguments)
4616 );
4617 };
4618 Git2.prototype.addRemote = function(remoteName, remoteRepo, then) {
4619 return this._runTask(
4620 addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)),
4621 trailingFunctionArgument2(arguments)
4622 );
4623 };
4624 Git2.prototype.removeRemote = function(remoteName, then) {
4625 return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments));
4626 };
4627 Git2.prototype.getRemotes = function(verbose, then) {
4628 return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments));
4629 };
4630 Git2.prototype.remote = function(options, then) {
4631 return this._runTask(
4632 remoteTask2(getTrailingOptions2(arguments)),
4633 trailingFunctionArgument2(arguments)
4634 );
4635 };
4636 Git2.prototype.tag = function(options, then) {
4637 const command = getTrailingOptions2(arguments);
4638 if (command[0] !== "tag") {
4639 command.unshift("tag");
4640 }
4641 return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments));
4642 };
4643 Git2.prototype.updateServerInfo = function(then) {
4644 return this._runTask(
4645 straightThroughStringTask2(["update-server-info"]),
4646 trailingFunctionArgument2(arguments)
4647 );
4648 };
4649 Git2.prototype.pushTags = function(remote, then) {
4650 const task = pushTagsTask2(
4651 { remote: filterType2(remote, filterString2) },
4652 getTrailingOptions2(arguments)
4653 );
4654 return this._runTask(task, trailingFunctionArgument2(arguments));
4655 };
4656 Git2.prototype.rm = function(files) {
4657 return this._runTask(
4658 straightThroughStringTask2(["rm", "-f", ...asArray2(files)]),
4659 trailingFunctionArgument2(arguments)
4660 );
4661 };
4662 Git2.prototype.rmKeepLocal = function(files) {
4663 return this._runTask(
4664 straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]),
4665 trailingFunctionArgument2(arguments)
4666 );
4667 };
4668 Git2.prototype.catFile = function(options, then) {
4669 return this._catFile("utf-8", arguments);
4670 };
4671 Git2.prototype.binaryCatFile = function() {
4672 return this._catFile("buffer", arguments);
4673 };
4674 Git2.prototype._catFile = function(format, args) {
4675 var handler = trailingFunctionArgument2(args);
4676 var command = ["cat-file"];
4677 var options = args[0];
4678 if (typeof options === "string") {
4679 return this._runTask(
4680 configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"),
4681 handler
4682 );
4683 }
4684 if (Array.isArray(options)) {
4685 command.push.apply(command, options);
4686 }
4687 const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command);
4688 return this._runTask(task, handler);
4689 };
4690 Git2.prototype.diff = function(options, then) {
4691 const task = filterString2(options) ? configurationErrorTask2(
4692 "git.diff: supplying options as a single string is no longer supported, switch to an array of strings"
4693 ) : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]);
4694 return this._runTask(task, trailingFunctionArgument2(arguments));
4695 };
4696 Git2.prototype.diffSummary = function() {
4697 return this._runTask(
4698 diffSummaryTask2(getTrailingOptions2(arguments, 1)),
4699 trailingFunctionArgument2(arguments)
4700 );
4701 };
4702 Git2.prototype.applyPatch = function(patches) {
4703 const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2(
4704 `git.applyPatch requires one or more string patches as the first argument`
4705 ) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1)));
4706 return this._runTask(task, trailingFunctionArgument2(arguments));
4707 };
4708 Git2.prototype.revparse = function() {
4709 const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)];
4710 return this._runTask(
4711 straightThroughStringTask2(commands, true),
4712 trailingFunctionArgument2(arguments)
4713 );
4714 };
4715 Git2.prototype.clean = function(mode, options, then) {
4716 const usingCleanOptionsArray = isCleanOptionsArray2(mode);
4717 const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || "";
4718 const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0));
4719 return this._runTask(
4720 cleanWithOptionsTask2(cleanMode, customArgs),
4721 trailingFunctionArgument2(arguments)
4722 );
4723 };
4724 Git2.prototype.exec = function(then) {
4725 const task = {
4726 commands: [],
4727 format: "utf-8",
4728 parser() {
4729 if (typeof then === "function") {
4730 then();
4731 }
4732 }
4733 };
4734 return this._runTask(task);
4735 };
4736 Git2.prototype.clearQueue = function() {
4737 return this;
4738 };
4739 Git2.prototype.checkIgnore = function(pathnames, then) {
4740 return this._runTask(
4741 checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))),
4742 trailingFunctionArgument2(arguments)
4743 );
4744 };
4745 Git2.prototype.checkIsRepo = function(checkType, then) {
4746 return this._runTask(
4747 checkIsRepoTask2(filterType2(checkType, filterString2)),
4748 trailingFunctionArgument2(arguments)
4749 );
4750 };
4751 module2.exports = Git2;
4752 }
4753});
4754
4755// src/lib/git-factory.ts
4756var git_factory_exports = {};
4757__export(git_factory_exports, {
4758 esModuleFactory: () => esModuleFactory,
4759 gitExportFactory: () => gitExportFactory,
4760 gitInstanceFactory: () => gitInstanceFactory
4761});
4762function esModuleFactory(defaultExport) {
4763 return Object.defineProperties(defaultExport, {
4764 __esModule: { value: true },
4765 default: { value: defaultExport }
4766 });
4767}
4768function gitExportFactory(factory) {
4769 return Object.assign(factory.bind(null), api_exports);
4770}
4771function gitInstanceFactory(baseDir, options) {
4772 var _a2;
4773 const plugins = new PluginStore();
4774 const config = createInstanceConfig(
4775 baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {},
4776 options
4777 );
4778 if (!folderExists(config.baseDir)) {
4779 throw new GitConstructError(
4780 config,
4781 `Cannot use simple-git on a directory that does not exist`
4782 );
4783 }
4784 if (Array.isArray(config.config)) {
4785 plugins.add(commandConfigPrefixingPlugin(config.config));
4786 }
4787 plugins.add(blockUnsafeOperationsPlugin(config.unsafe));
4788 plugins.add(suffixPathsPlugin());
4789 plugins.add(completionDetectionPlugin(config.completion));
4790 config.abort && plugins.add(abortPlugin(config.abort));
4791 config.progress && plugins.add(progressMonitorPlugin(config.progress));
4792 config.timeout && plugins.add(timeoutPlugin(config.timeout));
4793 config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions));
4794 plugins.add(errorDetectionPlugin(errorDetectionHandler(true)));
4795 config.errors && plugins.add(errorDetectionPlugin(config.errors));
4796 customBinaryPlugin(plugins, config.binary, (_a2 = config.unsafe) == null ? void 0 : _a2.allowUnsafeCustomBinary);
4797 return new Git(config, plugins);
4798}
4799var Git;
4800var init_git_factory = __esm({
4801 "src/lib/git-factory.ts"() {
4802 "use strict";
4803 init_api();
4804 init_plugins();
4805 init_suffix_paths_plugin();
4806 init_utils();
4807 Git = require_git();
4808 }
4809});
4810
4811// src/lib/runners/promise-wrapped.ts
4812var promise_wrapped_exports = {};
4813__export(promise_wrapped_exports, {
4814 gitP: () => gitP
4815});
4816function gitP(...args) {
4817 let git;
4818 let chain = Promise.resolve();
4819 try {
4820 git = gitInstanceFactory(...args);
4821 } catch (e) {
4822 chain = Promise.reject(e);
4823 }
4824 function builderReturn() {
4825 return promiseApi;
4826 }
4827 function chainReturn() {
4828 return chain;
4829 }
4830 const promiseApi = [...functionNamesBuilderApi, ...functionNamesPromiseApi].reduce(
4831 (api, name) => {
4832 const isAsync = functionNamesPromiseApi.includes(name);
4833 const valid = isAsync ? asyncWrapper(name, git) : syncWrapper(name, git, api);
4834 const alternative = isAsync ? chainReturn : builderReturn;
4835 Object.defineProperty(api, name, {
4836 enumerable: false,
4837 configurable: false,
4838 value: git ? valid : alternative
4839 });
4840 return api;
4841 },
4842 {}
4843 );
4844 return promiseApi;
4845 function asyncWrapper(fn, git2) {
4846 return function(...args2) {
4847 if (typeof args2[args2.length] === "function") {
4848 throw new TypeError(
4849 "Promise interface requires that handlers are not supplied inline, trailing function not allowed in call to " + fn
4850 );
4851 }
4852 return chain.then(function() {
4853 return new Promise(function(resolve, reject) {
4854 const callback = (err, result) => {
4855 if (err) {
4856 return reject(toError(err));
4857 }
4858 resolve(result);
4859 };
4860 args2.push(callback);
4861 git2[fn].apply(git2, args2);
4862 });
4863 });
4864 };
4865 }
4866 function syncWrapper(fn, git2, api) {
4867 return (...args2) => {
4868 git2[fn](...args2);
4869 return api;
4870 };
4871 }
4872}
4873function toError(error) {
4874 if (error instanceof Error) {
4875 return error;
4876 }
4877 if (typeof error === "string") {
4878 return new Error(error);
4879 }
4880 return new GitResponseError(error);
4881}
4882var functionNamesBuilderApi, functionNamesPromiseApi;
4883var init_promise_wrapped = __esm({
4884 "src/lib/runners/promise-wrapped.ts"() {
4885 "use strict";
4886 init_git_response_error();
4887 init_git_factory();
4888 functionNamesBuilderApi = ["customBinary", "env", "outputHandler", "silent"];
4889 functionNamesPromiseApi = [
4890 "add",
4891 "addAnnotatedTag",
4892 "addConfig",
4893 "addRemote",
4894 "addTag",
4895 "applyPatch",
4896 "binaryCatFile",
4897 "branch",
4898 "branchLocal",
4899 "catFile",
4900 "checkIgnore",
4901 "checkIsRepo",
4902 "checkout",
4903 "checkoutBranch",
4904 "checkoutLatestTag",
4905 "checkoutLocalBranch",
4906 "clean",
4907 "clone",
4908 "commit",
4909 "cwd",
4910 "deleteLocalBranch",
4911 "deleteLocalBranches",
4912 "diff",
4913 "diffSummary",
4914 "exec",
4915 "fetch",
4916 "getRemotes",
4917 "init",
4918 "listConfig",
4919 "listRemote",
4920 "log",
4921 "merge",
4922 "mergeFromTo",
4923 "mirror",
4924 "mv",
4925 "pull",
4926 "push",
4927 "pushTags",
4928 "raw",
4929 "rebase",
4930 "remote",
4931 "removeRemote",
4932 "reset",
4933 "revert",
4934 "revparse",
4935 "rm",
4936 "rmKeepLocal",
4937 "show",
4938 "stash",
4939 "stashList",
4940 "status",
4941 "subModule",
4942 "submoduleAdd",
4943 "submoduleInit",
4944 "submoduleUpdate",
4945 "tag",
4946 "tags",
4947 "updateServerInfo"
4948 ];
4949 }
4950});
4951
4952// src/index.js
4953var { gitP: gitP2 } = (init_promise_wrapped(), __toCommonJS(promise_wrapped_exports));
4954var { esModuleFactory: esModuleFactory2, gitInstanceFactory: gitInstanceFactory2, gitExportFactory: gitExportFactory2 } = (init_git_factory(), __toCommonJS(git_factory_exports));
4955var simpleGit = esModuleFactory2(gitExportFactory2(gitInstanceFactory2));
4956module.exports = Object.assign(simpleGit, { gitP: gitP2, simpleGit });
4957//# sourceMappingURL=index.js.map