} children
+ */
+ reduce: unmergedFiles.length !== 0 && (!dir || abortOnConflict) ? void 0 : async (parent, children2) => {
const entries = children2.filter(Boolean);
if (!parent)
return;
@@ -15609,7 +22315,7 @@ async function mergeTree({
return parent;
}
});
- if (!cleanMerge) {
+ if (unmergedFiles.length !== 0) {
if (dir && !abortOnConflict) {
await _walk({
fs,
@@ -15628,25 +22334,10 @@ async function mergeTree({
}
});
}
- throw new MergeConflictError(unmergedFiles);
+ return new MergeConflictError(unmergedFiles);
}
return results.oid;
}
-async function modified(entry, base) {
- if (!entry && !base)
- return false;
- if (entry && !base)
- return true;
- if (!entry && base)
- return true;
- if (await entry.type() === "tree" && await base.type() === "tree") {
- return false;
- }
- if (await entry.type() === await base.type() && await entry.mode() === await base.mode() && await entry.oid() === await base.oid()) {
- return false;
- }
- return true;
-}
async function mergeBlobs({
fs,
gitdir,
@@ -15680,9 +22371,9 @@ async function mergeBlobs({
mergeResult: { mode, path: path2, oid: await ours.oid(), type }
};
}
- const ourContent = Buffer2.from(await ours.content()).toString("utf8");
- const baseContent = Buffer2.from(await base.content()).toString("utf8");
- const theirContent = Buffer2.from(await theirs.content()).toString("utf8");
+ const ourContent = Buffer.from(await ours.content()).toString("utf8");
+ const baseContent = Buffer.from(await base.content()).toString("utf8");
+ const theirContent = Buffer.from(await theirs.content()).toString("utf8");
const { mergedText, cleanMerge } = await mergeDriver({
branches: [baseName, ourName, theirName],
contents: [baseContent, ourContent, theirContent],
@@ -15692,7 +22383,7 @@ async function mergeBlobs({
fs,
gitdir,
type: "blob",
- object: Buffer2.from(mergedText, "utf8"),
+ object: Buffer.from(mergedText, "utf8"),
dryRun
});
return { cleanMerge, mergeResult: { mode, path: path2, oid, type } };
@@ -15767,23 +22458,33 @@ async function _merge({
if (fastForwardOnly) {
throw new FastForwardError();
}
- const tree = await mergeTree({
- fs,
- cache,
- dir,
- gitdir,
- ourOid,
- theirOid,
- baseOid,
- ourName: abbreviateRef(ours),
- baseName: "base",
- theirName: abbreviateRef(theirs),
- dryRun,
- abortOnConflict,
- mergeDriver
- });
+ const tree = await GitIndexManager.acquire(
+ { fs, gitdir, cache, allowUnmerged: false },
+ async (index2) => {
+ return mergeTree({
+ fs,
+ cache,
+ dir,
+ gitdir,
+ index: index2,
+ ourOid,
+ theirOid,
+ baseOid,
+ ourName: abbreviateRef(ours),
+ baseName: "base",
+ theirName: abbreviateRef(theirs),
+ dryRun,
+ abortOnConflict,
+ mergeDriver
+ });
+ }
+ );
+ if (tree instanceof MergeConflictError)
+ throw tree;
if (!message) {
- message = `Merge branch '${abbreviateRef(theirs)}' into ${abbreviateRef(ours)}`;
+ message = `Merge branch '${abbreviateRef(theirs)}' into ${abbreviateRef(
+ ours
+ )}`;
}
const oid = await _commit({
fs,
@@ -15965,7 +22666,7 @@ async function fetch({
depth = null,
since = null,
exclude = [],
- relative = false,
+ relative: relative2 = false,
tags = false,
singleBranch = false,
headers = {},
@@ -15995,7 +22696,7 @@ async function fetch({
depth,
since,
exclude,
- relative,
+ relative: relative2,
tags,
singleBranch,
headers,
@@ -16239,9 +22940,9 @@ async function hashBlob({ object }) {
try {
assertParameter("object", object);
if (typeof object === "string") {
- object = Buffer2.from(object, "utf8");
+ object = Buffer.from(object, "utf8");
} else {
- object = Buffer2.from(object);
+ object = Buffer.from(object);
}
const type = "blob";
const { oid, object: _object } = await hashObject({
@@ -16350,7 +23051,7 @@ async function _isDescendent({
if (oid === ancestor)
return false;
const queue = [oid];
- const visited = new Set();
+ const visited = /* @__PURE__ */ new Set();
let searchdepth = 0;
while (queue.length) {
if (searchdepth++ === depth) {
@@ -16560,10 +23261,12 @@ async function listNotes({
async function _listRemotes({ fs, gitdir }) {
const config = await GitConfigManager.get({ fs, gitdir });
const remoteNames = await config.getSubsections("remote");
- const remotes = Promise.all(remoteNames.map(async (remote) => {
- const url = await config.get(`remote.${remote}.url`);
- return { remote, url };
- }));
+ const remotes = Promise.all(
+ remoteNames.map(async (remote) => {
+ const url = await config.get(`remote.${remote}.url`);
+ return { remote, url };
+ })
+ );
return remotes;
}
async function listRemotes({ fs, dir, gitdir = join(dir, ".git") }) {
@@ -16904,6 +23607,7 @@ async function log({
ref = "HEAD",
depth,
since,
+ // Date
force,
follow,
cache = {}
@@ -17008,7 +23712,7 @@ async function _pack({
const hash2 = new import_sha1.default();
const outputStream = [];
function write(chunk, enc) {
- const buff = Buffer2.from(chunk, enc);
+ const buff = Buffer.from(chunk, enc);
outputStream.push(buff);
hash2.update(buff);
}
@@ -17026,7 +23730,7 @@ async function _pack({
write(padHex(2, byte), "hex");
length = length >>> 7;
}
- write(Buffer2.from(await deflate(object)));
+ write(Buffer.from(await deflate(object)));
}
write("PACK");
write("00000002", "hex");
@@ -17041,7 +23745,7 @@ async function _pack({
}
async function _packObjects({ fs, cache, gitdir, oids, write }) {
const buffers = await _pack({ fs, cache, gitdir, oids });
- const packfile = Buffer2.from(await collect(buffers));
+ const packfile = Buffer.from(await collect(buffers));
const packfileSha = packfile.slice(-20).toString("hex");
const filename = `pack-${packfileSha}.pack`;
if (write) {
@@ -17158,8 +23862,8 @@ async function listCommitsAndTags({
finish
}) {
const shallows = await GitShallowManager.read({ fs, gitdir });
- const startingSet = new Set();
- const finishingSet = new Set();
+ const startingSet = /* @__PURE__ */ new Set();
+ const finishingSet = /* @__PURE__ */ new Set();
for (const ref of start) {
startingSet.add(await GitRefManager.resolve({ fs, gitdir, ref }));
}
@@ -17170,7 +23874,7 @@ async function listCommitsAndTags({
} catch (err) {
}
}
- const visited = new Set();
+ const visited = /* @__PURE__ */ new Set();
async function walk2(oid) {
visited.add(oid);
const { type, object } = await _readObject({ fs, cache, gitdir, oid });
@@ -17204,7 +23908,7 @@ async function listObjects({
gitdir = join(dir, ".git"),
oids
}) {
- const visited = new Set();
+ const visited = /* @__PURE__ */ new Set();
async function walk2(oid) {
if (visited.has(oid))
return;
@@ -17279,8 +23983,12 @@ async function writeReceivePackRequest({
const packstream = [];
let capsFirstLine = `\0 ${capabilities.join(" ")}`;
for (const trip of triplets) {
- packstream.push(GitPktLine.encode(`${trip.oldoid} ${trip.oid} ${trip.fullRef}${capsFirstLine}
-`));
+ packstream.push(
+ GitPktLine.encode(
+ `${trip.oldoid} ${trip.oid} ${trip.fullRef}${capsFirstLine}
+`
+ )
+ );
capsFirstLine = "";
}
packstream.push(GitPktLine.flush());
@@ -17356,10 +24064,10 @@ async function _push({
}
const oldoid = httpRemote.refs.get(fullRemoteRef) || "0000000000000000000000000000000000000000";
const thinPack = !httpRemote.capabilities.has("no-thin");
- let objects = new Set();
+ let objects = /* @__PURE__ */ new Set();
if (!_delete) {
const finish = [...httpRemote.refs.values()];
- let skipObjects = new Set();
+ let skipObjects = /* @__PURE__ */ new Set();
if (oldoid !== "0000000000000000000000000000000000000000") {
const mergebase = await _findMergeBase({
fs,
@@ -17424,7 +24132,10 @@ async function _push({
}
}
}
- const capabilities = filterCapabilities([...httpRemote.capabilities], ["report-status", "side-band-64k", `agent=${pkg.agent}`]);
+ const capabilities = filterCapabilities(
+ [...httpRemote.capabilities],
+ ["report-status", "side-band-64k", `agent=${pkg.agent}`]
+ );
const packstream1 = await writeReceivePackRequest({
capabilities,
triplets: [{ oldoid, oid, fullRef: fullRemoteRef }]
@@ -17457,7 +24168,10 @@ async function _push({
result.headers = res.headers;
}
if (remote && result.ok && result.refs[fullRemoteRef].ok) {
- const ref2 = `refs/remotes/${remote}/${fullRemoteRef.replace("refs/heads", "")}`;
+ const ref2 = `refs/remotes/${remote}/${fullRemoteRef.replace(
+ "refs/heads",
+ ""
+ )}`;
if (_delete) {
await GitRefManager.deleteRef({ fs, gitdir, ref: ref2 });
} else {
@@ -17691,7 +24405,11 @@ async function readObject({
result.object = GitAnnotatedTag.from(result.object).parse();
break;
default:
- throw new ObjectTypeError(result.oid, result.type, "blob|commit|tag|tree");
+ throw new ObjectTypeError(
+ result.oid,
+ result.type,
+ "blob|commit|tag|tree"
+ );
}
} else if (result.format === "deflated" || result.format === "wrapped") {
result.type = result.format;
@@ -17778,9 +24496,12 @@ async function remove({
assertParameter("fs", _fs);
assertParameter("gitdir", gitdir);
assertParameter("filepath", filepath);
- await GitIndexManager.acquire({ fs: new FileSystem(_fs), gitdir, cache }, async function(index2) {
- index2.delete({ filepath });
- });
+ await GitIndexManager.acquire(
+ { fs: new FileSystem(_fs), gitdir, cache },
+ async function(index2) {
+ index2.delete({ filepath });
+ }
+ );
} catch (err) {
err.caller = "git.remove";
throw err;
@@ -17904,7 +24625,13 @@ async function _renameBranch({
});
await GitRefManager.writeRef({ fs, gitdir, ref: fullnewref, value });
await GitRefManager.deleteRef({ fs, gitdir, ref: fulloldref });
- if (checkout2) {
+ const fullCurrentBranchRef = await _currentBranch({
+ fs,
+ gitdir,
+ fullname: true
+ });
+ const isCurrentBranch = fullCurrentBranchRef === fulloldref;
+ if (checkout2 || isCurrentBranch) {
await GitRefManager.writeSymbolicRef({
fs,
gitdir,
@@ -17977,8 +24704,8 @@ async function resetIndex({
}
}
let stats = {
- ctime: new Date(0),
- mtime: new Date(0),
+ ctime: /* @__PURE__ */ new Date(0),
+ mtime: /* @__PURE__ */ new Date(0),
dev: 0,
ino: 0,
mode: 0,
@@ -18085,13 +24812,16 @@ async function status({
tree: headTree,
path: filepath
});
- const indexEntry = await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) {
- for (const entry of index2) {
- if (entry.path === filepath)
- return entry;
+ const indexEntry = await GitIndexManager.acquire(
+ { fs, gitdir, cache },
+ async function(index2) {
+ for (const entry of index2) {
+ if (entry.path === filepath)
+ return entry;
+ }
+ return null;
}
- return null;
- });
+ );
const stats = await fs.lstat(join(dir, filepath));
const H = treeOid !== null;
const I = indexEntry !== null;
@@ -18151,9 +24881,9 @@ async function status({
async function getOidAtPath({ fs, cache, gitdir, tree, path: path2 }) {
if (typeof path2 === "string")
path2 = path2.split("/");
- const dirname2 = path2.shift();
+ const dirname3 = path2.shift();
for (const entry of tree) {
- if (entry.path === dirname2) {
+ if (entry.path === dirname3) {
if (path2.length === 0) {
return entry.oid;
}
@@ -18311,29 +25041,34 @@ async function updateIndex({
assertParameter("filepath", filepath);
const fs = new FileSystem(_fs);
if (remove3) {
- return await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) {
- let fileStats2;
- if (!force) {
- fileStats2 = await fs.lstat(join(dir, filepath));
- if (fileStats2) {
- if (fileStats2.isDirectory()) {
- throw new InvalidFilepathError("directory");
+ return await GitIndexManager.acquire(
+ { fs, gitdir, cache },
+ async function(index2) {
+ let fileStats2;
+ if (!force) {
+ fileStats2 = await fs.lstat(join(dir, filepath));
+ if (fileStats2) {
+ if (fileStats2.isDirectory()) {
+ throw new InvalidFilepathError("directory");
+ }
+ return;
}
- return;
+ }
+ if (index2.has({ filepath })) {
+ index2.delete({
+ filepath
+ });
}
}
- if (index2.has({ filepath })) {
- index2.delete({
- filepath
- });
- }
- });
+ );
}
let fileStats;
if (!oid) {
fileStats = await fs.lstat(join(dir, filepath));
if (!fileStats) {
- throw new NotFoundError(`file at "${filepath}" on disk and "remove" not set`);
+ throw new NotFoundError(
+ `file at "${filepath}" on disk and "remove" not set`
+ );
}
if (fileStats.isDirectory()) {
throw new InvalidFilepathError("directory");
@@ -18341,11 +25076,13 @@ async function updateIndex({
}
return await GitIndexManager.acquire({ fs, gitdir, cache }, async function(index2) {
if (!add2 && !index2.has({ filepath })) {
- throw new NotFoundError(`file at "${filepath}" in index and "add" not set`);
+ throw new NotFoundError(
+ `file at "${filepath}" in index and "add" not set`
+ );
}
let stats = {
- ctime: new Date(0),
- mtime: new Date(0),
+ ctime: /* @__PURE__ */ new Date(0),
+ mtime: /* @__PURE__ */ new Date(0),
dev: 0,
ino: 0,
mode,
@@ -18482,7 +25219,7 @@ async function writeObject({
object = GitTree.from(object).toObject();
break;
case "blob":
- object = Buffer2.from(object, encoding);
+ object = Buffer.from(object, encoding);
break;
case "tag":
object = GitAnnotatedTag.from(object).toObject();
@@ -18599,6 +25336,7 @@ var index = {
TREE,
WORKDIR,
add,
+ abortMerge,
addNote,
addRemote,
annotatedTag,
@@ -18665,1632 +25403,27 @@ var index = {
var isomorphic_git_default = index;
// src/main.ts
-var import_obsidian23 = __toModule(require("obsidian"));
+var import_obsidian30 = require("obsidian");
-// src/promiseQueue.ts
+// src/lineAuthor/lineAuthorIntegration.ts
init_polyfill_buffer();
-var PromiseQueue = class {
- constructor() {
- this.tasks = [];
- }
- addTask(task) {
- this.tasks.push(task);
- if (this.tasks.length === 1) {
- this.handleTask();
- }
- }
- async handleTask() {
- if (this.tasks.length > 0) {
- this.tasks[0]().finally(() => {
- this.tasks.shift();
- this.handleTask();
- });
- }
- }
-};
+var import_obsidian12 = require("obsidian");
-// src/settings.ts
+// src/gitManager/simpleGit.ts
init_polyfill_buffer();
-var import_obsidian7 = __toModule(require("obsidian"));
+var import_child_process2 = require("child_process");
+var import_debug2 = __toESM(require_browser());
+var import_obsidian4 = require("obsidian");
+var path = __toESM(require("path"));
+var import_path = require("path");
-// src/isomorphicGit.ts
+// node_modules/.pnpm/github.com+Vinzent03+git-js@6b9a2d899bc8256e38a1d6f0b8a88116ba2bf56a_supports-color@9.4.0_rdkutdaeyye3o67thmklazfzta/node_modules/simple-git/dist/esm/index.js
init_polyfill_buffer();
-
-// node_modules/diff/lib/index.mjs
-init_polyfill_buffer();
-function Diff() {
-}
-Diff.prototype = {
- diff: function diff(oldString, newString) {
- var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
- var callback = options.callback;
- if (typeof options === "function") {
- callback = options;
- options = {};
- }
- this.options = options;
- var self3 = this;
- function done(value) {
- if (callback) {
- setTimeout(function() {
- callback(void 0, value);
- }, 0);
- return true;
- } else {
- return value;
- }
- }
- oldString = this.castInput(oldString);
- newString = this.castInput(newString);
- oldString = this.removeEmpty(this.tokenize(oldString));
- newString = this.removeEmpty(this.tokenize(newString));
- var newLen = newString.length, oldLen = oldString.length;
- var editLength = 1;
- var maxEditLength = newLen + oldLen;
- if (options.maxEditLength) {
- maxEditLength = Math.min(maxEditLength, options.maxEditLength);
- }
- var bestPath = [{
- newPos: -1,
- components: []
- }];
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
- if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
- return done([{
- value: this.join(newString),
- count: newString.length
- }]);
- }
- function execEditLength() {
- for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
- var basePath = void 0;
- var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
- if (addPath) {
- bestPath[diagonalPath - 1] = void 0;
- }
- var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
- if (!canAdd && !canRemove) {
- bestPath[diagonalPath] = void 0;
- continue;
- }
- if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
- basePath = clonePath(removePath);
- self3.pushComponent(basePath.components, void 0, true);
- } else {
- basePath = addPath;
- basePath.newPos++;
- self3.pushComponent(basePath.components, true, void 0);
- }
- _oldPos = self3.extractCommon(basePath, newString, oldString, diagonalPath);
- if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
- return done(buildValues(self3, basePath.components, newString, oldString, self3.useLongestToken));
- } else {
- bestPath[diagonalPath] = basePath;
- }
- }
- editLength++;
- }
- if (callback) {
- (function exec() {
- setTimeout(function() {
- if (editLength > maxEditLength) {
- return callback();
- }
- if (!execEditLength()) {
- exec();
- }
- }, 0);
- })();
- } else {
- while (editLength <= maxEditLength) {
- var ret = execEditLength();
- if (ret) {
- return ret;
- }
- }
- }
- },
- pushComponent: function pushComponent(components, added, removed) {
- var last2 = components[components.length - 1];
- if (last2 && last2.added === added && last2.removed === removed) {
- components[components.length - 1] = {
- count: last2.count + 1,
- added,
- removed
- };
- } else {
- components.push({
- count: 1,
- added,
- removed
- });
- }
- },
- extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
- newPos++;
- oldPos++;
- commonCount++;
- }
- if (commonCount) {
- basePath.components.push({
- count: commonCount
- });
- }
- basePath.newPos = newPos;
- return oldPos;
- },
- equals: function equals(left, right) {
- if (this.options.comparator) {
- return this.options.comparator(left, right);
- } else {
- return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
- }
- },
- removeEmpty: function removeEmpty(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
- }
- }
- return ret;
- },
- castInput: function castInput(value) {
- return value;
- },
- tokenize: function tokenize(value) {
- return value.split("");
- },
- join: function join2(chars) {
- return chars.join("");
- }
-};
-function buildValues(diff2, components, newString, oldString, useLongestToken) {
- var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
- for (; componentPos < componentLen; componentPos++) {
- var component = components[componentPos];
- if (!component.removed) {
- if (!component.added && useLongestToken) {
- var value = newString.slice(newPos, newPos + component.count);
- value = value.map(function(value2, i) {
- var oldValue = oldString[oldPos + i];
- return oldValue.length > value2.length ? oldValue : value2;
- });
- component.value = diff2.join(value);
- } else {
- component.value = diff2.join(newString.slice(newPos, newPos + component.count));
- }
- newPos += component.count;
- if (!component.added) {
- oldPos += component.count;
- }
- } else {
- component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
- oldPos += component.count;
- if (componentPos && components[componentPos - 1].added) {
- var tmp = components[componentPos - 1];
- components[componentPos - 1] = components[componentPos];
- components[componentPos] = tmp;
- }
- }
- }
- var lastComponent = components[componentLen - 1];
- if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff2.equals("", lastComponent.value)) {
- components[componentLen - 2].value += lastComponent.value;
- components.pop();
- }
- return components;
-}
-function clonePath(path2) {
- return {
- newPos: path2.newPos,
- components: path2.components.slice(0)
- };
-}
-var characterDiff = new Diff();
-function diffChars(oldStr, newStr, options) {
- return characterDiff.diff(oldStr, newStr, options);
-}
-var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
-var reWhitespace = /\S/;
-var wordDiff = new Diff();
-wordDiff.equals = function(left, right) {
- if (this.options.ignoreCase) {
- left = left.toLowerCase();
- right = right.toLowerCase();
- }
- return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
-};
-wordDiff.tokenize = function(value) {
- var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
- for (var i = 0; i < tokens.length - 1; i++) {
- if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
- tokens[i] += tokens[i + 2];
- tokens.splice(i + 1, 2);
- i--;
- }
- }
- return tokens;
-};
-function diffWordsWithSpace(oldStr, newStr, options) {
- return wordDiff.diff(oldStr, newStr, options);
-}
-var lineDiff = new Diff();
-lineDiff.tokenize = function(value) {
- var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
- linesAndNewlines.pop();
- }
- for (var i = 0; i < linesAndNewlines.length; i++) {
- var line = linesAndNewlines[i];
- if (i % 2 && !this.options.newlineIsToken) {
- retLines[retLines.length - 1] += line;
- } else {
- if (this.options.ignoreWhitespace) {
- line = line.trim();
- }
- retLines.push(line);
- }
- }
- return retLines;
-};
-function diffLines(oldStr, newStr, callback) {
- return lineDiff.diff(oldStr, newStr, callback);
-}
-var sentenceDiff = new Diff();
-sentenceDiff.tokenize = function(value) {
- return value.split(/(\S.+?[.!?])(?=\s+|$)/);
-};
-var cssDiff = new Diff();
-cssDiff.tokenize = function(value) {
- return value.split(/([{}:;,]|\s+)/);
-};
-function _typeof(obj) {
- "@babel/helpers - typeof";
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function(obj2) {
- return typeof obj2;
- };
- } else {
- _typeof = function(obj2) {
- return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
- };
- }
- return _typeof(obj);
-}
-function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
-}
-function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr))
- return _arrayLikeToArray(arr);
-}
-function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter))
- return Array.from(iter);
-}
-function _unsupportedIterableToArray(o, minLen) {
- if (!o)
- return;
- if (typeof o === "string")
- return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor)
- n = o.constructor.name;
- if (n === "Map" || n === "Set")
- return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
- return _arrayLikeToArray(o, minLen);
-}
-function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length)
- len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++)
- arr2[i] = arr[i];
- return arr2;
-}
-function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
-}
-var objectPrototypeToString = Object.prototype.toString;
-var jsonDiff = new Diff();
-jsonDiff.useLongestToken = true;
-jsonDiff.tokenize = lineDiff.tokenize;
-jsonDiff.castInput = function(value) {
- var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
- return typeof v === "undefined" ? undefinedReplacement : v;
- } : _this$options$stringi;
- return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
-};
-jsonDiff.equals = function(left, right) {
- return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
-};
-function canonicalize(obj, stack, replacementStack, replacer, key2) {
- stack = stack || [];
- replacementStack = replacementStack || [];
- if (replacer) {
- obj = replacer(key2, obj);
- }
- var i;
- for (i = 0; i < stack.length; i += 1) {
- if (stack[i] === obj) {
- return replacementStack[i];
- }
- }
- var canonicalizedObj;
- if (objectPrototypeToString.call(obj) === "[object Array]") {
- stack.push(obj);
- canonicalizedObj = new Array(obj.length);
- replacementStack.push(canonicalizedObj);
- for (i = 0; i < obj.length; i += 1) {
- canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key2);
- }
- stack.pop();
- replacementStack.pop();
- return canonicalizedObj;
- }
- if (obj && obj.toJSON) {
- obj = obj.toJSON();
- }
- if (_typeof(obj) === "object" && obj !== null) {
- stack.push(obj);
- canonicalizedObj = {};
- replacementStack.push(canonicalizedObj);
- var sortedKeys = [], _key;
- for (_key in obj) {
- if (obj.hasOwnProperty(_key)) {
- sortedKeys.push(_key);
- }
- }
- sortedKeys.sort();
- for (i = 0; i < sortedKeys.length; i += 1) {
- _key = sortedKeys[i];
- canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
- }
- stack.pop();
- replacementStack.pop();
- } else {
- canonicalizedObj = obj;
- }
- return canonicalizedObj;
-}
-var arrayDiff = new Diff();
-arrayDiff.tokenize = function(value) {
- return value.slice();
-};
-arrayDiff.join = arrayDiff.removeEmpty = function(value) {
- return value;
-};
-function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- if (!options) {
- options = {};
- }
- if (typeof options.context === "undefined") {
- options.context = 4;
- }
- var diff2 = diffLines(oldStr, newStr, options);
- if (!diff2) {
- return;
- }
- diff2.push({
- value: "",
- lines: []
- });
- function contextLines(lines) {
- return lines.map(function(entry) {
- return " " + entry;
- });
- }
- var hunks = [];
- var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
- var _loop = function _loop2(i2) {
- var current = diff2[i2], lines = current.lines || current.value.replace(/\n$/, "").split("\n");
- current.lines = lines;
- if (current.added || current.removed) {
- var _curRange;
- if (!oldRangeStart) {
- var prev = diff2[i2 - 1];
- oldRangeStart = oldLine;
- newRangeStart = newLine;
- if (prev) {
- curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
- oldRangeStart -= curRange.length;
- newRangeStart -= curRange.length;
- }
- }
- (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) {
- return (current.added ? "+" : "-") + entry;
- })));
- if (current.added) {
- newLine += lines.length;
- } else {
- oldLine += lines.length;
- }
- } else {
- if (oldRangeStart) {
- if (lines.length <= options.context * 2 && i2 < diff2.length - 2) {
- var _curRange2;
- (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
- } else {
- var _curRange3;
- var contextSize = Math.min(lines.length, options.context);
- (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
- var hunk = {
- oldStart: oldRangeStart,
- oldLines: oldLine - oldRangeStart + contextSize,
- newStart: newRangeStart,
- newLines: newLine - newRangeStart + contextSize,
- lines: curRange
- };
- if (i2 >= diff2.length - 2 && lines.length <= options.context) {
- var oldEOFNewline = /\n$/.test(oldStr);
- var newEOFNewline = /\n$/.test(newStr);
- var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
- if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
- curRange.splice(hunk.oldLines, 0, "\\ No newline at end of file");
- }
- if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
- curRange.push("\\ No newline at end of file");
- }
- }
- hunks.push(hunk);
- oldRangeStart = 0;
- newRangeStart = 0;
- curRange = [];
- }
- }
- oldLine += lines.length;
- newLine += lines.length;
- }
- };
- for (var i = 0; i < diff2.length; i++) {
- _loop(i);
- }
- return {
- oldFileName,
- newFileName,
- oldHeader,
- newHeader,
- hunks
- };
-}
-function formatPatch(diff2) {
- var ret = [];
- if (diff2.oldFileName == diff2.newFileName) {
- ret.push("Index: " + diff2.oldFileName);
- }
- ret.push("===================================================================");
- ret.push("--- " + diff2.oldFileName + (typeof diff2.oldHeader === "undefined" ? "" : " " + diff2.oldHeader));
- ret.push("+++ " + diff2.newFileName + (typeof diff2.newHeader === "undefined" ? "" : " " + diff2.newHeader));
- for (var i = 0; i < diff2.hunks.length; i++) {
- var hunk = diff2.hunks[i];
- if (hunk.oldLines === 0) {
- hunk.oldStart -= 1;
- }
- if (hunk.newLines === 0) {
- hunk.newStart -= 1;
- }
- ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
- ret.push.apply(ret, hunk.lines);
- }
- return ret.join("\n") + "\n";
-}
-function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
-}
-function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
- return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
-}
-
-// src/isomorphicGit.ts
-var import_obsidian5 = __toModule(require("obsidian"));
-
-// src/gitManager.ts
-init_polyfill_buffer();
-var GitManager = class {
- constructor(plugin) {
- this.plugin = plugin;
- this.app = plugin.app;
- }
- getVaultPath(path2) {
- if (this.plugin.settings.basePath) {
- return this.plugin.settings.basePath + "/" + path2;
- } else {
- return path2;
- }
- }
- getPath(path2, relativeToVault) {
- return relativeToVault && this.plugin.settings.basePath.length > 0 ? path2.substring(this.plugin.settings.basePath.length + 1) : path2;
- }
- _getTreeStructure(children2, beginLength = 0) {
- const list = [];
- children2 = [...children2];
- while (children2.length > 0) {
- const first2 = children2.first();
- const restPath = first2.path.substring(beginLength);
- if (restPath.contains("/")) {
- const title = restPath.substring(0, restPath.indexOf("/"));
- const childrenWithSameTitle = children2.filter((item) => {
- return item.path.substring(beginLength).startsWith(title + "/");
- });
- childrenWithSameTitle.forEach((item) => children2.remove(item));
- const path2 = first2.path.substring(0, restPath.indexOf("/") + beginLength);
- list.push({
- title,
- path: path2,
- vaultPath: this.getVaultPath(path2),
- children: this._getTreeStructure(childrenWithSameTitle, (beginLength > 0 ? beginLength + title.length : title.length) + 1)
- });
- } else {
- list.push({
- title: restPath,
- statusResult: first2,
- path: first2.path,
- vaultPath: this.getVaultPath(first2.path)
- });
- children2.remove(first2);
- }
- }
- return list;
- }
- simplify(tree) {
- var _a2, _b, _c, _d;
- for (const node of tree) {
- while (true) {
- const singleChild = ((_a2 = node.children) == null ? void 0 : _a2.length) == 1;
- const singleChildIsDir = ((_c = (_b = node.children) == null ? void 0 : _b.first()) == null ? void 0 : _c.statusResult) == void 0;
- if (!(node.children != void 0 && singleChild && singleChildIsDir))
- break;
- const child = node.children.first();
- node.title += "/" + child.title;
- node.statusResult = child.statusResult;
- node.path = child.path;
- node.vaultPath = child.vaultPath;
- node.children = child.children;
- }
- if (node.children != void 0) {
- this.simplify(node.children);
- }
- (_d = node.children) == null ? void 0 : _d.sort((a, b) => {
- const dirCompare = (b.statusResult == void 0 ? 1 : 0) - (a.statusResult == void 0 ? 1 : 0);
- if (dirCompare != 0) {
- return dirCompare;
- } else {
- return a.title.localeCompare(b.title);
- }
- });
- }
- return tree.sort((a, b) => {
- const dirCompare = (b.statusResult == void 0 ? 1 : 0) - (a.statusResult == void 0 ? 1 : 0);
- if (dirCompare != 0) {
- return dirCompare;
- } else {
- return a.title.localeCompare(b.title);
- }
- });
- }
- getTreeStructure(children2) {
- const tree = this._getTreeStructure(children2);
- const res = this.simplify(tree);
- return res;
- }
- async formatCommitMessage(template) {
- let status2;
- if (template.includes("{{numFiles}}")) {
- status2 = await this.status();
- const numFiles = status2.staged.length;
- template = template.replace("{{numFiles}}", String(numFiles));
- }
- if (template.includes("{{hostname}}")) {
- const hostname = this.plugin.localStorage.getHostname() || "";
- template = template.replace("{{hostname}}", hostname);
- }
- if (template.includes("{{files}}")) {
- status2 = status2 != null ? status2 : await this.status();
- const changeset = {};
- status2.staged.forEach((value) => {
- if (value.index in changeset) {
- changeset[value.index].push(value.path);
- } else {
- changeset[value.index] = [value.path];
- }
- });
- const chunks = [];
- for (const [action, files2] of Object.entries(changeset)) {
- chunks.push(action + " " + files2.join(" "));
- }
- const files = chunks.join(", ");
- template = template.replace("{{files}}", files);
- }
- const moment = window.moment;
- template = template.replace("{{date}}", moment().format(this.plugin.settings.commitDateFormat));
- if (this.plugin.settings.listChangedFilesInMessageBody) {
- template = template + "\n\nAffected files:\n" + (status2 != null ? status2 : await this.status()).staged.map((e) => e.path).join("\n");
- }
- return template;
- }
-};
-
-// src/myAdapter.ts
-init_polyfill_buffer();
-var import_obsidian2 = __toModule(require("obsidian"));
-var MyAdapter = class {
- constructor(vault, plugin) {
- this.plugin = plugin;
- this.promises = {};
- this.adapter = vault.adapter;
- this.vault = vault;
- this.promises.readFile = this.readFile.bind(this);
- this.promises.writeFile = this.writeFile.bind(this);
- this.promises.readdir = this.readdir.bind(this);
- this.promises.mkdir = this.mkdir.bind(this);
- this.promises.rmdir = this.rmdir.bind(this);
- this.promises.stat = this.stat.bind(this);
- this.promises.unlink = this.unlink.bind(this);
- this.promises.lstat = this.lstat.bind(this);
- this.promises.readlink = this.readlink.bind(this);
- this.promises.symlink = this.symlink.bind(this);
- }
- async readFile(path2, opts) {
- var _a2;
- this.maybeLog("Read: " + path2 + JSON.stringify(opts));
- if (opts == "utf8" || opts.encoding == "utf8") {
- const file = this.vault.getAbstractFileByPath(path2);
- if (file instanceof import_obsidian2.TFile) {
- this.maybeLog("Reuse");
- return this.vault.read(file);
- } else {
- return this.adapter.read(path2);
- }
- } else {
- if (path2.endsWith(".git/index")) {
- return (_a2 = this.index) != null ? _a2 : this.adapter.readBinary(path2);
- }
- const file = this.vault.getAbstractFileByPath(path2);
- if (file instanceof import_obsidian2.TFile) {
- this.maybeLog("Reuse");
- return this.vault.readBinary(file);
- } else {
- return this.adapter.readBinary(path2);
- }
- }
- }
- async writeFile(path2, data) {
- this.maybeLog("Write: " + path2);
- if (typeof data === "string") {
- const file = this.vault.getAbstractFileByPath(path2);
- if (file instanceof import_obsidian2.TFile) {
- return this.vault.modify(file, data);
- } else {
- return this.adapter.write(path2, data);
- }
- } else {
- if (path2.endsWith(".git/index")) {
- this.index = data;
- this.indexmtime = Date.now();
- } else {
- const file = this.vault.getAbstractFileByPath(path2);
- if (file instanceof import_obsidian2.TFile) {
- return this.vault.modifyBinary(file, data);
- } else {
- return this.adapter.writeBinary(path2, data);
- }
- }
- }
- }
- async readdir(path2) {
- if (path2 === ".")
- path2 = "/";
- const res = await this.adapter.list(path2);
- const all = [...res.files, ...res.folders];
- let formattedAll;
- if (path2 !== "/") {
- formattedAll = all.map((e) => (0, import_obsidian2.normalizePath)(e.substring(path2.length)));
- } else {
- formattedAll = all;
- }
- return formattedAll;
- }
- async mkdir(path2) {
- return this.adapter.mkdir(path2);
- }
- async rmdir(path2, opts) {
- var _a2, _b;
- return this.adapter.rmdir(path2, (_b = (_a2 = opts == null ? void 0 : opts.options) == null ? void 0 : _a2.recursive) != null ? _b : false);
- }
- async stat(path2) {
- if (path2.endsWith(".git/index")) {
- if (this.index !== void 0 && this.indexctime != void 0 && this.indexmtime != void 0) {
- return {
- isFile: () => true,
- isDirectory: () => false,
- isSymbolicLink: () => false,
- size: this.index.length,
- type: "file",
- ctimeMs: this.indexctime,
- mtimeMs: this.indexmtime
- };
- } else {
- const stat = await this.adapter.stat(path2);
- if (stat == void 0) {
- throw { "code": "ENOENT" };
- }
- this.indexctime = stat.ctime;
- this.indexmtime = stat.mtime;
- return {
- ctimeMs: stat.ctime,
- mtimeMs: stat.mtime,
- size: stat.size,
- type: "file",
- isFile: () => true,
- isDirectory: () => false,
- isSymbolicLink: () => false
- };
- }
- }
- if (path2 === ".")
- path2 = "/";
- const file = this.vault.getAbstractFileByPath(path2);
- this.maybeLog("Stat: " + path2);
- if (file instanceof import_obsidian2.TFile) {
- this.maybeLog("Reuse stat");
- return {
- ctimeMs: file.stat.ctime,
- mtimeMs: file.stat.mtime,
- size: file.stat.size,
- type: "file",
- isFile: () => true,
- isDirectory: () => false,
- isSymbolicLink: () => false
- };
- } else {
- const stat = await this.adapter.stat(path2);
- if (stat) {
- return {
- ctimeMs: stat.ctime,
- mtimeMs: stat.mtime,
- size: stat.size,
- type: stat.type === "folder" ? "directory" : stat.type,
- isFile: () => stat.type === "file",
- isDirectory: () => stat.type === "folder",
- isSymbolicLink: () => false
- };
- } else {
- throw { "code": "ENOENT" };
- }
- }
- }
- async unlink(path2) {
- return this.adapter.remove(path2);
- }
- async lstat(path2) {
- return this.stat(path2);
- }
- async readlink(path2) {
- throw new Error(`readlink of (${path2}) is not implemented.`);
- }
- async symlink(path2) {
- throw new Error(`symlink of (${path2}) is not implemented.`);
- }
- async saveAndClear() {
- if (this.index !== void 0) {
- await this.adapter.writeBinary(this.plugin.gitManager.getVaultPath(".git/index"), this.index, {
- ctime: this.indexctime,
- mtime: this.indexmtime
- });
- }
- this.index = void 0;
- this.indexctime = void 0;
- this.indexmtime = void 0;
- }
- maybeLog(text2) {
- }
-};
-
-// src/types.ts
-init_polyfill_buffer();
-var PluginState;
-(function(PluginState2) {
- PluginState2[PluginState2["idle"] = 0] = "idle";
- PluginState2[PluginState2["status"] = 1] = "status";
- PluginState2[PluginState2["pull"] = 2] = "pull";
- PluginState2[PluginState2["add"] = 3] = "add";
- PluginState2[PluginState2["commit"] = 4] = "commit";
- PluginState2[PluginState2["push"] = 5] = "push";
- PluginState2[PluginState2["conflicted"] = 6] = "conflicted";
-})(PluginState || (PluginState = {}));
-var FileType;
-(function(FileType2) {
- FileType2[FileType2["staged"] = 0] = "staged";
- FileType2[FileType2["changed"] = 1] = "changed";
- FileType2[FileType2["pulled"] = 2] = "pulled";
-})(FileType || (FileType = {}));
-
-// src/ui/modals/generalModal.ts
-init_polyfill_buffer();
-var import_obsidian3 = __toModule(require("obsidian"));
-var generalModalConfigDefaults = {
- options: [],
- placeholder: "",
- allowEmpty: false,
- onlySelection: false,
- initialValue: void 0
-};
-var GeneralModal = class extends import_obsidian3.SuggestModal {
- constructor(config) {
- super(app);
- this.config = { ...generalModalConfigDefaults, ...config };
- this.setPlaceholder(this.config.placeholder);
- }
- open() {
- super.open();
- if (this.config.initialValue != void 0) {
- this.inputEl.value = this.config.initialValue;
- this.inputEl.dispatchEvent(new Event("input"));
- }
- return new Promise((resolve) => {
- this.resolve = resolve;
- });
- }
- selectSuggestion(value, evt) {
- if (this.resolve) {
- let res;
- if (this.config.allowEmpty && value === " ")
- res = "";
- else if (value === "...")
- res = void 0;
- else
- res = value;
- this.resolve(res);
- }
- super.selectSuggestion(value, evt);
- }
- onClose() {
- if (this.resolve)
- this.resolve(void 0);
- }
- getSuggestions(query) {
- if (this.config.onlySelection) {
- return this.config.options;
- } else if (this.config.allowEmpty) {
- return [query.length > 0 ? query : " ", ...this.config.options];
- } else {
- return [query.length > 0 ? query : "...", ...this.config.options];
- }
- }
- renderSuggestion(value, el) {
- el.setText(value);
- }
- onChooseSuggestion(item, evt) {
- }
-};
-
-// src/utils.ts
-init_polyfill_buffer();
-var import_obsidian4 = __toModule(require("obsidian"));
-var worthWalking2 = (filepath, root) => {
- if (filepath === "." || root == null || root.length === 0 || root === ".") {
- return true;
- }
- if (root.length >= filepath.length) {
- return root.startsWith(filepath);
- } else {
- return filepath.startsWith(root);
- }
-};
-function getNewLeaf(event) {
- let leaf;
- if (event) {
- if (event.button === 0 || event.button === 1) {
- const type = import_obsidian4.Keymap.isModEvent(event);
- leaf = app.workspace.getLeaf(type);
- }
- } else {
- leaf = app.workspace.getLeaf(false);
- }
- return leaf;
-}
-
-// src/isomorphicGit.ts
-var IsomorphicGit = class extends GitManager {
- constructor(plugin) {
- super(plugin);
- this.FILE = 0;
- this.HEAD = 1;
- this.WORKDIR = 2;
- this.STAGE = 3;
- this.status_mapping = {
- "000": " ",
- "003": "AD",
- "020": "??",
- "022": "A ",
- "023": "AM",
- "100": "D ",
- "101": " D",
- "103": "MD",
- "110": "DA",
- "111": " ",
- "120": "DA",
- "121": " M",
- "122": "M ",
- "123": "MM"
- };
- this.noticeLength = 999999;
- this.fs = new MyAdapter(this.app.vault, this.plugin);
- }
- getRepo() {
- return {
- fs: this.fs,
- dir: this.plugin.settings.basePath,
- onAuth: () => {
- var _a2;
- return {
- username: this.plugin.settings.username,
- password: (_a2 = this.plugin.localStorage.getPassword()) != null ? _a2 : void 0
- };
- },
- onAuthFailure: async () => {
- new import_obsidian5.Notice("Authentication failed. Please try with different credentials");
- const username = await new GeneralModal({ placeholder: "Specify your username" }).open();
- if (username) {
- const password = await new GeneralModal({ placeholder: "Specify your password/personal access token" }).open();
- if (password) {
- this.plugin.settings.username = username;
- await this.plugin.saveSettings();
- this.plugin.localStorage.setPassword(password);
- return {
- username,
- password
- };
- }
- }
- return { cancel: true };
- },
- http: {
- async request({
- url,
- method,
- headers,
- body
- }) {
- if (body) {
- body = await collect2(body);
- body = body.buffer;
- }
- const res = await (0, import_obsidian5.requestUrl)({ url, method, headers, body, throw: false });
- return {
- url,
- method,
- headers: res.headers,
- body: [new Uint8Array(res.arrayBuffer)],
- statusCode: res.status,
- statusMessage: res.status.toString()
- };
- }
- }
- };
- }
- async wrapFS(call) {
- try {
- const res = await call;
- await this.fs.saveAndClear();
- return res;
- } catch (error) {
- await this.fs.saveAndClear();
- throw error;
- }
- }
- async status() {
- const notice = new import_obsidian5.Notice("Getting status...", this.noticeLength);
- try {
- this.plugin.setState(PluginState.status);
- const status2 = (await this.wrapFS(isomorphic_git_default.statusMatrix({ ...this.getRepo() }))).map((row) => this.getFileStatusResult(row));
- const changed = status2.filter((fileStatus) => fileStatus.working_dir !== " ");
- const staged = status2.filter((fileStatus) => fileStatus.index !== " " && fileStatus.index !== "U");
- const conflicted = [];
- notice.hide();
- return { changed, staged, conflicted };
- } catch (error) {
- notice.hide();
- this.plugin.displayError(error);
- throw error;
- }
- }
- async commitAll({ message, status: status2, unstagedFiles }) {
- try {
- await this.stageAll({ status: status2, unstagedFiles });
- return this.commit(message);
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async commit(message) {
- try {
- this.plugin.setState(PluginState.commit);
- const formatMessage = await this.formatCommitMessage(message);
- const hadConflict = this.plugin.localStorage.getConflict() === "true";
- let parent = void 0;
- if (hadConflict) {
- const branchInfo = await this.branchInfo();
- parent = [branchInfo.current, branchInfo.tracking];
- }
- await this.wrapFS(isomorphic_git_default.commit({
- ...this.getRepo(),
- message: formatMessage,
- parent
- }));
- this.plugin.localStorage.setConflict("false");
- return;
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async stage(filepath, relativeToVault) {
- const gitPath = this.getPath(filepath, relativeToVault);
- let vaultPath;
- if (relativeToVault) {
- vaultPath = filepath;
- } else {
- vaultPath = this.getVaultPath(filepath);
- }
- try {
- this.plugin.setState(PluginState.add);
- if (await this.app.vault.adapter.exists(vaultPath)) {
- await this.wrapFS(isomorphic_git_default.add({ ...this.getRepo(), filepath: gitPath }));
- } else {
- await this.wrapFS(isomorphic_git_default.remove({ ...this.getRepo(), filepath: gitPath }));
- }
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async stageAll({ dir, status: status2, unstagedFiles }) {
- try {
- if (status2) {
- await Promise.all(status2.changed.map((file) => file.working_dir !== "D" ? this.wrapFS(isomorphic_git_default.add({ ...this.getRepo(), filepath: file.path })) : isomorphic_git_default.remove({ ...this.getRepo(), filepath: file.path })));
- } else {
- const filesToStage = unstagedFiles != null ? unstagedFiles : await this.getUnstagedFiles(dir != null ? dir : ".");
- await Promise.all(filesToStage.map(({ filepath, deleted }) => deleted ? isomorphic_git_default.remove({ ...this.getRepo(), filepath }) : this.wrapFS(isomorphic_git_default.add({ ...this.getRepo(), filepath }))));
- }
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async unstage(filepath, relativeToVault) {
- try {
- this.plugin.setState(PluginState.add);
- filepath = this.getPath(filepath, relativeToVault);
- await this.wrapFS(isomorphic_git_default.resetIndex({ ...this.getRepo(), filepath }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async unstageAll({ dir, status: status2 }) {
- try {
- let staged;
- if (status2) {
- staged = status2.staged.map((file) => file.path);
- } else {
- const res = await this.getStagedFiles(dir != null ? dir : ".");
- staged = res.map(({ filepath }) => filepath);
- }
- await this.wrapFS(Promise.all(staged.map((file) => isomorphic_git_default.resetIndex({ ...this.getRepo(), filepath: file }))));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async discard(filepath) {
- try {
- this.plugin.setState(PluginState.add);
- await this.wrapFS(isomorphic_git_default.checkout({ ...this.getRepo(), filepaths: [filepath], force: true }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async discardAll({ dir, status: status2 }) {
- let files = [];
- if (status2) {
- if (dir != void 0) {
- files = status2.changed.filter((file) => file.path.startsWith(dir)).map((file) => file.path);
- } else {
- files = status2.changed.map((file) => file.path);
- }
- } else {
- files = (await this.getUnstagedFiles(dir)).map(({ filepath }) => filepath);
- }
- try {
- await this.wrapFS(isomorphic_git_default.checkout({ ...this.getRepo(), filepaths: files, force: true }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- getProgressText(action, event) {
- let out = `${action} progress:`;
- if (event.phase) {
- out = `${out} ${event.phase}:`;
- }
- if (event.loaded) {
- out = `${out} ${event.loaded}`;
- if (event.total) {
- out = `${out} of ${event.total}`;
- }
- }
- return out;
- }
- resolveRef(ref) {
- return this.wrapFS(isomorphic_git_default.resolveRef({ ...this.getRepo(), ref }));
- }
- async pull() {
- const progressNotice = new import_obsidian5.Notice("Initializing pull", this.noticeLength);
- try {
- this.plugin.setState(PluginState.pull);
- const localCommit = await this.resolveRef("HEAD");
- await this.fetch();
- const branchInfo = await this.branchInfo();
- await this.wrapFS(isomorphic_git_default.merge({
- ...this.getRepo(),
- ours: branchInfo.current,
- theirs: branchInfo.tracking,
- abortOnConflict: false
- }));
- await this.wrapFS(isomorphic_git_default.checkout({
- ...this.getRepo(),
- ref: branchInfo.current,
- onProgress: (progress) => {
- progressNotice.noticeEl.innerText = this.getProgressText("Checkout", progress);
- },
- remote: branchInfo.remote
- }));
- progressNotice.hide();
- const upstreamCommit = await this.resolveRef("HEAD");
- this.plugin.lastUpdate = Date.now();
- const changedFiles = await this.getFileChangesCount(localCommit, upstreamCommit);
- new import_obsidian5.Notice("Finished pull");
- return changedFiles.map((file) => ({
- path: file.path,
- working_dir: "P",
- index: "P",
- vault_path: this.getVaultPath(file.path)
- }));
- } catch (error) {
- progressNotice.hide();
- if (error instanceof Errors.MergeConflictError) {
- this.plugin.handleConflict(error.data.filepaths.map((file) => this.getVaultPath(file)));
- }
- this.plugin.displayError(error);
- throw error;
- }
- }
- async push() {
- if (!await this.canPush()) {
- return 0;
- }
- const progressNotice = new import_obsidian5.Notice("Initializing push", this.noticeLength);
- try {
- this.plugin.setState(PluginState.status);
- const status2 = await this.branchInfo();
- const trackingBranch = status2.tracking;
- const currentBranch2 = status2.current;
- const numChangedFiles = (await this.getFileChangesCount(currentBranch2, trackingBranch)).length;
- this.plugin.setState(PluginState.push);
- await this.wrapFS(isomorphic_git_default.push({
- ...this.getRepo(),
- onProgress: (progress) => {
- progressNotice.noticeEl.innerText = this.getProgressText("Pushing", progress);
- }
- }));
- progressNotice.hide();
- return numChangedFiles;
- } catch (error) {
- progressNotice.hide();
- this.plugin.displayError(error);
- throw error;
- }
- }
- async canPush() {
- const status2 = await this.branchInfo();
- const trackingBranch = status2.tracking;
- const currentBranch2 = status2.current;
- const current = await this.resolveRef(currentBranch2);
- const tracking = await this.resolveRef(trackingBranch);
- return current != tracking;
- }
- async checkRequirements() {
- const headExists = await this.plugin.app.vault.adapter.exists(`${this.getRepo().dir}/.git/HEAD`);
- return headExists ? "valid" : "missing-repo";
- }
- async branchInfo() {
- var _a2, _b;
- try {
- const current = await isomorphic_git_default.currentBranch(this.getRepo()) || "";
- const branches = await isomorphic_git_default.listBranches(this.getRepo());
- const remote = (_a2 = await this.getConfig(`branch.${current}.remote`)) != null ? _a2 : "origin";
- const trackingBranch = (_b = await this.getConfig(`branch.${current}.merge`)) == null ? void 0 : _b.split("refs/heads")[1];
- const tracking = trackingBranch ? remote + trackingBranch : void 0;
- return {
- current,
- tracking,
- branches,
- remote
- };
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async getCurrentRemote() {
- var _a2;
- const current = await isomorphic_git_default.currentBranch(this.getRepo()) || "";
- const remote = (_a2 = await this.getConfig(`branch.${current}.remote`)) != null ? _a2 : "origin";
- return remote;
- }
- async checkout(branch2) {
- try {
- return this.wrapFS(isomorphic_git_default.checkout({
- ...this.getRepo(),
- ref: branch2
- }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async createBranch(branch2) {
- try {
- await this.wrapFS(isomorphic_git_default.branch({ ...this.getRepo(), ref: branch2, checkout: true }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async deleteBranch(branch2) {
- try {
- await this.wrapFS(isomorphic_git_default.deleteBranch({ ...this.getRepo(), ref: branch2 }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async branchIsMerged(branch2) {
- return true;
- }
- async init() {
- try {
- await this.wrapFS(isomorphic_git_default.init(this.getRepo()));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async clone(url, dir) {
- const progressNotice = new import_obsidian5.Notice("Initializing clone", this.noticeLength);
- try {
- await this.wrapFS(isomorphic_git_default.clone({
- ...this.getRepo(),
- dir,
- url,
- onProgress: (progress) => {
- progressNotice.noticeEl.innerText = this.getProgressText("Cloning", progress);
- }
- }));
- progressNotice.hide();
- } catch (error) {
- progressNotice.hide();
- this.plugin.displayError(error);
- throw error;
- }
- }
- async setConfig(path2, value) {
- try {
- return this.wrapFS(isomorphic_git_default.setConfig({
- ...this.getRepo(),
- path: path2,
- value
- }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async getConfig(path2) {
- try {
- return this.wrapFS(isomorphic_git_default.getConfig({
- ...this.getRepo(),
- path: path2
- }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async fetch(remote) {
- const progressNotice = new import_obsidian5.Notice("Initializing fetch", this.noticeLength);
- try {
- const args = {
- ...this.getRepo(),
- onProgress: (progress) => {
- progressNotice.noticeEl.innerText = this.getProgressText("Fetching", progress);
- },
- remote: remote != null ? remote : await this.getCurrentRemote()
- };
- await this.wrapFS(isomorphic_git_default.fetch(args));
- progressNotice.hide();
- } catch (error) {
- this.plugin.displayError(error);
- progressNotice.hide();
- throw error;
- }
- }
- async setRemote(name, url) {
- try {
- await this.wrapFS(isomorphic_git_default.addRemote({ ...this.getRepo(), remote: name, url }));
- } catch (error) {
- this.plugin.displayError(error);
- throw error;
- }
- }
- async getRemoteBranches(remote) {
- let remoteBranches = [];
- remoteBranches.push(...await this.wrapFS(isomorphic_git_default.listBranches({ ...this.getRepo(), remote })));
- remoteBranches.remove("HEAD");
- remoteBranches = remoteBranches.map((e) => `${remote}/${e}`);
- return remoteBranches;
- }
- async getRemotes() {
- return (await this.wrapFS(isomorphic_git_default.listRemotes({ ...this.getRepo() }))).map((remoteUrl) => remoteUrl.remote);
- }
- async removeRemote(remoteName) {
- await this.wrapFS(isomorphic_git_default.deleteRemote({ ...this.getRepo(), remote: remoteName }));
- }
- async getRemoteUrl(remote) {
- return (await this.wrapFS(isomorphic_git_default.listRemotes({ ...this.getRepo() }))).filter((item) => item.remote == remote)[0].url;
- }
- updateBasePath(basePath) {
- this.getRepo().dir = basePath;
- }
- async updateUpstreamBranch(remoteBranch) {
- const [remote, branch2] = remoteBranch.split("/");
- const branchInfo = await this.branchInfo();
- await this.setConfig(`branch.${branchInfo.current}.merge`, `refs/heads/${branch2}`);
- await this.setConfig(`branch.${branch2}.remote`, remote);
- }
- updateGitPath(gitPath) {
- return;
- }
- async getFileChangesCount(commitHash1, commitHash2) {
- return this.walkDifference({ walkers: [isomorphic_git_default.TREE({ ref: commitHash1 }), isomorphic_git_default.TREE({ ref: commitHash2 })] });
- }
- async walkDifference({ walkers, dir: base }) {
- const res = await this.wrapFS(isomorphic_git_default.walk({
- ...this.getRepo(),
- trees: walkers,
- map: async function(filepath, [A, B]) {
- if (!worthWalking2(filepath, base)) {
- return null;
- }
- if (await (A == null ? void 0 : A.type()) === "tree" || await (B == null ? void 0 : B.type()) === "tree") {
- return;
- }
- const Aoid = await (A == null ? void 0 : A.oid());
- const Boid = await (B == null ? void 0 : B.oid());
- let type = "equal";
- if (Aoid !== Boid) {
- type = "modify";
- }
- if (Aoid === void 0) {
- type = "add";
- }
- if (Boid === void 0) {
- type = "remove";
- }
- if (Aoid === void 0 && Boid === void 0) {
- console.log("Something weird happened:");
- console.log(A);
- console.log(B);
- }
- if (type === "equal") {
- return;
- }
- return {
- path: filepath,
- type
- };
- }
- }));
- return res;
- }
- async getStagedFiles(dir = ".") {
- const res = await this.walkDifference({
- walkers: [isomorphic_git_default.TREE({ ref: "HEAD" }), isomorphic_git_default.STAGE()],
- dir
- });
- return res.map((file) => {
- return {
- vault_path: this.getVaultPath(file.path),
- filepath: file.path
- };
- });
- }
- async getUnstagedFiles(base = ".") {
- const notice = new import_obsidian5.Notice("Getting status...", this.noticeLength);
- try {
- const repo = this.getRepo();
- const res = await this.wrapFS(isomorphic_git_default.walk({
- ...repo,
- trees: [isomorphic_git_default.WORKDIR(), isomorphic_git_default.STAGE()],
- map: async function(filepath, [workdir, stage]) {
- if (!stage && workdir) {
- const isIgnored2 = await isomorphic_git_default.isIgnored({
- ...repo,
- filepath
- });
- if (isIgnored2) {
- return null;
- }
- }
- if (!worthWalking2(filepath, base)) {
- return null;
- }
- const [workdirType, stageType] = await Promise.all([
- workdir && workdir.type(),
- stage && stage.type()
- ]);
- const isBlob = [workdirType, stageType].includes("blob");
- if ((workdirType === "tree" || workdirType === "special") && !isBlob)
- return;
- if (stageType === "commit")
- return null;
- if ((stageType === "tree" || stageType === "special") && !isBlob)
- return;
- const stageOid = stageType === "blob" ? await stage.oid() : void 0;
- let workdirOid;
- if (workdirType === "blob" && stageType !== "blob") {
- workdirOid = "42";
- } else if (workdirType === "blob") {
- workdirOid = await workdir.oid();
- }
- if (!workdirOid) {
- return {
- filepath,
- deleted: true
- };
- }
- if (workdirOid !== stageOid) {
- return {
- filepath,
- deleted: false
- };
- }
- return null;
- }
- }));
- notice.hide();
- return res;
- } catch (error) {
- notice.hide();
- this.plugin.displayError(error);
- throw error;
- }
- }
- async getDiffString(filePath, stagedChanges = false) {
- const map = async (file, [A]) => {
- if (filePath == file) {
- const oid = await A.oid();
- const contents = await isomorphic_git_default.readBlob({ ...this.getRepo(), oid });
- return contents.blob;
- }
- };
- const stagedBlob = (await isomorphic_git_default.walk({
- ...this.getRepo(),
- trees: [isomorphic_git_default.STAGE()],
- map
- })).first();
- const stagedContent = new TextDecoder().decode(stagedBlob);
- if (stagedChanges) {
- const headBlob = await readBlob({ ...this.getRepo(), filepath: filePath, oid: await this.resolveRef("HEAD") });
- const headContent = new TextDecoder().decode(headBlob.blob);
- const diff2 = createPatch(filePath, headContent, stagedContent);
- return diff2;
- } else {
- let workdirContent;
- if (await app.vault.adapter.exists(filePath)) {
- workdirContent = await app.vault.adapter.read(filePath);
- } else {
- workdirContent = "";
- }
- const diff2 = createPatch(filePath, stagedContent, workdirContent);
- return diff2;
- }
- }
- getFileStatusResult(row) {
- const status2 = this.status_mapping[`${row[this.HEAD]}${row[this.WORKDIR]}${row[this.STAGE]}`];
- return {
- index: status2[0] == "?" ? "U" : status2[0],
- working_dir: status2[1] == "?" ? "U" : status2[1],
- path: row[this.FILE],
- vault_path: this.getVaultPath(row[this.FILE])
- };
- }
-};
-function fromValue2(value) {
- let queue = [value];
- return {
- next() {
- return Promise.resolve({ done: queue.length === 0, value: queue.pop() });
- },
- return() {
- queue = [];
- return {};
- },
- [Symbol.asyncIterator]() {
- return this;
- }
- };
-}
-function getIterator2(iterable) {
- if (iterable[Symbol.asyncIterator]) {
- return iterable[Symbol.asyncIterator]();
- }
- if (iterable[Symbol.iterator]) {
- return iterable[Symbol.iterator]();
- }
- if (iterable.next) {
- return iterable;
- }
- return fromValue2(iterable);
-}
-async function forAwait2(iterable, cb) {
- const iter = getIterator2(iterable);
- while (true) {
- const { value, done } = await iter.next();
- if (value)
- await cb(value);
- if (done)
- break;
- }
- if (iter.return)
- iter.return();
-}
-async function collect2(iterable) {
- let size = 0;
- const buffers = [];
- await forAwait2(iterable, (value) => {
- buffers.push(value);
- size += value.byteLength;
- });
- const result = new Uint8Array(size);
- let nextIndex = 0;
- for (const buffer2 of buffers) {
- result.set(buffer2, nextIndex);
- nextIndex += buffer2.byteLength;
- }
- return result;
-}
-
-// src/simpleGit.ts
-init_polyfill_buffer();
-var import_child_process2 = __toModule(require("child_process"));
-var import_obsidian6 = __toModule(require("obsidian"));
-var path = __toModule(require("path"));
-var import_path = __toModule(require("path"));
-
-// node_modules/simple-git/dist/esm/index.js
-init_polyfill_buffer();
-var import_file_exists = __toModule(require_dist());
-var import_debug = __toModule(require_browser());
-var import_child_process = __toModule(require("child_process"));
-var import_promise_deferred = __toModule(require_dist2());
-var import_promise_deferred2 = __toModule(require_dist2());
+var import_file_exists = __toESM(require_dist(), 1);
+var import_debug = __toESM(require_browser(), 1);
+var import_child_process = require("child_process");
+var import_promise_deferred = __toESM(require_dist2(), 1);
+var import_promise_deferred2 = __toESM(require_dist2(), 1);
var __defProp2 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -20299,20 +25432,20 @@ var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
-var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp2(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
+var __defNormalProp2 = (obj, key2, value) => key2 in obj ? __defProp2(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp2.call(b, prop))
- __defNormalProp(a, prop, b[prop]);
+ __defNormalProp2(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
- __defNormalProp(a, prop, b[prop]);
+ __defNormalProp2(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
-var __markAsModule2 = (target) => __defProp2(target, "__esModule", { value: true });
+var __markAsModule = (target) => __defProp2(target, "__esModule", { value: true });
var __esm2 = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
};
@@ -20323,7 +25456,7 @@ var __export2 = (target, all) => {
for (var name in all)
__defProp2(target, name, { get: all[name], enumerable: true });
};
-var __reExport2 = (target, module2, copyDefault, desc) => {
+var __reExport = (target, module2, copyDefault, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key2 of __getOwnPropNames2(module2))
if (!__hasOwnProp2.call(target, key2) && (copyDefault || key2 !== "default"))
@@ -20331,9 +25464,9 @@ var __reExport2 = (target, module2, copyDefault, desc) => {
}
return target;
};
-var __toCommonJS = /* @__PURE__ */ ((cache) => {
+var __toCommonJS2 = /* @__PURE__ */ ((cache) => {
return (module2, temp) => {
- return cache && cache.get(module2) || (temp = __reExport2(__markAsModule2({}), module2, 1), cache && cache.set(module2, temp), temp);
+ return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
};
})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
var __async = (__this, __arguments, generator) => {
@@ -20478,7 +25611,7 @@ function prefixedArray(input, prefix) {
return output;
}
function bufferToString(input) {
- return (Array.isArray(input) ? Buffer2.concat(input) : input).toString("utf-8");
+ return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8");
}
function pick(source, properties) {
return Object.assign({}, ...properties.map((property) => property in source ? { [property]: source[property] } : {}));
@@ -20635,19 +25768,19 @@ var init_simple_git_options = __esm2({
};
}
});
-function appendTaskOptions(options, commands = []) {
+function appendTaskOptions(options, commands2 = []) {
if (!filterPlainObject(options)) {
- return commands;
+ return commands2;
}
- return Object.keys(options).reduce((commands2, key2) => {
+ return Object.keys(options).reduce((commands22, key2) => {
const value = options[key2];
if (filterPrimitives(value, ["boolean"])) {
- commands2.push(key2 + "=" + value);
+ commands22.push(key2 + "=" + value);
} else {
- commands2.push(key2);
+ commands22.push(key2);
}
- return commands2;
- }, commands);
+ return commands22;
+ }, commands2);
}
function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) {
const command = [];
@@ -20772,18 +25905,18 @@ function checkIsRepoTask(action) {
case "root":
return checkIsRepoRootTask();
}
- const commands = ["rev-parse", "--is-inside-work-tree"];
+ const commands2 = ["rev-parse", "--is-inside-work-tree"];
return {
- commands,
+ commands: commands2,
format: "utf-8",
onError,
parser
};
}
function checkIsRepoRootTask() {
- const commands = ["rev-parse", "--git-dir"];
+ const commands2 = ["rev-parse", "--git-dir"];
return {
- commands,
+ commands: commands2,
format: "utf-8",
onError,
parser(path2) {
@@ -20792,9 +25925,9 @@ function checkIsRepoRootTask() {
};
}
function checkIsBareRepoTask() {
- const commands = ["rev-parse", "--is-bare-repository"];
+ const commands2 = ["rev-parse", "--is-bare-repository"];
return {
- commands,
+ commands: commands2,
format: "utf-8",
onError,
parser
@@ -20817,7 +25950,7 @@ var init_check_is_repo = __esm2({
})(CheckRepoActions || {});
onError = ({ exitCode }, error, done, fail) => {
if (exitCode === 128 && isNotRepoMessage(error)) {
- return done(Buffer2.from("false"));
+ return done(Buffer.from("false"));
}
fail(error);
};
@@ -20882,18 +26015,18 @@ function configurationErrorTask(error) {
}
};
}
-function straightThroughStringTask(commands, trimmed2 = false) {
+function straightThroughStringTask(commands2, trimmed2 = false) {
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(text2) {
return trimmed2 ? String(text2).trim() : text2;
}
};
}
-function straightThroughBufferTask(commands) {
+function straightThroughBufferTask(commands2) {
return {
- commands,
+ commands: commands2,
format: "buffer",
parser(buffer2) {
return buffer2;
@@ -20938,9 +26071,9 @@ function cleanWithOptionsTask(mode, customArgs) {
return cleanTask(cleanMode, options);
}
function cleanTask(mode, customArgs) {
- const commands = ["clean", `-${mode}`, ...customArgs];
+ const commands2 = ["clean", `-${mode}`, ...customArgs];
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(text2) {
return cleanSummaryParser(mode === "n", text2);
@@ -21101,13 +26234,13 @@ function asConfigScope(scope, fallback) {
return fallback;
}
function addConfigTask(key2, value, append22, scope) {
- const commands = ["config", `--${scope}`];
+ const commands2 = ["config", `--${scope}`];
if (append22) {
- commands.push("--add");
+ commands2.push("--add");
}
- commands.push(key2, value);
+ commands2.push(key2, value);
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(text2) {
return text2;
@@ -21115,12 +26248,12 @@ function addConfigTask(key2, value, append22, scope) {
};
}
function getConfigTask(key2, scope) {
- const commands = ["config", "--null", "--show-origin", "--get-all", key2];
+ const commands2 = ["config", "--null", "--show-origin", "--get-all", key2];
if (scope) {
- commands.splice(1, 0, `--${scope}`);
+ commands2.splice(1, 0, `--${scope}`);
}
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(text2) {
return configGetParser(text2, key2);
@@ -21128,12 +26261,12 @@ function getConfigTask(key2, scope) {
};
}
function listConfigTask(scope) {
- const commands = ["config", "--list", "--show-origin", "--null"];
+ const commands2 = ["config", "--list", "--show-origin", "--null"];
if (scope) {
- commands.push(`--${scope}`);
+ commands2.push(`--${scope}`);
}
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(text2) {
return configListParser(text2);
@@ -21143,7 +26276,11 @@ function listConfigTask(scope) {
function config_default() {
return {
addConfig(key2, value, ...rest) {
- return this._runTask(addConfigTask(key2, value, rest[0] === true, asConfigScope(rest[1], "local")), trailingFunctionArgument(arguments));
+ return this._runTask(addConfigTask(key2, value, rest[0] === true, asConfigScope(
+ rest[1],
+ "local"
+ /* local */
+ )), trailingFunctionArgument(arguments));
},
getConfig(key2, scope) {
return this._runTask(getConfigTask(key2, asConfigScope(scope, void 0)), trailingFunctionArgument(arguments));
@@ -21200,9 +26337,9 @@ function grep_default() {
if (typeof searchTerm === "string") {
searchTerm = grepQueryBuilder().param(searchTerm);
}
- const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm];
+ const commands2 = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm];
return this._runTask({
- commands,
+ commands: commands2,
format: "utf-8",
parser(stdOut) {
return parseGrep(stdOut);
@@ -21248,12 +26385,12 @@ __export2(reset_exports, {
resetTask: () => resetTask
});
function resetTask(mode, customArgs) {
- const commands = ["reset"];
+ const commands2 = ["reset"];
if (isValidResetMode(mode)) {
- commands.push(`--${mode}`);
+ commands2.push(`--${mode}`);
}
- commands.push(...customArgs);
- return straightThroughStringTask(commands);
+ commands2.push(...customArgs);
+ return straightThroughStringTask(commands2);
}
function getResetMode(mode) {
if (isValidResetMode(mode)) {
@@ -21323,9 +26460,9 @@ function createLogger(label, verbose, initialStep, infoDebugger = createLog()) {
}
function step(phase) {
const stepPrefix = phase && `[${phase}]` || "";
- const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
- const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2);
- return Object.assign(debugDebugger ? debug2 : info, {
+ const debug22 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
+ const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug22);
+ return Object.assign(debugDebugger ? debug22 : info, {
label,
sibling,
info,
@@ -21338,7 +26475,7 @@ var init_git_logger = __esm2({
init_utils();
import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-");
import_debug.default.formatters.B = (value) => {
- if (Buffer2.isBuffer(value)) {
+ if (Buffer.isBuffer(value)) {
return value.toString("utf8");
}
return objectToString(value);
@@ -21410,16 +26547,16 @@ var init_tasks_pending_queue = __esm2({
TasksPendingQueue.counter = 0;
}
});
-function pluginContext(task, commands) {
+function pluginContext(task, commands2) {
return {
method: first(task.commands) || "",
- commands
+ commands: commands2
};
}
function onErrorReceived(target, logger) {
return (err) => {
logger(`[ERROR] child process exception %o`, err);
- target.push(Buffer2.from(String(err.stack), "ascii"));
+ target.push(Buffer.from(String(err.stack), "ascii"));
};
}
function onDataReceived(target, name, logger, output) {
@@ -21515,7 +26652,7 @@ var init_git_executor_chain = __esm2({
return task.onError(result, error, (newStdOut) => {
logger.info(`custom error handler treated as success`);
logger(`custom error returned a %s`, objectToString(newStdOut));
- done(new GitOutputStreams(Array.isArray(newStdOut) ? Buffer2.concat(newStdOut) : newStdOut, Buffer2.concat(stdErr)));
+ done(new GitOutputStreams(Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, Buffer.concat(stdErr)));
}, fail);
}
if (error) {
@@ -21523,7 +26660,7 @@ var init_git_executor_chain = __esm2({
return fail(error);
}
logger.info(`retrieving task output complete`);
- done(new GitOutputStreams(Buffer2.concat(stdOut), Buffer2.concat(stdErr)));
+ done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));
});
}
gitResponse(task, command, args, outputHandler, logger) {
@@ -21657,12 +26794,12 @@ var init_task_callback = __esm2({
init_utils();
}
});
-function changeWorkingDirectoryTask(directory, root) {
- return adhocExecTask((instance6) => {
+function changeWorkingDirectoryTask(directory, root2) {
+ return adhocExecTask((instance10) => {
if (!folderExists(directory)) {
throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`);
}
- return (root || instance6).cwd = directory;
+ return (root2 || instance10).cwd = directory;
});
}
var init_change_working_directory = __esm2({
@@ -21671,6 +26808,32 @@ var init_change_working_directory = __esm2({
init_task();
}
});
+function checkoutTask(args) {
+ const commands2 = ["checkout", ...args];
+ if (commands2[1] === "-b" && commands2.includes("-B")) {
+ commands2[1] = remove2(commands2, "-B");
+ }
+ return straightThroughStringTask(commands2);
+}
+function checkout_default() {
+ return {
+ checkout() {
+ return this._runTask(checkoutTask(getTrailingOptions(arguments, 1)), trailingFunctionArgument(arguments));
+ },
+ checkoutBranch(branchName, startPoint) {
+ return this._runTask(checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments));
+ },
+ checkoutLocalBranch(branchName) {
+ return this._runTask(checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments));
+ }
+ };
+}
+var init_checkout = __esm2({
+ "src/lib/tasks/checkout.ts"() {
+ init_utils();
+ init_task();
+ }
+});
function parseCommitResult(stdOut) {
const result = {
author: null,
@@ -21690,10 +26853,10 @@ var init_parse_commit = __esm2({
"src/lib/parsers/parse-commit.ts"() {
init_utils();
parsers = [
- new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch2, root, commit2]) => {
+ new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch2, root2, commit2]) => {
result.branch = branch2;
result.commit = commit2;
- result.root = !!root;
+ result.root = !!root2;
}),
new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => {
const parts = author.split("<");
@@ -21723,13 +26886,8 @@ var init_parse_commit = __esm2({
];
}
});
-var commit_exports = {};
-__export2(commit_exports, {
- commitTask: () => commitTask,
- default: () => commit_default
-});
function commitTask(message, files, customArgs) {
- const commands = [
+ const commands2 = [
"-c",
"core.abbrev=40",
"commit",
@@ -21738,7 +26896,7 @@ function commitTask(message, files, customArgs) {
...customArgs
];
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser: parseCommitResult
};
@@ -21763,11 +26921,11 @@ var init_commit = __esm2({
}
});
function hashObjectTask(filePath, write) {
- const commands = ["hash-object", filePath];
+ const commands2 = ["hash-object", filePath];
if (write) {
- commands.push("-w");
+ commands2.push("-w");
}
- return straightThroughStringTask(commands, true);
+ return straightThroughStringTask(commands2, true);
}
var init_hash_object = __esm2({
"src/lib/tasks/hash-object.ts"() {
@@ -21815,15 +26973,15 @@ function hasBareCommand(command) {
return command.includes(bareCommand);
}
function initTask(bare = false, path2, customArgs) {
- const commands = ["init", ...customArgs];
- if (bare && !hasBareCommand(commands)) {
- commands.splice(1, 0, bareCommand);
+ const commands2 = ["init", ...customArgs];
+ if (bare && !hasBareCommand(commands2)) {
+ commands2.splice(1, 0, bareCommand);
}
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(text2) {
- return parseInit(commands.includes("--bare"), path2, text2);
+ return parseInit(commands2.includes("--bare"), path2, text2);
}
};
}
@@ -21943,11 +27101,12 @@ var init_parse_diff_summary = __esm2({
})
];
nameStatusParser = [
- new LineParser(/([ACDMRTUXB])\s*(.+)$/, (result, [_status, file]) => {
+ new LineParser(/([ACDMRTUXB])([0-9][0-9][0-9])?\t(.[^\t]+)\t?(.*)?$/, (result, [status2, _similarity, from, to]) => {
result.changed++;
result.files.push({
- file,
+ file: to != null ? to : from,
changes: 0,
+ status: status2,
insertions: 0,
deletions: 0,
binary: false
@@ -21955,11 +27114,26 @@ var init_parse_diff_summary = __esm2({
})
];
diffSummaryParsers = {
- [""]: statParser,
- ["--stat"]: statParser,
- ["--numstat"]: numStatParser,
- ["--name-status"]: nameStatusParser,
- ["--name-only"]: nameOnlyParser
+ [
+ ""
+ /* NONE */
+ ]: statParser,
+ [
+ "--stat"
+ /* STAT */
+ ]: statParser,
+ [
+ "--numstat"
+ /* NUM_STAT */
+ ]: numStatParser,
+ [
+ "--name-status"
+ /* NAME_STATUS */
+ ]: nameStatusParser,
+ [
+ "--name-only"
+ /* NAME_ONLY */
+ ]: nameOnlyParser
};
}
});
@@ -22009,14 +27183,14 @@ __export2(diff_exports, {
});
function diffSummaryTask(customArgs) {
let logFormat = logFormatFromCommand(customArgs);
- const commands = ["diff"];
+ const commands2 = ["diff"];
if (logFormat === "") {
logFormat = "--stat";
- commands.push("--stat=4096");
+ commands2.push("--stat=4096");
}
- commands.push(...customArgs);
- return validateLogFormatConfig(commands) || {
- commands,
+ commands2.push(...customArgs);
+ return validateLogFormatConfig(commands2) || {
+ commands: commands2,
format: "utf-8",
parser: getDiffParser(logFormat)
};
@@ -22436,7 +27610,7 @@ var init_parse_push = __esm2({
local
});
}),
- new LineParser(/^[*-=]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => {
+ new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => {
result.pushed.push(pushResultPushedItem(local, remote, type));
}),
new LineParser(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, (result, [local, remote, remoteName]) => {
@@ -22479,18 +27653,18 @@ function pushTagsTask(ref = {}, customArgs) {
return pushTask(ref, customArgs);
}
function pushTask(ref = {}, customArgs) {
- const commands = ["push", ...customArgs];
+ const commands2 = ["push", ...customArgs];
if (ref.branch) {
- commands.splice(1, 0, ref.branch);
+ commands2.splice(1, 0, ref.branch);
}
if (ref.remote) {
- commands.splice(1, 0, ref.remote);
+ commands2.splice(1, 0, ref.remote);
}
- remove2(commands, "-v");
- append(commands, "--verbose");
- append(commands, "--porcelain");
+ remove2(commands2, "-v");
+ append(commands2, "--verbose");
+ append(commands2, "--porcelain");
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser: parsePushResult
};
@@ -22603,9 +27777,25 @@ var init_StatusSummary = __esm2({
append(_result.ignored = _result.ignored || [], _file);
}),
parser2("?", "?", (result, file) => append(result.not_added, file)),
- ...conflicts("A", "A", "U"),
- ...conflicts("D", "D", "U"),
- ...conflicts("U", "A", "D", "U"),
+ ...conflicts(
+ "A",
+ "A",
+ "U"
+ /* UNMERGED */
+ ),
+ ...conflicts(
+ "D",
+ "D",
+ "U"
+ /* UNMERGED */
+ ),
+ ...conflicts(
+ "U",
+ "A",
+ "D",
+ "U"
+ /* UNMERGED */
+ ),
[
"##",
(result, line) => {
@@ -22647,7 +27837,7 @@ var init_StatusSummary = __esm2({
}
});
function statusTask(customArgs) {
- const commands = [
+ const commands2 = [
"status",
"--porcelain",
"-b",
@@ -22657,7 +27847,7 @@ function statusTask(customArgs) {
];
return {
format: "utf-8",
- commands,
+ commands: commands2,
parser(text2) {
return parseStatusSummary(text2);
}
@@ -22697,7 +27887,7 @@ function version_default() {
parser: versionParser,
onError(result, error, done, fail) {
if (result.exitCode === -2) {
- return done(Buffer2.from(NOT_INSTALLED));
+ return done(Buffer.from(NOT_INSTALLED));
}
fail(error);
}
@@ -22736,6 +27926,7 @@ var init_simple_git_api = __esm2({
"src/lib/simple-git-api.ts"() {
init_task_callback();
init_change_working_directory();
+ init_checkout();
init_commit();
init_config();
init_grep();
@@ -22810,7 +28001,7 @@ var init_simple_git_api = __esm2({
return this._runTask(statusTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments));
}
};
- Object.assign(SimpleGitApi.prototype, commit_default(), config_default(), grep_default(), log_default(), version_default());
+ Object.assign(SimpleGitApi.prototype, checkout_default(), commit_default(), config_default(), grep_default(), log_default(), version_default());
}
});
var scheduler_exports = {};
@@ -22993,22 +28184,22 @@ __export2(branch_exports, {
deleteBranchTask: () => deleteBranchTask,
deleteBranchesTask: () => deleteBranchesTask
});
-function containsDeleteBranchCommand(commands) {
+function containsDeleteBranchCommand(commands2) {
const deleteCommands = ["-d", "-D", "--delete"];
- return commands.some((command) => deleteCommands.includes(command));
+ return commands2.some((command) => deleteCommands.includes(command));
}
function branchTask(customArgs) {
const isDelete = containsDeleteBranchCommand(customArgs);
- const commands = ["branch", ...customArgs];
- if (commands.length === 1) {
- commands.push("-a");
+ const commands2 = ["branch", ...customArgs];
+ if (commands2.length === 1) {
+ commands2.push("-a");
}
- if (!commands.includes("-v")) {
- commands.splice(1, 0, "-v");
+ if (!commands2.includes("-v")) {
+ commands2.splice(1, 0, "-v");
}
return {
format: "utf-8",
- commands,
+ commands: commands2,
parser(stdOut, stdErr) {
if (isDelete) {
return parseBranchDeletions(stdOut, stdErr).all[0];
@@ -23097,14 +28288,14 @@ function disallowedCommand(command) {
return /^--upload-pack(=|$)/.test(command);
}
function cloneTask(repo, directory, customArgs) {
- const commands = ["clone", ...customArgs];
- filterString(repo) && commands.push(repo);
- filterString(directory) && commands.push(directory);
- const banned = commands.find(disallowedCommand);
+ const commands2 = ["clone", ...customArgs];
+ filterString(repo) && commands2.push(repo);
+ filterString(directory) && commands2.push(directory);
+ const banned = commands2.find(disallowedCommand);
if (banned) {
return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
}
- return straightThroughStringTask(commands);
+ return straightThroughStringTask(commands2);
}
function cloneMirrorTask(repo, directory, customArgs) {
append(customArgs, "--mirror");
@@ -23171,16 +28362,16 @@ function disallowedCommand2(command) {
return /^--upload-pack(=|$)/.test(command);
}
function fetchTask(remote, branch2, customArgs) {
- const commands = ["fetch", ...customArgs];
+ const commands2 = ["fetch", ...customArgs];
if (remote && branch2) {
- commands.push(remote, branch2);
+ commands2.push(remote, branch2);
}
- const banned = commands.find(disallowedCommand2);
+ const banned = commands2.find(disallowedCommand2);
if (banned) {
return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);
}
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser: parseFetchResult
};
@@ -23227,12 +28418,12 @@ __export2(pull_exports, {
pullTask: () => pullTask
});
function pullTask(remote, branch2, customArgs) {
- const commands = ["pull", ...customArgs];
+ const commands2 = ["pull", ...customArgs];
if (remote && branch2) {
- commands.splice(1, 0, remote, branch2);
+ commands2.splice(1, 0, remote, branch2);
}
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser(stdOut, stdErr) {
return parsePullResult(stdOut, stdErr);
@@ -23293,29 +28484,29 @@ function addRemoteTask(remoteName, remoteRepo, customArgs = []) {
return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]);
}
function getRemotesTask(verbose) {
- const commands = ["remote"];
+ const commands2 = ["remote"];
if (verbose) {
- commands.push("-v");
+ commands2.push("-v");
}
return {
- commands,
+ commands: commands2,
format: "utf-8",
parser: verbose ? parseGetRemotesVerbose : parseGetRemotes
};
}
function listRemotesTask(customArgs = []) {
- const commands = [...customArgs];
- if (commands[0] !== "ls-remote") {
- commands.unshift("ls-remote");
+ const commands2 = [...customArgs];
+ if (commands2[0] !== "ls-remote") {
+ commands2.unshift("ls-remote");
}
- return straightThroughStringTask(commands);
+ return straightThroughStringTask(commands2);
}
function remoteTask(customArgs = []) {
- const commands = [...customArgs];
- if (commands[0] !== "remote") {
- commands.unshift("remote");
+ const commands2 = [...customArgs];
+ if (commands2[0] !== "remote") {
+ commands2.unshift("remote");
}
- return straightThroughStringTask(commands);
+ return straightThroughStringTask(commands2);
}
function removeRemoteTask(remoteName) {
return straightThroughStringTask(["remote", "remove", remoteName]);
@@ -23332,10 +28523,10 @@ __export2(stash_list_exports, {
});
function stashListTask(opt = {}, customArgs) {
const options = parseLogOptions(opt);
- const commands = ["stash", "list", ...options.commands, ...customArgs];
- const parser3 = createListLogSummaryParser(options.splitter, options.fields, logFormatFromCommand(commands));
- return validateLogFormatConfig(commands) || {
- commands,
+ const commands2 = ["stash", "list", ...options.commands, ...customArgs];
+ const parser3 = createListLogSummaryParser(options.splitter, options.fields, logFormatFromCommand(commands2));
+ return validateLogFormatConfig(commands2) || {
+ commands: commands2,
format: "utf-8",
parser: parser3
};
@@ -23362,11 +28553,11 @@ function initSubModuleTask(customArgs) {
return subModuleTask(["init", ...customArgs]);
}
function subModuleTask(customArgs) {
- const commands = [...customArgs];
- if (commands[0] !== "submodule") {
- commands.unshift("submodule");
+ const commands2 = [...customArgs];
+ if (commands2[0] !== "submodule") {
+ commands2.unshift("submodule");
}
- return straightThroughStringTask(commands);
+ return straightThroughStringTask(commands2);
}
function updateSubModuleTask(customArgs) {
return subModuleTask(["update", ...customArgs]);
@@ -23469,11 +28660,11 @@ var init_tag = __esm2({
}
});
var require_git = __commonJS2({
- "src/git.js"(exports, module2) {
- var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS(git_executor_exports));
- var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS(simple_git_api_exports));
- var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS(scheduler_exports));
- var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS(task_exports));
+ "src/git.js"(exports2, module2) {
+ var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS2(git_executor_exports));
+ var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS2(simple_git_api_exports));
+ var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS2(scheduler_exports));
+ var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS2(task_exports));
var {
asArray: asArray2,
filterArray: filterArray2,
@@ -23484,41 +28675,40 @@ var require_git = __commonJS2({
getTrailingOptions: getTrailingOptions2,
trailingFunctionArgument: trailingFunctionArgument2,
trailingOptionsArgument: trailingOptionsArgument2
- } = (init_utils(), __toCommonJS(utils_exports));
- var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS(apply_patch_exports));
+ } = (init_utils(), __toCommonJS2(utils_exports));
+ var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS2(apply_patch_exports));
var {
branchTask: branchTask2,
branchLocalTask: branchLocalTask2,
deleteBranchesTask: deleteBranchesTask2,
deleteBranchTask: deleteBranchTask2
- } = (init_branch(), __toCommonJS(branch_exports));
- var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS(check_ignore_exports));
- var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS(check_is_repo_exports));
- var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS(clone_exports));
- var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS(clean_exports));
- var { commitTask: commitTask2 } = (init_commit(), __toCommonJS(commit_exports));
- var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS(diff_exports));
- var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS(fetch_exports));
- var { moveTask: moveTask2 } = (init_move(), __toCommonJS(move_exports));
- var { pullTask: pullTask2 } = (init_pull(), __toCommonJS(pull_exports));
- var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS(push_exports));
+ } = (init_branch(), __toCommonJS2(branch_exports));
+ var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS2(check_ignore_exports));
+ var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS2(check_is_repo_exports));
+ var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS2(clone_exports));
+ var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS2(clean_exports));
+ var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS2(diff_exports));
+ var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS2(fetch_exports));
+ var { moveTask: moveTask2 } = (init_move(), __toCommonJS2(move_exports));
+ var { pullTask: pullTask2 } = (init_pull(), __toCommonJS2(pull_exports));
+ var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS2(push_exports));
var {
addRemoteTask: addRemoteTask2,
getRemotesTask: getRemotesTask2,
listRemotesTask: listRemotesTask2,
remoteTask: remoteTask2,
removeRemoteTask: removeRemoteTask2
- } = (init_remote(), __toCommonJS(remote_exports));
- var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS(reset_exports));
- var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS(stash_list_exports));
+ } = (init_remote(), __toCommonJS2(remote_exports));
+ var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS2(reset_exports));
+ var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS2(stash_list_exports));
var {
addSubModuleTask: addSubModuleTask2,
initSubModuleTask: initSubModuleTask2,
subModuleTask: subModuleTask2,
updateSubModuleTask: updateSubModuleTask2
- } = (init_sub_module(), __toCommonJS(sub_module_exports));
- var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS(tag_exports));
- var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS(task_exports));
+ } = (init_sub_module(), __toCommonJS2(sub_module_exports));
+ var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS2(tag_exports));
+ var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS2(task_exports));
function Git2(options, plugins) {
this._executor = new GitExecutor2(options.binary, options.baseDir, new Scheduler2(options.maxConcurrentProcesses), plugins);
this._trimmed = options.trimmed;
@@ -23595,16 +28785,6 @@ var require_git = __commonJS2({
Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) {
return this._runTask(addAnnotatedTagTask2(tagName, tagMessage), trailingFunctionArgument2(arguments));
};
- Git2.prototype.checkout = function() {
- const commands = ["checkout", ...getTrailingOptions2(arguments, true)];
- return this._runTask(straightThroughStringTask2(commands), trailingFunctionArgument2(arguments));
- };
- Git2.prototype.checkoutBranch = function(branchName, startPoint, then) {
- return this.checkout(["-b", branchName, startPoint], trailingFunctionArgument2(arguments));
- };
- Git2.prototype.checkoutLocalBranch = function(branchName, then) {
- return this.checkout(["-b", branchName], trailingFunctionArgument2(arguments));
- };
Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) {
return this._runTask(deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments));
};
@@ -23617,9 +28797,9 @@ var require_git = __commonJS2({
Git2.prototype.branchLocal = function(then) {
return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments));
};
- Git2.prototype.raw = function(commands) {
- const createRestCommands = !Array.isArray(commands);
- const command = [].slice.call(createRestCommands ? arguments : commands, 0);
+ Git2.prototype.raw = function(commands2) {
+ const createRestCommands = !Array.isArray(commands2);
+ const command = [].slice.call(createRestCommands ? arguments : commands2, 0);
for (let i = 0; i < command.length && createRestCommands; i++) {
if (!filterPrimitives2(command[i])) {
command.splice(i, command.length - i);
@@ -23711,8 +28891,8 @@ var require_git = __commonJS2({
return this._runTask(task, trailingFunctionArgument2(arguments));
};
Git2.prototype.revparse = function() {
- const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)];
- return this._runTask(straightThroughStringTask2(commands, true), trailingFunctionArgument2(arguments));
+ const commands2 = ["rev-parse", ...getTrailingOptions2(arguments, true)];
+ return this._runTask(straightThroughStringTask2(commands2, true), trailingFunctionArgument2(arguments));
};
Git2.prototype.show = function(options, then) {
return this._runTask(straightThroughStringTask2(["show", ...getTrailingOptions2(arguments, 1)]), trailingFunctionArgument2(arguments));
@@ -23795,6 +28975,45 @@ function abortPlugin(signal) {
};
return [onSpawnBefore, onSpawnAfter];
}
+function isConfigSwitch(arg) {
+ return typeof arg === "string" && arg.trim().toLowerCase() === "-c";
+}
+function preventProtocolOverride(arg, next) {
+ if (!isConfigSwitch(arg)) {
+ return;
+ }
+ if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) {
+ return;
+ }
+ throw new GitPluginError(void 0, "unsafe", "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol");
+}
+function preventUploadPack(arg, method2) {
+ if (/^\s*--(upload|receive)-pack/.test(arg)) {
+ throw new GitPluginError(void 0, "unsafe", `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`);
+ }
+ if (method2 === "clone" && /^\s*-u\b/.test(arg)) {
+ throw new GitPluginError(void 0, "unsafe", `Use of clone with option -u is not permitted without enabling allowUnsafePack`);
+ }
+ if (method2 === "push" && /^\s*--exec\b/.test(arg)) {
+ throw new GitPluginError(void 0, "unsafe", `Use of push with option --exec is not permitted without enabling allowUnsafePack`);
+ }
+}
+function blockUnsafeOperationsPlugin({
+ allowUnsafeProtocolOverride = false,
+ allowUnsafePack = false
+} = {}) {
+ return {
+ type: "spawn.args",
+ action(args, context) {
+ args.forEach((current, index2) => {
+ const next = index2 < args.length ? args[index2 + 1] : "";
+ allowUnsafeProtocolOverride || preventProtocolOverride(current, next);
+ allowUnsafePack || preventUploadPack(current, context.method);
+ });
+ return args;
+ }
+ };
+}
init_utils();
function commandConfigPrefixingPlugin(configuration) {
const prefix = prefixedArray(configuration, "-c");
@@ -23877,7 +29096,7 @@ function isTaskError(result) {
return !!(result.exitCode && result.stdErr.length);
}
function getErrorMessage(result) {
- return Buffer2.concat([...result.stdOut, ...result.stdErr]);
+ return Buffer.concat([...result.stdOut, ...result.stdErr]);
}
function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) {
return (error, result) => {
@@ -23896,7 +29115,7 @@ function errorDetectionPlugin(config) {
stdOut: context.stdOut,
exitCode: context.exitCode
});
- if (Buffer2.isBuffer(error)) {
+ if (Buffer.isBuffer(error)) {
return { error: new GitError(void 0, error.toString("utf-8")) };
}
return {
@@ -23979,7 +29198,9 @@ function spawnOptionsPlugin(spawnOptions) {
};
}
function timeoutPlugin({
- block
+ block,
+ stdErr = true,
+ stdOut = true
}) {
if (block > 0) {
return {
@@ -24003,8 +29224,8 @@ function timeoutPlugin({
stop();
context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`));
}
- (_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait3);
- (_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait3);
+ stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait3));
+ stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait3));
context.spawned.on("exit", stop);
context.spawned.on("close", stop);
wait3();
@@ -24023,6 +29244,7 @@ function gitInstanceFactory(baseDir, options) {
if (Array.isArray(config.config)) {
plugins.add(commandConfigPrefixingPlugin(config.config));
}
+ plugins.add(blockUnsafeOperationsPlugin(config.unsafe));
plugins.add(completionDetectionPlugin(config.completion));
config.abort && plugins.add(abortPlugin(config.abort));
config.progress && plugins.add(progressMonitorPlugin(config.progress));
@@ -24035,7 +29257,313 @@ function gitInstanceFactory(baseDir, options) {
init_git_response_error();
var esm_default = gitInstanceFactory;
-// src/simpleGit.ts
+// src/constants.ts
+init_polyfill_buffer();
+var import_obsidian2 = require("obsidian");
+var DATE_FORMAT = "YYYY-MM-DD";
+var DATE_TIME_FORMAT_MINUTES = `${DATE_FORMAT} HH:mm`;
+var DATE_TIME_FORMAT_SECONDS = `${DATE_FORMAT} HH:mm:ss`;
+var GIT_LINE_AUTHORING_MOVEMENT_DETECTION_MINIMAL_LENGTH = 40;
+var DEFAULT_SETTINGS = {
+ commitMessage: "vault backup: {{date}}",
+ commitDateFormat: DATE_TIME_FORMAT_SECONDS,
+ autoSaveInterval: 0,
+ autoPushInterval: 0,
+ autoPullInterval: 0,
+ autoPullOnBoot: false,
+ disablePush: false,
+ pullBeforePush: true,
+ disablePopups: false,
+ disablePopupsForNoChanges: false,
+ listChangedFilesInMessageBody: false,
+ showStatusBar: true,
+ updateSubmodules: false,
+ syncMethod: "merge",
+ customMessageOnAutoBackup: false,
+ autoBackupAfterFileChange: false,
+ treeStructure: false,
+ refreshSourceControl: import_obsidian2.Platform.isDesktopApp,
+ basePath: "",
+ differentIntervalCommitAndPush: false,
+ changedFilesInStatusBar: false,
+ showedMobileNotice: false,
+ refreshSourceControlTimer: 7e3,
+ showBranchStatusBar: true,
+ setLastSaveToLastCommit: false,
+ submoduleRecurseCheckout: false,
+ gitDir: "",
+ showFileMenu: true,
+ lineAuthor: {
+ show: false,
+ followMovement: "inactive",
+ authorDisplay: "initials",
+ showCommitHash: false,
+ dateTimeFormatOptions: "date",
+ dateTimeFormatCustomString: DATE_TIME_FORMAT_MINUTES,
+ dateTimeTimezone: "viewer-local",
+ coloringMaxAge: "1y",
+ // colors were picked via:
+ // https://color.adobe.com/de/create/color-accessibility
+ colorNew: { r: 255, g: 150, b: 150 },
+ colorOld: { r: 120, g: 160, b: 255 },
+ textColorCss: "var(--text-muted)",
+ // more pronounced than line numbers, but less than the content text
+ ignoreWhitespace: false,
+ gutterSpacingFallbackLength: 5
+ }
+};
+var SOURCE_CONTROL_VIEW_CONFIG = {
+ type: "git-view",
+ name: "Source Control",
+ icon: "git-pull-request"
+};
+var HISTORY_VIEW_CONFIG = {
+ type: "git-history-view",
+ name: "History",
+ icon: "history"
+};
+var DIFF_VIEW_CONFIG = {
+ type: "diff-view",
+ name: "Diff View",
+ icon: "git-pull-request"
+};
+
+// src/types.ts
+init_polyfill_buffer();
+function mergeSettingsByPriority(low, high) {
+ const lineAuthor = Object.assign({}, low.lineAuthor, high.lineAuthor);
+ return Object.assign({}, low, high, { lineAuthor });
+}
+
+// src/utils.ts
+init_polyfill_buffer();
+var cssColorConverter = __toESM(require_lib3());
+var import_deep_equal = __toESM(require_deep_equal());
+var import_obsidian3 = require("obsidian");
+var worthWalking2 = (filepath, root2) => {
+ if (filepath === "." || root2 == null || root2.length === 0 || root2 === ".") {
+ return true;
+ }
+ if (root2.length >= filepath.length) {
+ return root2.startsWith(filepath);
+ } else {
+ return filepath.startsWith(root2);
+ }
+};
+function getNewLeaf(event) {
+ let leaf;
+ if (event) {
+ if (event.button === 0 || event.button === 1) {
+ const type = import_obsidian3.Keymap.isModEvent(event);
+ leaf = app.workspace.getLeaf(type);
+ }
+ } else {
+ leaf = app.workspace.getLeaf(false);
+ }
+ return leaf;
+}
+function impossibleBranch(x) {
+ throw new Error("Impossible branch: " + x);
+}
+function rgbToString(rgb) {
+ return `rgb(${rgb.r},${rgb.g},${rgb.b})`;
+}
+function convertToRgb(str) {
+ var _a2;
+ const color = (_a2 = cssColorConverter.fromString(str)) == null ? void 0 : _a2.toRgbaArray();
+ if (color === void 0) {
+ return void 0;
+ }
+ const [r, g, b] = color;
+ return { r, g, b };
+}
+function momentToEpochSeconds(instant) {
+ return instant.diff(import_obsidian3.moment.unix(0), "seconds");
+}
+function median(array) {
+ if (array.length === 0)
+ return void 0;
+ return array.slice().sort()[Math.floor(array.length / 2)];
+}
+function strictDeepEqual(a, b) {
+ return (0, import_deep_equal.default)(a, b, { strict: true });
+}
+function resizeToLength(original, desiredLength, fillChar) {
+ if (original.length <= desiredLength) {
+ const prefix = new Array(desiredLength - original.length).fill(fillChar).join("");
+ return prefix + original;
+ } else {
+ return original.substring(original.length - desiredLength);
+ }
+}
+function prefixOfLengthAsWhitespace(toBeRenderedText, whitespacePrefixLength) {
+ if (whitespacePrefixLength <= 0)
+ return toBeRenderedText;
+ const whitespacePrefix = new Array(whitespacePrefixLength).fill(" ").join("");
+ const originalSuffix = toBeRenderedText.substring(
+ whitespacePrefixLength,
+ toBeRenderedText.length
+ );
+ return whitespacePrefix + originalSuffix;
+}
+function between(l, x, r) {
+ return l <= x && x <= r;
+}
+function splitRemoteBranch(remoteBranch) {
+ const [remote, ...branch2] = remoteBranch.split("/");
+ return [remote, branch2.length === 0 ? void 0 : branch2.join("/")];
+}
+function getDisplayPath(path2) {
+ if (path2.endsWith("/"))
+ return path2;
+ return path2.split("/").last().replace(".md", "");
+}
+function formatMinutes(minutes) {
+ if (minutes === 1)
+ return "1 minute";
+ return `${minutes} minutes`;
+}
+
+// src/gitManager/gitManager.ts
+init_polyfill_buffer();
+var GitManager = class {
+ constructor(plugin) {
+ this.plugin = plugin;
+ this.app = plugin.app;
+ }
+ getVaultPath(path2) {
+ if (this.plugin.settings.basePath) {
+ return this.plugin.settings.basePath + "/" + path2;
+ } else {
+ return path2;
+ }
+ }
+ asRepositoryRelativePath(path2, relativeToVault) {
+ return relativeToVault && this.plugin.settings.basePath.length > 0 ? path2.substring(this.plugin.settings.basePath.length + 1) : path2;
+ }
+ _getTreeStructure(children2, beginLength = 0) {
+ const list = [];
+ children2 = [...children2];
+ while (children2.length > 0) {
+ const first2 = children2.first();
+ const restPath = first2.path.substring(beginLength);
+ if (restPath.contains("/")) {
+ const title = restPath.substring(0, restPath.indexOf("/"));
+ const childrenWithSameTitle = children2.filter((item) => {
+ return item.path.substring(beginLength).startsWith(title + "/");
+ });
+ childrenWithSameTitle.forEach((item) => children2.remove(item));
+ const path2 = first2.path.substring(
+ 0,
+ restPath.indexOf("/") + beginLength
+ );
+ list.push({
+ title,
+ path: path2,
+ vaultPath: this.getVaultPath(path2),
+ children: this._getTreeStructure(
+ childrenWithSameTitle,
+ (beginLength > 0 ? beginLength + title.length : title.length) + 1
+ )
+ });
+ } else {
+ list.push({
+ title: restPath,
+ data: first2,
+ path: first2.path,
+ vaultPath: this.getVaultPath(first2.path)
+ });
+ children2.remove(first2);
+ }
+ }
+ return list;
+ }
+ /*
+ * Sorts the children and simplifies the title
+ * If a node only contains another subdirectory, that subdirectory is moved up one level and integrated into the parent node
+ */
+ simplify(tree) {
+ var _a2, _b, _c, _d;
+ for (const node of tree) {
+ while (true) {
+ const singleChild = ((_a2 = node.children) == null ? void 0 : _a2.length) == 1;
+ const singleChildIsDir = ((_c = (_b = node.children) == null ? void 0 : _b.first()) == null ? void 0 : _c.data) == void 0;
+ if (!(node.children != void 0 && singleChild && singleChildIsDir))
+ break;
+ const child = node.children.first();
+ node.title += "/" + child.title;
+ node.data = child.data;
+ node.path = child.path;
+ node.vaultPath = child.vaultPath;
+ node.children = child.children;
+ }
+ if (node.children != void 0) {
+ this.simplify(node.children);
+ }
+ (_d = node.children) == null ? void 0 : _d.sort((a, b) => {
+ const dirCompare = (b.data == void 0 ? 1 : 0) - (a.data == void 0 ? 1 : 0);
+ if (dirCompare != 0) {
+ return dirCompare;
+ } else {
+ return a.title.localeCompare(b.title);
+ }
+ });
+ }
+ return tree.sort((a, b) => {
+ const dirCompare = (b.data == void 0 ? 1 : 0) - (a.data == void 0 ? 1 : 0);
+ if (dirCompare != 0) {
+ return dirCompare;
+ } else {
+ return a.title.localeCompare(b.title);
+ }
+ });
+ }
+ getTreeStructure(children2) {
+ const tree = this._getTreeStructure(children2);
+ const res = this.simplify(tree);
+ return res;
+ }
+ async formatCommitMessage(template) {
+ let status2;
+ if (template.includes("{{numFiles}}")) {
+ status2 = await this.status();
+ const numFiles = status2.staged.length;
+ template = template.replace("{{numFiles}}", String(numFiles));
+ }
+ if (template.includes("{{hostname}}")) {
+ const hostname = this.plugin.localStorage.getHostname() || "";
+ template = template.replace("{{hostname}}", hostname);
+ }
+ if (template.includes("{{files}}")) {
+ status2 = status2 != null ? status2 : await this.status();
+ const changeset = {};
+ status2.staged.forEach((value) => {
+ if (value.index in changeset) {
+ changeset[value.index].push(value.path);
+ } else {
+ changeset[value.index] = [value.path];
+ }
+ });
+ const chunks = [];
+ for (const [action, files2] of Object.entries(changeset)) {
+ chunks.push(action + " " + files2.join(" "));
+ }
+ const files = chunks.join(", ");
+ template = template.replace("{{files}}", files);
+ }
+ const moment5 = window.moment;
+ template = template.replace(
+ "{{date}}",
+ moment5().format(this.plugin.settings.commitDateFormat)
+ );
+ if (this.plugin.settings.listChangedFilesInMessageBody) {
+ template = template + "\n\nAffected files:\n" + (status2 != null ? status2 : await this.status()).staged.map((e) => e.path).join("\n");
+ }
+ return template;
+ }
+};
+
+// src/gitManager/simpleGit.ts
var SimpleGit = class extends GitManager {
constructor(plugin) {
super(plugin);
@@ -24046,11 +29574,13 @@ var SimpleGit = class extends GitManager {
const path2 = adapter.getBasePath();
let basePath = path2;
if (this.plugin.settings.basePath) {
- const exists2 = await adapter.exists((0, import_obsidian6.normalizePath)(this.plugin.settings.basePath));
+ const exists2 = await adapter.exists(
+ (0, import_obsidian4.normalizePath)(this.plugin.settings.basePath)
+ );
if (exists2) {
basePath = path2 + import_path.sep + this.plugin.settings.basePath;
} else if (!ignoreError) {
- new import_obsidian6.Notice("ObsidianGit: Base path does not exist");
+ new import_obsidian4.Notice("ObsidianGit: Base path does not exist");
}
}
this.git = esm_default({
@@ -24058,35 +29588,90 @@ var SimpleGit = class extends GitManager {
binary: this.plugin.localStorage.getGitPath() || void 0,
config: ["core.quotepath=off"]
});
- this.git.cwd(await this.git.revparse("--show-toplevel"));
+ const pathPaths = this.plugin.localStorage.getPATHPaths();
+ const envVars = this.plugin.localStorage.getEnvVars();
+ const gitDir = this.plugin.settings.gitDir;
+ if (pathPaths.length > 0) {
+ const path3 = process.env["PATH"] + ":" + pathPaths.join(":");
+ process.env["PATH"] = path3;
+ }
+ if (gitDir) {
+ process.env["GIT_DIR"] = gitDir;
+ }
+ for (const envVar of envVars) {
+ const [key2, value] = envVar.split("=");
+ process.env[key2] = value;
+ }
+ import_debug2.default.enable("simple-git");
+ if (await this.git.checkIsRepo()) {
+ await this.git.cwd(await this.git.revparse("--show-toplevel"));
+ }
}
}
async status() {
- this.plugin.setState(PluginState.status);
+ this.plugin.setState(1 /* status */);
const status2 = await this.git.status((err) => this.onError(err));
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
+ const allFilesFormatted = status2.files.map((e) => {
+ const res = this.formatPath(e);
+ return {
+ path: res.path,
+ from: res.from,
+ index: e.index === "?" ? "U" : e.index,
+ working_dir: e.working_dir === "?" ? "U" : e.working_dir,
+ vault_path: this.getVaultPath(res.path)
+ };
+ });
return {
- changed: status2.files.filter((e) => e.working_dir !== " ").map((e) => {
- const res = this.formatPath(e);
- return {
- path: res.path,
- from: res.from,
- working_dir: e.working_dir === "?" ? "U" : e.working_dir,
- vault_path: this.getVaultPath(res.path)
- };
- }),
- staged: status2.files.filter((e) => e.index !== " " && e.index != "?").map((e) => {
- const res = this.formatPath(e, e.index === "R");
- return {
- path: res.path,
- from: res.from,
- index: e.index,
- vault_path: this.getVaultPath(res.path)
- };
- }),
- conflicted: status2.conflicted.map((path2) => this.formatPath({ path: path2 }).path)
+ all: allFilesFormatted,
+ changed: allFilesFormatted.filter((e) => e.working_dir !== " "),
+ staged: allFilesFormatted.filter(
+ (e) => e.index !== " " && e.index != "U"
+ ),
+ conflicted: status2.conflicted.map(
+ (path2) => this.formatPath({ path: path2 }).path
+ )
};
}
+ async submoduleAwareHeadRevisonInContainingDirectory(filepath) {
+ const repoPath = this.asRepositoryRelativePath(filepath, true);
+ const containingDirectory = path.dirname(repoPath);
+ const args = ["-C", containingDirectory, "rev-parse", "HEAD"];
+ const result = this.git.raw(args);
+ result.catch(
+ (err) => console.warn("obsidian-git: rev-parse error:", err)
+ );
+ return result;
+ }
+ async getSubmodulePaths() {
+ return new Promise(async (resolve) => {
+ this.git.outputHandler(async (cmd, stdout, stderr, args) => {
+ if (!(args.contains("submodule") && args.contains("foreach"))) {
+ return;
+ }
+ let body = "";
+ const root2 = this.app.vault.adapter.getBasePath() + (this.plugin.settings.basePath ? "/" + this.plugin.settings.basePath : "");
+ stdout.on("data", (chunk) => {
+ body += chunk.toString("utf8");
+ });
+ stdout.on("end", async () => {
+ const submods = body.split("\n");
+ const strippedSubmods = submods.map((i) => {
+ const submod = i.match(/'([^']*)'/);
+ if (submod != void 0) {
+ return root2 + "/" + submod[1] + import_path.sep;
+ }
+ }).filter((i) => !!i);
+ strippedSubmods.reverse();
+ resolve(strippedSubmods);
+ });
+ });
+ await this.git.subModule(["foreach", "--recursive", ""]);
+ this.git.outputHandler(() => {
+ });
+ });
+ }
+ //Remove wrong `"` like "My file.md"
formatPath(path2, renamed = false) {
function format(path3) {
if (path3 == void 0)
@@ -24108,90 +29693,141 @@ var SimpleGit = class extends GitManager {
};
}
}
+ async blame(path2, trackMovement, ignoreWhitespace) {
+ path2 = this.asRepositoryRelativePath(path2, true);
+ if (!await this.isTracked(path2))
+ return "untracked";
+ const inSubmodule = await this.getSubmoduleOfFile(path2);
+ const args = inSubmodule ? ["-C", inSubmodule.submodule] : [];
+ const relativePath = inSubmodule ? inSubmodule.relativeFilepath : path2;
+ args.push("blame", "--porcelain");
+ if (ignoreWhitespace)
+ args.push("-w");
+ const trackCArg = `-C${GIT_LINE_AUTHORING_MOVEMENT_DETECTION_MINIMAL_LENGTH}`;
+ switch (trackMovement) {
+ case "inactive":
+ break;
+ case "same-commit":
+ args.push("-C", trackCArg);
+ break;
+ case "all-commits":
+ args.push("-C", "-C", trackCArg);
+ break;
+ default:
+ impossibleBranch(trackMovement);
+ }
+ args.push("--", relativePath);
+ const rawBlame = await this.git.raw(
+ args,
+ (err) => err && console.warn("git-blame", err)
+ );
+ return parseBlame(rawBlame);
+ }
+ async isTracked(path2) {
+ const inSubmodule = await this.getSubmoduleOfFile(path2);
+ const args = inSubmodule ? ["-C", inSubmodule.submodule] : [];
+ const relativePath = inSubmodule ? inSubmodule.relativeFilepath : path2;
+ args.push("ls-files", "--", relativePath);
+ return this.git.raw(args, (err) => err && console.warn("ls-files", err)).then((x) => x.trim() !== "");
+ }
async commitAll({ message }) {
if (this.plugin.settings.updateSubmodules) {
- this.plugin.setState(PluginState.commit);
- await new Promise(async (resolve, reject) => {
- this.git.outputHandler(async (cmd, stdout, stderr, args) => {
- if (!(args.contains("submodule") && args.contains("foreach")))
- return;
- let body = "";
- const root = this.app.vault.adapter.getBasePath() + (this.plugin.settings.basePath ? "/" + this.plugin.settings.basePath : "");
- stdout.on("data", (chunk) => {
- body += chunk.toString("utf8");
- });
- stdout.on("end", async () => {
- const submods = body.split("\n");
- const strippedSubmods = submods.map((i) => {
- const submod = i.match(/'([^']*)'/);
- if (submod != void 0) {
- return root + "/" + submod[1] + import_path.sep;
- }
- });
- strippedSubmods.reverse();
- for (const item of strippedSubmods) {
- if (item != void 0) {
- await this.git.cwd({ path: item, root: false }).add("-A", (err) => this.onError(err));
- await this.git.cwd({ path: item, root: false }).commit(await this.formatCommitMessage(message), (err) => this.onError(err));
- }
- }
- resolve();
- });
- });
- await this.git.subModule(["foreach", "--recursive", ""]);
- this.git.outputHandler(() => {
- });
- });
+ this.plugin.setState(4 /* commit */);
+ const submodulePaths = await this.getSubmodulePaths();
+ for (const item of submodulePaths) {
+ await this.git.cwd({ path: item, root: false }).add("-A", (err) => this.onError(err));
+ await this.git.cwd({ path: item, root: false }).commit(
+ await this.formatCommitMessage(message),
+ (err) => this.onError(err)
+ );
+ }
}
- this.plugin.setState(PluginState.add);
+ this.plugin.setState(3 /* add */);
await this.git.add("-A", (err) => this.onError(err));
- this.plugin.setState(PluginState.commit);
- return (await this.git.commit(await this.formatCommitMessage(message), (err) => this.onError(err))).summary.changes;
+ this.plugin.setState(4 /* commit */);
+ const res = await this.git.commit(
+ await this.formatCommitMessage(message),
+ (err) => this.onError(err)
+ );
+ dispatchEvent(new CustomEvent("git-head-update"));
+ return res.summary.changes;
}
- async commit(message) {
- this.plugin.setState(PluginState.commit);
- const res = (await this.git.commit(await this.formatCommitMessage(message), (err) => this.onError(err))).summary.changes;
- this.plugin.setState(PluginState.idle);
+ async commit({
+ message,
+ amend
+ }) {
+ this.plugin.setState(4 /* commit */);
+ const res = (await this.git.commit(
+ await this.formatCommitMessage(message),
+ amend ? ["--amend"] : [],
+ (err) => this.onError(err)
+ )).summary.changes;
+ dispatchEvent(new CustomEvent("git-head-update"));
+ this.plugin.setState(0 /* idle */);
return res;
}
async stage(path2, relativeToVault) {
- this.plugin.setState(PluginState.add);
- path2 = this.getPath(path2, relativeToVault);
+ this.plugin.setState(3 /* add */);
+ path2 = this.asRepositoryRelativePath(path2, relativeToVault);
await this.git.add(["--", path2], (err) => this.onError(err));
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
}
async stageAll({ dir }) {
- this.plugin.setState(PluginState.add);
+ this.plugin.setState(3 /* add */);
await this.git.add(dir != null ? dir : "-A", (err) => this.onError(err));
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
}
async unstageAll({ dir }) {
- this.plugin.setState(PluginState.add);
- await this.git.reset(dir != void 0 ? ["--", dir] : [], (err) => this.onError(err));
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(3 /* add */);
+ await this.git.reset(
+ dir != void 0 ? ["--", dir] : [],
+ (err) => this.onError(err)
+ );
+ this.plugin.setState(0 /* idle */);
}
async unstage(path2, relativeToVault) {
- this.plugin.setState(PluginState.add);
- path2 = this.getPath(path2, relativeToVault);
+ this.plugin.setState(3 /* add */);
+ path2 = this.asRepositoryRelativePath(path2, relativeToVault);
await this.git.reset(["--", path2], (err) => this.onError(err));
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
}
async discard(filepath) {
- this.plugin.setState(PluginState.add);
+ this.plugin.setState(3 /* add */);
await this.git.checkout(["--", filepath], (err) => this.onError(err));
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
+ }
+ async hashObject(filepath) {
+ filepath = this.asRepositoryRelativePath(filepath, true);
+ const inSubmodule = await this.getSubmoduleOfFile(filepath);
+ const args = inSubmodule ? ["-C", inSubmodule.submodule] : [];
+ const relativeFilepath = inSubmodule ? inSubmodule.relativeFilepath : filepath;
+ args.push("hash-object", "--", relativeFilepath);
+ const revision = this.git.raw(args);
+ revision.catch(
+ (err) => err && console.warn("obsidian-git. hash-object failed:", err == null ? void 0 : err.message)
+ );
+ return revision;
}
async discardAll({ dir }) {
return this.discard(dir != null ? dir : ".");
}
async pull() {
- this.plugin.setState(PluginState.pull);
+ this.plugin.setState(2 /* pull */);
if (this.plugin.settings.updateSubmodules)
- await this.git.subModule(["update", "--remote", "--merge", "--recursive"], (err) => this.onError(err));
+ await this.git.subModule(
+ ["update", "--remote", "--merge", "--recursive"],
+ (err) => this.onError(err)
+ );
const branchInfo = await this.branchInfo();
- const localCommit = await this.git.revparse([branchInfo.current], (err) => this.onError(err));
+ const localCommit = await this.git.revparse(
+ [branchInfo.current],
+ (err) => this.onError(err)
+ );
await this.git.fetch((err) => this.onError(err));
- const upstreamCommit = await this.git.revparse([branchInfo.tracking], (err) => this.onError(err));
+ const upstreamCommit = await this.git.revparse(
+ [branchInfo.tracking],
+ (err) => this.onError(err)
+ );
if (localCommit !== upstreamCommit) {
if (this.plugin.settings.syncMethod === "merge" || this.plugin.settings.syncMethod === "rebase") {
try {
@@ -24203,19 +29839,37 @@ var SimpleGit = class extends GitManager {
await this.git.rebase([branchInfo.tracking]);
}
} catch (err) {
- this.plugin.displayError(`Pull failed (${this.plugin.settings.syncMethod}): ${err.message}`);
+ this.plugin.displayError(
+ `Pull failed (${this.plugin.settings.syncMethod}): ${err.message}`
+ );
return;
}
} else if (this.plugin.settings.syncMethod === "reset") {
try {
- await this.git.raw(["update-ref", `refs/heads/${branchInfo.current}`, upstreamCommit], (err) => this.onError(err));
+ await this.git.raw(
+ [
+ "update-ref",
+ `refs/heads/${branchInfo.current}`,
+ upstreamCommit
+ ],
+ (err) => this.onError(err)
+ );
await this.unstageAll({});
} catch (err) {
- this.plugin.displayError(`Sync failed (${this.plugin.settings.syncMethod}): ${err.message}`);
+ this.plugin.displayError(
+ `Sync failed (${this.plugin.settings.syncMethod}): ${err.message}`
+ );
}
}
- const afterMergeCommit = await this.git.revparse([branchInfo.current], (err) => this.onError(err));
- const filesChanged = await this.git.diff([`${localCommit}..${afterMergeCommit}`, "--name-only"]);
+ dispatchEvent(new CustomEvent("git-head-update"));
+ const afterMergeCommit = await this.git.revparse(
+ [branchInfo.current],
+ (err) => this.onError(err)
+ );
+ const filesChanged = await this.git.diff([
+ `${localCommit}..${afterMergeCommit}`,
+ "--name-only"
+ ]);
return filesChanged.split(/\r\n|\r|\n/).filter((value) => value.length > 0).map((e) => {
return {
path: e,
@@ -24228,16 +29882,39 @@ var SimpleGit = class extends GitManager {
}
}
async push() {
- this.plugin.setState(PluginState.status);
+ this.plugin.setState(1 /* status */);
const status2 = await this.git.status();
const trackingBranch = status2.tracking;
const currentBranch2 = status2.current;
- const remoteChangedFiles = (await this.git.diffSummary([currentBranch2, trackingBranch, "--"], (err) => this.onError(err))).changed;
- this.plugin.setState(PluginState.push);
+ const remoteChangedFiles = (await this.git.diffSummary(
+ [currentBranch2, trackingBranch, "--"],
+ (err) => this.onError(err)
+ )).changed;
+ this.plugin.setState(5 /* push */);
if (this.plugin.settings.updateSubmodules) {
- await this.git.env({ ...process.env, "OBSIDIAN_GIT": 1 }).subModule(["foreach", "--recursive", `tracking=$(git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"); echo $tracking; if [ ! -z "$(git diff --shortstat $tracking)" ]; then git push; fi`], (err) => this.onError(err));
+ await this.git.env({ ...process.env, OBSIDIAN_GIT: 1 }).subModule(
+ [
+ "foreach",
+ "--recursive",
+ `tracking=$(git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"); echo $tracking; if [ ! -z "$(git diff --shortstat $tracking)" ]; then git push; fi`
+ ],
+ (err) => this.onError(err)
+ );
}
- await this.git.env({ ...process.env, "OBSIDIAN_GIT": 1 }).push((err) => this.onError(err));
+ await this.git.env({ ...process.env, OBSIDIAN_GIT: 1 }).push((err) => this.onError(err));
+ return remoteChangedFiles;
+ }
+ async getUnpushedCommits() {
+ const status2 = await this.git.status();
+ const trackingBranch = status2.tracking;
+ const currentBranch2 = status2.current;
+ if (trackingBranch == null || currentBranch2 == null) {
+ return 0;
+ }
+ const remoteChangedFiles = (await this.git.diffSummary(
+ [currentBranch2, trackingBranch, "--"],
+ (err) => this.onError(err)
+ )).changed;
return remoteChangedFiles;
}
async canPush() {
@@ -24261,7 +29938,10 @@ var SimpleGit = class extends GitManager {
}
async branchInfo() {
const status2 = await this.git.status((err) => this.onError(err));
- const branches = await this.git.branch(["--no-color"], (err) => this.onError(err));
+ const branches = await this.git.branch(
+ ["--no-color"],
+ (err) => this.onError(err)
+ );
return {
current: status2.current || void 0,
tracking: status2.tracking || void 0,
@@ -24269,55 +29949,140 @@ var SimpleGit = class extends GitManager {
};
}
async getRemoteUrl(remote) {
- return await this.git.remote(["get-url", remote], (err, url) => this.onError(err)) || void 0;
+ try {
+ await this.git.remote(["get-url", remote]);
+ } catch (error) {
+ if (error.toString().contains(remote)) {
+ return void 0;
+ } else {
+ this.onError(error);
+ }
+ }
}
- async log(file, relativeToVault = true) {
- const path2 = this.getPath(file, relativeToVault);
- const res = await this.git.log({ file: path2 }, (err) => this.onError(err));
- return res.all;
+ // https://github.com/kometenstaub/obsidian-version-history-diff/issues/3
+ async log(file, relativeToVault = true, limit) {
+ let path2;
+ if (file) {
+ path2 = this.asRepositoryRelativePath(file, relativeToVault);
+ }
+ const res = await this.git.log(
+ {
+ file: path2,
+ maxCount: limit,
+ "-m": null,
+ "--name-status": null
+ },
+ (err) => this.onError(err)
+ );
+ return res.all.map((e) => {
+ var _a2, _b, _c, _d;
+ return {
+ ...e,
+ refs: e.refs.split(", "),
+ diff: {
+ ...e.diff,
+ files: (_b = (_a2 = e.diff) == null ? void 0 : _a2.files.map((f) => ({
+ ...f,
+ status: f.status,
+ path: f.file,
+ hash: e.hash,
+ vault_path: this.getVaultPath(f.file)
+ }))) != null ? _b : []
+ },
+ fileName: (_d = (_c = e.diff) == null ? void 0 : _c.files.first()) == null ? void 0 : _d.file
+ };
+ });
}
async show(commitHash, file, relativeToVault = true) {
- const path2 = this.getPath(file, relativeToVault);
- return this.git.show([commitHash + ":" + path2], (err) => this.onError(err));
+ const path2 = this.asRepositoryRelativePath(file, relativeToVault);
+ return this.git.show(
+ [commitHash + ":" + path2],
+ (err) => this.onError(err)
+ );
}
- async checkout(branch2) {
+ async checkout(branch2, remote) {
+ if (remote) {
+ branch2 = `${remote}/${branch2}`;
+ }
await this.git.checkout(branch2, (err) => this.onError(err));
+ if (this.plugin.settings.submoduleRecurseCheckout) {
+ const submodulePaths = await this.getSubmodulePaths();
+ for (const submodulePath of submodulePaths) {
+ const branchSummary = await this.git.cwd({ path: submodulePath, root: false }).branch();
+ if (Object.keys(branchSummary.branches).includes(branch2)) {
+ await this.git.cwd({ path: submodulePath, root: false }).checkout(branch2, (err) => this.onError(err));
+ }
+ }
+ }
}
async createBranch(branch2) {
await this.git.checkout(["-b", branch2], (err) => this.onError(err));
}
async deleteBranch(branch2, force) {
- await this.git.branch([force ? "-D" : "-d", branch2], (err) => this.onError(err));
+ await this.git.branch(
+ [force ? "-D" : "-d", branch2],
+ (err) => this.onError(err)
+ );
}
async branchIsMerged(branch2) {
- const notMergedBranches = await this.git.branch(["--no-merged"], (err) => this.onError(err));
+ const notMergedBranches = await this.git.branch(
+ ["--no-merged"],
+ (err) => this.onError(err)
+ );
return !notMergedBranches.all.contains(branch2);
}
async init() {
await this.git.init(false, (err) => this.onError(err));
}
- async clone(url, dir) {
- await this.git.clone(url, path.join(this.app.vault.adapter.getBasePath(), dir), [], (err) => this.onError(err));
+ async clone(url, dir, depth) {
+ await this.git.clone(
+ url,
+ path.join(
+ this.app.vault.adapter.getBasePath(),
+ dir
+ ),
+ depth ? ["--depth", `${depth}`] : [],
+ (err) => this.onError(err)
+ );
}
async setConfig(path2, value) {
- await this.git.addConfig(path2, value, (err) => this.onError(err));
+ if (value == void 0) {
+ await this.git.raw(["config", "--local", "--unset", path2]);
+ } else {
+ await this.git.addConfig(path2, value, (err) => this.onError(err));
+ }
}
async getConfig(path2) {
- const config = await this.git.listConfig((err) => this.onError(err));
+ const config = await this.git.listConfig(
+ "local",
+ (err) => this.onError(err)
+ );
return config.all[path2];
}
async fetch(remote) {
- await this.git.fetch(remote != void 0 ? [remote] : [], (err) => this.onError(err));
+ await this.git.fetch(
+ remote != void 0 ? [remote] : [],
+ (err) => this.onError(err)
+ );
}
async setRemote(name, url) {
if ((await this.getRemotes()).includes(name))
- await this.git.remote(["set-url", name, url], (err) => this.onError(err));
+ await this.git.remote(
+ ["set-url", name, url],
+ (err) => this.onError(err)
+ );
else {
- await this.git.remote(["add", name, url], (err) => this.onError(err));
+ await this.git.remote(
+ ["add", name, url],
+ (err) => this.onError(err)
+ );
}
}
async getRemoteBranches(remote) {
- const res = await this.git.branch(["-r", "--list", `${remote}*`], (err) => this.onError(err));
+ const res = await this.git.branch(
+ ["-r", "--list", `${remote}*`],
+ (err) => this.onError(err)
+ );
console.log(remote);
console.log(res);
const list = [];
@@ -24346,7 +30111,14 @@ var SimpleGit = class extends GitManager {
await this.git.branch(["--set-upstream", remoteBranch]);
} catch (e2) {
console.error(e2);
- await this.git.push(["--set-upstream", ...remoteBranch.split("/")], (err) => this.onError(err));
+ await this.git.push(
+ // A type error occurs here because the third element could be undefined.
+ // However, it is unlikely to be undefined due to the `remoteBranch`'s format, and error handling is in place.
+ // Therefore, we temporarily ignore the error.
+ // @ts-ignore
+ ["--set-upstream", ...splitRemoteBranch(remoteBranch)],
+ (err) => this.onError(err)
+ );
}
}
}
@@ -24356,19 +30128,61 @@ var SimpleGit = class extends GitManager {
updateBasePath(basePath) {
this.setGitInstance(true);
}
- async getDiffString(filePath, stagedChanges = false) {
+ async getDiffString(filePath, stagedChanges = false, hash2) {
if (stagedChanges)
return await this.git.diff(["--cached", "--", filePath]);
+ if (hash2)
+ return await this.git.show([`${hash2}`, "--", filePath]);
else
return await this.git.diff(["--", filePath]);
}
async diff(file, commit1, commit2) {
return await this.git.diff([`${commit1}..${commit2}`, "--", file]);
}
+ async getSubmoduleOfFile(repositoryRelativeFile) {
+ let submoduleRoot = await this.git.raw(
+ [
+ "-C",
+ path.dirname(repositoryRelativeFile),
+ "rev-parse",
+ "--show-toplevel"
+ ],
+ (err) => err && console.warn("get-submodule-of-file", err == null ? void 0 : err.message)
+ );
+ submoduleRoot = submoduleRoot.trim();
+ const superProject = await this.git.raw(
+ [
+ "-C",
+ path.dirname(repositoryRelativeFile),
+ "rev-parse",
+ "--show-superproject-working-tree"
+ ],
+ (err) => err && console.warn("get-submodule-of-file", err == null ? void 0 : err.message)
+ );
+ if (superProject.trim() === "") {
+ return void 0;
+ }
+ const fsAdapter = this.app.vault.adapter;
+ const absolutePath = fsAdapter.getFullPath(
+ path.normalize(repositoryRelativeFile)
+ );
+ const newRelativePath = path.relative(submoduleRoot, absolutePath);
+ return { submodule: submoduleRoot, relativeFilepath: newRelativePath };
+ }
+ async getLastCommitTime() {
+ const res = await this.git.log({ n: 1 }, (err) => this.onError(err));
+ if (res != null && res.latest != null) {
+ return new Date(res.latest.date);
+ }
+ }
isGitInstalled() {
- const command = (0, import_child_process2.spawnSync)(this.plugin.localStorage.getGitPath() || "git", ["--version"], {
- stdio: "ignore"
- });
+ const command = (0, import_child_process2.spawnSync)(
+ this.plugin.localStorage.getGitPath() || "git",
+ ["--version"],
+ {
+ stdio: "ignore"
+ }
+ );
if (command.error) {
console.error(command.error);
return false;
@@ -24377,23 +30191,1947 @@ var SimpleGit = class extends GitManager {
}
onError(error) {
if (error) {
- const networkFailure = error.message.contains("Could not resolve host") || error.message.match(/ssh: connect to host .*? port .*?: Operation timed out/);
+ const networkFailure = error.message.contains("Could not resolve host") || error.message.match(
+ /ssh: connect to host .*? port .*?: Operation timed out/
+ ) || error.message.match(
+ /ssh: connect to host .*? port .*?: Network is unreachable/
+ );
if (!networkFailure) {
this.plugin.displayError(error.message);
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
} else if (!this.plugin.offlineMode) {
- this.plugin.displayError("Git: Going into offline mode. Future network errors will no longer be displayed.", 2e3);
+ this.plugin.displayError(
+ "Git: Going into offline mode. Future network errors will no longer be displayed.",
+ 2e3
+ );
}
if (networkFailure) {
this.plugin.offlineMode = true;
- this.plugin.setState(PluginState.idle);
+ this.plugin.setState(0 /* idle */);
}
}
}
};
+var zeroCommit = {
+ hash: "000000",
+ isZeroCommit: true,
+ summary: ""
+};
+function parseBlame(blameOutputUnnormalized) {
+ const blameOutput = blameOutputUnnormalized.replace("\r\n", "\n");
+ const blameLines = blameOutput.split("\n");
+ const result = {
+ commits: /* @__PURE__ */ new Map(),
+ hashPerLine: [void 0],
+ // one-based indices
+ originalFileLineNrPerLine: [void 0],
+ finalFileLineNrPerLine: [void 0],
+ groupSizePerStartingLine: /* @__PURE__ */ new Map()
+ };
+ let line = 1;
+ for (let bi = 0; bi < blameLines.length; ) {
+ if (startsWithNonWhitespace(blameLines[bi])) {
+ const lineInfo = blameLines[bi].split(" ");
+ const commitHash = parseLineInfoInto(lineInfo, line, result);
+ bi++;
+ for (; startsWithNonWhitespace(blameLines[bi]); bi++) {
+ const spaceSeparatedHeaderValues = blameLines[bi].split(" ");
+ parseHeaderInto(spaceSeparatedHeaderValues, result, line);
+ }
+ finalizeBlameCommitInfo(result.commits.get(commitHash));
+ line += 1;
+ } else if (blameLines[bi] === "" && bi === blameLines.length - 1) {
+ } else {
+ throw Error(
+ `Expected non-whitespace line or EOF, but found: ${blameLines[bi]}`
+ );
+ }
+ bi++;
+ }
+ return result;
+}
+function parseLineInfoInto(lineInfo, line, result) {
+ const hash2 = lineInfo[0];
+ result.hashPerLine.push(hash2);
+ result.originalFileLineNrPerLine.push(parseInt(lineInfo[1]));
+ result.finalFileLineNrPerLine.push(parseInt(lineInfo[2]));
+ lineInfo.length >= 4 && result.groupSizePerStartingLine.set(line, parseInt(lineInfo[3]));
+ if (parseInt(lineInfo[2]) !== line) {
+ throw Error(
+ `git-blame output is out of order: ${line} vs ${lineInfo[2]}`
+ );
+ }
+ return hash2;
+}
+function parseHeaderInto(header, out, line) {
+ const key2 = header[0];
+ const value = header.slice(1).join(" ");
+ const commitHash = out.hashPerLine[line];
+ const commit2 = out.commits.get(commitHash) || {
+ hash: commitHash,
+ author: {},
+ committer: {},
+ previous: {}
+ };
+ switch (key2) {
+ case "summary":
+ commit2.summary = value;
+ break;
+ case "author":
+ commit2.author.name = value;
+ break;
+ case "author-mail":
+ commit2.author.email = removeEmailBrackets(value);
+ break;
+ case "author-time":
+ commit2.author.epochSeconds = parseInt(value);
+ break;
+ case "author-tz":
+ commit2.author.tz = value;
+ break;
+ case "committer":
+ commit2.committer.name = value;
+ break;
+ case "committer-mail":
+ commit2.committer.email = removeEmailBrackets(value);
+ break;
+ case "committer-time":
+ commit2.committer.epochSeconds = parseInt(value);
+ break;
+ case "committer-tz":
+ commit2.committer.tz = value;
+ break;
+ case "previous":
+ commit2.previous.commitHash = value;
+ break;
+ case "filename":
+ commit2.previous.filename = value;
+ break;
+ }
+ out.commits.set(commitHash, commit2);
+}
+function finalizeBlameCommitInfo(commit2) {
+ if (commit2.summary === void 0) {
+ throw Error(`Summary not provided for commit: ${commit2.hash}`);
+ }
+ if (isUndefinedOrEmptyObject(commit2.author)) {
+ commit2.author = void 0;
+ }
+ if (isUndefinedOrEmptyObject(commit2.committer)) {
+ commit2.committer = void 0;
+ }
+ if (isUndefinedOrEmptyObject(commit2.previous)) {
+ commit2.previous = void 0;
+ }
+ commit2.isZeroCommit = Boolean(commit2.hash.match(/^0*$/));
+}
+function isUndefinedOrEmptyObject(obj) {
+ return !obj || Object.keys(obj).length === 0;
+}
+function startsWithNonWhitespace(str) {
+ return str.length > 0 && str[0].trim() === str[0];
+}
+function removeEmailBrackets(gitEmail) {
+ const prefixCleaned = gitEmail.startsWith("<") ? gitEmail.substring(1) : gitEmail;
+ return prefixCleaned.endsWith(">") ? prefixCleaned.substring(0, prefixCleaned.length - 1) : prefixCleaned;
+}
-// src/settings.ts
-var ObsidianGitSettingsTab = class extends import_obsidian7.PluginSettingTab {
+// src/lineAuthor/lineAuthorProvider.ts
+init_polyfill_buffer();
+var import_state4 = require("@codemirror/state");
+
+// src/lineAuthor/control.ts
+init_polyfill_buffer();
+var import_state2 = require("@codemirror/state");
+var import_obsidian9 = require("obsidian");
+
+// src/lineAuthor/eventsPerFilepath.ts
+init_polyfill_buffer();
+var SECONDS = 1e3;
+var REMOVE_STALES_FREQUENCY = 60 * SECONDS;
+var EventsPerFilePath = class {
+ constructor() {
+ this.eventsPerFilepath = /* @__PURE__ */ new Map();
+ this.startRemoveStalesSubscribersInterval();
+ }
+ /**
+ * Run the {@link handler} on the subscribers to {@link filepath}.
+ */
+ ifFilepathDefinedTransformSubscribers(filepath, handler) {
+ if (!filepath)
+ return;
+ this.ensureInitialized(filepath);
+ return handler(this.eventsPerFilepath.get(filepath));
+ }
+ forEachSubscriber(handler) {
+ this.eventsPerFilepath.forEach((subs) => subs.forEach(handler));
+ }
+ ensureInitialized(filepath) {
+ if (!this.eventsPerFilepath.get(filepath))
+ this.eventsPerFilepath.set(filepath, /* @__PURE__ */ new Set());
+ }
+ startRemoveStalesSubscribersInterval() {
+ this.removeStalesSubscribersTimer = window.setInterval(
+ () => this == null ? void 0 : this.forEachSubscriber((las) => las == null ? void 0 : las.removeIfStale()),
+ REMOVE_STALES_FREQUENCY
+ );
+ }
+ clear() {
+ window.clearInterval(this.removeStalesSubscribersTimer);
+ this.eventsPerFilepath.clear();
+ }
+};
+var eventsPerFilePathSingleton = new EventsPerFilePath();
+
+// src/lineAuthor/model.ts
+init_polyfill_buffer();
+var import_state = require("@codemirror/state");
+var import_js_sha256 = __toESM(require_sha256());
+
+// src/setting/settings.ts
+init_polyfill_buffer();
+var import_obsidian8 = require("obsidian");
+
+// src/gitManager/isomorphicGit.ts
+init_polyfill_buffer();
+
+// node_modules/.pnpm/diff@5.1.0/node_modules/diff/lib/index.mjs
+init_polyfill_buffer();
+function Diff() {
+}
+Diff.prototype = {
+ diff: function diff(oldString, newString) {
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
+ var callback = options.callback;
+ if (typeof options === "function") {
+ callback = options;
+ options = {};
+ }
+ this.options = options;
+ var self2 = this;
+ function done(value) {
+ if (callback) {
+ setTimeout(function() {
+ callback(void 0, value);
+ }, 0);
+ return true;
+ } else {
+ return value;
+ }
+ }
+ oldString = this.castInput(oldString);
+ newString = this.castInput(newString);
+ oldString = this.removeEmpty(this.tokenize(oldString));
+ newString = this.removeEmpty(this.tokenize(newString));
+ var newLen = newString.length, oldLen = oldString.length;
+ var editLength = 1;
+ var maxEditLength = newLen + oldLen;
+ if (options.maxEditLength) {
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
+ }
+ var bestPath = [{
+ newPos: -1,
+ components: []
+ }];
+ var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+ if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
+ return done([{
+ value: this.join(newString),
+ count: newString.length
+ }]);
+ }
+ function execEditLength() {
+ for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
+ var basePath = void 0;
+ var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+ if (addPath) {
+ bestPath[diagonalPath - 1] = void 0;
+ }
+ var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
+ if (!canAdd && !canRemove) {
+ bestPath[diagonalPath] = void 0;
+ continue;
+ }
+ if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
+ basePath = clonePath(removePath);
+ self2.pushComponent(basePath.components, void 0, true);
+ } else {
+ basePath = addPath;
+ basePath.newPos++;
+ self2.pushComponent(basePath.components, true, void 0);
+ }
+ _oldPos = self2.extractCommon(basePath, newString, oldString, diagonalPath);
+ if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
+ return done(buildValues(self2, basePath.components, newString, oldString, self2.useLongestToken));
+ } else {
+ bestPath[diagonalPath] = basePath;
+ }
+ }
+ editLength++;
+ }
+ if (callback) {
+ (function exec() {
+ setTimeout(function() {
+ if (editLength > maxEditLength) {
+ return callback();
+ }
+ if (!execEditLength()) {
+ exec();
+ }
+ }, 0);
+ })();
+ } else {
+ while (editLength <= maxEditLength) {
+ var ret = execEditLength();
+ if (ret) {
+ return ret;
+ }
+ }
+ }
+ },
+ pushComponent: function pushComponent(components, added, removed) {
+ var last2 = components[components.length - 1];
+ if (last2 && last2.added === added && last2.removed === removed) {
+ components[components.length - 1] = {
+ count: last2.count + 1,
+ added,
+ removed
+ };
+ } else {
+ components.push({
+ count: 1,
+ added,
+ removed
+ });
+ }
+ },
+ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
+ var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
+ newPos++;
+ oldPos++;
+ commonCount++;
+ }
+ if (commonCount) {
+ basePath.components.push({
+ count: commonCount
+ });
+ }
+ basePath.newPos = newPos;
+ return oldPos;
+ },
+ equals: function equals(left, right) {
+ if (this.options.comparator) {
+ return this.options.comparator(left, right);
+ } else {
+ return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
+ }
+ },
+ removeEmpty: function removeEmpty(array) {
+ var ret = [];
+ for (var i = 0; i < array.length; i++) {
+ if (array[i]) {
+ ret.push(array[i]);
+ }
+ }
+ return ret;
+ },
+ castInput: function castInput(value) {
+ return value;
+ },
+ tokenize: function tokenize(value) {
+ return value.split("");
+ },
+ join: function join3(chars) {
+ return chars.join("");
+ }
+};
+function buildValues(diff2, components, newString, oldString, useLongestToken) {
+ var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
+ for (; componentPos < componentLen; componentPos++) {
+ var component = components[componentPos];
+ if (!component.removed) {
+ if (!component.added && useLongestToken) {
+ var value = newString.slice(newPos, newPos + component.count);
+ value = value.map(function(value2, i) {
+ var oldValue = oldString[oldPos + i];
+ return oldValue.length > value2.length ? oldValue : value2;
+ });
+ component.value = diff2.join(value);
+ } else {
+ component.value = diff2.join(newString.slice(newPos, newPos + component.count));
+ }
+ newPos += component.count;
+ if (!component.added) {
+ oldPos += component.count;
+ }
+ } else {
+ component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
+ oldPos += component.count;
+ if (componentPos && components[componentPos - 1].added) {
+ var tmp = components[componentPos - 1];
+ components[componentPos - 1] = components[componentPos];
+ components[componentPos] = tmp;
+ }
+ }
+ }
+ var lastComponent = components[componentLen - 1];
+ if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff2.equals("", lastComponent.value)) {
+ components[componentLen - 2].value += lastComponent.value;
+ components.pop();
+ }
+ return components;
+}
+function clonePath(path2) {
+ return {
+ newPos: path2.newPos,
+ components: path2.components.slice(0)
+ };
+}
+var characterDiff = new Diff();
+function diffChars(oldStr, newStr, options) {
+ return characterDiff.diff(oldStr, newStr, options);
+}
+var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
+var reWhitespace = /\S/;
+var wordDiff = new Diff();
+wordDiff.equals = function(left, right) {
+ if (this.options.ignoreCase) {
+ left = left.toLowerCase();
+ right = right.toLowerCase();
+ }
+ return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
+};
+wordDiff.tokenize = function(value) {
+ var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
+ for (var i = 0; i < tokens.length - 1; i++) {
+ if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
+ tokens[i] += tokens[i + 2];
+ tokens.splice(i + 1, 2);
+ i--;
+ }
+ }
+ return tokens;
+};
+function diffWordsWithSpace(oldStr, newStr, options) {
+ return wordDiff.diff(oldStr, newStr, options);
+}
+var lineDiff = new Diff();
+lineDiff.tokenize = function(value) {
+ var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
+ linesAndNewlines.pop();
+ }
+ for (var i = 0; i < linesAndNewlines.length; i++) {
+ var line = linesAndNewlines[i];
+ if (i % 2 && !this.options.newlineIsToken) {
+ retLines[retLines.length - 1] += line;
+ } else {
+ if (this.options.ignoreWhitespace) {
+ line = line.trim();
+ }
+ retLines.push(line);
+ }
+ }
+ return retLines;
+};
+function diffLines(oldStr, newStr, callback) {
+ return lineDiff.diff(oldStr, newStr, callback);
+}
+var sentenceDiff = new Diff();
+sentenceDiff.tokenize = function(value) {
+ return value.split(/(\S.+?[.!?])(?=\s+|$)/);
+};
+var cssDiff = new Diff();
+cssDiff.tokenize = function(value) {
+ return value.split(/([{}:;,]|\s+)/);
+};
+function _typeof(obj) {
+ "@babel/helpers - typeof";
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
+ _typeof = function(obj2) {
+ return typeof obj2;
+ };
+ } else {
+ _typeof = function(obj2) {
+ return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
+ };
+ }
+ return _typeof(obj);
+}
+function _toConsumableArray(arr) {
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
+}
+function _arrayWithoutHoles(arr) {
+ if (Array.isArray(arr))
+ return _arrayLikeToArray(arr);
+}
+function _iterableToArray(iter) {
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter))
+ return Array.from(iter);
+}
+function _unsupportedIterableToArray(o, minLen) {
+ if (!o)
+ return;
+ if (typeof o === "string")
+ return _arrayLikeToArray(o, minLen);
+ var n = Object.prototype.toString.call(o).slice(8, -1);
+ if (n === "Object" && o.constructor)
+ n = o.constructor.name;
+ if (n === "Map" || n === "Set")
+ return Array.from(o);
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
+ return _arrayLikeToArray(o, minLen);
+}
+function _arrayLikeToArray(arr, len) {
+ if (len == null || len > arr.length)
+ len = arr.length;
+ for (var i = 0, arr2 = new Array(len); i < len; i++)
+ arr2[i] = arr[i];
+ return arr2;
+}
+function _nonIterableSpread() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+var objectPrototypeToString = Object.prototype.toString;
+var jsonDiff = new Diff();
+jsonDiff.useLongestToken = true;
+jsonDiff.tokenize = lineDiff.tokenize;
+jsonDiff.castInput = function(value) {
+ var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
+ return typeof v === "undefined" ? undefinedReplacement : v;
+ } : _this$options$stringi;
+ return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
+};
+jsonDiff.equals = function(left, right) {
+ return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
+};
+function canonicalize(obj, stack, replacementStack, replacer, key2) {
+ stack = stack || [];
+ replacementStack = replacementStack || [];
+ if (replacer) {
+ obj = replacer(key2, obj);
+ }
+ var i;
+ for (i = 0; i < stack.length; i += 1) {
+ if (stack[i] === obj) {
+ return replacementStack[i];
+ }
+ }
+ var canonicalizedObj;
+ if ("[object Array]" === objectPrototypeToString.call(obj)) {
+ stack.push(obj);
+ canonicalizedObj = new Array(obj.length);
+ replacementStack.push(canonicalizedObj);
+ for (i = 0; i < obj.length; i += 1) {
+ canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key2);
+ }
+ stack.pop();
+ replacementStack.pop();
+ return canonicalizedObj;
+ }
+ if (obj && obj.toJSON) {
+ obj = obj.toJSON();
+ }
+ if (_typeof(obj) === "object" && obj !== null) {
+ stack.push(obj);
+ canonicalizedObj = {};
+ replacementStack.push(canonicalizedObj);
+ var sortedKeys = [], _key;
+ for (_key in obj) {
+ if (obj.hasOwnProperty(_key)) {
+ sortedKeys.push(_key);
+ }
+ }
+ sortedKeys.sort();
+ for (i = 0; i < sortedKeys.length; i += 1) {
+ _key = sortedKeys[i];
+ canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
+ }
+ stack.pop();
+ replacementStack.pop();
+ } else {
+ canonicalizedObj = obj;
+ }
+ return canonicalizedObj;
+}
+var arrayDiff = new Diff();
+arrayDiff.tokenize = function(value) {
+ return value.slice();
+};
+arrayDiff.join = arrayDiff.removeEmpty = function(value) {
+ return value;
+};
+function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+ if (!options) {
+ options = {};
+ }
+ if (typeof options.context === "undefined") {
+ options.context = 4;
+ }
+ var diff2 = diffLines(oldStr, newStr, options);
+ if (!diff2) {
+ return;
+ }
+ diff2.push({
+ value: "",
+ lines: []
+ });
+ function contextLines(lines) {
+ return lines.map(function(entry) {
+ return " " + entry;
+ });
+ }
+ var hunks = [];
+ var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
+ var _loop = function _loop2(i2) {
+ var current = diff2[i2], lines = current.lines || current.value.replace(/\n$/, "").split("\n");
+ current.lines = lines;
+ if (current.added || current.removed) {
+ var _curRange;
+ if (!oldRangeStart) {
+ var prev = diff2[i2 - 1];
+ oldRangeStart = oldLine;
+ newRangeStart = newLine;
+ if (prev) {
+ curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
+ oldRangeStart -= curRange.length;
+ newRangeStart -= curRange.length;
+ }
+ }
+ (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) {
+ return (current.added ? "+" : "-") + entry;
+ })));
+ if (current.added) {
+ newLine += lines.length;
+ } else {
+ oldLine += lines.length;
+ }
+ } else {
+ if (oldRangeStart) {
+ if (lines.length <= options.context * 2 && i2 < diff2.length - 2) {
+ var _curRange2;
+ (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
+ } else {
+ var _curRange3;
+ var contextSize = Math.min(lines.length, options.context);
+ (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
+ var hunk = {
+ oldStart: oldRangeStart,
+ oldLines: oldLine - oldRangeStart + contextSize,
+ newStart: newRangeStart,
+ newLines: newLine - newRangeStart + contextSize,
+ lines: curRange
+ };
+ if (i2 >= diff2.length - 2 && lines.length <= options.context) {
+ var oldEOFNewline = /\n$/.test(oldStr);
+ var newEOFNewline = /\n$/.test(newStr);
+ var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
+ if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
+ curRange.splice(hunk.oldLines, 0, "\\ No newline at end of file");
+ }
+ if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
+ curRange.push("\\ No newline at end of file");
+ }
+ }
+ hunks.push(hunk);
+ oldRangeStart = 0;
+ newRangeStart = 0;
+ curRange = [];
+ }
+ }
+ oldLine += lines.length;
+ newLine += lines.length;
+ }
+ };
+ for (var i = 0; i < diff2.length; i++) {
+ _loop(i);
+ }
+ return {
+ oldFileName,
+ newFileName,
+ oldHeader,
+ newHeader,
+ hunks
+ };
+}
+function formatPatch(diff2) {
+ var ret = [];
+ if (diff2.oldFileName == diff2.newFileName) {
+ ret.push("Index: " + diff2.oldFileName);
+ }
+ ret.push("===================================================================");
+ ret.push("--- " + diff2.oldFileName + (typeof diff2.oldHeader === "undefined" ? "" : " " + diff2.oldHeader));
+ ret.push("+++ " + diff2.newFileName + (typeof diff2.newHeader === "undefined" ? "" : " " + diff2.newHeader));
+ for (var i = 0; i < diff2.hunks.length; i++) {
+ var hunk = diff2.hunks[i];
+ if (hunk.oldLines === 0) {
+ hunk.oldStart -= 1;
+ }
+ if (hunk.newLines === 0) {
+ hunk.newStart -= 1;
+ }
+ ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
+ ret.push.apply(ret, hunk.lines);
+ }
+ return ret.join("\n") + "\n";
+}
+function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+ return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
+}
+function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
+ return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
+}
+
+// src/gitManager/isomorphicGit.ts
+var import_obsidian7 = require("obsidian");
+
+// src/ui/modals/generalModal.ts
+init_polyfill_buffer();
+var import_obsidian5 = require("obsidian");
+var generalModalConfigDefaults = {
+ options: [],
+ placeholder: "",
+ allowEmpty: false,
+ onlySelection: false,
+ initialValue: void 0
+};
+var GeneralModal = class extends import_obsidian5.SuggestModal {
+ constructor(config) {
+ super(app);
+ this.config = { ...generalModalConfigDefaults, ...config };
+ this.setPlaceholder(this.config.placeholder);
+ }
+ open() {
+ super.open();
+ if (this.config.initialValue != void 0) {
+ this.inputEl.value = this.config.initialValue;
+ this.inputEl.dispatchEvent(new Event("input"));
+ }
+ return new Promise((resolve) => {
+ this.resolve = resolve;
+ });
+ }
+ selectSuggestion(value, evt) {
+ if (this.resolve) {
+ let res;
+ if (this.config.allowEmpty && value === " ")
+ res = "";
+ else if (value === "...")
+ res = void 0;
+ else
+ res = value;
+ this.resolve(res);
+ }
+ super.selectSuggestion(value, evt);
+ }
+ onClose() {
+ if (this.resolve)
+ this.resolve(void 0);
+ }
+ getSuggestions(query) {
+ if (this.config.onlySelection) {
+ return this.config.options;
+ } else if (this.config.allowEmpty) {
+ return [query.length > 0 ? query : " ", ...this.config.options];
+ } else {
+ return [query.length > 0 ? query : "...", ...this.config.options];
+ }
+ }
+ renderSuggestion(value, el) {
+ el.setText(value);
+ }
+ onChooseSuggestion(item, evt) {
+ }
+};
+
+// src/gitManager/myAdapter.ts
+init_polyfill_buffer();
+var import_obsidian6 = require("obsidian");
+var MyAdapter = class {
+ constructor(vault, plugin) {
+ this.plugin = plugin;
+ this.promises = {};
+ this.adapter = vault.adapter;
+ this.vault = vault;
+ this.lastBasePath = this.plugin.settings.basePath;
+ this.promises.readFile = this.readFile.bind(this);
+ this.promises.writeFile = this.writeFile.bind(this);
+ this.promises.readdir = this.readdir.bind(this);
+ this.promises.mkdir = this.mkdir.bind(this);
+ this.promises.rmdir = this.rmdir.bind(this);
+ this.promises.stat = this.stat.bind(this);
+ this.promises.unlink = this.unlink.bind(this);
+ this.promises.lstat = this.lstat.bind(this);
+ this.promises.readlink = this.readlink.bind(this);
+ this.promises.symlink = this.symlink.bind(this);
+ }
+ async readFile(path2, opts) {
+ var _a2;
+ this.maybeLog("Read: " + path2 + JSON.stringify(opts));
+ if (opts == "utf8" || opts.encoding == "utf8") {
+ const file = this.vault.getAbstractFileByPath(path2);
+ if (file instanceof import_obsidian6.TFile) {
+ this.maybeLog("Reuse");
+ return this.vault.read(file);
+ } else {
+ return this.adapter.read(path2);
+ }
+ } else {
+ if (path2.endsWith(this.gitDir + "/index")) {
+ if (this.plugin.settings.basePath != this.lastBasePath) {
+ this.clearIndex();
+ this.lastBasePath = this.plugin.settings.basePath;
+ return this.adapter.readBinary(path2);
+ }
+ return (_a2 = this.index) != null ? _a2 : this.adapter.readBinary(path2);
+ }
+ const file = this.vault.getAbstractFileByPath(path2);
+ if (file instanceof import_obsidian6.TFile) {
+ this.maybeLog("Reuse");
+ return this.vault.readBinary(file);
+ } else {
+ return this.adapter.readBinary(path2);
+ }
+ }
+ }
+ async writeFile(path2, data) {
+ this.maybeLog("Write: " + path2);
+ if (typeof data === "string") {
+ const file = this.vault.getAbstractFileByPath(path2);
+ if (file instanceof import_obsidian6.TFile) {
+ return this.vault.modify(file, data);
+ } else {
+ return this.adapter.write(path2, data);
+ }
+ } else {
+ if (path2.endsWith(this.gitDir + "/index")) {
+ this.index = data;
+ this.indexmtime = Date.now();
+ } else {
+ const file = this.vault.getAbstractFileByPath(path2);
+ if (file instanceof import_obsidian6.TFile) {
+ return this.vault.modifyBinary(file, data);
+ } else {
+ return this.adapter.writeBinary(path2, data);
+ }
+ }
+ }
+ }
+ async readdir(path2) {
+ if (path2 === ".")
+ path2 = "/";
+ const res = await this.adapter.list(path2);
+ const all = [...res.files, ...res.folders];
+ let formattedAll;
+ if (path2 !== "/") {
+ formattedAll = all.map(
+ (e) => (0, import_obsidian6.normalizePath)(e.substring(path2.length))
+ );
+ } else {
+ formattedAll = all;
+ }
+ return formattedAll;
+ }
+ async mkdir(path2) {
+ return this.adapter.mkdir(path2);
+ }
+ async rmdir(path2, opts) {
+ var _a2, _b;
+ return this.adapter.rmdir(path2, (_b = (_a2 = opts == null ? void 0 : opts.options) == null ? void 0 : _a2.recursive) != null ? _b : false);
+ }
+ async stat(path2) {
+ if (path2.endsWith(this.gitDir + "/index")) {
+ if (this.index !== void 0 && this.indexctime != void 0 && this.indexmtime != void 0) {
+ return {
+ isFile: () => true,
+ isDirectory: () => false,
+ isSymbolicLink: () => false,
+ size: this.index.length,
+ type: "file",
+ ctimeMs: this.indexctime,
+ mtimeMs: this.indexmtime
+ };
+ } else {
+ const stat = await this.adapter.stat(path2);
+ if (stat == void 0) {
+ throw { code: "ENOENT" };
+ }
+ this.indexctime = stat.ctime;
+ this.indexmtime = stat.mtime;
+ return {
+ ctimeMs: stat.ctime,
+ mtimeMs: stat.mtime,
+ size: stat.size,
+ type: "file",
+ isFile: () => true,
+ isDirectory: () => false,
+ isSymbolicLink: () => false
+ };
+ }
+ }
+ if (path2 === ".")
+ path2 = "/";
+ const file = this.vault.getAbstractFileByPath(path2);
+ this.maybeLog("Stat: " + path2);
+ if (file instanceof import_obsidian6.TFile) {
+ this.maybeLog("Reuse stat");
+ return {
+ ctimeMs: file.stat.ctime,
+ mtimeMs: file.stat.mtime,
+ size: file.stat.size,
+ type: "file",
+ isFile: () => true,
+ isDirectory: () => false,
+ isSymbolicLink: () => false
+ };
+ } else {
+ const stat = await this.adapter.stat(path2);
+ if (stat) {
+ return {
+ ctimeMs: stat.ctime,
+ mtimeMs: stat.mtime,
+ size: stat.size,
+ type: stat.type === "folder" ? "directory" : stat.type,
+ isFile: () => stat.type === "file",
+ isDirectory: () => stat.type === "folder",
+ isSymbolicLink: () => false
+ };
+ } else {
+ throw { code: "ENOENT" };
+ }
+ }
+ }
+ async unlink(path2) {
+ return this.adapter.remove(path2);
+ }
+ async lstat(path2) {
+ return this.stat(path2);
+ }
+ async readlink(path2) {
+ throw new Error(`readlink of (${path2}) is not implemented.`);
+ }
+ async symlink(path2) {
+ throw new Error(`symlink of (${path2}) is not implemented.`);
+ }
+ async saveAndClear() {
+ if (this.index !== void 0) {
+ await this.adapter.writeBinary(
+ this.plugin.gitManager.getVaultPath(this.gitDir + "/index"),
+ this.index,
+ {
+ ctime: this.indexctime,
+ mtime: this.indexmtime
+ }
+ );
+ }
+ this.clearIndex();
+ }
+ clearIndex() {
+ this.index = void 0;
+ this.indexctime = void 0;
+ this.indexmtime = void 0;
+ }
+ get gitDir() {
+ return this.plugin.settings.gitDir || ".git";
+ }
+ maybeLog(text2) {
+ }
+};
+
+// src/gitManager/isomorphicGit.ts
+var IsomorphicGit = class extends GitManager {
+ constructor(plugin) {
+ super(plugin);
+ this.FILE = 0;
+ this.HEAD = 1;
+ this.WORKDIR = 2;
+ this.STAGE = 3;
+ // Mapping from statusMatrix to git status codes based off git status --short
+ // See: https://isomorphic-git.org/docs/en/statusMatrix
+ this.status_mapping = {
+ "000": " ",
+ "003": "AD",
+ "020": "??",
+ "022": "A ",
+ "023": "AM",
+ "100": "D ",
+ "101": " D",
+ "103": "MD",
+ "110": "DA",
+ // Technically, two files: first one is deleted "D " and second one is untracked "??"
+ "111": " ",
+ "113": "MM",
+ "120": "DA",
+ // Same as "110"
+ "121": " M",
+ "122": "M ",
+ "123": "MM"
+ };
+ this.noticeLength = 999999;
+ this.fs = new MyAdapter(this.app.vault, this.plugin);
+ }
+ getRepo() {
+ return {
+ fs: this.fs,
+ dir: this.plugin.settings.basePath,
+ gitdir: this.plugin.settings.gitDir || void 0,
+ onAuth: () => {
+ var _a2, _b;
+ return {
+ username: (_a2 = this.plugin.localStorage.getUsername()) != null ? _a2 : void 0,
+ password: (_b = this.plugin.localStorage.getPassword()) != null ? _b : void 0
+ };
+ },
+ onAuthFailure: async () => {
+ new import_obsidian7.Notice(
+ "Authentication failed. Please try with different credentials"
+ );
+ const username = await new GeneralModal({
+ placeholder: "Specify your username"
+ }).open();
+ if (username) {
+ const password = await new GeneralModal({
+ placeholder: "Specify your password/personal access token"
+ }).open();
+ if (password) {
+ this.plugin.localStorage.setUsername(username);
+ this.plugin.localStorage.setPassword(password);
+ return {
+ username,
+ password
+ };
+ }
+ }
+ return { cancel: true };
+ },
+ http: {
+ async request({
+ url,
+ method: method2,
+ headers,
+ body
+ }) {
+ if (body) {
+ body = await collect2(body);
+ body = body.buffer;
+ }
+ const res = await (0, import_obsidian7.requestUrl)({
+ url,
+ method: method2,
+ headers,
+ body,
+ throw: false
+ });
+ return {
+ url,
+ method: method2,
+ headers: res.headers,
+ body: [new Uint8Array(res.arrayBuffer)],
+ statusCode: res.status,
+ statusMessage: res.status.toString()
+ };
+ }
+ }
+ };
+ }
+ async wrapFS(call) {
+ try {
+ const res = await call;
+ await this.fs.saveAndClear();
+ return res;
+ } catch (error) {
+ await this.fs.saveAndClear();
+ throw error;
+ }
+ }
+ async status() {
+ let notice;
+ const timeout = window.setTimeout(function() {
+ notice = new import_obsidian7.Notice(
+ "This takes longer: Getting status",
+ this.noticeLength
+ );
+ }, 2e4);
+ try {
+ this.plugin.setState(1 /* status */);
+ const status2 = (await this.wrapFS(isomorphic_git_default.statusMatrix({ ...this.getRepo() }))).map((row) => this.getFileStatusResult(row));
+ const changed = status2.filter(
+ (fileStatus) => fileStatus.working_dir !== " "
+ );
+ const staged = status2.filter(
+ (fileStatus) => fileStatus.index !== " " && fileStatus.index !== "U"
+ );
+ const conflicted = [];
+ window.clearTimeout(timeout);
+ notice == null ? void 0 : notice.hide();
+ return { all: status2, changed, staged, conflicted };
+ } catch (error) {
+ window.clearTimeout(timeout);
+ notice == null ? void 0 : notice.hide();
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async commitAll({
+ message,
+ status: status2,
+ unstagedFiles
+ }) {
+ try {
+ await this.checkAuthorInfo();
+ await this.stageAll({ status: status2, unstagedFiles });
+ return this.commit({ message });
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async commit({
+ message
+ }) {
+ try {
+ await this.checkAuthorInfo();
+ this.plugin.setState(4 /* commit */);
+ const formatMessage = await this.formatCommitMessage(message);
+ const hadConflict = this.plugin.localStorage.getConflict();
+ let parent = void 0;
+ if (hadConflict) {
+ const branchInfo = await this.branchInfo();
+ parent = [branchInfo.current, branchInfo.tracking];
+ }
+ await this.wrapFS(
+ isomorphic_git_default.commit({
+ ...this.getRepo(),
+ message: formatMessage,
+ parent
+ })
+ );
+ this.plugin.localStorage.setConflict(false);
+ return;
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async stage(filepath, relativeToVault) {
+ const gitPath = this.asRepositoryRelativePath(
+ filepath,
+ relativeToVault
+ );
+ let vaultPath;
+ if (relativeToVault) {
+ vaultPath = filepath;
+ } else {
+ vaultPath = this.getVaultPath(filepath);
+ }
+ try {
+ this.plugin.setState(3 /* add */);
+ if (await this.app.vault.adapter.exists(vaultPath)) {
+ await this.wrapFS(
+ isomorphic_git_default.add({ ...this.getRepo(), filepath: gitPath })
+ );
+ } else {
+ await this.wrapFS(
+ isomorphic_git_default.remove({ ...this.getRepo(), filepath: gitPath })
+ );
+ }
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async stageAll({
+ dir,
+ status: status2,
+ unstagedFiles
+ }) {
+ try {
+ if (status2) {
+ await Promise.all(
+ status2.changed.map(
+ (file) => file.working_dir !== "D" ? this.wrapFS(
+ isomorphic_git_default.add({
+ ...this.getRepo(),
+ filepath: file.path
+ })
+ ) : isomorphic_git_default.remove({
+ ...this.getRepo(),
+ filepath: file.path
+ })
+ )
+ );
+ } else {
+ const filesToStage = unstagedFiles != null ? unstagedFiles : await this.getUnstagedFiles(dir != null ? dir : ".");
+ await Promise.all(
+ filesToStage.map(
+ ({ filepath, deleted }) => deleted ? isomorphic_git_default.remove({ ...this.getRepo(), filepath }) : this.wrapFS(
+ isomorphic_git_default.add({ ...this.getRepo(), filepath })
+ )
+ )
+ );
+ }
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async unstage(filepath, relativeToVault) {
+ try {
+ this.plugin.setState(3 /* add */);
+ filepath = this.asRepositoryRelativePath(filepath, relativeToVault);
+ await this.wrapFS(
+ isomorphic_git_default.resetIndex({ ...this.getRepo(), filepath })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async unstageAll({
+ dir,
+ status: status2
+ }) {
+ try {
+ let staged;
+ if (status2) {
+ staged = status2.staged.map((file) => file.path);
+ } else {
+ const res = await this.getStagedFiles(dir != null ? dir : ".");
+ staged = res.map(({ filepath }) => filepath);
+ }
+ await this.wrapFS(
+ Promise.all(
+ staged.map(
+ (file) => isomorphic_git_default.resetIndex({ ...this.getRepo(), filepath: file })
+ )
+ )
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async discard(filepath) {
+ try {
+ this.plugin.setState(3 /* add */);
+ await this.wrapFS(
+ isomorphic_git_default.checkout({
+ ...this.getRepo(),
+ filepaths: [filepath],
+ force: true
+ })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async discardAll({
+ dir,
+ status: status2
+ }) {
+ let files = [];
+ if (status2) {
+ if (dir != void 0) {
+ files = status2.changed.filter((file) => file.path.startsWith(dir)).map((file) => file.path);
+ } else {
+ files = status2.changed.map((file) => file.path);
+ }
+ } else {
+ files = (await this.getUnstagedFiles(dir)).map(
+ ({ filepath }) => filepath
+ );
+ }
+ try {
+ await this.wrapFS(
+ isomorphic_git_default.checkout({
+ ...this.getRepo(),
+ filepaths: files,
+ force: true
+ })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ getProgressText(action, event) {
+ let out = `${action} progress:`;
+ if (event.phase) {
+ out = `${out} ${event.phase}:`;
+ }
+ if (event.loaded) {
+ out = `${out} ${event.loaded}`;
+ if (event.total) {
+ out = `${out} of ${event.total}`;
+ }
+ }
+ return out;
+ }
+ resolveRef(ref) {
+ return this.wrapFS(isomorphic_git_default.resolveRef({ ...this.getRepo(), ref }));
+ }
+ async pull() {
+ const progressNotice = this.showNotice("Initializing pull");
+ try {
+ this.plugin.setState(2 /* pull */);
+ const localCommit = await this.resolveRef("HEAD");
+ await this.fetch();
+ const branchInfo = await this.branchInfo();
+ await this.checkAuthorInfo();
+ const mergeRes = await this.wrapFS(
+ isomorphic_git_default.merge({
+ ...this.getRepo(),
+ ours: branchInfo.current,
+ theirs: branchInfo.tracking,
+ abortOnConflict: false
+ })
+ );
+ if (!mergeRes.alreadyMerged) {
+ await this.wrapFS(
+ isomorphic_git_default.checkout({
+ ...this.getRepo(),
+ ref: branchInfo.current,
+ onProgress: (progress) => {
+ if (progressNotice !== void 0) {
+ progressNotice.noticeEl.innerText = this.getProgressText("Checkout", progress);
+ }
+ },
+ remote: branchInfo.remote
+ })
+ );
+ }
+ progressNotice == null ? void 0 : progressNotice.hide();
+ const upstreamCommit = await this.resolveRef("HEAD");
+ const changedFiles = await this.getFileChangesCount(
+ localCommit,
+ upstreamCommit
+ );
+ this.showNotice("Finished pull", false);
+ return changedFiles.map((file) => ({
+ path: file.path,
+ working_dir: "P",
+ index: "P",
+ vault_path: this.getVaultPath(file.path)
+ }));
+ } catch (error) {
+ progressNotice == null ? void 0 : progressNotice.hide();
+ if (error instanceof Errors.MergeConflictError) {
+ this.plugin.handleConflict(
+ error.data.filepaths.map((file) => this.getVaultPath(file))
+ );
+ }
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async push() {
+ if (!await this.canPush()) {
+ return 0;
+ }
+ const progressNotice = this.showNotice("Initializing push");
+ try {
+ this.plugin.setState(1 /* status */);
+ const status2 = await this.branchInfo();
+ const trackingBranch = status2.tracking;
+ const currentBranch2 = status2.current;
+ const numChangedFiles = (await this.getFileChangesCount(currentBranch2, trackingBranch)).length;
+ this.plugin.setState(5 /* push */);
+ await this.wrapFS(
+ isomorphic_git_default.push({
+ ...this.getRepo(),
+ onProgress: (progress) => {
+ if (progressNotice !== void 0) {
+ progressNotice.noticeEl.innerText = this.getProgressText("Pushing", progress);
+ }
+ }
+ })
+ );
+ progressNotice == null ? void 0 : progressNotice.hide();
+ return numChangedFiles;
+ } catch (error) {
+ progressNotice == null ? void 0 : progressNotice.hide();
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async getUnpushedCommits() {
+ const status2 = await this.branchInfo();
+ const trackingBranch = status2.tracking;
+ const currentBranch2 = status2.current;
+ if (trackingBranch == null || currentBranch2 == null) {
+ return 0;
+ }
+ const localCommit = await this.resolveRef(currentBranch2);
+ const upstreamCommit = await this.resolveRef(trackingBranch);
+ const changedFiles = await this.getFileChangesCount(
+ localCommit,
+ upstreamCommit
+ );
+ return changedFiles.length;
+ }
+ async canPush() {
+ const status2 = await this.branchInfo();
+ const trackingBranch = status2.tracking;
+ const currentBranch2 = status2.current;
+ const current = await this.resolveRef(currentBranch2);
+ const tracking = await this.resolveRef(trackingBranch);
+ return current != tracking;
+ }
+ async checkRequirements() {
+ const headExists = await this.plugin.app.vault.adapter.exists(
+ `${this.getRepo().dir}/.git/HEAD`
+ );
+ return headExists ? "valid" : "missing-repo";
+ }
+ async branchInfo() {
+ var _a2, _b;
+ try {
+ const current = await isomorphic_git_default.currentBranch(this.getRepo()) || "";
+ const branches = await isomorphic_git_default.listBranches(this.getRepo());
+ const remote = (_a2 = await this.getConfig(`branch.${current}.remote`)) != null ? _a2 : "origin";
+ const trackingBranch = (_b = await this.getConfig(`branch.${current}.merge`)) == null ? void 0 : _b.split("refs/heads")[1];
+ const tracking = trackingBranch ? remote + trackingBranch : void 0;
+ return {
+ current,
+ tracking,
+ branches,
+ remote
+ };
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async getCurrentRemote() {
+ var _a2;
+ const current = await isomorphic_git_default.currentBranch(this.getRepo()) || "";
+ const remote = (_a2 = await this.getConfig(`branch.${current}.remote`)) != null ? _a2 : "origin";
+ return remote;
+ }
+ async checkout(branch2, remote) {
+ try {
+ return this.wrapFS(
+ isomorphic_git_default.checkout({
+ ...this.getRepo(),
+ ref: branch2,
+ force: !!remote,
+ remote
+ })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async createBranch(branch2) {
+ try {
+ await this.wrapFS(
+ isomorphic_git_default.branch({ ...this.getRepo(), ref: branch2, checkout: true })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async deleteBranch(branch2) {
+ try {
+ await this.wrapFS(
+ isomorphic_git_default.deleteBranch({ ...this.getRepo(), ref: branch2 })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async branchIsMerged(_) {
+ return true;
+ }
+ async init() {
+ try {
+ await this.wrapFS(isomorphic_git_default.init(this.getRepo()));
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async clone(url, dir, depth) {
+ const progressNotice = this.showNotice("Initializing clone");
+ try {
+ await this.wrapFS(
+ isomorphic_git_default.clone({
+ ...this.getRepo(),
+ dir,
+ url,
+ depth,
+ onProgress: (progress) => {
+ if (progressNotice !== void 0) {
+ progressNotice.noticeEl.innerText = this.getProgressText("Cloning", progress);
+ }
+ }
+ })
+ );
+ progressNotice == null ? void 0 : progressNotice.hide();
+ } catch (error) {
+ progressNotice == null ? void 0 : progressNotice.hide();
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async setConfig(path2, value) {
+ try {
+ return this.wrapFS(
+ isomorphic_git_default.setConfig({
+ ...this.getRepo(),
+ path: path2,
+ value
+ })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async getConfig(path2) {
+ try {
+ return this.wrapFS(
+ isomorphic_git_default.getConfig({
+ ...this.getRepo(),
+ path: path2
+ })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async fetch(remote) {
+ const progressNotice = this.showNotice("Initializing fetch");
+ try {
+ const args = {
+ ...this.getRepo(),
+ onProgress: (progress) => {
+ if (progressNotice !== void 0) {
+ progressNotice.noticeEl.innerText = this.getProgressText("Fetching", progress);
+ }
+ },
+ remote: remote != null ? remote : await this.getCurrentRemote()
+ };
+ await this.wrapFS(isomorphic_git_default.fetch(args));
+ progressNotice == null ? void 0 : progressNotice.hide();
+ } catch (error) {
+ this.plugin.displayError(error);
+ progressNotice == null ? void 0 : progressNotice.hide();
+ throw error;
+ }
+ }
+ async setRemote(name, url) {
+ try {
+ await this.wrapFS(
+ isomorphic_git_default.addRemote({
+ ...this.getRepo(),
+ remote: name,
+ url,
+ force: true
+ })
+ );
+ } catch (error) {
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async getRemoteBranches(remote) {
+ let remoteBranches = [];
+ remoteBranches.push(
+ ...await this.wrapFS(
+ isomorphic_git_default.listBranches({ ...this.getRepo(), remote })
+ )
+ );
+ remoteBranches.remove("HEAD");
+ remoteBranches = remoteBranches.map((e) => `${remote}/${e}`);
+ return remoteBranches;
+ }
+ async getRemotes() {
+ return (await this.wrapFS(isomorphic_git_default.listRemotes({ ...this.getRepo() }))).map(
+ (remoteUrl) => remoteUrl.remote
+ );
+ }
+ async removeRemote(remoteName) {
+ await this.wrapFS(
+ isomorphic_git_default.deleteRemote({ ...this.getRepo(), remote: remoteName })
+ );
+ }
+ async getRemoteUrl(remote) {
+ var _a2;
+ return (_a2 = (await this.wrapFS(isomorphic_git_default.listRemotes({ ...this.getRepo() }))).filter((item) => item.remote == remote)[0]) == null ? void 0 : _a2.url;
+ }
+ async log(_, __ = true, limit) {
+ const logs = await this.wrapFS(
+ isomorphic_git_default.log({ ...this.getRepo(), depth: limit })
+ );
+ return Promise.all(
+ logs.map(async (log2) => {
+ const completeMessage = log2.commit.message.split("\n\n");
+ return {
+ message: completeMessage[0],
+ body: completeMessage.slice(1).join("\n\n"),
+ date: new Date(
+ log2.commit.committer.timestamp
+ ).toDateString(),
+ diff: {
+ changed: 0,
+ files: (await this.getFileChangesCount(
+ log2.commit.parent.first(),
+ log2.oid
+ )).map((item) => {
+ return {
+ path: item.path,
+ status: item.type,
+ vault_path: this.getVaultPath(item.path),
+ hash: log2.oid,
+ binary: void 0
+ };
+ })
+ },
+ hash: log2.oid,
+ refs: []
+ };
+ })
+ );
+ }
+ updateBasePath(basePath) {
+ this.getRepo().dir = basePath;
+ }
+ async updateUpstreamBranch(remoteBranch) {
+ const [remote, branch2] = splitRemoteBranch(remoteBranch);
+ const branchInfo = await this.branchInfo();
+ await this.setConfig(
+ `branch.${branchInfo.current}.merge`,
+ `refs/heads/${branch2}`
+ );
+ await this.setConfig(`branch.${branch2}.remote`, remote);
+ }
+ updateGitPath(_) {
+ return;
+ }
+ async getFileChangesCount(commitHash1, commitHash2) {
+ return this.walkDifference({
+ walkers: [
+ isomorphic_git_default.TREE({ ref: commitHash1 }),
+ isomorphic_git_default.TREE({ ref: commitHash2 })
+ ]
+ });
+ }
+ async walkDifference({
+ walkers,
+ dir: base
+ }) {
+ const res = await this.wrapFS(
+ isomorphic_git_default.walk({
+ ...this.getRepo(),
+ trees: walkers,
+ map: async function(filepath, [A, B]) {
+ if (!worthWalking2(filepath, base)) {
+ return null;
+ }
+ if (await (A == null ? void 0 : A.type()) === "tree" || await (B == null ? void 0 : B.type()) === "tree") {
+ return;
+ }
+ const Aoid = await (A == null ? void 0 : A.oid());
+ const Boid = await (B == null ? void 0 : B.oid());
+ let type = "equal";
+ if (Aoid !== Boid) {
+ type = "M";
+ }
+ if (Aoid === void 0) {
+ type = "A";
+ }
+ if (Boid === void 0) {
+ type = "D";
+ }
+ if (Aoid === void 0 && Boid === void 0) {
+ console.log("Something weird happened:");
+ console.log(A);
+ console.log(B);
+ }
+ if (type === "equal") {
+ return;
+ }
+ return {
+ path: filepath,
+ type
+ };
+ }
+ })
+ );
+ return res;
+ }
+ async getStagedFiles(dir = ".") {
+ const res = await this.walkDifference({
+ walkers: [isomorphic_git_default.TREE({ ref: "HEAD" }), isomorphic_git_default.STAGE()],
+ dir
+ });
+ return res.map((file) => {
+ return {
+ vault_path: this.getVaultPath(file.path),
+ filepath: file.path
+ };
+ });
+ }
+ async getUnstagedFiles(base = ".") {
+ let notice;
+ const timeout = window.setTimeout(function() {
+ notice = new import_obsidian7.Notice(
+ "This takes longer: Getting status",
+ this.noticeLength
+ );
+ }, 2e4);
+ try {
+ const repo = this.getRepo();
+ const res = await this.wrapFS(
+ //Modified from `git.statusMatrix`
+ isomorphic_git_default.walk({
+ ...repo,
+ trees: [isomorphic_git_default.WORKDIR(), isomorphic_git_default.STAGE()],
+ map: async function(filepath, [workdir, stage]) {
+ if (!stage && workdir) {
+ const isIgnored2 = await isomorphic_git_default.isIgnored({
+ ...repo,
+ filepath
+ });
+ if (isIgnored2) {
+ return null;
+ }
+ }
+ if (!worthWalking2(filepath, base)) {
+ return null;
+ }
+ const [workdirType, stageType] = await Promise.all([
+ workdir && workdir.type(),
+ stage && stage.type()
+ ]);
+ const isBlob = [workdirType, stageType].includes(
+ "blob"
+ );
+ if ((workdirType === "tree" || workdirType === "special") && !isBlob)
+ return;
+ if (stageType === "commit")
+ return null;
+ if ((stageType === "tree" || stageType === "special") && !isBlob)
+ return;
+ const stageOid = stageType === "blob" ? await stage.oid() : void 0;
+ let workdirOid;
+ if (workdirType === "blob" && stageType !== "blob") {
+ workdirOid = "42";
+ } else if (workdirType === "blob") {
+ workdirOid = await workdir.oid();
+ }
+ if (!workdirOid) {
+ return {
+ filepath,
+ deleted: true
+ };
+ }
+ if (workdirOid !== stageOid) {
+ return {
+ filepath,
+ deleted: false
+ };
+ }
+ return null;
+ }
+ })
+ );
+ window.clearTimeout(timeout);
+ notice == null ? void 0 : notice.hide();
+ return res;
+ } catch (error) {
+ window.clearTimeout(timeout);
+ notice == null ? void 0 : notice.hide();
+ this.plugin.displayError(error);
+ throw error;
+ }
+ }
+ async getDiffString(filePath, stagedChanges = false, hash2) {
+ const vaultPath = this.getVaultPath(filePath);
+ const map = async (file, [A]) => {
+ if (filePath == file) {
+ const oid = await A.oid();
+ const contents = await isomorphic_git_default.readBlob({
+ ...this.getRepo(),
+ oid
+ });
+ return contents.blob;
+ }
+ };
+ if (hash2) {
+ const commitContent = await readBlob({
+ ...this.getRepo(),
+ filepath: filePath,
+ oid: hash2
+ }).then((headBlob) => new TextDecoder().decode(headBlob.blob)).catch((err) => {
+ if (err instanceof isomorphic_git_default.Errors.NotFoundError)
+ return void 0;
+ throw err;
+ });
+ const commit2 = await isomorphic_git_default.readCommit({
+ ...this.getRepo(),
+ oid: hash2
+ });
+ const previousContent = await readBlob({
+ ...this.getRepo(),
+ filepath: filePath,
+ oid: commit2.commit.parent.first()
+ }).then((headBlob) => new TextDecoder().decode(headBlob.blob)).catch((err) => {
+ if (err instanceof isomorphic_git_default.Errors.NotFoundError)
+ return void 0;
+ throw err;
+ });
+ const diff2 = createPatch(
+ vaultPath,
+ previousContent != null ? previousContent : "",
+ commitContent != null ? commitContent : ""
+ );
+ return diff2;
+ }
+ const stagedBlob = (await isomorphic_git_default.walk({
+ ...this.getRepo(),
+ trees: [isomorphic_git_default.STAGE()],
+ map
+ })).first();
+ const stagedContent = new TextDecoder().decode(stagedBlob);
+ if (stagedChanges) {
+ const headContent = await this.resolveRef("HEAD").then(
+ (oid) => readBlob({
+ ...this.getRepo(),
+ filepath: filePath,
+ oid
+ })
+ ).then((headBlob) => new TextDecoder().decode(headBlob.blob)).catch((err) => {
+ if (err instanceof isomorphic_git_default.Errors.NotFoundError)
+ return void 0;
+ throw err;
+ });
+ const diff2 = createPatch(
+ vaultPath,
+ headContent != null ? headContent : "",
+ stagedContent
+ );
+ return diff2;
+ } else {
+ let workdirContent;
+ if (await this.app.vault.adapter.exists(vaultPath)) {
+ workdirContent = await this.app.vault.adapter.read(vaultPath);
+ } else {
+ workdirContent = "";
+ }
+ const diff2 = createPatch(vaultPath, stagedContent, workdirContent);
+ return diff2;
+ }
+ }
+ async getLastCommitTime() {
+ const repo = this.getRepo();
+ const oid = await this.resolveRef("HEAD");
+ const commit2 = await isomorphic_git_default.readCommit({ ...repo, oid });
+ const date = commit2.commit.committer.timestamp;
+ return new Date(date * 1e3);
+ }
+ getFileStatusResult(row) {
+ const status2 = this.status_mapping[`${row[this.HEAD]}${row[this.WORKDIR]}${row[this.STAGE]}`];
+ return {
+ index: status2[0] == "?" ? "U" : status2[0],
+ working_dir: status2[1] == "?" ? "U" : status2[1],
+ path: row[this.FILE],
+ vault_path: this.getVaultPath(row[this.FILE])
+ };
+ }
+ async checkAuthorInfo() {
+ const name = await this.getConfig("user.name");
+ const email = await this.getConfig("user.email");
+ if (!name || !email) {
+ throw "Git author information is not set. Please set it in the settings.";
+ }
+ }
+ showNotice(message, infinity = true) {
+ if (!this.plugin.settings.disablePopups) {
+ return new import_obsidian7.Notice(
+ message,
+ infinity ? this.noticeLength : void 0
+ );
+ }
+ }
+};
+function fromValue2(value) {
+ let queue = [value];
+ return {
+ next() {
+ return Promise.resolve({
+ done: queue.length === 0,
+ value: queue.pop()
+ });
+ },
+ return() {
+ queue = [];
+ return {};
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ }
+ };
+}
+function getIterator2(iterable) {
+ if (iterable[Symbol.asyncIterator]) {
+ return iterable[Symbol.asyncIterator]();
+ }
+ if (iterable[Symbol.iterator]) {
+ return iterable[Symbol.iterator]();
+ }
+ if (iterable.next) {
+ return iterable;
+ }
+ return fromValue2(iterable);
+}
+async function forAwait2(iterable, cb) {
+ const iter = getIterator2(iterable);
+ while (true) {
+ const { value, done } = await iter.next();
+ if (value)
+ await cb(value);
+ if (done)
+ break;
+ }
+ if (iter.return)
+ iter.return();
+}
+async function collect2(iterable) {
+ let size = 0;
+ const buffers = [];
+ await forAwait2(iterable, (value) => {
+ buffers.push(value);
+ size += value.byteLength;
+ });
+ const result = new Uint8Array(size);
+ let nextIndex = 0;
+ for (const buffer2 of buffers) {
+ result.set(buffer2, nextIndex);
+ nextIndex += buffer2.byteLength;
+ }
+ return result;
+}
+
+// src/setting/settings.ts
+var FORMAT_STRING_REFERENCE_URL = "https://momentjs.com/docs/#/parsing/string-format/";
+var LINE_AUTHOR_FEATURE_WIKI_LINK = "https://publish.obsidian.md/git-doc/Line+Authoring";
+var ObsidianGitSettingsTab = class extends import_obsidian8.PluginSettingTab {
+ constructor() {
+ super(...arguments);
+ this.lineAuthorColorSettings = /* @__PURE__ */ new Map();
+ }
+ // narrow type from PluginSettingTab.plugin
+ get settings() {
+ return this.plugin.settings;
+ }
display() {
const { containerEl } = this;
const plugin = this.plugin;
@@ -24402,119 +32140,215 @@ var ObsidianGitSettingsTab = class extends import_obsidian7.PluginSettingTab {
containerEl.empty();
containerEl.createEl("h2", { text: "Git Backup settings" });
if (!gitReady) {
- containerEl.createEl("p", { text: "Git is not ready. When all settings are correct you can configure auto backup, etc." });
+ containerEl.createEl("p", {
+ text: "Git is not ready. When all settings are correct you can configure auto backup, etc."
+ });
}
if (gitReady) {
containerEl.createEl("br");
containerEl.createEl("h3", { text: "Automatic" });
- new import_obsidian7.Setting(containerEl).setName("Split automatic commit and push").setDesc("Enable to use separate timer for commit and push").addToggle((toggle) => toggle.setValue(plugin.settings.differentIntervalCommitAndPush).onChange((value) => {
- plugin.settings.differentIntervalCommitAndPush = value;
- plugin.saveSettings();
- plugin.clearAutoBackup();
- plugin.clearAutoPush();
- if (plugin.settings.autoSaveInterval > 0) {
- plugin.startAutoBackup(plugin.settings.autoSaveInterval);
- }
- if (value && plugin.settings.autoPushInterval > 0) {
- plugin.startAutoPush(plugin.settings.autoPushInterval);
- }
- this.display();
- }));
- new import_obsidian7.Setting(containerEl).setName(`Vault ${commitOrBackup} interval (minutes)`).setDesc(`${plugin.settings.differentIntervalCommitAndPush ? "Commit" : "Commit and push"} changes every X minutes. Set to 0 (default) to disable. (See below setting for further configuration!)`).addText((text2) => text2.setValue(String(plugin.settings.autoSaveInterval)).onChange((value) => {
- if (!isNaN(Number(value))) {
- plugin.settings.autoSaveInterval = Number(value);
+ new import_obsidian8.Setting(containerEl).setName("Split automatic commit and push").setDesc("Enable to use separate timer for commit and push").addToggle(
+ (toggle) => toggle.setValue(
+ plugin.settings.differentIntervalCommitAndPush
+ ).onChange((value) => {
+ plugin.settings.differentIntervalCommitAndPush = value;
plugin.saveSettings();
+ plugin.clearAutoBackup();
+ plugin.clearAutoPush();
if (plugin.settings.autoSaveInterval > 0) {
- plugin.clearAutoBackup();
- plugin.startAutoBackup(plugin.settings.autoSaveInterval);
- new import_obsidian7.Notice(`Automatic ${commitOrBackup} enabled! Every ${plugin.settings.autoSaveInterval} minutes.`);
- } else if (plugin.settings.autoSaveInterval <= 0) {
- plugin.clearAutoBackup() && new import_obsidian7.Notice(`Automatic ${commitOrBackup} disabled!`);
+ plugin.startAutoBackup(
+ plugin.settings.autoSaveInterval
+ );
}
- } else {
- new import_obsidian7.Notice("Please specify a valid number.");
- }
- }));
- new import_obsidian7.Setting(containerEl).setName(`If turned on, do auto ${commitOrBackup} every X minutes after last change. Prevents auto ${commitOrBackup} while editing a file. If turned off, do auto ${commitOrBackup} every X minutes. It's independent from last change.`).addToggle((toggle) => toggle.setValue(plugin.settings.autoBackupAfterFileChange).onChange((value) => {
- plugin.settings.autoBackupAfterFileChange = value;
- plugin.saveSettings();
- plugin.clearAutoBackup();
- if (plugin.settings.autoSaveInterval > 0) {
- plugin.startAutoBackup(plugin.settings.autoSaveInterval);
- }
- }));
- if (plugin.settings.differentIntervalCommitAndPush) {
- new import_obsidian7.Setting(containerEl).setName(`Vault push interval (minutes)`).setDesc("Push changes every X minutes. Set to 0 (default) to disable.").addText((text2) => text2.setValue(String(plugin.settings.autoPushInterval)).onChange((value) => {
+ if (value && plugin.settings.autoPushInterval > 0) {
+ plugin.startAutoPush(
+ plugin.settings.autoPushInterval
+ );
+ }
+ this.display();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName(`Vault ${commitOrBackup} interval (minutes)`).setDesc(
+ `${plugin.settings.differentIntervalCommitAndPush ? "Commit" : "Commit and push"} changes every X minutes. Set to 0 (default) to disable. (See below setting for further configuration!)`
+ ).addText(
+ (text2) => text2.setValue(String(plugin.settings.autoSaveInterval)).onChange((value) => {
if (!isNaN(Number(value))) {
- plugin.settings.autoPushInterval = Number(value);
+ plugin.settings.autoSaveInterval = Number(value);
plugin.saveSettings();
- if (plugin.settings.autoPushInterval > 0) {
- plugin.clearAutoPush();
- plugin.startAutoPush(plugin.settings.autoPushInterval);
- new import_obsidian7.Notice(`Automatic push enabled! Every ${plugin.settings.autoPushInterval} minutes.`);
- } else if (plugin.settings.autoPushInterval <= 0) {
- plugin.clearAutoPush() && new import_obsidian7.Notice("Automatic push disabled!");
+ if (plugin.settings.autoSaveInterval > 0) {
+ plugin.clearAutoBackup();
+ plugin.startAutoBackup(
+ plugin.settings.autoSaveInterval
+ );
+ new import_obsidian8.Notice(
+ `Automatic ${commitOrBackup} enabled! Every ${formatMinutes(
+ plugin.settings.autoSaveInterval
+ )}.`
+ );
+ } else if (plugin.settings.autoSaveInterval <= 0) {
+ plugin.clearAutoBackup() && new import_obsidian8.Notice(
+ `Automatic ${commitOrBackup} disabled!`
+ );
}
} else {
- new import_obsidian7.Notice("Please specify a valid number.");
+ new import_obsidian8.Notice("Please specify a valid number.");
}
- }));
+ })
+ );
+ if (!plugin.settings.setLastSaveToLastCommit)
+ new import_obsidian8.Setting(containerEl).setName(`Auto Backup after stopping file edits`).setDesc(
+ `Requires the ${commitOrBackup} interval not to be 0.
+ If turned on, do auto ${commitOrBackup} every ${formatMinutes(
+ plugin.settings.autoSaveInterval
+ )} after stopping file edits.
+ This also prevents auto ${commitOrBackup} while editing a file. If turned off, it's independent from the last change.`
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.autoBackupAfterFileChange).onChange((value) => {
+ plugin.settings.autoBackupAfterFileChange = value;
+ this.display();
+ plugin.saveSettings();
+ plugin.clearAutoBackup();
+ if (plugin.settings.autoSaveInterval > 0) {
+ plugin.startAutoBackup(
+ plugin.settings.autoSaveInterval
+ );
+ }
+ })
+ );
+ if (!plugin.settings.autoBackupAfterFileChange)
+ new import_obsidian8.Setting(containerEl).setName(`Auto ${commitOrBackup} after latest commit`).setDesc(
+ `If turned on, set last auto ${commitOrBackup} time to latest commit`
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.setLastSaveToLastCommit).onChange(async (value) => {
+ plugin.settings.setLastSaveToLastCommit = value;
+ plugin.saveSettings();
+ this.display();
+ plugin.clearAutoBackup();
+ await plugin.setUpAutoBackup();
+ })
+ );
+ if (plugin.settings.differentIntervalCommitAndPush) {
+ new import_obsidian8.Setting(containerEl).setName(`Vault push interval (minutes)`).setDesc(
+ "Push changes every X minutes. Set to 0 (default) to disable."
+ ).addText(
+ (text2) => text2.setValue(String(plugin.settings.autoPushInterval)).onChange((value) => {
+ if (!isNaN(Number(value))) {
+ plugin.settings.autoPushInterval = Number(value);
+ plugin.saveSettings();
+ if (plugin.settings.autoPushInterval > 0) {
+ plugin.clearAutoPush();
+ plugin.startAutoPush(
+ plugin.settings.autoPushInterval
+ );
+ new import_obsidian8.Notice(
+ `Automatic push enabled! Every ${formatMinutes(
+ plugin.settings.autoPushInterval
+ )}.`
+ );
+ } else if (plugin.settings.autoPushInterval <= 0) {
+ plugin.clearAutoPush() && new import_obsidian8.Notice(
+ "Automatic push disabled!"
+ );
+ }
+ } else {
+ new import_obsidian8.Notice(
+ "Please specify a valid number."
+ );
+ }
+ })
+ );
}
- new import_obsidian7.Setting(containerEl).setName("Auto pull interval (minutes)").setDesc("Pull changes every X minutes. Set to 0 (default) to disable.").addText((text2) => text2.setValue(String(plugin.settings.autoPullInterval)).onChange((value) => {
- if (!isNaN(Number(value))) {
- plugin.settings.autoPullInterval = Number(value);
- plugin.saveSettings();
- if (plugin.settings.autoPullInterval > 0) {
- plugin.clearAutoPull();
- plugin.startAutoPull(plugin.settings.autoPullInterval);
- new import_obsidian7.Notice(`Automatic pull enabled! Every ${plugin.settings.autoPullInterval} minutes.`);
- } else if (plugin.settings.autoPullInterval <= 0) {
- plugin.clearAutoPull() && new import_obsidian7.Notice("Automatic pull disabled!");
+ new import_obsidian8.Setting(containerEl).setName("Auto pull interval (minutes)").setDesc(
+ "Pull changes every X minutes. Set to 0 (default) to disable."
+ ).addText(
+ (text2) => text2.setValue(String(plugin.settings.autoPullInterval)).onChange((value) => {
+ if (!isNaN(Number(value))) {
+ plugin.settings.autoPullInterval = Number(value);
+ plugin.saveSettings();
+ if (plugin.settings.autoPullInterval > 0) {
+ plugin.clearAutoPull();
+ plugin.startAutoPull(
+ plugin.settings.autoPullInterval
+ );
+ new import_obsidian8.Notice(
+ `Automatic pull enabled! Every ${formatMinutes(
+ plugin.settings.autoPullInterval
+ )}.`
+ );
+ } else if (plugin.settings.autoPullInterval <= 0) {
+ plugin.clearAutoPull() && new import_obsidian8.Notice("Automatic pull disabled!");
+ }
+ } else {
+ new import_obsidian8.Notice("Please specify a valid number.");
}
- } else {
- new import_obsidian7.Notice("Please specify a valid number.");
- }
- }));
- new import_obsidian7.Setting(containerEl).setName("Commit message on manual backup/commit").setDesc("Available placeholders: {{date}} (see below), {{hostname}} (see below) and {{numFiles}} (number of changed files in the commit)").addText((text2) => text2.setPlaceholder("vault backup: {{date}}").setValue(plugin.settings.commitMessage ? plugin.settings.commitMessage : "").onChange((value) => {
- plugin.settings.commitMessage = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Specify custom commit message on auto backup").setDesc("You will get a pop up to specify your message").addToggle((toggle) => toggle.setValue(plugin.settings.customMessageOnAutoBackup).onChange((value) => {
- plugin.settings.customMessageOnAutoBackup = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Commit message on auto backup/commit").setDesc("Available placeholders: {{date}} (see below), {{hostname}} (see below) and {{numFiles}} (number of changed files in the commit)").addText((text2) => text2.setPlaceholder("vault backup: {{date}}").setValue(plugin.settings.autoCommitMessage).onChange((value) => {
- plugin.settings.autoCommitMessage = value;
- plugin.saveSettings();
- }));
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Specify custom commit message on auto backup").setDesc("You will get a pop up to specify your message").addToggle(
+ (toggle) => toggle.setValue(plugin.settings.customMessageOnAutoBackup).onChange((value) => {
+ plugin.settings.customMessageOnAutoBackup = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Commit message on auto backup/commit").setDesc(
+ "Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message)"
+ ).addTextArea(
+ (text2) => text2.setPlaceholder("vault backup: {{date}}").setValue(plugin.settings.autoCommitMessage).onChange((value) => {
+ plugin.settings.autoCommitMessage = value;
+ plugin.saveSettings();
+ })
+ );
containerEl.createEl("br");
containerEl.createEl("h3", { text: "Commit message" });
- new import_obsidian7.Setting(containerEl).setName("{{date}} placeholder format").setDesc('Specify custom date format. E.g. "YYYY-MM-DD HH:mm:ss"').addText((text2) => text2.setPlaceholder(plugin.settings.commitDateFormat).setValue(plugin.settings.commitDateFormat).onChange(async (value) => {
- plugin.settings.commitDateFormat = value;
- await plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("{{hostname}} placeholder replacement").setDesc("Specify custom hostname for every device.").addText((text2) => {
- var _a2;
- return text2.setValue((_a2 = plugin.localStorage.getHostname()) != null ? _a2 : "").onChange(async (value) => {
- plugin.localStorage.setHostname(value);
- });
- });
- new import_obsidian7.Setting(containerEl).setName("Preview commit message").addButton((button) => button.setButtonText("Preview").onClick(async () => {
- const commitMessagePreview = await plugin.gitManager.formatCommitMessage(plugin.settings.commitMessage);
- new import_obsidian7.Notice(`${commitMessagePreview}`);
- }));
- new import_obsidian7.Setting(containerEl).setName("List filenames affected by commit in the commit body").addToggle((toggle) => toggle.setValue(plugin.settings.listChangedFilesInMessageBody).onChange((value) => {
- plugin.settings.listChangedFilesInMessageBody = value;
- plugin.saveSettings();
- }));
+ new import_obsidian8.Setting(containerEl).setName("Commit message on manual backup/commit").setDesc(
+ "Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message)"
+ ).addTextArea(
+ (text2) => text2.setPlaceholder("vault backup: {{date}}").setValue(
+ plugin.settings.commitMessage ? plugin.settings.commitMessage : ""
+ ).onChange((value) => {
+ plugin.settings.commitMessage = value;
+ plugin.saveSettings();
+ })
+ );
+ const datePlaceholderSetting = new import_obsidian8.Setting(containerEl).setName("{{date}} placeholder format").addText(
+ (text2) => text2.setPlaceholder(plugin.settings.commitDateFormat).setValue(plugin.settings.commitDateFormat).onChange(async (value) => {
+ plugin.settings.commitDateFormat = value;
+ await plugin.saveSettings();
+ })
+ );
+ datePlaceholderSetting.descEl.innerHTML = `
+ Specify custom date format. E.g. "${DATE_TIME_FORMAT_SECONDS}. See Moment.js for more formats.`;
+ new import_obsidian8.Setting(containerEl).setName("{{hostname}} placeholder replacement").setDesc("Specify custom hostname for every device.").addText(
+ (text2) => {
+ var _a2;
+ return text2.setValue((_a2 = plugin.localStorage.getHostname()) != null ? _a2 : "").onChange(async (value) => {
+ plugin.localStorage.setHostname(value);
+ });
+ }
+ );
+ new import_obsidian8.Setting(containerEl).setName("Preview commit message").addButton(
+ (button) => button.setButtonText("Preview").onClick(async () => {
+ const commitMessagePreview = await plugin.gitManager.formatCommitMessage(
+ plugin.settings.commitMessage
+ );
+ new import_obsidian8.Notice(`${commitMessagePreview}`);
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("List filenames affected by commit in the commit body").addToggle(
+ (toggle) => toggle.setValue(plugin.settings.listChangedFilesInMessageBody).onChange((value) => {
+ plugin.settings.listChangedFilesInMessageBody = value;
+ plugin.saveSettings();
+ })
+ );
containerEl.createEl("br");
containerEl.createEl("h3", { text: "Backup" });
if (plugin.gitManager instanceof SimpleGit)
- new import_obsidian7.Setting(containerEl).setName("Sync Method").setDesc("Selects the method used for handling new changes found in your remote git repository.").addDropdown((dropdown) => {
+ new import_obsidian8.Setting(containerEl).setName("Sync Method").setDesc(
+ "Selects the method used for handling new changes found in your remote git repository."
+ ).addDropdown((dropdown) => {
const options = {
- "merge": "Merge",
- "rebase": "Rebase",
- "reset": "Other sync service (Only updates the HEAD without touching the working directory)"
+ merge: "Merge",
+ rebase: "Rebase",
+ reset: "Other sync service (Only updates the HEAD without touching the working directory)"
};
dropdown.addOptions(options);
dropdown.setValue(plugin.settings.syncMethod);
@@ -24523,55 +32357,177 @@ var ObsidianGitSettingsTab = class extends import_obsidian7.PluginSettingTab {
plugin.saveSettings();
});
});
- new import_obsidian7.Setting(containerEl).setName("Pull updates on startup").setDesc("Automatically pull updates when Obsidian starts").addToggle((toggle) => toggle.setValue(plugin.settings.autoPullOnBoot).onChange((value) => {
- plugin.settings.autoPullOnBoot = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Push on backup").setDesc("Disable to only commit changes").addToggle((toggle) => toggle.setValue(!plugin.settings.disablePush).onChange((value) => {
- plugin.settings.disablePush = !value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Pull changes before push").setDesc("Commit -> pull -> push (Only if pushing is enabled)").addToggle((toggle) => toggle.setValue(plugin.settings.pullBeforePush).onChange((value) => {
- plugin.settings.pullBeforePush = value;
- plugin.saveSettings();
- }));
+ new import_obsidian8.Setting(containerEl).setName("Pull updates on startup").setDesc("Automatically pull updates when Obsidian starts").addToggle(
+ (toggle) => toggle.setValue(plugin.settings.autoPullOnBoot).onChange((value) => {
+ plugin.settings.autoPullOnBoot = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Push on backup").setDesc("Disable to only commit changes").addToggle(
+ (toggle) => toggle.setValue(!plugin.settings.disablePush).onChange((value) => {
+ plugin.settings.disablePush = !value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Pull changes before push").setDesc("Commit -> pull -> push (Only if pushing is enabled)").addToggle(
+ (toggle) => toggle.setValue(plugin.settings.pullBeforePush).onChange((value) => {
+ plugin.settings.pullBeforePush = value;
+ plugin.saveSettings();
+ })
+ );
+ if (plugin.gitManager instanceof SimpleGit) {
+ containerEl.createEl("br");
+ containerEl.createEl("h3", { text: "Line author information" });
+ this.addLineAuthorInfoSettings();
+ }
}
containerEl.createEl("br");
containerEl.createEl("h3", { text: "Miscellaneous" });
- new import_obsidian7.Setting(containerEl).setName("Automatically refresh Source Control View on file changes").setDesc("On slower machines this may cause lags. If so, just disable this option").addToggle((toggle) => toggle.setValue(plugin.settings.refreshSourceControl).onChange((value) => {
- plugin.settings.refreshSourceControl = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Source Control View refresh interval").setDesc("Milliseconds to wait after file change before refreshing the Source Control View").addText((toggle) => toggle.setValue(plugin.settings.refreshSourceControlTimer.toString()).setPlaceholder("7000").onChange((value) => {
- plugin.settings.refreshSourceControlTimer = Math.max(parseInt(value), 500);
- plugin.saveSettings();
- plugin.setRefreshDebouncer();
- }));
- new import_obsidian7.Setting(containerEl).setName("Disable notifications").setDesc("Disable notifications for git operations to minimize distraction (refer to status bar for updates). Errors are still shown as notifications even if you enable this setting").addToggle((toggle) => toggle.setValue(plugin.settings.disablePopups).onChange((value) => {
- plugin.settings.disablePopups = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Show status bar").setDesc("Obsidian must be restarted for the changes to take affect").addToggle((toggle) => toggle.setValue(plugin.settings.showStatusBar).onChange((value) => {
- plugin.settings.showStatusBar = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Show branch status bar").setDesc("Obsidian must be restarted for the changes to take affect").addToggle((toggle) => toggle.setValue(plugin.settings.showBranchStatusBar).onChange((value) => {
- plugin.settings.showBranchStatusBar = value;
- plugin.saveSettings();
- }));
- new import_obsidian7.Setting(containerEl).setName("Show changes files count in status bar").addToggle((toggle) => toggle.setValue(plugin.settings.changedFilesInStatusBar).onChange((value) => {
- plugin.settings.changedFilesInStatusBar = value;
- plugin.saveSettings();
- }));
+ new import_obsidian8.Setting(containerEl).setName(
+ "Automatically refresh Source Control View on file changes"
+ ).setDesc(
+ "On slower machines this may cause lags. If so, just disable this option"
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.refreshSourceControl).onChange((value) => {
+ plugin.settings.refreshSourceControl = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Source Control View refresh interval").setDesc(
+ "Milliseconds to wait after file change before refreshing the Source Control View"
+ ).addText(
+ (toggle) => toggle.setValue(
+ plugin.settings.refreshSourceControlTimer.toString()
+ ).setPlaceholder("7000").onChange((value) => {
+ plugin.settings.refreshSourceControlTimer = Math.max(
+ parseInt(value),
+ 500
+ );
+ plugin.saveSettings();
+ plugin.setRefreshDebouncer();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Disable notifications").setDesc(
+ "Disable notifications for git operations to minimize distraction (refer to status bar for updates). Errors are still shown as notifications even if you enable this setting"
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.disablePopups).onChange((value) => {
+ plugin.settings.disablePopups = value;
+ this.display();
+ plugin.saveSettings();
+ })
+ );
+ if (!plugin.settings.disablePopups)
+ new import_obsidian8.Setting(containerEl).setName("Hide notifications for no changes").setDesc(
+ "Don't show notifications when there are no changes to commit/push"
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.disablePopupsForNoChanges).onChange((value) => {
+ plugin.settings.disablePopupsForNoChanges = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Show status bar").setDesc(
+ "Obsidian must be restarted for the changes to take affect"
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.showStatusBar).onChange((value) => {
+ plugin.settings.showStatusBar = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Show stage/unstage button in file menu").addToggle(
+ (toggle) => toggle.setValue(plugin.settings.showFileMenu).onChange((value) => {
+ plugin.settings.showFileMenu = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Show branch status bar").setDesc(
+ "Obsidian must be restarted for the changes to take affect"
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.showBranchStatusBar).onChange((value) => {
+ plugin.settings.showBranchStatusBar = value;
+ plugin.saveSettings();
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Show the count of modified files in the status bar").addToggle(
+ (toggle) => toggle.setValue(plugin.settings.changedFilesInStatusBar).onChange((value) => {
+ plugin.settings.changedFilesInStatusBar = value;
+ plugin.saveSettings();
+ })
+ );
+ containerEl.createEl("br");
+ if (plugin.gitManager instanceof IsomorphicGit) {
+ containerEl.createEl("h3", {
+ text: "Authentication/Commit Author"
+ });
+ } else {
+ containerEl.createEl("h3", { text: "Commit Author" });
+ }
+ if (plugin.gitManager instanceof IsomorphicGit)
+ new import_obsidian8.Setting(containerEl).setName(
+ "Username on your git server. E.g. your username on GitHub"
+ ).addText((cb) => {
+ var _a2;
+ cb.setValue((_a2 = plugin.localStorage.getUsername()) != null ? _a2 : "");
+ cb.onChange((value) => {
+ plugin.localStorage.setUsername(value);
+ });
+ });
+ if (plugin.gitManager instanceof IsomorphicGit)
+ new import_obsidian8.Setting(containerEl).setName("Password/Personal access token").setDesc(
+ "Type in your password. You won't be able to see it again."
+ ).addText((cb) => {
+ cb.inputEl.autocapitalize = "off";
+ cb.inputEl.autocomplete = "off";
+ cb.inputEl.spellcheck = false;
+ cb.onChange((value) => {
+ plugin.localStorage.setPassword(value);
+ });
+ });
+ if (plugin.gitReady)
+ new import_obsidian8.Setting(containerEl).setName("Author name for commit").addText(async (cb) => {
+ cb.setValue(await plugin.gitManager.getConfig("user.name"));
+ cb.onChange((value) => {
+ plugin.gitManager.setConfig(
+ "user.name",
+ value == "" ? void 0 : value
+ );
+ });
+ });
+ if (plugin.gitReady)
+ new import_obsidian8.Setting(containerEl).setName("Author email for commit").addText(async (cb) => {
+ cb.setValue(
+ await plugin.gitManager.getConfig("user.email")
+ );
+ cb.onChange((value) => {
+ plugin.gitManager.setConfig(
+ "user.email",
+ value == "" ? void 0 : value
+ );
+ });
+ });
containerEl.createEl("br");
containerEl.createEl("h3", { text: "Advanced" });
+ if (plugin.gitManager instanceof SimpleGit) {
+ new import_obsidian8.Setting(containerEl).setName("Update submodules").setDesc(
+ '"Create backup" and "pull" takes care of submodules. Missing features: Conflicted files, count of pulled/pushed/committed files. Tracking branch needs to be set for each submodule'
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.updateSubmodules).onChange((value) => {
+ plugin.settings.updateSubmodules = value;
+ plugin.saveSettings();
+ })
+ );
+ if (plugin.settings.updateSubmodules) {
+ new import_obsidian8.Setting(containerEl).setName("Submodule recurse checkout/switch").setDesc(
+ "Whenever a checkout happens on the root repository, recurse the checkout on the submodules (if the branches exist)."
+ ).addToggle(
+ (toggle) => toggle.setValue(plugin.settings.submoduleRecurseCheckout).onChange((value) => {
+ plugin.settings.submoduleRecurseCheckout = value;
+ plugin.saveSettings();
+ })
+ );
+ }
+ }
if (plugin.gitManager instanceof SimpleGit)
- new import_obsidian7.Setting(containerEl).setName("Update submodules").setDesc('"Create backup" and "pull" takes care of submodules. Missing features: Conflicted files, count of pulled/pushed/committed files. Tracking branch needs to be set for each submodule').addToggle((toggle) => toggle.setValue(plugin.settings.updateSubmodules).onChange((value) => {
- plugin.settings.updateSubmodules = value;
- plugin.saveSettings();
- }));
- if (plugin.gitManager instanceof SimpleGit)
- new import_obsidian7.Setting(containerEl).setName("Custom Git binary path").addText((cb) => {
+ new import_obsidian8.Setting(containerEl).setName("Custom Git binary path").addText((cb) => {
var _a2;
cb.setValue((_a2 = plugin.localStorage.getGitPath()) != null ? _a2 : "");
cb.setPlaceholder("git");
@@ -24580,41 +32536,39 @@ var ObsidianGitSettingsTab = class extends import_obsidian7.PluginSettingTab {
plugin.gitManager.updateGitPath(value || "git");
});
});
- if (plugin.gitManager instanceof IsomorphicGit)
- new import_obsidian7.Setting(containerEl).setName("Username on your git server. E.g. your username on GitHub").addText((cb) => {
- cb.setValue(plugin.settings.username);
+ if (plugin.gitManager instanceof SimpleGit)
+ new import_obsidian8.Setting(containerEl).setName("Additional environment variables").setDesc(
+ "Use each line for a new environment variable in the format KEY=VALUE"
+ ).addTextArea((cb) => {
+ cb.setPlaceholder("GIT_DIR=/path/to/git/dir");
+ cb.setValue(plugin.localStorage.getEnvVars().join("\n"));
cb.onChange((value) => {
- plugin.settings.username = value;
- plugin.saveSettings();
+ plugin.localStorage.setEnvVars(value.split("\n"));
});
});
- if (plugin.gitManager instanceof IsomorphicGit)
- new import_obsidian7.Setting(containerEl).setName("Password/Personal access token").setDesc("Type in your password. You won't be able to see it again.").addText((cb) => {
- cb.inputEl.autocapitalize = "off";
- cb.inputEl.autocomplete = "off";
- cb.inputEl.spellcheck = false;
+ if (plugin.gitManager instanceof SimpleGit)
+ new import_obsidian8.Setting(containerEl).setName("Additional PATH environment variable paths").setDesc("Use each line for one path").addTextArea((cb) => {
+ cb.setValue(plugin.localStorage.getPATHPaths().join("\n"));
cb.onChange((value) => {
- plugin.localStorage.setPassword(value);
+ plugin.localStorage.setPATHPaths(value.split("\n"));
});
});
- if (gitReady)
- new import_obsidian7.Setting(containerEl).setName("Author name for commit").addText(async (cb) => {
- cb.setValue(await plugin.gitManager.getConfig("user.name"));
- cb.onChange((value) => {
- plugin.gitManager.setConfig("user.name", value);
+ if (plugin.gitManager instanceof SimpleGit)
+ new import_obsidian8.Setting(containerEl).setName("Reload with new environment variables").setDesc(
+ "Removing previously added environment variables will not take effect until Obsidian is restarted."
+ ).addButton((cb) => {
+ cb.setButtonText("Reload");
+ cb.setCta();
+ cb.onClick(() => {
+ plugin.gitManager.setGitInstance();
});
});
- if (gitReady)
- new import_obsidian7.Setting(containerEl).setName("Author email for commit").addText(async (cb) => {
- cb.setValue(await plugin.gitManager.getConfig("user.email"));
- cb.onChange((value) => {
- plugin.gitManager.setConfig("user.email", value);
- });
- });
- new import_obsidian7.Setting(containerEl).setName("Custom base path (Git repository path)").setDesc(`
+ new import_obsidian8.Setting(containerEl).setName("Custom base path (Git repository path)").setDesc(
+ `
Sets the relative path to the vault from which the Git binary should be executed.
Mostly used to set the path to the Git repository, which is only required if the Git repository is below the vault root directory. Use "\\" instead of "/" on Windows.
- `).addText((cb) => {
+ `
+ ).addText((cb) => {
cb.setValue(plugin.settings.basePath);
cb.setPlaceholder("directory/directory-with-git-repo");
cb.onChange((value) => {
@@ -24623,35 +32577,1425 @@ var ObsidianGitSettingsTab = class extends import_obsidian7.PluginSettingTab {
plugin.gitManager.updateBasePath(value || "");
});
});
- new import_obsidian7.Setting(containerEl).setName("Disable on this device").addToggle((toggle) => toggle.setValue(plugin.localStorage.getPluginDisabled()).onChange((value) => {
- plugin.localStorage.setPluginDisabled(value);
- if (value) {
- plugin.unloadPlugin();
- } else {
- plugin.loadPlugin();
- }
- new import_obsidian7.Notice("Obsidian must be restarted for the changes to take affect");
- }));
- new import_obsidian7.Setting(containerEl).setName("Donate").setDesc("If you like this Plugin, consider donating to support continued development.").addButton((bt) => {
+ new import_obsidian8.Setting(containerEl).setName("Custom Git directory path (Instead of '.git')").setDesc(
+ `Requires restart of Obsidian to take effect. Use "\\" instead of "/" on Windows.`
+ ).addText((cb) => {
+ cb.setValue(plugin.settings.gitDir);
+ cb.setPlaceholder(".git");
+ cb.onChange((value) => {
+ plugin.settings.gitDir = value;
+ plugin.saveSettings();
+ });
+ });
+ new import_obsidian8.Setting(containerEl).setName("Disable on this device").addToggle(
+ (toggle) => toggle.setValue(plugin.localStorage.getPluginDisabled()).onChange((value) => {
+ plugin.localStorage.setPluginDisabled(value);
+ if (value) {
+ plugin.unloadPlugin();
+ } else {
+ plugin.loadPlugin();
+ }
+ new import_obsidian8.Notice(
+ "Obsidian must be restarted for the changes to take affect"
+ );
+ })
+ );
+ new import_obsidian8.Setting(containerEl).setName("Donate").setDesc(
+ "If you like this Plugin, consider donating to support continued development."
+ ).addButton((bt) => {
bt.buttonEl.outerHTML = "
";
});
const info = containerEl.createDiv();
info.setAttr("align", "center");
- info.setText("Debugging and logging:\nYou can always see the logs of this and every other plugin by opening the console with");
+ info.setText(
+ "Debugging and logging:\nYou can always see the logs of this and every other plugin by opening the console with"
+ );
const keys = containerEl.createDiv();
keys.setAttr("align", "center");
keys.addClass("obsidian-git-shortcuts");
- if (import_obsidian7.Platform.isMacOS === true) {
+ if (import_obsidian8.Platform.isMacOS === true) {
keys.createEl("kbd", { text: "CMD (\u2318) + OPTION (\u2325) + I" });
} else {
keys.createEl("kbd", { text: "CTRL + SHIFT + I" });
}
}
+ configureLineAuthorShowStatus(show) {
+ this.settings.lineAuthor.show = show;
+ this.plugin.saveSettings();
+ if (show)
+ this.plugin.lineAuthoringFeature.activateFeature();
+ else
+ this.plugin.lineAuthoringFeature.deactivateFeature();
+ }
+ /**
+ * Persists the setting {@link key} with value {@link value} and
+ * refreshes the line author info views.
+ */
+ lineAuthorSettingHandler(key2, value) {
+ this.settings.lineAuthor[key2] = value;
+ this.plugin.saveSettings();
+ this.plugin.lineAuthoringFeature.refreshLineAuthorViews();
+ }
+ /**
+ * Ensure, that certain last shown values are persisten in the settings.
+ *
+ * Necessary for the line author info gutter context menus.
+ */
+ beforeSaveSettings() {
+ const laSettings = this.settings.lineAuthor;
+ if (laSettings.authorDisplay !== "hide") {
+ laSettings.lastShownAuthorDisplay = laSettings.authorDisplay;
+ }
+ if (laSettings.dateTimeFormatOptions !== "hide") {
+ laSettings.lastShownDateTimeFormatOptions = laSettings.dateTimeFormatOptions;
+ }
+ }
+ addLineAuthorInfoSettings() {
+ const baseLineAuthorInfoSetting = new import_obsidian8.Setting(this.containerEl).setName(
+ "Show commit authoring information next to each line"
+ );
+ if (!this.plugin.lineAuthoringFeature.isAvailableOnCurrentPlatform()) {
+ baseLineAuthorInfoSetting.setDesc("Only available on desktop currently.").setDisabled(true);
+ }
+ baseLineAuthorInfoSetting.descEl.innerHTML = `
+ Feature guide and quick examples
+ The commit hash, author name and authoring date can all be individually toggled.Hide everything, to only show the age-colored sidebar.`;
+ baseLineAuthorInfoSetting.addToggle(
+ (toggle) => toggle.setValue(this.settings.lineAuthor.show).onChange((value) => {
+ this.configureLineAuthorShowStatus(value);
+ this.display();
+ })
+ );
+ if (this.settings.lineAuthor.show) {
+ const trackMovement = new import_obsidian8.Setting(this.containerEl).setName("Follow movement and copies across files and commits").setDesc("").addDropdown((dropdown) => {
+ dropdown.addOptions({
+ inactive: "Do not follow (default)",
+ "same-commit": "Follow within same commit",
+ "all-commits": "Follow within all commits (maybe slow)"
+ });
+ dropdown.setValue(this.settings.lineAuthor.followMovement);
+ dropdown.onChange(
+ (value) => this.lineAuthorSettingHandler("followMovement", value)
+ );
+ });
+ trackMovement.descEl.innerHTML = `
+ By default (deactivated), each line only shows the newest commit where it was changed.
+
+ With same commit, cut-copy-paste-ing of text is followed within the same commit and the original commit of authoring will be shown.
+
+ With all commits, cut-copy-paste-ing text inbetween multiple commits will be detected.
+
+ It uses git-blame and
+ for matches (at least ${GIT_LINE_AUTHORING_MOVEMENT_DETECTION_MINIMAL_LENGTH} characters) within the same (or all) commit(s), the originating commit's information is shown.`;
+ new import_obsidian8.Setting(this.containerEl).setName("Show commit hash").addToggle((tgl) => {
+ tgl.setValue(this.settings.lineAuthor.showCommitHash);
+ tgl.onChange(
+ async (value) => this.lineAuthorSettingHandler("showCommitHash", value)
+ );
+ });
+ new import_obsidian8.Setting(this.containerEl).setName("Author name display").setDesc("If and how the author is displayed").addDropdown((dropdown) => {
+ const options = {
+ hide: "Hide",
+ initials: "Initials (default)",
+ "first name": "First name",
+ "last name": "Last name",
+ full: "Full name"
+ };
+ dropdown.addOptions(options);
+ dropdown.setValue(this.settings.lineAuthor.authorDisplay);
+ dropdown.onChange(
+ async (value) => this.lineAuthorSettingHandler("authorDisplay", value)
+ );
+ });
+ new import_obsidian8.Setting(this.containerEl).setName("Authoring date display").setDesc(
+ "If and how the date and time of authoring the line is displayed"
+ ).addDropdown((dropdown) => {
+ const options = {
+ hide: "Hide",
+ date: "Date (default)",
+ datetime: "Date and time",
+ "natural language": "Natural language",
+ custom: "Custom"
+ };
+ dropdown.addOptions(options);
+ dropdown.setValue(
+ this.settings.lineAuthor.dateTimeFormatOptions
+ );
+ dropdown.onChange(
+ async (value) => {
+ this.lineAuthorSettingHandler(
+ "dateTimeFormatOptions",
+ value
+ );
+ this.display();
+ }
+ );
+ });
+ if (this.settings.lineAuthor.dateTimeFormatOptions === "custom") {
+ const dateTimeFormatCustomStringSetting = new import_obsidian8.Setting(
+ this.containerEl
+ );
+ dateTimeFormatCustomStringSetting.setName("Custom authoring date format").addText((cb) => {
+ cb.setValue(
+ this.settings.lineAuthor.dateTimeFormatCustomString
+ );
+ cb.setPlaceholder("YYYY-MM-DD HH:mm");
+ cb.onChange((value) => {
+ this.lineAuthorSettingHandler(
+ "dateTimeFormatCustomString",
+ value
+ );
+ dateTimeFormatCustomStringSetting.descEl.innerHTML = this.previewCustomDateTimeDescriptionHtml(
+ value
+ );
+ });
+ });
+ dateTimeFormatCustomStringSetting.descEl.innerHTML = this.previewCustomDateTimeDescriptionHtml(
+ this.settings.lineAuthor.dateTimeFormatCustomString
+ );
+ }
+ new import_obsidian8.Setting(this.containerEl).setName("Authoring date display timezone").addDropdown((dropdown) => {
+ const options = {
+ "viewer-local": "My local (default)",
+ "author-local": "Author's local",
+ utc0000: "UTC+0000/Z"
+ };
+ dropdown.addOptions(options);
+ dropdown.setValue(
+ this.settings.lineAuthor.dateTimeTimezone
+ );
+ dropdown.onChange(
+ async (value) => this.lineAuthorSettingHandler("dateTimeTimezone", value)
+ );
+ }).descEl.innerHTML = `
+ The time-zone in which the authoring date should be shown.
+ Either your local time-zone (default),
+ the author's time-zone during commit creation or
+ UTC\xB100:00.
+ `;
+ const oldestAgeSetting = new import_obsidian8.Setting(this.containerEl).setName(
+ "Oldest age in coloring"
+ );
+ oldestAgeSetting.descEl.innerHTML = this.previewOldestAgeDescriptionHtml(
+ this.settings.lineAuthor.coloringMaxAge
+ )[0];
+ oldestAgeSetting.addText((text2) => {
+ text2.setPlaceholder("1y");
+ text2.setValue(this.settings.lineAuthor.coloringMaxAge);
+ text2.onChange((value) => {
+ const [preview, valid] = this.previewOldestAgeDescriptionHtml(value);
+ oldestAgeSetting.descEl.innerHTML = preview;
+ if (valid) {
+ this.lineAuthorSettingHandler("coloringMaxAge", value);
+ this.refreshColorSettingsName("oldest");
+ }
+ });
+ });
+ this.createColorSetting("newest");
+ this.createColorSetting("oldest");
+ new import_obsidian8.Setting(this.containerEl).setName("Text color").addText((field) => {
+ field.setValue(this.settings.lineAuthor.textColorCss);
+ field.onChange((value) => {
+ this.lineAuthorSettingHandler("textColorCss", value);
+ });
+ }).descEl.innerHTML = `
+ The CSS color of the gutter text.
+
+ It is higly recommended to use
+
+ CSS variables
+ defined by themes
+ (e.g. var(--text-muted)
or
+ var(--text-on-accent)
,
+ because they automatically adapt to theme changes.
+
+ See:
+ List of available CSS variables in Obsidian
+
+ `;
+ new import_obsidian8.Setting(this.containerEl).setName("Ignore whitespace and newlines in changes").addToggle((tgl) => {
+ tgl.setValue(this.settings.lineAuthor.ignoreWhitespace);
+ tgl.onChange(
+ (value) => this.lineAuthorSettingHandler("ignoreWhitespace", value)
+ );
+ }).descEl.innerHTML = `
+ Whitespace and newlines are interpreted as
+ part of the document and in changes
+ by default (hence not ignored).
+ This makes the last line being shown as 'changed'
+ when a new subsequent line is added,
+ even if the previously last line's text is the same.
+
+ If you don't care about purely-whitespace changes
+ (e.g. list nesting / quote indentation changes),
+ then activating this will provide more meaningful change detection.
+ `;
+ }
+ }
+ createColorSetting(which) {
+ const setting = new import_obsidian8.Setting(this.containerEl).setName("").addText((text2) => {
+ const color = pickColor(which, this.settings.lineAuthor);
+ const defaultColor = pickColor(
+ which,
+ DEFAULT_SETTINGS.lineAuthor
+ );
+ text2.setPlaceholder(rgbToString(defaultColor));
+ text2.setValue(rgbToString(color));
+ text2.onChange((colorNew) => {
+ const rgb = convertToRgb(colorNew);
+ if (rgb !== void 0) {
+ const key2 = which === "newest" ? "colorNew" : "colorOld";
+ this.lineAuthorSettingHandler(key2, rgb);
+ }
+ this.refreshColorSettingsDesc(which, rgb);
+ });
+ });
+ this.lineAuthorColorSettings.set(which, setting);
+ this.refreshColorSettingsName(which);
+ this.refreshColorSettingsDesc(
+ which,
+ pickColor(which, this.settings.lineAuthor)
+ );
+ }
+ refreshColorSettingsName(which) {
+ const settingsDom = this.lineAuthorColorSettings.get(which);
+ if (settingsDom) {
+ const whichDescriber = which === "oldest" ? `oldest (${this.settings.lineAuthor.coloringMaxAge} or older)` : "newest";
+ settingsDom.nameEl.innerText = `Color for ${whichDescriber} commits`;
+ }
+ }
+ refreshColorSettingsDesc(which, rgb) {
+ const settingsDom = this.lineAuthorColorSettings.get(which);
+ if (settingsDom) {
+ settingsDom.descEl.innerHTML = this.colorSettingPreviewDescHtml(
+ which,
+ this.settings.lineAuthor,
+ rgb !== void 0
+ );
+ }
+ }
+ colorSettingPreviewDescHtml(which, laSettings, colorIsValid) {
+ const rgbStr = colorIsValid ? previewColor(which, laSettings) : `rgba(127,127,127,0.3)`;
+ const today = import_obsidian8.moment.unix(import_obsidian8.moment.now() / 1e3).format("YYYY-MM-DD");
+ const text2 = colorIsValid ? `abcdef Author Name ${today}` : "invalid color";
+ const preview = `${text2}
`;
+ return `Supports 'rgb(r,g,b)', 'hsl(h,s,l)', hex (#) and
+ named colors (e.g. 'black', 'purple'). Color preview: ${preview}`;
+ }
+ previewCustomDateTimeDescriptionHtml(dateTimeFormatCustomString) {
+ const formattedDateTime = (0, import_obsidian8.moment)().format(dateTimeFormatCustomString);
+ return `Format string to display the authoring date.Currently: ${formattedDateTime}`;
+ }
+ previewOldestAgeDescriptionHtml(coloringMaxAge) {
+ const duration = parseColoringMaxAgeDuration(coloringMaxAge);
+ const durationString = duration !== void 0 ? `${duration.asDays()} days` : "invalid!";
+ return [
+ `The oldest age in the line author coloring. Everything older will have the same color.
+ Smallest valid age is "1d". Currently: ${durationString}`,
+ duration
+ ];
+ }
+};
+function pickColor(which, las) {
+ return which === "oldest" ? las.colorOld : las.colorNew;
+}
+function parseColoringMaxAgeDuration(durationString) {
+ const duration = import_obsidian8.moment.duration("P" + durationString.toUpperCase());
+ return duration.isValid() && duration.asDays() && duration.asDays() >= 1 ? duration : void 0;
+}
+
+// src/lineAuthor/model.ts
+function lineAuthoringId(head, objHash, path2) {
+ if (head === void 0 || objHash === void 0 || path2 === void 0) {
+ return void 0;
+ }
+ return `head${head}-obj${objHash}-path${path2}`;
+}
+var LineAuthoringContainerType = import_state.Annotation.define();
+function newComputationResultAsTransaction(key2, la, state) {
+ return state.update({
+ annotations: LineAuthoringContainerType.of({
+ key: key2,
+ la,
+ lineOffsetsFromUnsavedChanges: /* @__PURE__ */ new Map()
+ })
+ });
+}
+function getLineAuthorAnnotation(tr) {
+ return tr.annotation(LineAuthoringContainerType);
+}
+var lineAuthorState = import_state.StateField.define({
+ create: (_state) => void 0,
+ /**
+ * The state can be updated from either an annotated transaction containing
+ * the newest line authoring (for the saved document) - or from
+ * unsaved changes of the document as the user is actively typing in the editor.
+ *
+ * In the first case, we take the new line authoring and discard anything we had remembered
+ * from unsaved changes. In the second case, we use the unsaved changes in {@link enrichUnsavedChanges} to pre-compute information to immediately update the
+ * line author gutter without needing to wait until the document is saved and the
+ * line authoring is properly computed.
+ */
+ update: (previous, transaction) => {
+ var _a2;
+ return (_a2 = getLineAuthorAnnotation(transaction)) != null ? _a2 : enrichUnsavedChanges(transaction, previous);
+ },
+ // compare cache keys.
+ // equality rate is >= 95% :)
+ // hence avoids recomputation of views
+ compare: (l, r) => (l == null ? void 0 : l.key) === (r == null ? void 0 : r.key)
+});
+function laStateDigest(laState) {
+ var _a2;
+ const digest = import_js_sha256.sha256.create();
+ if (!laState)
+ return digest;
+ const { la, key: key2, lineOffsetsFromUnsavedChanges } = laState;
+ digest.update(la === "untracked" ? "t" : "f");
+ digest.update(key2);
+ for (const [k, v] of (_a2 = lineOffsetsFromUnsavedChanges.entries()) != null ? _a2 : [])
+ digest.update([k, v]);
+ return digest;
+}
+var latestSettings = {
+ get: void 0,
+ save: void 0
+};
+function provideSettingsAccess(settingsGetter, settingsSetter) {
+ latestSettings.get = settingsGetter;
+ latestSettings.save = settingsSetter;
+}
+function maxAgeInDaysFromSettings(settings) {
+ var _a2, _b;
+ return (_b = (_a2 = parseColoringMaxAgeDuration(settings.coloringMaxAge)) == null ? void 0 : _a2.asDays()) != null ? _b : parseColoringMaxAgeDuration(
+ DEFAULT_SETTINGS.lineAuthor.coloringMaxAge
+ ).asDays();
+}
+function enrichUnsavedChanges(tr, prev) {
+ if (!prev)
+ return void 0;
+ if (!tr.changes.empty) {
+ tr.changes.iterChanges((fromA, toA, fromB, toB) => {
+ var _a2;
+ const oldDoc = tr.startState.doc;
+ const { newDoc } = tr;
+ const beforeFrom = oldDoc.lineAt(fromA).number;
+ const beforeTo = oldDoc.lineAt(toA).number;
+ const afterFrom = newDoc.lineAt(fromB).number;
+ const afterTo = newDoc.lineAt(toB).number;
+ const beforeLen = beforeTo - beforeFrom + 1;
+ const afterLen = afterTo - afterFrom + 1;
+ for (let afterI = afterFrom; afterI <= afterTo; afterI++) {
+ let offset = (_a2 = prev.lineOffsetsFromUnsavedChanges.get(afterI)) != null ? _a2 : 0;
+ const isLastLine = afterTo === afterI;
+ const changeInNumberOfLines = afterLen - beforeLen;
+ if (isLastLine)
+ offset += changeInNumberOfLines;
+ prev.lineOffsetsFromUnsavedChanges.set(afterI, offset);
+ }
+ });
+ }
+ return prev;
+}
+
+// src/lineAuthor/control.ts
+var LineAuthoringSubscriber = class {
+ // remember path to detect and adapt to renames
+ constructor(state) {
+ this.state = state;
+ this.subscribeMe();
+ }
+ async notifyLineAuthoring(id, la) {
+ if (this.view === void 0) {
+ console.warn(
+ `Git: View is not defined for editor cache key. Unforeseen situation. id: ${id}`
+ );
+ return;
+ }
+ const state = this.view.state;
+ const transaction = newComputationResultAsTransaction(id, la, state);
+ this.view.dispatch(transaction);
+ }
+ updateToNewState(state) {
+ const filepathChanged = this.lastSeenPath && this.filepath != this.lastSeenPath;
+ this.state = state;
+ if (filepathChanged) {
+ this.unsubscribeMe(this.lastSeenPath);
+ this.subscribeMe();
+ }
+ return this;
+ }
+ removeIfStale() {
+ if (this.view.destroyed) {
+ this.unsubscribeMe(this.lastSeenPath);
+ }
+ }
+ subscribeMe() {
+ if (this.filepath === void 0)
+ return;
+ eventsPerFilePathSingleton.ifFilepathDefinedTransformSubscribers(
+ this.filepath,
+ (subs) => subs.add(this)
+ );
+ this.lastSeenPath = this.filepath;
+ }
+ unsubscribeMe(oldFilepath) {
+ eventsPerFilePathSingleton.ifFilepathDefinedTransformSubscribers(
+ oldFilepath,
+ (subs) => subs.delete(this)
+ );
+ }
+ get filepath() {
+ var _a2, _b;
+ return (_b = (_a2 = this.state.field(import_obsidian9.editorViewField)) == null ? void 0 : _a2.file) == null ? void 0 : _b.path;
+ }
+ get view() {
+ return this.state.field(import_obsidian9.editorEditorField);
+ }
+};
+var subscribeNewEditor = import_state2.StateField.define({
+ create: (state) => new LineAuthoringSubscriber(state),
+ update: (v, transaction) => v.updateToNewState(transaction.state),
+ compare: (a, b) => a === b
+});
+
+// src/lineAuthor/view/cache.ts
+init_polyfill_buffer();
+function clearViewCache() {
+ longestRenderedGutter = void 0;
+ renderedAgeInDaysForAdaptiveInitialColoring = [];
+ ageIdx = 0;
+ gutterInstances.clear();
+ gutterMarkersRangeSet.clear();
+ attachedGutterElements.clear();
+}
+var longestRenderedGutter = void 0;
+var getLongestRenderedGutter = () => longestRenderedGutter;
+function conditionallyUpdateLongestRenderedGutter(gutter2, text2) {
+ var _a2;
+ const length = text2.length;
+ if (length < ((_a2 = longestRenderedGutter == null ? void 0 : longestRenderedGutter.length) != null ? _a2 : 0))
+ return;
+ longestRenderedGutter = { gutter: gutter2, length, text: text2 };
+ const settings = latestSettings.get();
+ if (length !== settings.gutterSpacingFallbackLength) {
+ settings.gutterSpacingFallbackLength = length;
+ latestSettings.save(settings);
+ }
+}
+var renderedAgeInDaysForAdaptiveInitialColoring = [];
+var ADAPTIVE_INITIAL_COLORING_AGE_CACHE_SIZE = 15;
+var ageIdx = 0;
+function recordRenderedAgeInDays(age) {
+ renderedAgeInDaysForAdaptiveInitialColoring[ageIdx] = age;
+ ageIdx = (ageIdx + 1) % ADAPTIVE_INITIAL_COLORING_AGE_CACHE_SIZE;
+}
+function computeAdaptiveInitialColoringAgeInDays() {
+ return median(renderedAgeInDaysForAdaptiveInitialColoring);
+}
+var gutterInstances = /* @__PURE__ */ new Map();
+var gutterMarkersRangeSet = /* @__PURE__ */ new Map();
+var attachedGutterElements = /* @__PURE__ */ new Set();
+
+// src/lineAuthor/view/view.ts
+init_polyfill_buffer();
+var import_state3 = require("@codemirror/state");
+var import_view2 = require("@codemirror/view");
+
+// src/lineAuthor/view/gutter/gutter.ts
+init_polyfill_buffer();
+var import_view = require("@codemirror/view");
+var import_js_sha2562 = __toESM(require_sha256());
+var import_obsidian10 = require("obsidian");
+
+// src/lineAuthor/view/contextMenu.ts
+init_polyfill_buffer();
+
+// src/lineAuthor/view/gutter/gutterElementSearch.ts
+init_polyfill_buffer();
+var mouseXY = { x: -10, y: -10 };
+function prepareGutterSearchForContextMenuHandling() {
+ if (mouseXY.x === -10) {
+ window.addEventListener("mousedown", (e) => {
+ mouseXY.x = e.clientX;
+ mouseXY.y = e.clientY;
+ });
+ }
+}
+function findGutterElementUnderMouse() {
+ for (const elt of attachedGutterElements) {
+ if (contains(elt, mouseXY))
+ return elt;
+ }
+}
+function contains(elt, pt) {
+ const { x, y, width, height } = elt.getBoundingClientRect();
+ return x <= pt.x && pt.x <= x + width && y <= pt.y && pt.y <= y + height;
+}
+
+// src/pluginGlobalRef.ts
+init_polyfill_buffer();
+var pluginRef = {};
+
+// src/lineAuthor/view/contextMenu.ts
+var COMMIT_ATTR = "data-commit";
+function handleContextMenu(menu, editor, _mdv) {
+ if (editor.hasFocus())
+ return;
+ const gutterElement = findGutterElementUnderMouse();
+ if (!gutterElement)
+ return;
+ const info = getCommitInfo(gutterElement);
+ if (!info)
+ return;
+ if (!info.isZeroCommit && !info.isWaitingGutter) {
+ addCopyHashMenuItem(info, menu);
+ }
+ addConfigurableLineAuthorSettings("showCommitHash", menu);
+ addConfigurableLineAuthorSettings("authorDisplay", menu);
+ addConfigurableLineAuthorSettings("dateTimeFormatOptions", menu);
+}
+function addCopyHashMenuItem(commit2, menu) {
+ menu.addItem(
+ (item) => item.setTitle("Copy commit hash").setIcon("copy").setSection("obs-git-line-author-copy").onClick((_e) => navigator.clipboard.writeText(commit2.hash))
+ );
+}
+function addConfigurableLineAuthorSettings(key2, menu) {
+ var _a2, _b;
+ let title;
+ let actionNewValue;
+ const settings = pluginRef.plugin.settings.lineAuthor;
+ const currentValue = settings[key2];
+ const currentlyShown = typeof currentValue === "boolean" ? currentValue : currentValue !== "hide";
+ const defaultValue = DEFAULT_SETTINGS.lineAuthor[key2];
+ if (key2 === "showCommitHash") {
+ title = "Show commit hash";
+ actionNewValue = !currentValue;
+ } else if (key2 === "authorDisplay") {
+ const showOption = (_a2 = settings.lastShownAuthorDisplay) != null ? _a2 : defaultValue;
+ title = "Show author " + (currentlyShown ? currentValue : showOption);
+ actionNewValue = currentlyShown ? "hide" : showOption;
+ } else if (key2 === "dateTimeFormatOptions") {
+ const showOption = (_b = settings.lastShownDateTimeFormatOptions) != null ? _b : defaultValue;
+ title = "Show " + (currentlyShown ? currentValue : showOption);
+ title += !title.contains("date") ? " date" : "";
+ actionNewValue = currentlyShown ? "hide" : showOption;
+ } else {
+ impossibleBranch(key2);
+ }
+ menu.addItem(
+ (item) => item.setTitle(title).setSection("obs-git-line-author-configure").setChecked(currentlyShown).onClick(
+ (_e) => {
+ var _a3, _b2;
+ return (_b2 = (_a3 = pluginRef.plugin) == null ? void 0 : _a3.settingsTab) == null ? void 0 : _b2.lineAuthorSettingHandler(
+ key2,
+ actionNewValue
+ );
+ }
+ )
+ );
+}
+function enrichCommitInfoForContextMenu(commit2, isWaitingGutter, elt) {
+ elt.setAttr(
+ COMMIT_ATTR,
+ JSON.stringify({
+ hash: commit2.hash,
+ isZeroCommit: commit2.isZeroCommit,
+ isWaitingGutter
+ })
+ );
+}
+function getCommitInfo(elt) {
+ const commitInfoStr = elt.getAttr(COMMIT_ATTR);
+ return commitInfoStr ? JSON.parse(commitInfoStr) : void 0;
+}
+
+// src/lineAuthor/view/gutter/coloring.ts
+init_polyfill_buffer();
+function previewColor(which, settings) {
+ return which === "oldest" ? coloringBasedOnCommitAge(0, false, settings).color : coloringBasedOnCommitAge(void 0, true, settings).color;
+}
+function coloringBasedOnCommitAge(commitAuthorEpochSeonds, isZeroCommit, settings) {
+ const maxAgeInDays = maxAgeInDaysFromSettings(settings);
+ const epochSecondsNow = Date.now() / 1e3;
+ const authoringEpochSeconds = commitAuthorEpochSeonds != null ? commitAuthorEpochSeonds : 0;
+ const secondsSinceCommit = isZeroCommit ? 0 : epochSecondsNow - authoringEpochSeconds;
+ const daysSinceCommit = secondsSinceCommit / 60 / 60 / 24;
+ const x = Math.pow(
+ Math.clamp(daysSinceCommit / maxAgeInDays, 0, 1),
+ 1 / 2.3
+ );
+ const dark = isDarkMode();
+ const color0 = settings.colorNew;
+ const color1 = settings.colorOld;
+ const scaling = dark ? 0.4 : 1;
+ const r = lin(color0.r, color1.r, x) * scaling;
+ const g = lin(color0.g, color1.g, x) * scaling;
+ const b = lin(color0.b, color1.b, x) * scaling;
+ const a = dark ? 0.75 : 0.25;
+ return { color: `rgba(${r},${g},${b},${a})`, daysSinceCommit };
+}
+function lin(z0, z1, x) {
+ return z0 + (z1 - z0) * x;
+}
+function isDarkMode() {
+ const obsidian = window == null ? void 0 : window.app;
+ return (obsidian == null ? void 0 : obsidian.getTheme()) === "obsidian";
+}
+function setTextColorCssBasedOnSetting(settings) {
+ document.body.style.setProperty(
+ "--obs-git-gutter-text",
+ settings.textColorCss
+ );
+}
+
+// src/lineAuthor/view/gutter/commitChoice.ts
+init_polyfill_buffer();
+function chooseNewestCommit(lineAuthoring, startLine, endLine) {
+ let newest = void 0;
+ for (let line = startLine; line <= endLine; line++) {
+ const currentHash = lineAuthoring.hashPerLine[line];
+ const currentCommit = lineAuthoring.commits.get(currentHash);
+ if (!newest || currentCommit.isZeroCommit || isNewerThan(currentCommit, newest)) {
+ newest = currentCommit;
+ }
+ }
+ return newest;
+}
+function isNewerThan(left, right) {
+ var _a2, _b, _c, _d;
+ const l = (_b = (_a2 = left.author) == null ? void 0 : _a2.epochSeconds) != null ? _b : 0;
+ const r = (_d = (_c = right.author) == null ? void 0 : _c.epochSeconds) != null ? _d : 0;
+ return l > r;
+}
+
+// src/lineAuthor/view/gutter/gutter.ts
+var VALUE_NOT_FOUND_FALLBACK = "-";
+var NEW_CHANGE_CHARACTER = "+";
+var NEW_CHANGE_NUMBER_OF_CHARACTERS = 3;
+var DIFFERING_AUTHOR_COMMITTER_MARKER = "*";
+var NON_WHITESPACE_REGEXP = /\S/g;
+var UNINTRUSIVE_CHARACTER_FOR_WAITING_RENDERING = "%";
+var TextGutter = class extends import_view.GutterMarker {
+ constructor(text2) {
+ super();
+ this.text = text2;
+ }
+ eq(other) {
+ return this.text === (other == null ? void 0 : other.text);
+ }
+ toDOM() {
+ return document.createTextNode(this.text);
+ }
+ destroy(dom) {
+ if (!document.body.contains(dom))
+ dom.remove();
+ }
+};
+var LineAuthoringGutter = class extends import_view.GutterMarker {
+ /**
+ * **This should only be called {@link lineAuthoringGutterMarker}!**
+ *
+ * We want to avoid creating the same instance multiple times for improved performance.
+ */
+ constructor(lineAuthoring, startLine, endLine, key2, settings, options) {
+ super();
+ this.lineAuthoring = lineAuthoring;
+ this.startLine = startLine;
+ this.endLine = endLine;
+ this.key = key2;
+ this.settings = settings;
+ this.options = options;
+ this.point = false;
+ this.elementClass = "obs-git-blame-gutter";
+ }
+ // Equality used by CodeMirror for optimisations
+ eq(other) {
+ return this.key === (other == null ? void 0 : other.key) && this.startLine === (other == null ? void 0 : other.startLine) && this.endLine === (other == null ? void 0 : other.endLine) && (this == null ? void 0 : this.options) === (other == null ? void 0 : other.options);
+ }
+ /**
+ * Renders to a Html node.
+ *
+ * It choses the newest commit within the line-range,
+ * renders it, makes adjustments for fake-commits and finally warps
+ * it into HTML.
+ *
+ * The DOM is actually precomputed with {@link computeDom},
+ * which provides a finaliser to run before the DOM is handed over to CodeMirror.
+ * This is done, because this method is called frequently. It is called,
+ * whenever a gutter gets into the viewport and needs to be rendered.
+ *
+ * The age in days is recorded via {@link recordRenderedAgeInDays} to enable adaptive coloring.
+ */
+ toDOM() {
+ var _a2;
+ this.precomputedDomProvider = (_a2 = this.precomputedDomProvider) != null ? _a2 : this.computeDom();
+ return this.precomputedDomProvider();
+ }
+ destroy(dom) {
+ if (!document.body.contains(dom)) {
+ dom.remove();
+ attachedGutterElements.delete(dom);
+ }
+ }
+ /**
+ * Prepares the DOM for this gutter.
+ */
+ computeDom() {
+ const commit2 = chooseNewestCommit(
+ this.lineAuthoring,
+ this.startLine,
+ this.endLine
+ );
+ let toBeRenderedText = commit2.isZeroCommit ? "" : this.renderNonZeroCommit(commit2);
+ const isTrueCommit = !commit2.isZeroCommit && this.options !== "waiting-for-result";
+ if (isTrueCommit) {
+ conditionallyUpdateLongestRenderedGutter(this, toBeRenderedText);
+ } else {
+ toBeRenderedText = this.adaptTextForFakeCommit(
+ commit2,
+ toBeRenderedText,
+ this.options
+ );
+ }
+ const domProvider = this.createHtmlNode(
+ commit2,
+ toBeRenderedText,
+ this.options === "waiting-for-result"
+ );
+ return domProvider;
+ }
+ createHtmlNode(commit2, text2, isWaitingGutter) {
+ var _a2;
+ const templateElt = window.createDiv();
+ templateElt.innerText = text2;
+ const { color, daysSinceCommit } = coloringBasedOnCommitAge(
+ (_a2 = commit2 == null ? void 0 : commit2.author) == null ? void 0 : _a2.epochSeconds,
+ commit2 == null ? void 0 : commit2.isZeroCommit,
+ this.settings
+ );
+ templateElt.style.backgroundColor = color;
+ enrichCommitInfoForContextMenu(commit2, isWaitingGutter, templateElt);
+ function prepareForDomAttachment() {
+ const elt = templateElt.cloneNode(true);
+ attachedGutterElements.add(elt);
+ if (!isWaitingGutter)
+ recordRenderedAgeInDays(daysSinceCommit);
+ return elt;
+ }
+ return prepareForDomAttachment;
+ }
+ renderNonZeroCommit(commit2) {
+ const optionalShortHash = this.settings.showCommitHash ? this.renderHash(commit2) : "";
+ const optionalAuthorName = this.settings.authorDisplay === "hide" ? "" : `${this.renderAuthorName(
+ commit2,
+ this.settings.authorDisplay
+ )}`;
+ const optionalAuthoringDate = this.settings.dateTimeFormatOptions === "hide" ? "" : `${this.renderAuthoringDate(
+ commit2,
+ this.settings.dateTimeFormatOptions,
+ this.settings.dateTimeFormatCustomString,
+ this.settings.dateTimeTimezone
+ )}`;
+ const parts = [
+ optionalShortHash,
+ optionalAuthorName,
+ optionalAuthoringDate
+ ];
+ return parts.filter((x) => x.length >= 1).join(" ");
+ }
+ renderHash(nonZeroCommit) {
+ return nonZeroCommit.hash.substring(0, 6);
+ }
+ renderAuthorName(nonZeroCommit, authorDisplay) {
+ var _a2, _b, _c, _d;
+ const name = (_b = (_a2 = nonZeroCommit == null ? void 0 : nonZeroCommit.author) == null ? void 0 : _a2.name) != null ? _b : "";
+ const words = name.split(" ").filter((word) => word.length >= 1);
+ let rendered;
+ switch (authorDisplay) {
+ case "initials":
+ rendered = words.map((word) => word[0].toUpperCase()).join("");
+ break;
+ case "first name":
+ rendered = (_c = words.first()) != null ? _c : VALUE_NOT_FOUND_FALLBACK;
+ break;
+ case "last name":
+ rendered = (_d = words.last()) != null ? _d : VALUE_NOT_FOUND_FALLBACK;
+ break;
+ case "full":
+ rendered = name;
+ break;
+ default:
+ return impossibleBranch(authorDisplay);
+ }
+ if (!strictDeepEqual(nonZeroCommit == null ? void 0 : nonZeroCommit.author, nonZeroCommit == null ? void 0 : nonZeroCommit.committer)) {
+ rendered = rendered + DIFFERING_AUTHOR_COMMITTER_MARKER;
+ }
+ return rendered;
+ }
+ renderAuthoringDate(nonZeroCommit, dateTimeFormatOptions, dateTimeFormatCustomString, dateTimeTimezone) {
+ var _a2;
+ const FALLBACK_COMMIT_DATE = "?";
+ if (((_a2 = nonZeroCommit == null ? void 0 : nonZeroCommit.author) == null ? void 0 : _a2.epochSeconds) === void 0)
+ return FALLBACK_COMMIT_DATE;
+ let dateTimeFormatting;
+ switch (dateTimeFormatOptions) {
+ case "date":
+ dateTimeFormatting = DATE_FORMAT;
+ break;
+ case "datetime":
+ dateTimeFormatting = DATE_TIME_FORMAT_MINUTES;
+ break;
+ case "custom":
+ dateTimeFormatting = dateTimeFormatCustomString;
+ break;
+ case "natural language":
+ dateTimeFormatting = (time) => {
+ const diff2 = time.diff((0, import_obsidian10.moment)());
+ const addFluentSuffix = true;
+ return import_obsidian10.moment.duration(diff2).humanize(addFluentSuffix);
+ };
+ break;
+ default:
+ return impossibleBranch(dateTimeFormatOptions);
+ }
+ let authoringDate = import_obsidian10.moment.unix(
+ nonZeroCommit.author.epochSeconds
+ );
+ switch (dateTimeTimezone) {
+ case "viewer-local":
+ break;
+ case "author-local":
+ authoringDate = authoringDate.utcOffset(
+ nonZeroCommit.author.tz
+ );
+ dateTimeFormatting += " Z";
+ break;
+ case "utc0000":
+ authoringDate = authoringDate.utc();
+ dateTimeFormatting += "[Z]";
+ break;
+ default:
+ return impossibleBranch(dateTimeTimezone);
+ }
+ if (typeof dateTimeFormatting === "string") {
+ return authoringDate.format(dateTimeFormatting);
+ } else {
+ return dateTimeFormatting(authoringDate);
+ }
+ }
+ adaptTextForFakeCommit(commit2, toBeRenderedText, options) {
+ var _a2, _b, _c, _d;
+ const original = (_b = (_a2 = getLongestRenderedGutter()) == null ? void 0 : _a2.text) != null ? _b : toBeRenderedText;
+ const fillCharacter = options !== "waiting-for-result" && commit2.isZeroCommit ? NEW_CHANGE_CHARACTER : UNINTRUSIVE_CHARACTER_FOR_WAITING_RENDERING;
+ toBeRenderedText = original.replace(
+ NON_WHITESPACE_REGEXP,
+ fillCharacter
+ );
+ const desiredTextLength = (_d = (_c = latestSettings.get()) == null ? void 0 : _c.gutterSpacingFallbackLength) != null ? _d : toBeRenderedText.length;
+ toBeRenderedText = resizeToLength(
+ toBeRenderedText,
+ desiredTextLength,
+ fillCharacter
+ );
+ if (options !== "waiting-for-result" && commit2.isZeroCommit) {
+ const numberOfLastCharactersToKeep = Math.min(
+ desiredTextLength,
+ NEW_CHANGE_NUMBER_OF_CHARACTERS
+ );
+ toBeRenderedText = prefixOfLengthAsWhitespace(
+ toBeRenderedText,
+ desiredTextLength - numberOfLastCharactersToKeep
+ );
+ }
+ return toBeRenderedText;
+ }
+};
+function lineAuthoringGutterMarker(la, startLine, endLine, key2, settings, options) {
+ const digest = import_js_sha2562.sha256.create();
+ digest.update(Object.values(settings).join(","));
+ digest.update(`s${startLine}-e${endLine}-k${key2}-o${options}`);
+ const cacheKey = digest.hex();
+ const cached = gutterInstances.get(cacheKey);
+ if (cached)
+ return cached;
+ const result = new LineAuthoringGutter(
+ la,
+ startLine,
+ endLine,
+ key2,
+ settings,
+ options
+ );
+ gutterInstances.set(cacheKey, result);
+ return result;
+}
+
+// src/lineAuthor/view/gutter/initial.ts
+init_polyfill_buffer();
+var import_obsidian11 = require("obsidian");
+function initialSpacingGutter() {
+ var _a2, _b;
+ const length = (_b = (_a2 = latestSettings.get()) == null ? void 0 : _a2.gutterSpacingFallbackLength) != null ? _b : DEFAULT_SETTINGS.lineAuthor.gutterSpacingFallbackLength;
+ return new TextGutter(Array(length).fill("-").join(""));
+}
+function initialLineAuthoringGutter(settings) {
+ const { lineAuthoring, ageForInitialRender } = adaptiveInitialColoredWaitingLineAuthoring(settings);
+ return lineAuthoringGutterMarker(
+ lineAuthoring,
+ 1,
+ 1,
+ "initialGutter" + ageForInitialRender,
+ // use a age coloring based cache key
+ settings,
+ "waiting-for-result"
+ );
+}
+function adaptiveInitialColoredWaitingLineAuthoring(settings) {
+ var _a2;
+ const ageForInitialRender = (_a2 = computeAdaptiveInitialColoringAgeInDays()) != null ? _a2 : maxAgeInDaysFromSettings(settings) * 0.25;
+ const slightlyOlderAgeForInitialRender = (0, import_obsidian11.moment)().add(
+ -ageForInitialRender,
+ "days"
+ );
+ const dummyAuthor = {
+ name: "",
+ epochSeconds: momentToEpochSeconds(slightlyOlderAgeForInitialRender),
+ tz: "+0000"
+ };
+ const dummyCommit = {
+ hash: "waiting-for-result",
+ author: dummyAuthor,
+ committer: dummyAuthor,
+ isZeroCommit: false
+ };
+ return {
+ lineAuthoring: {
+ hashPerLine: [void 0, "waiting-for-result"],
+ commits: /* @__PURE__ */ new Map([["waiting-for-result", dummyCommit]])
+ },
+ ageForInitialRender
+ };
+}
+
+// src/lineAuthor/view/gutter/untrackedFile.ts
+init_polyfill_buffer();
+function newUntrackedFileGutter(key2, settings) {
+ const dummyLineAuthoring = {
+ hashPerLine: [void 0, "000000"],
+ commits: /* @__PURE__ */ new Map([["000000", zeroCommit]])
+ };
+ return lineAuthoringGutterMarker(dummyLineAuthoring, 1, 1, key2, settings);
+}
+
+// src/lineAuthor/view/view.ts
+var UNDISPLAYED = new TextGutter("");
+var lineAuthorGutter = (0, import_view2.gutter)({
+ class: "line-author-gutter-container",
+ markers(view) {
+ const lineAuthoring = view.state.field(lineAuthorState, false);
+ return lineAuthoringGutterMarkersRangeSet(view, lineAuthoring);
+ },
+ lineMarkerChange(update2) {
+ const newLineAuthoringId = laStateDigest(
+ update2.state.field(lineAuthorState)
+ );
+ const oldLineAuthoringId = laStateDigest(
+ update2.startState.field(lineAuthorState)
+ );
+ return oldLineAuthoringId !== newLineAuthoringId;
+ },
+ renderEmptyElements: true,
+ initialSpacer: (view) => {
+ temporaryWorkaroundGutterSpacingForRenderedLineAuthoring(view);
+ return initialSpacingGutter();
+ },
+ updateSpacer: (_sp, update2) => {
+ var _a2, _b;
+ temporaryWorkaroundGutterSpacingForRenderedLineAuthoring(update2.view);
+ return (_b = (_a2 = getLongestRenderedGutter()) == null ? void 0 : _a2.gutter) != null ? _b : initialSpacingGutter();
+ }
+});
+function lineAuthoringGutterMarkersRangeSet(view, optLA) {
+ const digest = laStateDigest(optLA);
+ const doc = view.state.doc;
+ const lineBlockEndPos = /* @__PURE__ */ new Map();
+ for (let line = 1; line <= doc.lines; line++) {
+ const from = doc.line(line).from;
+ const to = view.lineBlockAt(from).to;
+ lineBlockEndPos.set(line, [from, to]);
+ digest.update([from, to, 0]);
+ }
+ const laSettings = latestSettings.get();
+ digest.update("s" + Object.values(latestSettings).join(","));
+ const cacheKey = digest.hex();
+ const cached = gutterMarkersRangeSet.get(cacheKey);
+ if (cached)
+ return cached;
+ const { result, allowCache } = computeLineAuthoringGutterMarkersRangeSet(
+ doc,
+ lineBlockEndPos,
+ laSettings,
+ optLA
+ );
+ if (allowCache)
+ gutterMarkersRangeSet.set(cacheKey, result);
+ return result;
+}
+function computeLineAuthoringGutterMarkersRangeSet(doc, blocksPerLine, settings, optLA) {
+ let allowCache = true;
+ const docLastLine = doc.lines;
+ const ranges = [];
+ function add2(from, to, gutter2) {
+ return ranges.push(gutter2.range(from, to));
+ }
+ const lineFrom = computeLineMappingForUnsavedChanges(docLastLine, optLA);
+ const emptyDoc = doc.length === 0;
+ const lastLineIsEmpty = doc.iterLines(docLastLine, docLastLine + 1).next().value === "";
+ for (let startLine = 1; startLine <= docLastLine; startLine++) {
+ const [from, to] = blocksPerLine.get(startLine);
+ const endLine = doc.lineAt(to).number;
+ if (emptyDoc) {
+ add2(from, to, UNDISPLAYED);
+ continue;
+ }
+ if (startLine === docLastLine && lastLineIsEmpty) {
+ add2(from, to, UNDISPLAYED);
+ continue;
+ }
+ if (optLA === void 0) {
+ add2(from, to, initialLineAuthoringGutter(settings));
+ allowCache = false;
+ continue;
+ }
+ const { key: key2, la } = optLA;
+ if (la === "untracked") {
+ add2(from, to, newUntrackedFileGutter(la, settings));
+ continue;
+ }
+ const lastAuthorLine = la.hashPerLine.length - 1;
+ const laStartLine = lineFrom[startLine];
+ const laEndLine = lineFrom[endLine];
+ if (laEndLine && laEndLine > lastAuthorLine) {
+ add2(from, to, UNDISPLAYED);
+ }
+ if (laStartLine !== void 0 && between(1, laStartLine, lastAuthorLine) && laEndLine !== void 0 && between(1, laEndLine, lastAuthorLine)) {
+ add2(
+ from,
+ to,
+ lineAuthoringGutterMarker(
+ la,
+ laStartLine,
+ laEndLine,
+ key2,
+ settings
+ )
+ );
+ continue;
+ }
+ if (lastAuthorLine < 1) {
+ add2(from, to, initialLineAuthoringGutter(settings));
+ allowCache = false;
+ continue;
+ }
+ const start = Math.clamp(laStartLine != null ? laStartLine : startLine, 1, lastAuthorLine);
+ const end = Math.clamp(laEndLine != null ? laEndLine : endLine, 1, lastAuthorLine);
+ add2(
+ from,
+ to,
+ lineAuthoringGutterMarker(
+ la,
+ start,
+ end,
+ key2 + "computing",
+ settings,
+ "waiting-for-result"
+ )
+ );
+ }
+ return { result: import_state3.RangeSet.of(
+ ranges,
+ /* sort = */
+ true
+ ), allowCache };
+}
+function computeLineMappingForUnsavedChanges(docLastLine, optLA) {
+ if (!(optLA == null ? void 0 : optLA.lineOffsetsFromUnsavedChanges)) {
+ return Array.from(new Array(docLastLine + 1), (ln) => ln);
+ }
+ const lineFrom = [void 0];
+ let cumulativeLineOffset = 0;
+ for (let ln = 1; ln <= docLastLine; ln++) {
+ const unsavedChanges = optLA.lineOffsetsFromUnsavedChanges.get(ln);
+ cumulativeLineOffset += unsavedChanges != null ? unsavedChanges : 0;
+ lineFrom[ln] = unsavedChanges === void 0 ? ln - cumulativeLineOffset : void 0;
+ }
+ return lineFrom;
+}
+function temporaryWorkaroundGutterSpacingForRenderedLineAuthoring(view) {
+ const guttersContainers = view.dom.querySelectorAll(
+ ".cm-gutters"
+ );
+ guttersContainers.forEach((cont) => {
+ if (!(cont == null ? void 0 : cont.style))
+ return;
+ if (!cont.style.marginLeft) {
+ cont.style.marginLeft = "unset";
+ }
+ });
+}
+
+// src/lineAuthor/lineAuthorProvider.ts
+var LineAuthorProvider = class {
+ constructor(plugin) {
+ this.plugin = plugin;
+ /**
+ * Saves all computed line authoring results.
+ *
+ * See {@link LineAuthoringId}
+ */
+ this.lineAuthorings = /* @__PURE__ */ new Map();
+ }
+ async trackChanged(file) {
+ this.trackChangedHelper(file).catch((reason) => {
+ console.warn("Git: Error in trackChanged." + reason);
+ return Promise.reject(reason);
+ });
+ }
+ async trackChangedHelper(file) {
+ if (!file)
+ return;
+ if (file.path === void 0) {
+ console.warn(
+ "Git: Attempted to track change of undefined filepath. Unforeseen situation."
+ );
+ return;
+ }
+ this.computeLineAuthorInfo(file.path);
+ }
+ destroy() {
+ this.lineAuthorings.clear();
+ eventsPerFilePathSingleton.clear();
+ clearViewCache();
+ }
+ async computeLineAuthorInfo(filepath) {
+ const gitManager = this.plugin.lineAuthoringFeature.isAvailableOnCurrentPlatform().gitManager;
+ const headRevision = await gitManager.submoduleAwareHeadRevisonInContainingDirectory(
+ filepath
+ );
+ const fileHash = await gitManager.hashObject(filepath);
+ const key2 = lineAuthoringId(headRevision, fileHash, filepath);
+ if (key2 === void 0) {
+ return;
+ }
+ if (this.lineAuthorings.has(key2)) {
+ } else {
+ const gitAuthorResult = await gitManager.blame(
+ filepath,
+ this.plugin.settings.lineAuthor.followMovement,
+ this.plugin.settings.lineAuthor.ignoreWhitespace
+ );
+ this.lineAuthorings.set(key2, gitAuthorResult);
+ }
+ this.notifyComputationResultToSubscribers(filepath, key2);
+ }
+ notifyComputationResultToSubscribers(filepath, key2) {
+ eventsPerFilePathSingleton.ifFilepathDefinedTransformSubscribers(
+ filepath,
+ async (subs) => subs.forEach(
+ (sub) => sub.notifyLineAuthoring(key2, this.lineAuthorings.get(key2))
+ )
+ );
+ }
+};
+var enabledLineAuthorInfoExtensions = import_state4.Prec.high([
+ subscribeNewEditor,
+ lineAuthorState,
+ lineAuthorGutter
+]);
+
+// src/lineAuthor/lineAuthorIntegration.ts
+var LineAuthoringFeature = class {
+ constructor(plg) {
+ this.plg = plg;
+ this.codeMirrorExtensions = [];
+ this.handleWorkspaceLeaf = (leaf) => {
+ const obsView = leaf == null ? void 0 : leaf.view;
+ const file = obsView == null ? void 0 : obsView.file;
+ if (!this.lineAuthorInfoProvider) {
+ console.warn(
+ "Git: undefined lineAuthorInfoProvider. Unexpected situation."
+ );
+ return;
+ }
+ if (file === void 0 || (obsView == null ? void 0 : obsView.allowNoFile) === true)
+ return;
+ this.lineAuthorInfoProvider.trackChanged(file);
+ };
+ }
+ // ========================= INIT and DE-INIT ==========================
+ onLoadPlugin() {
+ this.plg.registerEditorExtension(this.codeMirrorExtensions);
+ provideSettingsAccess(
+ () => this.plg.settings.lineAuthor,
+ (laSettings) => {
+ this.plg.settings.lineAuthor = laSettings;
+ this.plg.saveSettings();
+ }
+ );
+ }
+ conditionallyActivateBySettings() {
+ if (this.plg.settings.lineAuthor.show) {
+ this.activateFeature();
+ }
+ }
+ activateFeature() {
+ try {
+ if (!this.isAvailableOnCurrentPlatform())
+ return;
+ setTextColorCssBasedOnSetting(this.plg.settings.lineAuthor);
+ this.lineAuthorInfoProvider = new LineAuthorProvider(this.plg);
+ this.createEventHandlers();
+ this.activateCodeMirrorExtensions();
+ console.log(this.plg.manifest.name + ": Enabled line authoring.");
+ } catch (e) {
+ console.warn("Git: Error while loading line authoring feature.", e);
+ this.deactivateFeature();
+ }
+ }
+ /**
+ * Deactivates the feature. This function is very defensive, as it is also
+ * called to cleanup, if a critical error in the line authoring has occurred.
+ */
+ deactivateFeature() {
+ var _a2;
+ this.destroyEventHandlers();
+ this.deactivateCodeMirrorExtensions();
+ (_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.destroy();
+ this.lineAuthorInfoProvider = void 0;
+ console.log(this.plg.manifest.name + ": Disabled line authoring.");
+ }
+ isAvailableOnCurrentPlatform() {
+ return {
+ available: this.plg.useSimpleGit && import_obsidian12.Platform.isDesktopApp,
+ gitManager: this.plg.gitManager instanceof SimpleGit ? this.plg.gitManager : void 0
+ };
+ }
+ // ========================= REFRESH ==========================
+ refreshLineAuthorViews() {
+ if (this.plg.settings.lineAuthor.show) {
+ this.deactivateFeature();
+ this.activateFeature();
+ }
+ }
+ // ========================= CODEMIRROR EXTENSIONS ==========================
+ activateCodeMirrorExtensions() {
+ this.codeMirrorExtensions.push(enabledLineAuthorInfoExtensions);
+ this.plg.app.workspace.updateOptions();
+ this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf);
+ }
+ deactivateCodeMirrorExtensions() {
+ for (const ext of this.codeMirrorExtensions) {
+ this.codeMirrorExtensions.remove(ext);
+ }
+ this.plg.app.workspace.updateOptions();
+ }
+ // ========================= HANDLERS ==========================
+ createEventHandlers() {
+ this.gutterContextMenuEvent = this.createGutterContextMenuHandler();
+ this.fileOpenEvent = this.createFileOpenEvent();
+ this.workspaceLeafChangeEvent = this.createWorkspaceLeafChangeEvent();
+ this.fileModificationEvent = this.createVaultFileModificationHandler();
+ this.refreshOnCssChangeEvent = this.createCssRefreshHandler();
+ this.fileRenameEvent = this.createFileRenameEvent();
+ prepareGutterSearchForContextMenuHandling();
+ this.plg.registerEvent(this.gutterContextMenuEvent);
+ this.plg.registerEvent(this.refreshOnCssChangeEvent);
+ this.plg.registerEvent(this.fileOpenEvent);
+ this.plg.registerEvent(this.workspaceLeafChangeEvent);
+ this.plg.registerEvent(this.fileModificationEvent);
+ this.plg.registerEvent(this.fileRenameEvent);
+ }
+ destroyEventHandlers() {
+ this.plg.app.workspace.offref(this.refreshOnCssChangeEvent);
+ this.plg.app.workspace.offref(this.fileOpenEvent);
+ this.plg.app.workspace.offref(this.workspaceLeafChangeEvent);
+ this.plg.app.workspace.offref(this.refreshOnCssChangeEvent);
+ this.plg.app.vault.offref(this.fileRenameEvent);
+ this.plg.app.workspace.offref(this.gutterContextMenuEvent);
+ }
+ createFileOpenEvent() {
+ return this.plg.app.workspace.on(
+ "file-open",
+ (file) => {
+ var _a2;
+ return (_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.trackChanged(file);
+ }
+ );
+ }
+ createWorkspaceLeafChangeEvent() {
+ return this.plg.app.workspace.on(
+ "active-leaf-change",
+ this.handleWorkspaceLeaf
+ );
+ }
+ createFileRenameEvent() {
+ return this.plg.app.vault.on(
+ "rename",
+ (file, _old) => {
+ var _a2;
+ return file instanceof import_obsidian12.TFile && ((_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.trackChanged(file));
+ }
+ );
+ }
+ createVaultFileModificationHandler() {
+ return this.plg.app.vault.on(
+ "modify",
+ (anyPath) => {
+ var _a2;
+ return anyPath instanceof import_obsidian12.TFile && ((_a2 = this.lineAuthorInfoProvider) == null ? void 0 : _a2.trackChanged(anyPath));
+ }
+ );
+ }
+ createCssRefreshHandler() {
+ return this.plg.app.workspace.on(
+ "css-change",
+ () => this.refreshLineAuthorViews()
+ );
+ }
+ createGutterContextMenuHandler() {
+ return this.plg.app.workspace.on("editor-menu", handleContextMenu);
+ }
+};
+
+// src/promiseQueue.ts
+init_polyfill_buffer();
+var PromiseQueue = class {
+ constructor() {
+ this.tasks = [];
+ }
+ addTask(task) {
+ this.tasks.push(task);
+ if (this.tasks.length === 1) {
+ this.handleTask();
+ }
+ }
+ async handleTask() {
+ if (this.tasks.length > 0) {
+ this.tasks[0]().finally(() => {
+ this.tasks.shift();
+ this.handleTask();
+ });
+ }
+ }
};
// src/statusBar.ts
init_polyfill_buffer();
-var import_obsidian8 = __toModule(require("obsidian"));
+var import_obsidian13 = require("obsidian");
var StatusBar = class {
constructor(statusBarEl, plugin) {
this.statusBarEl = statusBarEl;
@@ -24659,6 +34003,8 @@ var StatusBar = class {
this.messages = [];
this.base = "obsidian-git-statusbar-";
this.statusBarEl.setAttribute("aria-label-position", "top");
+ this.statusBarEl.setAttribute("data-tooltip-position", "top");
+ addEventListener("git-refresh", this.refreshCommitTimestamp.bind(this));
}
displayMessage(message, timeout) {
this.messages.push({
@@ -24694,75 +34040,89 @@ var StatusBar = class {
this.iconEl.style.float = "left";
}
switch (this.plugin.state) {
- case PluginState.idle:
- this.displayFromNow(this.plugin.lastUpdate);
+ case 0 /* idle */:
+ this.displayFromNow();
break;
- case PluginState.status:
+ case 1 /* status */:
this.statusBarEl.ariaLabel = "Checking repository status...";
- (0, import_obsidian8.setIcon)(this.iconEl, "refresh-cw");
+ (0, import_obsidian13.setIcon)(this.iconEl, "refresh-cw");
this.statusBarEl.addClass(this.base + "status");
break;
- case PluginState.add:
+ case 3 /* add */:
this.statusBarEl.ariaLabel = "Adding files...";
- (0, import_obsidian8.setIcon)(this.iconEl, "refresh-w");
+ (0, import_obsidian13.setIcon)(this.iconEl, "refresh-w");
this.statusBarEl.addClass(this.base + "add");
break;
- case PluginState.commit:
+ case 4 /* commit */:
this.statusBarEl.ariaLabel = "Committing changes...";
- (0, import_obsidian8.setIcon)(this.iconEl, "git-commit");
+ (0, import_obsidian13.setIcon)(this.iconEl, "git-commit");
this.statusBarEl.addClass(this.base + "commit");
break;
- case PluginState.push:
+ case 5 /* push */:
this.statusBarEl.ariaLabel = "Pushing changes...";
- (0, import_obsidian8.setIcon)(this.iconEl, "upload");
+ (0, import_obsidian13.setIcon)(this.iconEl, "upload");
this.statusBarEl.addClass(this.base + "push");
break;
- case PluginState.pull:
+ case 2 /* pull */:
this.statusBarEl.ariaLabel = "Pulling changes...";
- (0, import_obsidian8.setIcon)(this.iconEl, "download");
+ (0, import_obsidian13.setIcon)(this.iconEl, "download");
this.statusBarEl.addClass(this.base + "pull");
break;
- case PluginState.conflicted:
+ case 6 /* conflicted */:
this.statusBarEl.ariaLabel = "You have conflict files...";
- (0, import_obsidian8.setIcon)(this.iconEl, "alert-circle");
+ (0, import_obsidian13.setIcon)(this.iconEl, "alert-circle");
this.statusBarEl.addClass(this.base + "conflict");
break;
default:
this.statusBarEl.ariaLabel = "Failed on initialization!";
- (0, import_obsidian8.setIcon)(this.iconEl, "alert-triangle");
+ (0, import_obsidian13.setIcon)(this.iconEl, "alert-triangle");
this.statusBarEl.addClass(this.base + "failed-init");
break;
}
}
- displayFromNow(timestamp) {
+ displayFromNow() {
+ var _a2;
+ const timestamp = this.lastCommitTimestamp;
if (timestamp) {
- const moment = window.moment;
- const fromNow = moment(timestamp).fromNow();
- this.statusBarEl.ariaLabel = `${this.plugin.offlineMode ? "Offline: " : ""}Last Git update: ${fromNow}`;
+ const moment5 = window.moment;
+ const fromNow = moment5(timestamp).fromNow();
+ this.statusBarEl.ariaLabel = `${this.plugin.offlineMode ? "Offline: " : ""}Last Commit: ${fromNow}`;
+ if ((_a2 = this.unPushedCommits) != null ? _a2 : 0 > 0) {
+ this.statusBarEl.ariaLabel += `
+(${this.unPushedCommits} unpushed commits)`;
+ }
} else {
this.statusBarEl.ariaLabel = this.plugin.offlineMode ? "Git is offline" : "Git is ready";
}
if (this.plugin.offlineMode) {
- (0, import_obsidian8.setIcon)(this.iconEl, "globe");
+ (0, import_obsidian13.setIcon)(this.iconEl, "globe");
} else {
- (0, import_obsidian8.setIcon)(this.iconEl, "check");
+ (0, import_obsidian13.setIcon)(this.iconEl, "check");
}
if (this.plugin.settings.changedFilesInStatusBar && this.plugin.cachedStatus) {
- this.textEl.setText(this.plugin.cachedStatus.changed.length.toString());
+ this.textEl.setText(
+ this.plugin.cachedStatus.changed.length.toString()
+ );
}
this.statusBarEl.addClass(this.base + "idle");
}
+ async refreshCommitTimestamp() {
+ this.lastCommitTimestamp = await this.plugin.gitManager.getLastCommitTime();
+ this.unPushedCommits = await this.plugin.gitManager.getUnpushedCommits();
+ }
};
// src/ui/modals/changedFilesModal.ts
init_polyfill_buffer();
-var import_obsidian9 = __toModule(require("obsidian"));
-var ChangedFilesModal = class extends import_obsidian9.FuzzySuggestModal {
+var import_obsidian14 = require("obsidian");
+var ChangedFilesModal = class extends import_obsidian14.FuzzySuggestModal {
constructor(plugin, changedFiles) {
super(plugin.app);
this.plugin = plugin;
this.changedFiles = changedFiles;
- this.setPlaceholder("Not supported files will be opened by default app!");
+ this.setPlaceholder(
+ "Not supported files will be opened by default app!"
+ );
}
getItems() {
return this.changedFiles;
@@ -24774,13 +34134,16 @@ var ChangedFilesModal = class extends import_obsidian9.FuzzySuggestModal {
let working_dir = "";
let index2 = "";
if (item.working_dir != " ")
- working_dir = `Working dir: ${item.working_dir} `;
+ working_dir = `Working Dir: ${item.working_dir} `;
if (item.index != " ")
index2 = `Index: ${item.index}`;
return `${working_dir}${index2} | ${item.vault_path}`;
}
onChooseItem(item, _) {
- if (this.plugin.app.metadataCache.getFirstLinkpathDest(item.vault_path, "") == null) {
+ if (this.plugin.app.metadataCache.getFirstLinkpathDest(
+ item.vault_path,
+ ""
+ ) == null) {
this.app.openWithDefaultApp(item.vault_path);
} else {
this.plugin.app.workspace.openLinkText(item.vault_path, "/");
@@ -24790,14 +34153,16 @@ var ChangedFilesModal = class extends import_obsidian9.FuzzySuggestModal {
// src/ui/modals/customMessageModal.ts
init_polyfill_buffer();
-var import_obsidian10 = __toModule(require("obsidian"));
-var CustomMessageModal = class extends import_obsidian10.SuggestModal {
+var import_obsidian15 = require("obsidian");
+var CustomMessageModal = class extends import_obsidian15.SuggestModal {
constructor(plugin, fromAutoBackup) {
super(plugin.app);
this.fromAutoBackup = fromAutoBackup;
this.resolve = null;
this.plugin = plugin;
- this.setPlaceholder("Type your message and select optional the version with the added date.");
+ this.setPlaceholder(
+ "Type your message and select optional the version with the added date."
+ );
}
open() {
super.open();
@@ -24827,48 +34192,82 @@ var CustomMessageModal = class extends import_obsidian10.SuggestModal {
}
};
-// src/constants.ts
+// src/openInGitHub.ts
init_polyfill_buffer();
-var import_obsidian11 = __toModule(require("obsidian"));
-var DEFAULT_SETTINGS = {
- commitMessage: "vault backup: {{date}}",
- autoCommitMessage: void 0,
- commitDateFormat: "YYYY-MM-DD HH:mm:ss",
- autoSaveInterval: 0,
- autoPushInterval: 0,
- autoPullInterval: 0,
- autoPullOnBoot: false,
- disablePush: false,
- pullBeforePush: true,
- disablePopups: false,
- listChangedFilesInMessageBody: false,
- showStatusBar: true,
- updateSubmodules: false,
- syncMethod: "merge",
- customMessageOnAutoBackup: false,
- autoBackupAfterFileChange: false,
- treeStructure: false,
- refreshSourceControl: import_obsidian11.Platform.isDesktopApp,
- basePath: "",
- differentIntervalCommitAndPush: false,
- changedFilesInStatusBar: false,
- username: "",
- showedMobileNotice: false,
- refreshSourceControlTimer: 7e3,
- showBranchStatusBar: true
-};
-var GIT_VIEW_CONFIG = {
- type: "git-view",
- name: "Source Control",
- icon: "git-pull-request"
-};
-var DIFF_VIEW_CONFIG = {
- type: "diff-view",
- name: "Diff View",
- icon: "git-pull-request"
-};
+var import_obsidian16 = require("obsidian");
+async function openLineInGitHub(editor, file, manager) {
+ const data = await getData(manager);
+ if (data.result === "failure") {
+ new import_obsidian16.Notice(data.reason);
+ return;
+ }
+ const { isGitHub, branch: branch2, repo, user } = data;
+ if (isGitHub) {
+ const path2 = manager.asRepositoryRelativePath(file.path, true);
+ const from = editor.getCursor("from").line + 1;
+ const to = editor.getCursor("to").line + 1;
+ if (from === to) {
+ window.open(
+ `https://github.com/${user}/${repo}/blob/${branch2}/${path2}?plain=1#L${from}`
+ );
+ } else {
+ window.open(
+ `https://github.com/${user}/${repo}/blob/${branch2}/${path2}?plain=1#L${from}-L${to}`
+ );
+ }
+ } else {
+ new import_obsidian16.Notice("It seems like you are not using GitHub");
+ }
+}
+async function openHistoryInGitHub(file, manager) {
+ const data = await getData(manager);
+ if (data.result === "failure") {
+ new import_obsidian16.Notice(data.reason);
+ return;
+ }
+ const { isGitHub, branch: branch2, repo, user } = data;
+ const path2 = manager.asRepositoryRelativePath(file.path, true);
+ if (isGitHub) {
+ window.open(
+ `https://github.com/${user}/${repo}/commits/${branch2}/${path2}`
+ );
+ } else {
+ new import_obsidian16.Notice("It seems like you are not using GitHub");
+ }
+}
+async function getData(manager) {
+ const branchInfo = await manager.branchInfo();
+ const remoteBranch = branchInfo.tracking;
+ const branch2 = branchInfo.current;
+ if (remoteBranch == null) {
+ return {
+ result: "failure",
+ reason: "Remote branch is not configured"
+ };
+ }
+ if (branch2 == null) {
+ return {
+ result: "failure",
+ reason: "Failed to get current branch name"
+ };
+ }
+ const remote = remoteBranch.substring(0, remoteBranch.indexOf("/"));
+ const remoteUrl = await manager.getConfig(
+ `remote.${remote}.url`
+ );
+ const [isGitHub, httpsUser, httpsRepo, sshUser, sshRepo] = remoteUrl.match(
+ /(?:^https:\/\/github\.com\/(.*)\/(.*)\.git$)|(?:^[a-zA-Z]+@github\.com:(.*)\/(.*)\.git$)/
+ );
+ return {
+ result: "success",
+ isGitHub: !!isGitHub,
+ repo: httpsRepo || sshRepo,
+ user: httpsUser || sshUser,
+ branch: branch2
+ };
+}
-// src/localStorageSettings.ts
+// src/setting/localStorageSettings.ts
init_polyfill_buffer();
var LocalStorageSettings = class {
constructor(plugin) {
@@ -24876,7 +34275,16 @@ var LocalStorageSettings = class {
this.prefix = this.plugin.manifest.id + ":";
}
migrate() {
- const keys = ["password", "hostname", "conflict", "lastAutoPull", "lastAutoBackup", "lastAutoPush", "gitPath", "pluginDisabled"];
+ const keys = [
+ "password",
+ "hostname",
+ "conflict",
+ "lastAutoPull",
+ "lastAutoBackup",
+ "lastAutoPush",
+ "gitPath",
+ "pluginDisabled"
+ ];
for (const key2 of keys) {
const old = localStorage.getItem(this.prefix + key2);
if (app.loadLocalStorage(this.prefix + key2) == null && old != null) {
@@ -24893,6 +34301,12 @@ var LocalStorageSettings = class {
setPassword(value) {
return app.saveLocalStorage(this.prefix + "password", value);
}
+ getUsername() {
+ return app.loadLocalStorage(this.prefix + "username");
+ }
+ setUsername(value) {
+ return app.saveLocalStorage(this.prefix + "username", value);
+ }
getHostname() {
return app.loadLocalStorage(this.prefix + "hostname");
}
@@ -24900,10 +34314,10 @@ var LocalStorageSettings = class {
return app.saveLocalStorage(this.prefix + "hostname", value);
}
getConflict() {
- return app.loadLocalStorage(this.prefix + "conflict");
+ return app.loadLocalStorage(this.prefix + "conflict") == "true";
}
setConflict(value) {
- return app.saveLocalStorage(this.prefix + "conflict", value);
+ return app.saveLocalStorage(this.prefix + "conflict", `${value}`);
}
getLastAutoPull() {
return app.loadLocalStorage(this.prefix + "lastAutoPull");
@@ -24929,6 +34343,25 @@ var LocalStorageSettings = class {
setGitPath(value) {
return app.saveLocalStorage(this.prefix + "gitPath", value);
}
+ getPATHPaths() {
+ var _a2, _b;
+ return (_b = (_a2 = app.loadLocalStorage(this.prefix + "PATHPaths")) == null ? void 0 : _a2.split(":")) != null ? _b : [];
+ }
+ setPATHPaths(value) {
+ return app.saveLocalStorage(this.prefix + "PATHPaths", value.join(":"));
+ }
+ getEnvVars() {
+ var _a2;
+ return JSON.parse(
+ (_a2 = app.loadLocalStorage(this.prefix + "envVars")) != null ? _a2 : "[]"
+ );
+ }
+ setEnvVars(value) {
+ return app.saveLocalStorage(
+ this.prefix + "envVars",
+ JSON.stringify(value)
+ );
+ }
getPluginDisabled() {
return app.loadLocalStorage(this.prefix + "pluginDisabled") == "true";
}
@@ -24937,58 +34370,16 @@ var LocalStorageSettings = class {
}
};
-// src/openInGitHub.ts
-init_polyfill_buffer();
-var import_obsidian12 = __toModule(require("obsidian"));
-async function openLineInGitHub(editor, file, manager) {
- const { isGitHub, branch: branch2, repo, user } = await getData(manager);
- if (isGitHub) {
- const path2 = manager.getPath(file.path, true);
- const from = editor.getCursor("from").line + 1;
- const to = editor.getCursor("to").line + 1;
- if (from === to) {
- window.open(`https://github.com/${user}/${repo}/blob/${branch2}/${path2}?plain=1#L${from}`);
- } else {
- window.open(`https://github.com/${user}/${repo}/blob/${branch2}/${path2}?plain=1#L${from}-L${to}`);
- }
- } else {
- new import_obsidian12.Notice("It seems like you are not using GitHub");
- }
-}
-async function openHistoryInGitHub(file, manager) {
- const { isGitHub, branch: branch2, repo, user } = await getData(manager);
- const path2 = manager.getPath(file.path, true);
- if (isGitHub) {
- window.open(`https://github.com/${user}/${repo}/commits/${branch2}/${path2}`);
- } else {
- new import_obsidian12.Notice("It seems like you are not using GitHub");
- }
-}
-async function getData(manager) {
- const branchInfo = await manager.branchInfo();
- const remoteBranch = branchInfo.tracking;
- const branch2 = branchInfo.current;
- const remote = remoteBranch.substring(0, remoteBranch.indexOf("/"));
- const remoteUrl = await manager.getConfig(`remote.${remote}.url`);
- const [isGitHub, httpsUser, httpsRepo, sshUser, sshRepo] = remoteUrl.match(/(?:^https:\/\/github\.com\/(.*)\/(.*)\.git$)|(?:^git@github\.com:(.*)\/(.*)\.git$)/);
- return {
- isGitHub: !!isGitHub,
- repo: httpsRepo || sshRepo,
- user: httpsUser || sshUser,
- branch: branch2
- };
-}
-
// src/ui/diff/diffView.ts
init_polyfill_buffer();
-// node_modules/diff2html/lib-esm/diff2html.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/diff2html.js
init_polyfill_buffer();
-// node_modules/diff2html/lib-esm/diff-parser.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/diff-parser.js
init_polyfill_buffer();
-// node_modules/diff2html/lib-esm/types.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/types.js
init_polyfill_buffer();
var LineType;
(function(LineType2) {
@@ -25010,7 +34401,7 @@ var DiffStyleType = {
CHAR: "char"
};
-// node_modules/diff2html/lib-esm/utils.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/utils.js
init_polyfill_buffer();
var specials = [
"-",
@@ -25038,8 +34429,8 @@ function unifyPath(path2) {
return path2 ? path2.replace(/\\/g, "/") : path2;
}
function hashCode(text2) {
- var i, chr, len;
- var hash2 = 0;
+ let i, chr, len;
+ let hash2 = 0;
for (i = 0, len = text2.length; i < len; i++) {
chr = text2.charCodeAt(i);
hash2 = (hash2 << 5) - hash2 + chr;
@@ -25048,36 +34439,21 @@ function hashCode(text2) {
return hash2;
}
-// node_modules/diff2html/lib-esm/diff-parser.js
-var __spreadArray = function(to, from, pack) {
- if (pack || arguments.length === 2)
- for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar)
- ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
-};
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/diff-parser.js
function getExtension(filename, language) {
- var filenameParts = filename.split(".");
+ const filenameParts = filename.split(".");
return filenameParts.length > 1 ? filenameParts[filenameParts.length - 1] : language;
}
function startsWithAny(str, prefixes) {
- return prefixes.reduce(function(startsWith, prefix) {
- return startsWith || str.startsWith(prefix);
- }, false);
+ return prefixes.reduce((startsWith, prefix) => startsWith || str.startsWith(prefix), false);
}
var baseDiffFilenamePrefixes = ["a/", "b/", "i/", "w/", "c/", "o/"];
function getFilename(line, linePrefix, extraPrefix) {
- var prefixes = extraPrefix !== void 0 ? __spreadArray(__spreadArray([], baseDiffFilenamePrefixes, true), [extraPrefix], false) : baseDiffFilenamePrefixes;
- var FilenameRegExp = linePrefix ? new RegExp("^".concat(escapeForRegExp(linePrefix), ' "?(.+?)"?$')) : new RegExp('^"?(.+?)"?$');
- var _a2 = FilenameRegExp.exec(line) || [], _b = _a2[1], filename = _b === void 0 ? "" : _b;
- var matchingPrefix = prefixes.find(function(p) {
- return filename.indexOf(p) === 0;
- });
- var fnameWithoutPrefix = matchingPrefix ? filename.slice(matchingPrefix.length) : filename;
+ const prefixes = extraPrefix !== void 0 ? [...baseDiffFilenamePrefixes, extraPrefix] : baseDiffFilenamePrefixes;
+ const FilenameRegExp = linePrefix ? new RegExp(`^${escapeForRegExp(linePrefix)} "?(.+?)"?$`) : new RegExp('^"?(.+?)"?$');
+ const [, filename = ""] = FilenameRegExp.exec(line) || [];
+ const matchingPrefix = prefixes.find((p) => filename.indexOf(p) === 0);
+ const fnameWithoutPrefix = matchingPrefix ? filename.slice(matchingPrefix.length) : filename;
return fnameWithoutPrefix.replace(/\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4}.*$/, "");
}
function getSrcFilename(line, srcPrefix) {
@@ -25086,39 +34462,36 @@ function getSrcFilename(line, srcPrefix) {
function getDstFilename(line, dstPrefix) {
return getFilename(line, "+++", dstPrefix);
}
-function parse(diffInput, config) {
- if (config === void 0) {
- config = {};
- }
- var files = [];
- var currentFile = null;
- var currentBlock = null;
- var oldLine = null;
- var oldLine2 = null;
- var newLine = null;
- var possibleOldName = null;
- var possibleNewName = null;
- var oldFileNameHeader = "--- ";
- var newFileNameHeader = "+++ ";
- var hunkHeaderPrefix = "@@";
- var oldMode = /^old mode (\d{6})/;
- var newMode = /^new mode (\d{6})/;
- var deletedFileMode = /^deleted file mode (\d{6})/;
- var newFileMode = /^new file mode (\d{6})/;
- var copyFrom = /^copy from "?(.+)"?/;
- var copyTo = /^copy to "?(.+)"?/;
- var renameFrom = /^rename from "?(.+)"?/;
- var renameTo = /^rename to "?(.+)"?/;
- var similarityIndex = /^similarity index (\d+)%/;
- var dissimilarityIndex = /^dissimilarity index (\d+)%/;
- var index2 = /^index ([\da-z]+)\.\.([\da-z]+)\s*(\d{6})?/;
- var binaryFiles = /^Binary files (.*) and (.*) differ/;
- var binaryDiff = /^GIT binary patch/;
- var combinedIndex = /^index ([\da-z]+),([\da-z]+)\.\.([\da-z]+)/;
- var combinedMode = /^mode (\d{6}),(\d{6})\.\.(\d{6})/;
- var combinedNewFile = /^new file mode (\d{6})/;
- var combinedDeletedFile = /^deleted file mode (\d{6}),(\d{6})/;
- var diffLines2 = diffInput.replace(/\\ No newline at end of file/g, "").replace(/\r\n?/g, "\n").split("\n");
+function parse(diffInput, config = {}) {
+ const files = [];
+ let currentFile = null;
+ let currentBlock = null;
+ let oldLine = null;
+ let oldLine2 = null;
+ let newLine = null;
+ let possibleOldName = null;
+ let possibleNewName = null;
+ const oldFileNameHeader = "--- ";
+ const newFileNameHeader = "+++ ";
+ const hunkHeaderPrefix = "@@";
+ const oldMode = /^old mode (\d{6})/;
+ const newMode = /^new mode (\d{6})/;
+ const deletedFileMode = /^deleted file mode (\d{6})/;
+ const newFileMode = /^new file mode (\d{6})/;
+ const copyFrom = /^copy from "?(.+)"?/;
+ const copyTo = /^copy to "?(.+)"?/;
+ const renameFrom = /^rename from "?(.+)"?/;
+ const renameTo = /^rename to "?(.+)"?/;
+ const similarityIndex = /^similarity index (\d+)%/;
+ const dissimilarityIndex = /^dissimilarity index (\d+)%/;
+ const index2 = /^index ([\da-z]+)\.\.([\da-z]+)\s*(\d{6})?/;
+ const binaryFiles = /^Binary files (.*) and (.*) differ/;
+ const binaryDiff = /^GIT binary patch/;
+ const combinedIndex = /^index ([\da-z]+),([\da-z]+)\.\.([\da-z]+)/;
+ const combinedMode = /^mode (\d{6}),(\d{6})\.\.(\d{6})/;
+ const combinedNewFile = /^new file mode (\d{6})/;
+ const combinedDeletedFile = /^deleted file mode (\d{6}),(\d{6})/;
+ const diffLines2 = diffInput.replace(/\\ No newline at end of file/g, "").replace(/\r\n?/g, "\n").split("\n");
function saveBlock() {
if (currentBlock !== null && currentFile !== null) {
currentFile.blocks.push(currentBlock);
@@ -25152,7 +34525,7 @@ function parse(diffInput, config) {
}
function startBlock(line) {
saveBlock();
- var values;
+ let values;
if (currentFile !== null) {
if (values = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@.*/.exec(line)) {
currentFile.isCombined = false;
@@ -25183,11 +34556,11 @@ function parse(diffInput, config) {
function createLine(line) {
if (currentFile === null || currentBlock === null || oldLine === null || newLine === null)
return;
- var currentLine = {
+ const currentLine = {
content: line
};
- var addedPrefixes = currentFile.isCombined ? ["+ ", " +", "++"] : ["+"];
- var deletedPrefixes = currentFile.isCombined ? ["- ", " -", "--"] : ["-"];
+ const addedPrefixes = currentFile.isCombined ? ["+ ", " +", "++"] : ["+"];
+ const deletedPrefixes = currentFile.isCombined ? ["- ", " -", "--"] : ["-"];
if (startsWithAny(line, addedPrefixes)) {
currentFile.addedLines++;
currentLine.type = LineType.INSERT;
@@ -25206,7 +34579,7 @@ function parse(diffInput, config) {
currentBlock.lines.push(currentLine);
}
function existHunkHeader(line, lineIdx) {
- var idx = lineIdx;
+ let idx = lineIdx;
while (idx < diffLines2.length - 3) {
if (line.startsWith("diff")) {
return false;
@@ -25218,17 +34591,17 @@ function parse(diffInput, config) {
}
return false;
}
- diffLines2.forEach(function(line, lineIndex) {
+ diffLines2.forEach((line, lineIndex) => {
if (!line || line.startsWith("*")) {
return;
}
- var values;
- var prevLine = diffLines2[lineIndex - 1];
- var nxtLine = diffLines2[lineIndex + 1];
- var afterNxtLine = diffLines2[lineIndex + 2];
- if (line.startsWith("diff")) {
+ let values;
+ const prevLine = diffLines2[lineIndex - 1];
+ const nxtLine = diffLines2[lineIndex + 1];
+ const afterNxtLine = diffLines2[lineIndex + 2];
+ if (line.startsWith("diff --git") || line.startsWith("diff --combined")) {
startFile();
- var gitDiffStart = /^diff --git "?([a-ciow]\/.+)"? "?([a-ciow]\/.+)"?/;
+ const gitDiffStart = /^diff --git "?([a-ciow]\/.+)"? "?([a-ciow]\/.+)"?/;
if (values = gitDiffStart.exec(line)) {
possibleOldName = getFilename(values[1], void 0, config.dstPrefix);
possibleNewName = getFilename(values[2], void 0, config.srcPrefix);
@@ -25239,6 +34612,19 @@ function parse(diffInput, config) {
currentFile.isGitDiff = true;
return;
}
+ if (line.startsWith("Binary files") && !(currentFile === null || currentFile === void 0 ? void 0 : currentFile.isGitDiff)) {
+ startFile();
+ const unixDiffBinaryStart = /^Binary files "?([a-ciow]\/.+)"? and "?([a-ciow]\/.+)"? differ/;
+ if (values = unixDiffBinaryStart.exec(line)) {
+ possibleOldName = getFilename(values[1], void 0, config.dstPrefix);
+ possibleNewName = getFilename(values[2], void 0, config.srcPrefix);
+ }
+ if (currentFile === null) {
+ throw new Error("Where is my file !!!");
+ }
+ currentFile.isBinary = true;
+ return;
+ }
if (!currentFile || !currentFile.isGitDiff && currentFile && line.startsWith(oldFileNameHeader) && nxtLine.startsWith(newFileNameHeader) && afterNxtLine.startsWith(hunkHeaderPrefix)) {
startFile();
}
@@ -25251,7 +34637,7 @@ function parse(diffInput, config) {
currentFile.deletedLines = 0;
currentFile.blocks = [];
currentBlock = null;
- var message = typeof config.diffTooBigMessage === "function" ? config.diffTooBigMessage(files.length) : "Diff too big to be displayed";
+ const message = typeof config.diffTooBigMessage === "function" ? config.diffTooBigMessage(files.length) : "Diff too big to be displayed";
startBlock(message);
return;
}
@@ -25275,7 +34661,7 @@ function parse(diffInput, config) {
createLine(line);
return;
}
- var doesNotExistHunkHeader = !existHunkHeader(line, lineIndex);
+ const doesNotExistHunkHeader = !existHunkHeader(line, lineIndex);
if (currentFile === null) {
throw new Error("Where is my file !!!");
}
@@ -25344,13 +34730,13 @@ function parse(diffInput, config) {
return files;
}
-// node_modules/diff2html/lib-esm/file-list-renderer.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/file-list-renderer.js
init_polyfill_buffer();
-// node_modules/diff2html/lib-esm/render-utils.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/render-utils.js
init_polyfill_buffer();
-// node_modules/diff2html/lib-esm/rematch.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/rematch.js
init_polyfill_buffer();
function levenshtein(a, b) {
if (a.length === 0) {
@@ -25359,12 +34745,12 @@ function levenshtein(a, b) {
if (b.length === 0) {
return a.length;
}
- var matrix = [];
- var i;
+ const matrix = [];
+ let i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
- var j;
+ let j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
@@ -25380,24 +34766,21 @@ function levenshtein(a, b) {
return matrix[b.length][a.length];
}
function newDistanceFn(str) {
- return function(x, y) {
- var xValue = str(x).trim();
- var yValue = str(y).trim();
- var lev = levenshtein(xValue, yValue);
+ return (x, y) => {
+ const xValue = str(x).trim();
+ const yValue = str(y).trim();
+ const lev = levenshtein(xValue, yValue);
return lev / (xValue.length + yValue.length);
};
}
function newMatcherFn(distance2) {
- function findBestMatch(a, b, cache) {
- if (cache === void 0) {
- cache = new Map();
- }
- var bestMatchDist = Infinity;
- var bestMatch;
- for (var i = 0; i < a.length; ++i) {
- for (var j = 0; j < b.length; ++j) {
- var cacheKey = JSON.stringify([a[i], b[j]]);
- var md = void 0;
+ function findBestMatch(a, b, cache = /* @__PURE__ */ new Map()) {
+ let bestMatchDist = Infinity;
+ let bestMatch;
+ for (let i = 0; i < a.length; ++i) {
+ for (let j = 0; j < b.length; ++j) {
+ const cacheKey = JSON.stringify([a[i], b[j]]);
+ let md;
if (!(cache.has(cacheKey) && (md = cache.get(cacheKey)))) {
md = distance2(a[i], b[j]);
cache.set(cacheKey, md);
@@ -25410,29 +34793,23 @@ function newMatcherFn(distance2) {
}
return bestMatch;
}
- function group(a, b, level, cache) {
- if (level === void 0) {
- level = 0;
- }
- if (cache === void 0) {
- cache = new Map();
- }
- var bm = findBestMatch(a, b, cache);
+ function group(a, b, level = 0, cache = /* @__PURE__ */ new Map()) {
+ const bm = findBestMatch(a, b, cache);
if (!bm || a.length + b.length < 3) {
return [[a, b]];
}
- var a1 = a.slice(0, bm.indexA);
- var b1 = b.slice(0, bm.indexB);
- var aMatch = [a[bm.indexA]];
- var bMatch = [b[bm.indexB]];
- var tailA = bm.indexA + 1;
- var tailB = bm.indexB + 1;
- var a2 = a.slice(tailA);
- var b2 = b.slice(tailB);
- var group1 = group(a1, b1, level + 1, cache);
- var groupMatch = group(aMatch, bMatch, level + 1, cache);
- var group2 = group(a2, b2, level + 1, cache);
- var result = groupMatch;
+ const a1 = a.slice(0, bm.indexA);
+ const b1 = b.slice(0, bm.indexB);
+ const aMatch = [a[bm.indexA]];
+ const bMatch = [b[bm.indexB]];
+ const tailA = bm.indexA + 1;
+ const tailB = bm.indexB + 1;
+ const a2 = a.slice(tailA);
+ const b2 = b.slice(tailB);
+ const group1 = group(a1, b1, level + 1, cache);
+ const groupMatch = group(aMatch, bMatch, level + 1, cache);
+ const group2 = group(a2, b2, level + 1, cache);
+ let result = groupMatch;
if (bm.indexA > 0 || bm.indexB > 0) {
result = group1.concat(result);
}
@@ -25444,19 +34821,7 @@ function newMatcherFn(distance2) {
return group;
}
-// node_modules/diff2html/lib-esm/render-utils.js
-var __assign = function() {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/render-utils.js
var CSSLineClass = {
INSERTS: "d2h-ins",
DELETES: "d2h-del",
@@ -25472,9 +34837,7 @@ var defaultRenderConfig = {
diffStyle: DiffStyleType.WORD
};
var separator = "/";
-var distance = newDistanceFn(function(change) {
- return change.value;
-});
+var distance = newDistanceFn((change) => change.value);
var matcher = newMatcherFn(distance);
function isDevNullName(name) {
return name.indexOf("dev/null") !== -1;
@@ -25501,29 +34864,26 @@ function prefixLength(isCombined) {
function escapeForHtml(str) {
return str.slice(0).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/\//g, "/");
}
-function deconstructLine(line, isCombined, escape) {
- if (escape === void 0) {
- escape = true;
- }
- var indexToSplit = prefixLength(isCombined);
+function deconstructLine(line, isCombined, escape = true) {
+ const indexToSplit = prefixLength(isCombined);
return {
prefix: line.substring(0, indexToSplit),
content: escape ? escapeForHtml(line.substring(indexToSplit)) : line.substring(indexToSplit)
};
}
function filenameDiff(file) {
- var oldFilename = unifyPath(file.oldName);
- var newFilename = unifyPath(file.newName);
+ const oldFilename = unifyPath(file.oldName);
+ const newFilename = unifyPath(file.newName);
if (oldFilename !== newFilename && !isDevNullName(oldFilename) && !isDevNullName(newFilename)) {
- var prefixPaths = [];
- var suffixPaths = [];
- var oldFilenameParts = oldFilename.split(separator);
- var newFilenameParts = newFilename.split(separator);
- var oldFilenamePartsSize = oldFilenameParts.length;
- var newFilenamePartsSize = newFilenameParts.length;
- var i = 0;
- var j = oldFilenamePartsSize - 1;
- var k = newFilenamePartsSize - 1;
+ const prefixPaths = [];
+ const suffixPaths = [];
+ const oldFilenameParts = oldFilename.split(separator);
+ const newFilenameParts = newFilename.split(separator);
+ const oldFilenamePartsSize = oldFilenameParts.length;
+ const newFilenamePartsSize = newFilenameParts.length;
+ let i = 0;
+ let j = oldFilenamePartsSize - 1;
+ let k = newFilenamePartsSize - 1;
while (i < j && i < k) {
if (oldFilenameParts[i] === newFilenameParts[i]) {
prefixPaths.push(newFilenameParts[i]);
@@ -25541,10 +34901,10 @@ function filenameDiff(file) {
break;
}
}
- var finalPrefix = prefixPaths.join(separator);
- var finalSuffix = suffixPaths.join(separator);
- var oldRemainingPath = oldFilenameParts.slice(i, j + 1).join(separator);
- var newRemainingPath = newFilenameParts.slice(i, k + 1).join(separator);
+ const finalPrefix = prefixPaths.join(separator);
+ const finalSuffix = suffixPaths.join(separator);
+ const oldRemainingPath = oldFilenameParts.slice(i, j + 1).join(separator);
+ const newRemainingPath = newFilenameParts.slice(i, k + 1).join(separator);
if (finalPrefix.length && finalSuffix.length) {
return finalPrefix + separator + "{" + oldRemainingPath + " \u2192 " + newRemainingPath + "}" + separator + finalSuffix;
} else if (finalPrefix.length) {
@@ -25560,10 +34920,10 @@ function filenameDiff(file) {
}
}
function getHtmlId(file) {
- return "d2h-".concat(hashCode(filenameDiff(file)).toString().slice(-6));
+ return `d2h-${hashCode(filenameDiff(file)).toString().slice(-6)}`;
}
function getFileIcon(file) {
- var templateName = "file-changed";
+ let templateName = "file-changed";
if (file.isRename) {
templateName = "file-renamed";
} else if (file.isCopy) {
@@ -25577,13 +34937,10 @@ function getFileIcon(file) {
}
return templateName;
}
-function diffHighlight(diffLine1, diffLine2, isCombined, config) {
- if (config === void 0) {
- config = {};
- }
- var _a2 = __assign(__assign({}, defaultRenderConfig), config), matching = _a2.matching, maxLineLengthHighlight = _a2.maxLineLengthHighlight, matchWordsThreshold = _a2.matchWordsThreshold, diffStyle = _a2.diffStyle;
- var line1 = deconstructLine(diffLine1, isCombined, false);
- var line2 = deconstructLine(diffLine2, isCombined, false);
+function diffHighlight(diffLine1, diffLine2, isCombined, config = {}) {
+ const { matching, maxLineLengthHighlight, matchWordsThreshold, diffStyle } = Object.assign(Object.assign({}, defaultRenderConfig), config);
+ const line1 = deconstructLine(diffLine1, isCombined, false);
+ const line2 = deconstructLine(diffLine2, isCombined, false);
if (line1.content.length > maxLineLengthHighlight || line2.content.length > maxLineLengthHighlight) {
return {
oldLine: {
@@ -25596,19 +34953,15 @@ function diffHighlight(diffLine1, diffLine2, isCombined, config) {
}
};
}
- var diff2 = diffStyle === "char" ? diffChars(line1.content, line2.content) : diffWordsWithSpace(line1.content, line2.content);
- var changedWords = [];
+ const diff2 = diffStyle === "char" ? diffChars(line1.content, line2.content) : diffWordsWithSpace(line1.content, line2.content);
+ const changedWords = [];
if (diffStyle === "word" && matching === "words") {
- var removed = diff2.filter(function(element2) {
- return element2.removed;
- });
- var added = diff2.filter(function(element2) {
- return element2.added;
- });
- var chunks = matcher(added, removed);
- chunks.forEach(function(chunk) {
+ const removed = diff2.filter((element2) => element2.removed);
+ const added = diff2.filter((element2) => element2.added);
+ const chunks = matcher(added, removed);
+ chunks.forEach((chunk) => {
if (chunk[0].length === 1 && chunk[1].length === 1) {
- var dist = distance(chunk[0][0], chunk[1][0]);
+ const dist = distance(chunk[0][0], chunk[1][0]);
if (dist < matchWordsThreshold) {
changedWords.push(chunk[0][0]);
changedWords.push(chunk[1][0]);
@@ -25616,11 +34969,11 @@ function diffHighlight(diffLine1, diffLine2, isCombined, config) {
}
});
}
- var highlightedLine = diff2.reduce(function(highlightedLine2, part) {
- var elemType = part.added ? "ins" : part.removed ? "del" : null;
- var addClass = changedWords.indexOf(part) > -1 ? ' class="d2h-change"' : "";
- var escapedValue = escapeForHtml(part.value);
- return elemType !== null ? "".concat(highlightedLine2, "<").concat(elemType).concat(addClass, ">").concat(escapedValue, "").concat(elemType, ">") : "".concat(highlightedLine2).concat(escapedValue);
+ const highlightedLine = diff2.reduce((highlightedLine2, part) => {
+ const elemType = part.added ? "ins" : part.removed ? "del" : null;
+ const addClass = changedWords.indexOf(part) > -1 ? ' class="d2h-change"' : "";
+ const escapedValue = escapeForHtml(part.value);
+ return elemType !== null ? `${highlightedLine2}<${elemType}${addClass}>${escapedValue}${elemType}>` : `${highlightedLine2}${escapedValue}`;
}, "");
return {
oldLine: {
@@ -25634,75 +34987,57 @@ function diffHighlight(diffLine1, diffLine2, isCombined, config) {
};
}
-// node_modules/diff2html/lib-esm/file-list-renderer.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/file-list-renderer.js
var baseTemplatesPath = "file-summary";
var iconsBaseTemplatesPath = "icon";
function render(diffFiles, hoganUtils) {
- var files = diffFiles.map(function(file) {
- return hoganUtils.render(baseTemplatesPath, "line", {
- fileHtmlId: getHtmlId(file),
- oldName: file.oldName,
- newName: file.newName,
- fileName: filenameDiff(file),
- deletedLines: "-" + file.deletedLines,
- addedLines: "+" + file.addedLines
- }, {
- fileIcon: hoganUtils.template(iconsBaseTemplatesPath, getFileIcon(file))
- });
- }).join("\n");
+ const files = diffFiles.map((file) => hoganUtils.render(baseTemplatesPath, "line", {
+ fileHtmlId: getHtmlId(file),
+ oldName: file.oldName,
+ newName: file.newName,
+ fileName: filenameDiff(file),
+ deletedLines: "-" + file.deletedLines,
+ addedLines: "+" + file.addedLines
+ }, {
+ fileIcon: hoganUtils.template(iconsBaseTemplatesPath, getFileIcon(file))
+ })).join("\n");
return hoganUtils.render(baseTemplatesPath, "wrapper", {
filesNumber: diffFiles.length,
files
});
}
-// node_modules/diff2html/lib-esm/line-by-line-renderer.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/line-by-line-renderer.js
init_polyfill_buffer();
-var __assign2 = function() {
- __assign2 = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign2.apply(this, arguments);
-};
-var defaultLineByLineRendererConfig = __assign2(__assign2({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 });
+var defaultLineByLineRendererConfig = Object.assign(Object.assign({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 });
var genericTemplatesPath = "generic";
var baseTemplatesPath2 = "line-by-line";
var iconsBaseTemplatesPath2 = "icon";
var tagsBaseTemplatesPath = "tag";
-var LineByLineRenderer = function() {
- function LineByLineRenderer2(hoganUtils, config) {
- if (config === void 0) {
- config = {};
- }
+var LineByLineRenderer = class {
+ constructor(hoganUtils, config = {}) {
this.hoganUtils = hoganUtils;
- this.config = __assign2(__assign2({}, defaultLineByLineRendererConfig), config);
+ this.config = Object.assign(Object.assign({}, defaultLineByLineRendererConfig), config);
}
- LineByLineRenderer2.prototype.render = function(diffFiles) {
- var _this = this;
- var diffsHtml = diffFiles.map(function(file) {
- var diffs;
+ render(diffFiles) {
+ const diffsHtml = diffFiles.map((file) => {
+ let diffs;
if (file.blocks.length) {
- diffs = _this.generateFileHtml(file);
+ diffs = this.generateFileHtml(file);
} else {
- diffs = _this.generateEmptyDiff();
+ diffs = this.generateEmptyDiff();
}
- return _this.makeFileDiffHtml(file, diffs);
+ return this.makeFileDiffHtml(file, diffs);
}).join("\n");
return this.hoganUtils.render(genericTemplatesPath, "wrapper", { content: diffsHtml });
- };
- LineByLineRenderer2.prototype.makeFileDiffHtml = function(file, diffs) {
+ }
+ makeFileDiffHtml(file, diffs) {
if (this.config.renderNothingWhenEmpty && Array.isArray(file.blocks) && file.blocks.length === 0)
return "";
- var fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath2, "file-diff");
- var filePathTemplate = this.hoganUtils.template(genericTemplatesPath, "file-path");
- var fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath2, "file");
- var fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath, getFileIcon(file));
+ const fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath2, "file-diff");
+ const filePathTemplate = this.hoganUtils.template(genericTemplatesPath, "file-path");
+ const fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath2, "file");
+ const fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath, getFileIcon(file));
return fileDiffTemplate.render({
file,
fileHtmlId: getHtmlId(file),
@@ -25714,38 +35049,33 @@ var LineByLineRenderer = function() {
fileTag: fileTagTemplate
})
});
- };
- LineByLineRenderer2.prototype.generateEmptyDiff = function() {
+ }
+ generateEmptyDiff() {
return this.hoganUtils.render(genericTemplatesPath, "empty-diff", {
contentClass: "d2h-code-line",
CSSLineClass
});
- };
- LineByLineRenderer2.prototype.generateFileHtml = function(file) {
- var _this = this;
- var matcher2 = newMatcherFn(newDistanceFn(function(e) {
- return deconstructLine(e.content, file.isCombined).content;
- }));
- return file.blocks.map(function(block) {
- var lines = _this.hoganUtils.render(genericTemplatesPath, "block-header", {
+ }
+ generateFileHtml(file) {
+ const matcher2 = newMatcherFn(newDistanceFn((e) => deconstructLine(e.content, file.isCombined).content));
+ return file.blocks.map((block) => {
+ let lines = this.hoganUtils.render(genericTemplatesPath, "block-header", {
CSSLineClass,
blockHeader: file.isTooBig ? block.header : escapeForHtml(block.header),
lineClass: "d2h-code-linenumber",
contentClass: "d2h-code-line"
});
- _this.applyLineGroupping(block).forEach(function(_a2) {
- var contextLines = _a2[0], oldLines = _a2[1], newLines = _a2[2];
+ this.applyLineGroupping(block).forEach(([contextLines, oldLines, newLines]) => {
if (oldLines.length && newLines.length && !contextLines.length) {
- _this.applyRematchMatching(oldLines, newLines, matcher2).map(function(_a3) {
- var oldLines2 = _a3[0], newLines2 = _a3[1];
- var _b2 = _this.processChangedLines(file.isCombined, oldLines2, newLines2), left2 = _b2.left, right2 = _b2.right;
- lines += left2;
- lines += right2;
+ this.applyRematchMatching(oldLines, newLines, matcher2).map(([oldLines2, newLines2]) => {
+ const { left, right } = this.processChangedLines(file, file.isCombined, oldLines2, newLines2);
+ lines += left;
+ lines += right;
});
} else if (contextLines.length) {
- contextLines.forEach(function(line) {
- var _a3 = deconstructLine(line.content, file.isCombined), prefix = _a3.prefix, content = _a3.content;
- lines += _this.generateSingleLineHtml({
+ contextLines.forEach((line) => {
+ const { prefix, content } = deconstructLine(line.content, file.isCombined);
+ lines += this.generateSingleLineHtml(file, {
type: CSSLineClass.CONTEXT,
prefix,
content,
@@ -25754,7 +35084,7 @@ var LineByLineRenderer = function() {
});
});
} else if (oldLines.length || newLines.length) {
- var _b = _this.processChangedLines(file.isCombined, oldLines, newLines), left = _b.left, right = _b.right;
+ const { left, right } = this.processChangedLines(file, file.isCombined, oldLines, newLines);
lines += left;
lines += right;
} else {
@@ -25763,13 +35093,13 @@ var LineByLineRenderer = function() {
});
return lines;
}).join("\n");
- };
- LineByLineRenderer2.prototype.applyLineGroupping = function(block) {
- var blockLinesGroups = [];
- var oldLines = [];
- var newLines = [];
- for (var i = 0; i < block.lines.length; i++) {
- var diffLine = block.lines[i];
+ }
+ applyLineGroupping(block) {
+ const blockLinesGroups = [];
+ let oldLines = [];
+ let newLines = [];
+ for (let i = 0; i < block.lines.length; i++) {
+ const diffLine = block.lines[i];
if (diffLine.type !== LineType.INSERT && newLines.length || diffLine.type === LineType.CONTEXT && oldLines.length > 0) {
blockLinesGroups.push([[], oldLines, newLines]);
oldLines = [];
@@ -25791,51 +35121,49 @@ var LineByLineRenderer = function() {
newLines = [];
}
return blockLinesGroups;
- };
- LineByLineRenderer2.prototype.applyRematchMatching = function(oldLines, newLines, matcher2) {
- var comparisons = oldLines.length * newLines.length;
- var maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map(function(elem) {
- return elem.content.length;
- })));
- var doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words");
+ }
+ applyRematchMatching(oldLines, newLines, matcher2) {
+ const comparisons = oldLines.length * newLines.length;
+ const maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map((elem) => elem.content.length)));
+ const doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words");
return doMatching ? matcher2(oldLines, newLines) : [[oldLines, newLines]];
- };
- LineByLineRenderer2.prototype.processChangedLines = function(isCombined, oldLines, newLines) {
- var fileHtml = {
+ }
+ processChangedLines(file, isCombined, oldLines, newLines) {
+ const fileHtml = {
right: "",
left: ""
};
- var maxLinesNumber = Math.max(oldLines.length, newLines.length);
- for (var i = 0; i < maxLinesNumber; i++) {
- var oldLine = oldLines[i];
- var newLine = newLines[i];
- var diff2 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0;
- var preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? __assign2(__assign2({}, diff2 !== void 0 ? {
+ const maxLinesNumber = Math.max(oldLines.length, newLines.length);
+ for (let i = 0; i < maxLinesNumber; i++) {
+ const oldLine = oldLines[i];
+ const newLine = newLines[i];
+ const diff2 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0;
+ const preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? Object.assign(Object.assign({}, diff2 !== void 0 ? {
prefix: diff2.oldLine.prefix,
content: diff2.oldLine.content,
type: CSSLineClass.DELETE_CHANGES
- } : __assign2(__assign2({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { oldNumber: oldLine.oldNumber, newNumber: oldLine.newNumber }) : void 0;
- var preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? __assign2(__assign2({}, diff2 !== void 0 ? {
+ } : Object.assign(Object.assign({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { oldNumber: oldLine.oldNumber, newNumber: oldLine.newNumber }) : void 0;
+ const preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? Object.assign(Object.assign({}, diff2 !== void 0 ? {
prefix: diff2.newLine.prefix,
content: diff2.newLine.content,
type: CSSLineClass.INSERT_CHANGES
- } : __assign2(__assign2({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { oldNumber: newLine.oldNumber, newNumber: newLine.newNumber }) : void 0;
- var _a2 = this.generateLineHtml(preparedOldLine, preparedNewLine), left = _a2.left, right = _a2.right;
+ } : Object.assign(Object.assign({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { oldNumber: newLine.oldNumber, newNumber: newLine.newNumber }) : void 0;
+ const { left, right } = this.generateLineHtml(file, preparedOldLine, preparedNewLine);
fileHtml.left += left;
fileHtml.right += right;
}
return fileHtml;
- };
- LineByLineRenderer2.prototype.generateLineHtml = function(oldLine, newLine) {
+ }
+ generateLineHtml(file, oldLine, newLine) {
return {
- left: this.generateSingleLineHtml(oldLine),
- right: this.generateSingleLineHtml(newLine)
+ left: this.generateSingleLineHtml(file, oldLine),
+ right: this.generateSingleLineHtml(file, newLine)
};
- };
- LineByLineRenderer2.prototype.generateSingleLineHtml = function(line) {
+ }
+ generateSingleLineHtml(file, line) {
if (line === void 0)
return "";
- var lineNumberHtml = this.hoganUtils.render(baseTemplatesPath2, "numbers", {
+ const lineNumberHtml = this.hoganUtils.render(baseTemplatesPath2, "numbers", {
oldNumber: line.oldNumber || "",
newNumber: line.newNumber || ""
});
@@ -25845,60 +35173,44 @@ var LineByLineRenderer = function() {
contentClass: "d2h-code-line",
prefix: line.prefix === " " ? " " : line.prefix,
content: line.content,
- lineNumber: lineNumberHtml
+ lineNumber: lineNumberHtml,
+ line,
+ file
});
- };
- return LineByLineRenderer2;
-}();
-var line_by_line_renderer_default = LineByLineRenderer;
-
-// node_modules/diff2html/lib-esm/side-by-side-renderer.js
-init_polyfill_buffer();
-var __assign3 = function() {
- __assign3 = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign3.apply(this, arguments);
+ }
};
-var defaultSideBySideRendererConfig = __assign3(__assign3({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 });
+
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/side-by-side-renderer.js
+init_polyfill_buffer();
+var defaultSideBySideRendererConfig = Object.assign(Object.assign({}, defaultRenderConfig), { renderNothingWhenEmpty: false, matchingMaxComparisons: 2500, maxLineSizeInBlockForComparison: 200 });
var genericTemplatesPath2 = "generic";
var baseTemplatesPath3 = "side-by-side";
var iconsBaseTemplatesPath3 = "icon";
var tagsBaseTemplatesPath2 = "tag";
-var SideBySideRenderer = function() {
- function SideBySideRenderer2(hoganUtils, config) {
- if (config === void 0) {
- config = {};
- }
+var SideBySideRenderer = class {
+ constructor(hoganUtils, config = {}) {
this.hoganUtils = hoganUtils;
- this.config = __assign3(__assign3({}, defaultSideBySideRendererConfig), config);
+ this.config = Object.assign(Object.assign({}, defaultSideBySideRendererConfig), config);
}
- SideBySideRenderer2.prototype.render = function(diffFiles) {
- var _this = this;
- var diffsHtml = diffFiles.map(function(file) {
- var diffs;
+ render(diffFiles) {
+ const diffsHtml = diffFiles.map((file) => {
+ let diffs;
if (file.blocks.length) {
- diffs = _this.generateFileHtml(file);
+ diffs = this.generateFileHtml(file);
} else {
- diffs = _this.generateEmptyDiff();
+ diffs = this.generateEmptyDiff();
}
- return _this.makeFileDiffHtml(file, diffs);
+ return this.makeFileDiffHtml(file, diffs);
}).join("\n");
return this.hoganUtils.render(genericTemplatesPath2, "wrapper", { content: diffsHtml });
- };
- SideBySideRenderer2.prototype.makeFileDiffHtml = function(file, diffs) {
+ }
+ makeFileDiffHtml(file, diffs) {
if (this.config.renderNothingWhenEmpty && Array.isArray(file.blocks) && file.blocks.length === 0)
return "";
- var fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath3, "file-diff");
- var filePathTemplate = this.hoganUtils.template(genericTemplatesPath2, "file-path");
- var fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath3, "file");
- var fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath2, getFileIcon(file));
+ const fileDiffTemplate = this.hoganUtils.template(baseTemplatesPath3, "file-diff");
+ const filePathTemplate = this.hoganUtils.template(genericTemplatesPath2, "file-path");
+ const fileIconTemplate = this.hoganUtils.template(iconsBaseTemplatesPath3, "file");
+ const fileTagTemplate = this.hoganUtils.template(tagsBaseTemplatesPath2, getFileIcon(file));
return fileDiffTemplate.render({
file,
fileHtmlId: getHtmlId(file),
@@ -25910,8 +35222,8 @@ var SideBySideRenderer = function() {
fileTag: fileTagTemplate
})
});
- };
- SideBySideRenderer2.prototype.generateEmptyDiff = function() {
+ }
+ generateEmptyDiff() {
return {
right: "",
left: this.hoganUtils.render(genericTemplatesPath2, "empty-diff", {
@@ -25919,30 +35231,25 @@ var SideBySideRenderer = function() {
CSSLineClass
})
};
- };
- SideBySideRenderer2.prototype.generateFileHtml = function(file) {
- var _this = this;
- var matcher2 = newMatcherFn(newDistanceFn(function(e) {
- return deconstructLine(e.content, file.isCombined).content;
- }));
- return file.blocks.map(function(block) {
- var fileHtml = {
- left: _this.makeHeaderHtml(block.header, file),
- right: _this.makeHeaderHtml("")
+ }
+ generateFileHtml(file) {
+ const matcher2 = newMatcherFn(newDistanceFn((e) => deconstructLine(e.content, file.isCombined).content));
+ return file.blocks.map((block) => {
+ const fileHtml = {
+ left: this.makeHeaderHtml(block.header, file),
+ right: this.makeHeaderHtml("")
};
- _this.applyLineGroupping(block).forEach(function(_a2) {
- var contextLines = _a2[0], oldLines = _a2[1], newLines = _a2[2];
+ this.applyLineGroupping(block).forEach(([contextLines, oldLines, newLines]) => {
if (oldLines.length && newLines.length && !contextLines.length) {
- _this.applyRematchMatching(oldLines, newLines, matcher2).map(function(_a3) {
- var oldLines2 = _a3[0], newLines2 = _a3[1];
- var _b2 = _this.processChangedLines(file.isCombined, oldLines2, newLines2), left2 = _b2.left, right2 = _b2.right;
- fileHtml.left += left2;
- fileHtml.right += right2;
+ this.applyRematchMatching(oldLines, newLines, matcher2).map(([oldLines2, newLines2]) => {
+ const { left, right } = this.processChangedLines(file.isCombined, oldLines2, newLines2);
+ fileHtml.left += left;
+ fileHtml.right += right;
});
} else if (contextLines.length) {
- contextLines.forEach(function(line) {
- var _a3 = deconstructLine(line.content, file.isCombined), prefix = _a3.prefix, content = _a3.content;
- var _b2 = _this.generateLineHtml({
+ contextLines.forEach((line) => {
+ const { prefix, content } = deconstructLine(line.content, file.isCombined);
+ const { left, right } = this.generateLineHtml({
type: CSSLineClass.CONTEXT,
prefix,
content,
@@ -25952,12 +35259,12 @@ var SideBySideRenderer = function() {
prefix,
content,
number: line.newNumber
- }), left2 = _b2.left, right2 = _b2.right;
- fileHtml.left += left2;
- fileHtml.right += right2;
+ });
+ fileHtml.left += left;
+ fileHtml.right += right;
});
} else if (oldLines.length || newLines.length) {
- var _b = _this.processChangedLines(file.isCombined, oldLines, newLines), left = _b.left, right = _b.right;
+ const { left, right } = this.processChangedLines(file.isCombined, oldLines, newLines);
fileHtml.left += left;
fileHtml.right += right;
} else {
@@ -25965,16 +35272,16 @@ var SideBySideRenderer = function() {
}
});
return fileHtml;
- }).reduce(function(accomulated, html2) {
+ }).reduce((accomulated, html2) => {
return { left: accomulated.left + html2.left, right: accomulated.right + html2.right };
}, { left: "", right: "" });
- };
- SideBySideRenderer2.prototype.applyLineGroupping = function(block) {
- var blockLinesGroups = [];
- var oldLines = [];
- var newLines = [];
- for (var i = 0; i < block.lines.length; i++) {
- var diffLine = block.lines[i];
+ }
+ applyLineGroupping(block) {
+ const blockLinesGroups = [];
+ let oldLines = [];
+ let newLines = [];
+ for (let i = 0; i < block.lines.length; i++) {
+ const diffLine = block.lines[i];
if (diffLine.type !== LineType.INSERT && newLines.length || diffLine.type === LineType.CONTEXT && oldLines.length > 0) {
blockLinesGroups.push([[], oldLines, newLines]);
oldLines = [];
@@ -25996,78 +35303,74 @@ var SideBySideRenderer = function() {
newLines = [];
}
return blockLinesGroups;
- };
- SideBySideRenderer2.prototype.applyRematchMatching = function(oldLines, newLines, matcher2) {
- var comparisons = oldLines.length * newLines.length;
- var maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map(function(elem) {
- return elem.content.length;
- })));
- var doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words");
+ }
+ applyRematchMatching(oldLines, newLines, matcher2) {
+ const comparisons = oldLines.length * newLines.length;
+ const maxLineSizeInBlock = Math.max.apply(null, [0].concat(oldLines.concat(newLines).map((elem) => elem.content.length)));
+ const doMatching = comparisons < this.config.matchingMaxComparisons && maxLineSizeInBlock < this.config.maxLineSizeInBlockForComparison && (this.config.matching === "lines" || this.config.matching === "words");
return doMatching ? matcher2(oldLines, newLines) : [[oldLines, newLines]];
- };
- SideBySideRenderer2.prototype.makeHeaderHtml = function(blockHeader, file) {
+ }
+ makeHeaderHtml(blockHeader, file) {
return this.hoganUtils.render(genericTemplatesPath2, "block-header", {
CSSLineClass,
blockHeader: (file === null || file === void 0 ? void 0 : file.isTooBig) ? blockHeader : escapeForHtml(blockHeader),
lineClass: "d2h-code-side-linenumber",
contentClass: "d2h-code-side-line"
});
- };
- SideBySideRenderer2.prototype.processChangedLines = function(isCombined, oldLines, newLines) {
- var fileHtml = {
+ }
+ processChangedLines(isCombined, oldLines, newLines) {
+ const fileHtml = {
right: "",
left: ""
};
- var maxLinesNumber = Math.max(oldLines.length, newLines.length);
- for (var i = 0; i < maxLinesNumber; i++) {
- var oldLine = oldLines[i];
- var newLine = newLines[i];
- var diff2 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0;
- var preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? __assign3(__assign3({}, diff2 !== void 0 ? {
+ const maxLinesNumber = Math.max(oldLines.length, newLines.length);
+ for (let i = 0; i < maxLinesNumber; i++) {
+ const oldLine = oldLines[i];
+ const newLine = newLines[i];
+ const diff2 = oldLine !== void 0 && newLine !== void 0 ? diffHighlight(oldLine.content, newLine.content, isCombined, this.config) : void 0;
+ const preparedOldLine = oldLine !== void 0 && oldLine.oldNumber !== void 0 ? Object.assign(Object.assign({}, diff2 !== void 0 ? {
prefix: diff2.oldLine.prefix,
content: diff2.oldLine.content,
type: CSSLineClass.DELETE_CHANGES
- } : __assign3(__assign3({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { number: oldLine.oldNumber }) : void 0;
- var preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? __assign3(__assign3({}, diff2 !== void 0 ? {
+ } : Object.assign(Object.assign({}, deconstructLine(oldLine.content, isCombined)), { type: toCSSClass(oldLine.type) })), { number: oldLine.oldNumber }) : void 0;
+ const preparedNewLine = newLine !== void 0 && newLine.newNumber !== void 0 ? Object.assign(Object.assign({}, diff2 !== void 0 ? {
prefix: diff2.newLine.prefix,
content: diff2.newLine.content,
type: CSSLineClass.INSERT_CHANGES
- } : __assign3(__assign3({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { number: newLine.newNumber }) : void 0;
- var _a2 = this.generateLineHtml(preparedOldLine, preparedNewLine), left = _a2.left, right = _a2.right;
+ } : Object.assign(Object.assign({}, deconstructLine(newLine.content, isCombined)), { type: toCSSClass(newLine.type) })), { number: newLine.newNumber }) : void 0;
+ const { left, right } = this.generateLineHtml(preparedOldLine, preparedNewLine);
fileHtml.left += left;
fileHtml.right += right;
}
return fileHtml;
- };
- SideBySideRenderer2.prototype.generateLineHtml = function(oldLine, newLine) {
+ }
+ generateLineHtml(oldLine, newLine) {
return {
left: this.generateSingleHtml(oldLine),
right: this.generateSingleHtml(newLine)
};
- };
- SideBySideRenderer2.prototype.generateSingleHtml = function(line) {
- var lineClass = "d2h-code-side-linenumber";
- var contentClass = "d2h-code-side-line";
+ }
+ generateSingleHtml(line) {
+ const lineClass = "d2h-code-side-linenumber";
+ const contentClass = "d2h-code-side-line";
return this.hoganUtils.render(genericTemplatesPath2, "line", {
- type: (line === null || line === void 0 ? void 0 : line.type) || "".concat(CSSLineClass.CONTEXT, " d2h-emptyplaceholder"),
- lineClass: line !== void 0 ? lineClass : "".concat(lineClass, " d2h-code-side-emptyplaceholder"),
- contentClass: line !== void 0 ? contentClass : "".concat(contentClass, " d2h-code-side-emptyplaceholder"),
+ type: (line === null || line === void 0 ? void 0 : line.type) || `${CSSLineClass.CONTEXT} d2h-emptyplaceholder`,
+ lineClass: line !== void 0 ? lineClass : `${lineClass} d2h-code-side-emptyplaceholder`,
+ contentClass: line !== void 0 ? contentClass : `${contentClass} d2h-code-side-emptyplaceholder`,
prefix: (line === null || line === void 0 ? void 0 : line.prefix) === " " ? " " : line === null || line === void 0 ? void 0 : line.prefix,
content: line === null || line === void 0 ? void 0 : line.content,
lineNumber: line === null || line === void 0 ? void 0 : line.number
});
- };
- return SideBySideRenderer2;
-}();
-var side_by_side_renderer_default = SideBySideRenderer;
+ }
+};
-// node_modules/diff2html/lib-esm/hoganjs-utils.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/hoganjs-utils.js
init_polyfill_buffer();
-var Hogan3 = __toModule(require_hogan());
+var Hogan3 = __toESM(require_hogan());
-// node_modules/diff2html/lib-esm/diff2html-templates.js
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/diff2html-templates.js
init_polyfill_buffer();
-var Hogan2 = __toModule(require_hogan());
+var Hogan2 = __toESM(require_hogan());
var defaultTemplates = {};
defaultTemplates["file-summary-line"] = new Hogan2.Template({ code: function(c, p, i) {
var t = this;
@@ -26145,7 +35448,16 @@ defaultTemplates["generic-block-header"] = new Hogan2.Template({ code: function(
t.b(' ');
- t.b(t.t(t.f("blockHeader", c, p, 0)));
+ if (t.s(t.f("blockHeader", c, p, 1), c, p, 0, 156, 173, "{{ }}")) {
+ t.rs(c, p, function(c2, p2, t2) {
+ t2.b(t2.t(t2.f("blockHeader", c2, p2, 0)));
+ });
+ c.pop();
+ }
+ if (!t.s(t.f("blockHeader", c, p, 1), c, p, 1, 0, 0, "")) {
+ t.b(" ");
+ }
+ ;
t.b("
");
t.b("\n" + i);
t.b(" ");
@@ -26461,93 +35773,71 @@ defaultTemplates["tag-file-renamed"] = new Hogan2.Template({ code: function(c, p
return t.fl();
}, partials: {}, subs: {} });
-// node_modules/diff2html/lib-esm/hoganjs-utils.js
-var __assign4 = function() {
- __assign4 = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign4.apply(this, arguments);
-};
-var HoganJsUtils = function() {
- function HoganJsUtils2(_a2) {
- var _b = _a2.compiledTemplates, compiledTemplates = _b === void 0 ? {} : _b, _c = _a2.rawTemplates, rawTemplates = _c === void 0 ? {} : _c;
- var compiledRawTemplates = Object.entries(rawTemplates).reduce(function(previousTemplates, _a3) {
- var _b2;
- var name = _a3[0], templateString = _a3[1];
- var compiledTemplate = Hogan3.compile(templateString, { asString: false });
- return __assign4(__assign4({}, previousTemplates), (_b2 = {}, _b2[name] = compiledTemplate, _b2));
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/hoganjs-utils.js
+var HoganJsUtils = class {
+ constructor({ compiledTemplates = {}, rawTemplates = {} }) {
+ const compiledRawTemplates = Object.entries(rawTemplates).reduce((previousTemplates, [name, templateString]) => {
+ const compiledTemplate = Hogan3.compile(templateString, { asString: false });
+ return Object.assign(Object.assign({}, previousTemplates), { [name]: compiledTemplate });
}, {});
- this.preCompiledTemplates = __assign4(__assign4(__assign4({}, defaultTemplates), compiledTemplates), compiledRawTemplates);
+ this.preCompiledTemplates = Object.assign(Object.assign(Object.assign({}, defaultTemplates), compiledTemplates), compiledRawTemplates);
}
- HoganJsUtils2.compile = function(templateString) {
+ static compile(templateString) {
return Hogan3.compile(templateString, { asString: false });
- };
- HoganJsUtils2.prototype.render = function(namespace, view, params, partials, indent2) {
- var templateKey = this.templateKey(namespace, view);
+ }
+ render(namespace, view, params, partials, indent2) {
+ const templateKey = this.templateKey(namespace, view);
try {
- var template = this.preCompiledTemplates[templateKey];
+ const template = this.preCompiledTemplates[templateKey];
return template.render(params, partials, indent2);
} catch (e) {
- throw new Error("Could not find template to render '".concat(templateKey, "'"));
+ throw new Error(`Could not find template to render '${templateKey}'`);
}
- };
- HoganJsUtils2.prototype.template = function(namespace, view) {
- return this.preCompiledTemplates[this.templateKey(namespace, view)];
- };
- HoganJsUtils2.prototype.templateKey = function(namespace, view) {
- return "".concat(namespace, "-").concat(view);
- };
- return HoganJsUtils2;
-}();
-var hoganjs_utils_default = HoganJsUtils;
-
-// node_modules/diff2html/lib-esm/diff2html.js
-var __assign5 = function() {
- __assign5 = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign5.apply(this, arguments);
-};
-var defaultDiff2HtmlConfig = __assign5(__assign5(__assign5({}, defaultLineByLineRendererConfig), defaultSideBySideRendererConfig), { outputFormat: OutputFormatType.LINE_BY_LINE, drawFileList: true });
-function html(diffInput, configuration) {
- if (configuration === void 0) {
- configuration = {};
}
- var config = __assign5(__assign5({}, defaultDiff2HtmlConfig), configuration);
- var diffJson = typeof diffInput === "string" ? parse(diffInput, config) : diffInput;
- var hoganUtils = new hoganjs_utils_default(config);
- var fileList = config.drawFileList ? render(diffJson, hoganUtils) : "";
- var diffOutput = config.outputFormat === "side-by-side" ? new side_by_side_renderer_default(hoganUtils, config).render(diffJson) : new line_by_line_renderer_default(hoganUtils, config).render(diffJson);
+ template(namespace, view) {
+ return this.preCompiledTemplates[this.templateKey(namespace, view)];
+ }
+ templateKey(namespace, view) {
+ return `${namespace}-${view}`;
+ }
+};
+
+// node_modules/.pnpm/diff2html@3.4.41/node_modules/diff2html/lib-esm/diff2html.js
+var defaultDiff2HtmlConfig = Object.assign(Object.assign(Object.assign({}, defaultLineByLineRendererConfig), defaultSideBySideRendererConfig), { outputFormat: OutputFormatType.LINE_BY_LINE, drawFileList: true });
+function html(diffInput, configuration = {}) {
+ const config = Object.assign(Object.assign({}, defaultDiff2HtmlConfig), configuration);
+ const diffJson = typeof diffInput === "string" ? parse(diffInput, config) : diffInput;
+ const hoganUtils = new HoganJsUtils(config);
+ const fileList = config.drawFileList ? render(diffJson, hoganUtils) : "";
+ const diffOutput = config.outputFormat === "side-by-side" ? new SideBySideRenderer(hoganUtils, config).render(diffJson) : new LineByLineRenderer(hoganUtils, config).render(diffJson);
return fileList + diffOutput;
}
// src/ui/diff/diffView.ts
-var import_obsidian13 = __toModule(require("obsidian"));
-var DiffView = class extends import_obsidian13.ItemView {
+var import_obsidian17 = require("obsidian");
+var DiffView = class extends import_obsidian17.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.plugin = plugin;
this.gettingDiff = false;
+ this.gitRefreshBind = this.refresh.bind(this);
+ this.gitViewRefreshBind = this.refresh.bind(this);
this.parser = new DOMParser();
this.navigation = true;
- addEventListener("git-refresh", this.refresh.bind(this));
+ addEventListener("git-refresh", this.gitRefreshBind);
+ addEventListener("git-view-refresh", this.gitViewRefreshBind);
}
getViewType() {
return DIFF_VIEW_CONFIG.type;
}
getDisplayText() {
+ var _a2;
+ if (((_a2 = this.state) == null ? void 0 : _a2.file) != null) {
+ let fileName = this.state.file.split("/").last();
+ if (fileName == null ? void 0 : fileName.endsWith(".md"))
+ fileName = fileName.slice(0, -3);
+ return DIFF_VIEW_CONFIG.name + ` (${fileName})`;
+ }
return DIFF_VIEW_CONFIG.name;
}
getIcon() {
@@ -26555,14 +35845,17 @@ var DiffView = class extends import_obsidian13.ItemView {
}
async setState(state, result) {
this.state = state;
+ if (import_obsidian17.Platform.isMobile) {
+ this.leaf.view.titleEl.textContent = this.getDisplayText();
+ }
await this.refresh();
- return;
}
getState() {
return this.state;
}
onClose() {
- removeEventListener("git-refresh", this.refresh.bind(this));
+ removeEventListener("git-refresh", this.gitRefreshBind);
+ removeEventListener("git-view-refresh", this.gitViewRefreshBind);
return super.onClose();
}
onOpen() {
@@ -26573,100 +35866,58 @@ var DiffView = class extends import_obsidian13.ItemView {
var _a2;
if (((_a2 = this.state) == null ? void 0 : _a2.file) && !this.gettingDiff && this.plugin.gitManager) {
this.gettingDiff = true;
- let diff2 = await this.plugin.gitManager.getDiffString(this.state.file, this.state.staged);
- this.contentEl.empty();
- if (!diff2) {
- const content = await this.app.vault.adapter.read(this.plugin.gitManager.getVaultPath(this.state.file));
- const header = `--- /dev/null
+ try {
+ let diff2 = await this.plugin.gitManager.getDiffString(
+ this.state.file,
+ this.state.staged,
+ this.state.hash
+ );
+ this.contentEl.empty();
+ if (!diff2) {
+ if (this.plugin.gitManager instanceof SimpleGit && await this.plugin.gitManager.isTracked(
+ this.state.file
+ )) {
+ diff2 = [
+ `--- ${this.state.file}`,
+ `+++ ${this.state.file}`,
+ ""
+ ].join("\n");
+ } else {
+ const content = await this.app.vault.adapter.read(
+ this.plugin.gitManager.getVaultPath(this.state.file)
+ );
+ const header = `--- /dev/null
+++ ${this.state.file}
@@ -0,0 +1,${content.split("\n").length} @@`;
- diff2 = [...header.split("\n"), ...content.split("\n").map((line) => `+${line}`)].join("\n");
+ diff2 = [
+ ...header.split("\n"),
+ ...content.split("\n").map((line) => `+${line}`)
+ ].join("\n");
+ }
+ }
+ const diffEl = this.parser.parseFromString(html(diff2), "text/html").querySelector(".d2h-file-diff");
+ this.contentEl.append(diffEl);
+ } finally {
+ this.gettingDiff = false;
}
- const diffEl = this.parser.parseFromString(html(diff2), "text/html").querySelector(".d2h-file-diff");
- this.contentEl.append(diffEl);
- this.gettingDiff = false;
}
}
};
-// src/ui/modals/branchModal.ts
+// src/ui/history/historyView.ts
init_polyfill_buffer();
-var import_obsidian14 = __toModule(require("obsidian"));
-var BranchModal = class extends import_obsidian14.FuzzySuggestModal {
- constructor(branches) {
- super(app);
- this.branches = branches;
- this.setPlaceholder("Select branch to checkout");
- }
- getItems() {
- return this.branches;
- }
- getItemText(item) {
- return item;
- }
- onChooseItem(item, evt) {
- this.resolve(item);
- }
- open() {
- super.open();
- return new Promise((resolve) => {
- this.resolve = resolve;
- });
- }
- async onClose() {
- await new Promise((resolve) => setTimeout(resolve, 10));
- if (this.resolve)
- this.resolve(void 0);
- }
-};
+var import_obsidian20 = require("obsidian");
-// src/ui/modals/ignoreModal.ts
-init_polyfill_buffer();
-var import_obsidian15 = __toModule(require("obsidian"));
-var IgnoreModal = class extends import_obsidian15.Modal {
- constructor(app2, content) {
- super(app2);
- this.content = content;
- this.resolve = null;
- }
- open() {
- super.open();
- return new Promise((resolve) => {
- this.resolve = resolve;
- });
- }
- onOpen() {
- const { contentEl, titleEl } = this;
- titleEl.setText("Edit .gitignore");
- const div = contentEl.createDiv();
- const text2 = div.createEl("textarea", {
- text: this.content,
- cls: ["obsidian-git-textarea"],
- attr: { rows: 10, cols: 30, wrap: "off" }
- });
- div.createEl("button", {
- cls: ["mod-cta", "obsidian-git-center-button"],
- text: "Save"
- }).addEventListener("click", async () => {
- this.resolve(text2.value);
- this.close();
- });
- }
- onClose() {
- const { contentEl } = this;
- this.resolve(void 0);
- contentEl.empty();
- }
-};
-
-// src/ui/sidebar/sidebarView.ts
-init_polyfill_buffer();
-var import_obsidian22 = __toModule(require("obsidian"));
-
-// src/ui/sidebar/gitView.svelte
+// src/ui/history/historyView.svelte
init_polyfill_buffer();
-// node_modules/svelte/internal/index.mjs
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/index.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/animations.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/utils.js
init_polyfill_buffer();
function noop() {
}
@@ -26675,7 +35926,7 @@ function run(fn) {
return fn();
}
function blank_object() {
- return Object.create(null);
+ return /* @__PURE__ */ Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
@@ -26684,15 +35935,21 @@ function is_function(thing) {
return typeof thing === "function";
}
function safe_not_equal(a, b) {
- return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function");
+ return a != a ? b == b : a !== b || a && typeof a === "object" || typeof a === "function";
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/environment.js
+init_polyfill_buffer();
var is_client = typeof window !== "undefined";
var now = is_client ? () => window.performance.now() : () => Date.now();
var raf = is_client ? (cb) => requestAnimationFrame(cb) : noop;
-var tasks = new Set();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/loop.js
+init_polyfill_buffer();
+var tasks = /* @__PURE__ */ new Set();
function run_tasks(now2) {
tasks.forEach((task) => {
if (!task.c(now2)) {
@@ -26716,6 +35973,72 @@ function loop(callback) {
}
};
}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/style_manager.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/dom.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/globals.js
+init_polyfill_buffer();
+var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : (
+ // @ts-ignore Node typings have this
+ global
+);
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js
+var ResizeObserverSingleton = class _ResizeObserverSingleton {
+ /** @param {ResizeObserverOptions} options */
+ constructor(options) {
+ /**
+ * @private
+ * @readonly
+ * @type {WeakMap}
+ */
+ __publicField(this, "_listeners", "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0);
+ /**
+ * @private
+ * @type {ResizeObserver}
+ */
+ __publicField(this, "_observer");
+ /** @type {ResizeObserverOptions} */
+ __publicField(this, "options");
+ this.options = options;
+ }
+ /**
+ * @param {Element} element
+ * @param {import('./private.js').Listener} listener
+ * @returns {() => void}
+ */
+ observe(element2, listener) {
+ this._listeners.set(element2, listener);
+ this._getObserver().observe(element2, this.options);
+ return () => {
+ this._listeners.delete(element2);
+ this._observer.unobserve(element2);
+ };
+ }
+ /**
+ * @private
+ */
+ _getObserver() {
+ var _a2;
+ return (_a2 = this._observer) != null ? _a2 : this._observer = new ResizeObserver((entries) => {
+ var _a3;
+ for (const entry of entries) {
+ _ResizeObserverSingleton.entries.set(entry.target, entry);
+ (_a3 = this._listeners.get(entry.target)) == null ? void 0 : _a3(entry);
+ }
+ });
+ }
+};
+ResizeObserverSingleton.entries = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0;
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/dom.js
var is_hydrating = false;
function start_hydrating() {
is_hydrating = true;
@@ -26738,26 +36061,37 @@ function append_styles(target, style_sheet_id, styles) {
function get_root_for_style(node) {
if (!node)
return document;
- const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
- if (root && root.host) {
- return root;
+ const root2 = node.getRootNode ? node.getRootNode() : node.ownerDocument;
+ if (root2 && /** @type {ShadowRoot} */
+ root2.host) {
+ return (
+ /** @type {ShadowRoot} */
+ root2
+ );
}
return node.ownerDocument;
}
function append_empty_stylesheet(node) {
const style_element = element("style");
+ style_element.textContent = "/* empty */";
append_stylesheet(get_root_for_style(node), style_element);
return style_element.sheet;
}
function append_stylesheet(node, style) {
- append2(node.head || node, style);
+ append2(
+ /** @type {Document} */
+ node.head || node,
+ style
+ );
return style.sheet;
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
- node.parentNode.removeChild(node);
+ if (node.parentNode) {
+ node.parentNode.removeChild(node);
+ }
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
@@ -26781,10 +36115,10 @@ function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
-function self2(fn) {
+function stop_propagation(fn) {
return function(event) {
- if (event.target === this)
- fn.call(this, event);
+ event.stopPropagation();
+ return fn.call(this, event);
};
}
function attr(node, attribute, value) {
@@ -26798,28 +36132,40 @@ function children(element2) {
}
function set_data(text2, data) {
data = "" + data;
- if (text2.wholeText !== data)
- text2.data = data;
+ if (text2.data === data)
+ return;
+ text2.data = /** @type {string} */
+ data;
}
function set_input_value(input, value) {
input.value = value == null ? "" : value;
}
function set_style(node, key2, value, important) {
- if (value === null) {
+ if (value == null) {
node.style.removeProperty(key2);
} else {
node.style.setProperty(key2, value, important ? "important" : "");
}
}
function toggle_class(element2, name, toggle) {
- element2.classList[toggle ? "add" : "remove"](name);
+ element2.classList.toggle(name, !!toggle);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
- const e = document.createEvent("CustomEvent");
- e.initCustomEvent(type, bubbles, cancelable, detail);
- return e;
+ return new CustomEvent(type, { detail, bubbles, cancelable });
}
-var managed_styles = new Map();
+function get_custom_elements_slots(element2) {
+ const result = {};
+ element2.childNodes.forEach(
+ /** @param {Element} node */
+ (node) => {
+ result[node.slot || "default"] = true;
+ }
+ );
+ return result;
+}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/style_manager.js
+var managed_styles = /* @__PURE__ */ new Map();
var active = 0;
function hash(str) {
let hash2 = 5381;
@@ -26857,7 +36203,10 @@ function create_rule(node, a, b, duration, delay2, ease, fn, uid = 0) {
}
function delete_rule(node, name) {
const previous = (node.style.animation || "").split(", ");
- const next = previous.filter(name ? (anim) => anim.indexOf(name) < 0 : (anim) => anim.indexOf("__svelte") === -1);
+ const next = previous.filter(
+ name ? (anim) => anim.indexOf(name) < 0 : (anim) => anim.indexOf("__svelte") === -1
+ // remove all Svelte animations
+ );
const deleted = previous.length - next.length;
if (deleted) {
node.style.animation = next.join(", ");
@@ -26878,6 +36227,18 @@ function clear_rules() {
managed_styles.clear();
});
}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/await_block.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/transitions.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/scheduler.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/lifecycle.js
+init_polyfill_buffer();
var current_component;
function set_current_component(component) {
current_component = component;
@@ -26896,11 +36257,13 @@ function bubble(component, event) {
callbacks.slice().forEach((fn) => fn.call(this, event));
}
}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/scheduler.js
var dirty_components = [];
var binding_callbacks = [];
var render_callbacks = [];
var flush_callbacks = [];
-var resolved_promise = Promise.resolve();
+var resolved_promise = /* @__PURE__ */ Promise.resolve();
var update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
@@ -26911,16 +36274,25 @@ function schedule_update() {
function add_render_callback(fn) {
render_callbacks.push(fn);
}
-var seen_callbacks = new Set();
+var seen_callbacks = /* @__PURE__ */ new Set();
var flushidx = 0;
function flush() {
+ if (flushidx !== 0) {
+ return;
+ }
const saved_component = current_component;
do {
- while (flushidx < dirty_components.length) {
- const component = dirty_components[flushidx];
- flushidx++;
- set_current_component(component);
- update(component.$$);
+ try {
+ while (flushidx < dirty_components.length) {
+ const component = dirty_components[flushidx];
+ flushidx++;
+ set_current_component(component);
+ update(component.$$);
+ }
+ } catch (e) {
+ dirty_components.length = 0;
+ flushidx = 0;
+ throw e;
}
set_current_component(null);
dirty_components.length = 0;
@@ -26953,6 +36325,15 @@ function update($$) {
$$.after_update.forEach(add_render_callback);
}
}
+function flush_render_callbacks(fns) {
+ const filtered = [];
+ const targets = [];
+ render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
+ targets.forEach((c) => c());
+ render_callbacks = filtered;
+}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/transitions.js
var promise;
function wait() {
if (!promise) {
@@ -26966,13 +36347,14 @@ function wait() {
function dispatch(node, direction, kind) {
node.dispatchEvent(custom_event(`${direction ? "intro" : "outro"}${kind}`));
}
-var outroing = new Set();
+var outroing = /* @__PURE__ */ new Set();
var outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros
+ // parent group
};
}
function check_outros() {
@@ -27007,17 +36389,22 @@ function transition_out(block, local, detach2, callback) {
}
var null_transition = { duration: 0 };
function create_bidirectional_transition(node, fn, params, intro) {
- let config = fn(node, params);
+ const options = { direction: "both" };
+ let config = fn(node, params, options);
let t = intro ? 0 : 1;
let running_program = null;
let pending_program = null;
let animation_name = null;
+ let original_inert_value;
function clear_animation() {
if (animation_name)
delete_rule(node, animation_name);
}
function init3(program, duration) {
- const d = program.b - t;
+ const d = (
+ /** @type {Program['d']} */
+ program.b - t
+ );
duration *= Math.abs(d);
return {
a: t,
@@ -27030,7 +36417,13 @@ function create_bidirectional_transition(node, fn, params, intro) {
};
}
function go(b) {
- const { delay: delay2 = 0, duration = 300, easing = identity, tick: tick2 = noop, css } = config || null_transition;
+ const {
+ delay: delay2 = 0,
+ duration = 300,
+ easing = identity,
+ tick: tick2 = noop,
+ css
+ } = config || null_transition;
const program = {
start: now() + delay2,
b
@@ -27039,6 +36432,17 @@ function create_bidirectional_transition(node, fn, params, intro) {
program.group = outros;
outros.r += 1;
}
+ if ("inert" in node) {
+ if (b) {
+ if (original_inert_value !== void 0) {
+ node.inert = original_inert_value;
+ }
+ } else {
+ original_inert_value = /** @type {HTMLElement} */
+ node.inert;
+ node.inert = true;
+ }
+ }
if (running_program || pending_program) {
pending_program = program;
} else {
@@ -27057,7 +36461,15 @@ function create_bidirectional_transition(node, fn, params, intro) {
dispatch(node, running_program.b, "start");
if (css) {
clear_animation();
- animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
+ animation_name = create_rule(
+ node,
+ t,
+ running_program.b,
+ running_program.duration,
+ 0,
+ easing,
+ config.css
+ );
}
}
if (running_program) {
@@ -27087,7 +36499,8 @@ function create_bidirectional_transition(node, fn, params, intro) {
run(b) {
if (is_function(config)) {
wait().then(() => {
- config = config();
+ const opts = { direction: b ? "in" : "out" };
+ config = config(opts);
go(b);
});
} else {
@@ -27100,57 +36513,79 @@ function create_bidirectional_transition(node, fn, params, intro) {
}
};
}
-var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global;
-var boolean_attributes = new Set([
- "allowfullscreen",
- "allowpaymentrequest",
- "async",
- "autofocus",
- "autoplay",
- "checked",
- "controls",
- "default",
- "defer",
- "disabled",
- "formnovalidate",
- "hidden",
- "inert",
- "ismap",
- "itemscope",
- "loop",
- "multiple",
- "muted",
- "nomodule",
- "novalidate",
- "open",
- "playsinline",
- "readonly",
- "required",
- "reversed",
- "selected"
-]);
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/each.js
+init_polyfill_buffer();
+function ensure_array_like(array_like_or_iterator) {
+ return (array_like_or_iterator == null ? void 0 : array_like_or_iterator.length) !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator);
+}
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/spread.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/ssr.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/shared/boolean_attributes.js
+init_polyfill_buffer();
+var _boolean_attributes = (
+ /** @type {const} */
+ [
+ "allowfullscreen",
+ "allowpaymentrequest",
+ "async",
+ "autofocus",
+ "autoplay",
+ "checked",
+ "controls",
+ "default",
+ "defer",
+ "disabled",
+ "formnovalidate",
+ "hidden",
+ "inert",
+ "ismap",
+ "loop",
+ "multiple",
+ "muted",
+ "nomodule",
+ "novalidate",
+ "open",
+ "playsinline",
+ "readonly",
+ "required",
+ "reversed",
+ "selected"
+ ]
+);
+var boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]);
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/shared/utils/names.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/Component.js
+init_polyfill_buffer();
function create_component(block) {
block && block.c();
}
-function mount_component(component, target, anchor, customElement) {
+function mount_component(component, target, anchor) {
const { fragment, after_update } = component.$$;
fragment && fragment.m(target, anchor);
- if (!customElement) {
- add_render_callback(() => {
- const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
- if (component.$$.on_destroy) {
- component.$$.on_destroy.push(...new_on_destroy);
- } else {
- run_all(new_on_destroy);
- }
- component.$$.on_mount = [];
- });
- }
+ add_render_callback(() => {
+ const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
+ if (component.$$.on_destroy) {
+ component.$$.on_destroy.push(...new_on_destroy);
+ } else {
+ run_all(new_on_destroy);
+ }
+ component.$$.on_mount = [];
+ });
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
+ flush_render_callbacks($$.after_update);
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
$$.on_destroy = $$.fragment = null;
@@ -27165,22 +36600,25 @@ function make_dirty(component, i) {
}
component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}
-function init2(component, options, instance6, create_fragment6, not_equal, props, append_styles2, dirty = [-1]) {
+function init2(component, options, instance10, create_fragment10, not_equal, props, append_styles2, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const $$ = component.$$ = {
fragment: null,
ctx: [],
+ // state
props,
update: noop,
not_equal,
bound: blank_object(),
+ // lifecycle
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
+ // everything else
callbacks: blank_object(),
dirty,
skip_bound: false,
@@ -27188,7 +36626,7 @@ function init2(component, options, instance6, create_fragment6, not_equal, props
};
append_styles2 && append_styles2($$.root);
let ready = false;
- $$.ctx = instance6 ? instance6(component, options.props || {}, (i, ret, ...rest) => {
+ $$.ctx = instance10 ? instance10(component, options.props || {}, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if (!$$.skip_bound && $$.bound[i])
@@ -27201,7 +36639,7 @@ function init2(component, options, instance6, create_fragment6, not_equal, props
$$.update();
ready = true;
run_all($$.before_update);
- $$.fragment = create_fragment6 ? create_fragment6($$.ctx) : false;
+ $$.fragment = create_fragment10 ? create_fragment10($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
start_hydrating();
@@ -27213,7 +36651,7 @@ function init2(component, options, instance6, create_fragment6, not_equal, props
}
if (options.intro)
transition_in(component.$$.fragment);
- mount_component(component, options.target, options.anchor, options.customElement);
+ mount_component(component, options.target, options.anchor);
end_hydrating();
flush();
}
@@ -27222,53 +36660,226 @@ function init2(component, options, instance6, create_fragment6, not_equal, props
var SvelteElement;
if (typeof HTMLElement === "function") {
SvelteElement = class extends HTMLElement {
- constructor() {
+ constructor($$componentCtor, $$slots, use_shadow_dom) {
super();
- this.attachShadow({ mode: "open" });
- }
- connectedCallback() {
- const { on_mount } = this.$$;
- this.$$.on_disconnect = on_mount.map(run).filter(is_function);
- for (const key2 in this.$$.slotted) {
- this.appendChild(this.$$.slotted[key2]);
+ /** The Svelte component constructor */
+ __publicField(this, "$$ctor");
+ /** Slots */
+ __publicField(this, "$$s");
+ /** The Svelte component instance */
+ __publicField(this, "$$c");
+ /** Whether or not the custom element is connected */
+ __publicField(this, "$$cn", false);
+ /** Component props data */
+ __publicField(this, "$$d", {});
+ /** `true` if currently in the process of reflecting component props back to attributes */
+ __publicField(this, "$$r", false);
+ /** @type {Record} Props definition (name, reflected, type etc) */
+ __publicField(this, "$$p_d", {});
+ /** @type {Record} Event listeners */
+ __publicField(this, "$$l", {});
+ /** @type {Map} Event listener unsubscribe functions */
+ __publicField(this, "$$l_u", /* @__PURE__ */ new Map());
+ this.$$ctor = $$componentCtor;
+ this.$$s = $$slots;
+ if (use_shadow_dom) {
+ this.attachShadow({ mode: "open" });
}
}
+ addEventListener(type, listener, options) {
+ this.$$l[type] = this.$$l[type] || [];
+ this.$$l[type].push(listener);
+ if (this.$$c) {
+ const unsub = this.$$c.$on(type, listener);
+ this.$$l_u.set(listener, unsub);
+ }
+ super.addEventListener(type, listener, options);
+ }
+ removeEventListener(type, listener, options) {
+ super.removeEventListener(type, listener, options);
+ if (this.$$c) {
+ const unsub = this.$$l_u.get(listener);
+ if (unsub) {
+ unsub();
+ this.$$l_u.delete(listener);
+ }
+ }
+ }
+ async connectedCallback() {
+ this.$$cn = true;
+ if (!this.$$c) {
+ let create_slot = function(name) {
+ return () => {
+ let node;
+ const obj = {
+ c: function create() {
+ node = element("slot");
+ if (name !== "default") {
+ attr(node, "name", name);
+ }
+ },
+ /**
+ * @param {HTMLElement} target
+ * @param {HTMLElement} [anchor]
+ */
+ m: function mount(target, anchor) {
+ insert(target, node, anchor);
+ },
+ d: function destroy(detaching) {
+ if (detaching) {
+ detach(node);
+ }
+ }
+ };
+ return obj;
+ };
+ };
+ await Promise.resolve();
+ if (!this.$$cn) {
+ return;
+ }
+ const $$slots = {};
+ const existing_slots = get_custom_elements_slots(this);
+ for (const name of this.$$s) {
+ if (name in existing_slots) {
+ $$slots[name] = [create_slot(name)];
+ }
+ }
+ for (const attribute of this.attributes) {
+ const name = this.$$g_p(attribute.name);
+ if (!(name in this.$$d)) {
+ this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp");
+ }
+ }
+ this.$$c = new this.$$ctor({
+ target: this.shadowRoot || this,
+ props: {
+ ...this.$$d,
+ $$slots,
+ $$scope: {
+ ctx: []
+ }
+ }
+ });
+ const reflect_attributes = () => {
+ this.$$r = true;
+ for (const key2 in this.$$p_d) {
+ this.$$d[key2] = this.$$c.$$.ctx[this.$$c.$$.props[key2]];
+ if (this.$$p_d[key2].reflect) {
+ const attribute_value = get_custom_element_value(
+ key2,
+ this.$$d[key2],
+ this.$$p_d,
+ "toAttribute"
+ );
+ if (attribute_value == null) {
+ this.removeAttribute(key2);
+ } else {
+ this.setAttribute(this.$$p_d[key2].attribute || key2, attribute_value);
+ }
+ }
+ }
+ this.$$r = false;
+ };
+ this.$$c.$$.after_update.push(reflect_attributes);
+ reflect_attributes();
+ for (const type in this.$$l) {
+ for (const listener of this.$$l[type]) {
+ const unsub = this.$$c.$on(type, listener);
+ this.$$l_u.set(listener, unsub);
+ }
+ }
+ this.$$l = {};
+ }
+ }
+ // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte
+ // and setting attributes through setAttribute etc, this is helpful
attributeChangedCallback(attr2, _oldValue, newValue) {
- this[attr2] = newValue;
+ var _a2;
+ if (this.$$r)
+ return;
+ attr2 = this.$$g_p(attr2);
+ this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
+ (_a2 = this.$$c) == null ? void 0 : _a2.$set({ [attr2]: this.$$d[attr2] });
}
disconnectedCallback() {
- run_all(this.$$.on_disconnect);
+ this.$$cn = false;
+ Promise.resolve().then(() => {
+ if (!this.$$cn) {
+ this.$$c.$destroy();
+ this.$$c = void 0;
+ }
+ });
}
- $destroy() {
- destroy_component(this, 1);
- this.$destroy = noop;
- }
- $on(type, callback) {
- if (!is_function(callback)) {
- return noop;
- }
- const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
- callbacks.push(callback);
- return () => {
- const index2 = callbacks.indexOf(callback);
- if (index2 !== -1)
- callbacks.splice(index2, 1);
- };
- }
- $set($$props) {
- if (this.$$set && !is_empty($$props)) {
- this.$$.skip_bound = true;
- this.$$set($$props);
- this.$$.skip_bound = false;
- }
+ $$g_p(attribute_name) {
+ return Object.keys(this.$$p_d).find(
+ (key2) => this.$$p_d[key2].attribute === attribute_name || !this.$$p_d[key2].attribute && key2.toLowerCase() === attribute_name
+ ) || attribute_name;
}
};
}
+function get_custom_element_value(prop, value, props_definition, transform) {
+ var _a2;
+ const type = (_a2 = props_definition[prop]) == null ? void 0 : _a2.type;
+ value = type === "Boolean" && typeof value !== "boolean" ? value != null : value;
+ if (!transform || !props_definition[prop]) {
+ return value;
+ } else if (transform === "toAttribute") {
+ switch (type) {
+ case "Object":
+ case "Array":
+ return value == null ? null : JSON.stringify(value);
+ case "Boolean":
+ return value ? "" : null;
+ case "Number":
+ return value == null ? null : value;
+ default:
+ return value;
+ }
+ } else {
+ switch (type) {
+ case "Object":
+ case "Array":
+ return value && JSON.parse(value);
+ case "Boolean":
+ return value;
+ case "Number":
+ return value != null ? +value : value;
+ default:
+ return value;
+ }
+ }
+}
var SvelteComponent = class {
+ constructor() {
+ /**
+ * ### PRIVATE API
+ *
+ * Do not use, may change at any time
+ *
+ * @type {any}
+ */
+ __publicField(this, "$$");
+ /**
+ * ### PRIVATE API
+ *
+ * Do not use, may change at any time
+ *
+ * @type {any}
+ */
+ __publicField(this, "$$set");
+ }
+ /** @returns {void} */
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
+ /**
+ * @template {Extract} K
+ * @param {K} type
+ * @param {((e: Events[K]) => void) | null | undefined} callback
+ * @returns {() => void}
+ */
$on(type, callback) {
if (!is_function(callback)) {
return noop;
@@ -27281,54 +36892,2035 @@ var SvelteComponent = class {
callbacks.splice(index2, 1);
};
}
- $set($$props) {
- if (this.$$set && !is_empty($$props)) {
+ /**
+ * @param {Partial} props
+ * @returns {void}
+ */
+ $set(props) {
+ if (this.$$set && !is_empty(props)) {
this.$$.skip_bound = true;
- this.$$set($$props);
+ this.$$set(props);
this.$$.skip_bound = false;
}
}
};
-// src/ui/sidebar/gitView.svelte
-var import_obsidian21 = __toModule(require("obsidian"));
-
-// node_modules/svelte/index.mjs
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/dev.js
init_polyfill_buffer();
-// node_modules/svelte/transition/index.mjs
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/shared/version.js
+init_polyfill_buffer();
+var PUBLIC_VERSION = "4";
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/internal/disclose-version/index.js
+init_polyfill_buffer();
+if (typeof window !== "undefined")
+ (window.__svelte || (window.__svelte = { v: /* @__PURE__ */ new Set() })).v.add(PUBLIC_VERSION);
+
+// node_modules/.pnpm/tslib@2.6.2/node_modules/tslib/tslib.es6.mjs
+init_polyfill_buffer();
+function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) {
+ return value instanceof P ? value : new P(function(resolve) {
+ resolve(value);
+ });
+ }
+ return new (P || (P = Promise))(function(resolve, reject) {
+ function fulfilled(value) {
+ try {
+ step(generator.next(value));
+ } catch (e) {
+ reject(e);
+ }
+ }
+ function rejected(value) {
+ try {
+ step(generator["throw"](value));
+ } catch (e) {
+ reject(e);
+ }
+ }
+ function step(result) {
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
+ }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+// src/ui/history/historyView.svelte
+var import_obsidian19 = require("obsidian");
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/index.js
init_polyfill_buffer();
-// node_modules/svelte/easing/index.mjs
+// src/ui/history/components/logComponent.svelte
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/transition/index.js
+init_polyfill_buffer();
+
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/easing/index.js
init_polyfill_buffer();
function cubicOut(t) {
const f = t - 1;
return f * f * f + 1;
}
-// node_modules/svelte/transition/index.mjs
-function slide(node, { delay: delay2 = 0, duration = 400, easing = cubicOut } = {}) {
+// node_modules/.pnpm/svelte@4.2.0/node_modules/svelte/src/runtime/transition/index.js
+function slide(node, { delay: delay2 = 0, duration = 400, easing = cubicOut, axis = "y" } = {}) {
const style = getComputedStyle(node);
const opacity = +style.opacity;
- const height = parseFloat(style.height);
- const padding_top = parseFloat(style.paddingTop);
- const padding_bottom = parseFloat(style.paddingBottom);
- const margin_top = parseFloat(style.marginTop);
- const margin_bottom = parseFloat(style.marginBottom);
- const border_top_width = parseFloat(style.borderTopWidth);
- const border_bottom_width = parseFloat(style.borderBottomWidth);
+ const primary_property = axis === "y" ? "height" : "width";
+ const primary_property_value = parseFloat(style[primary_property]);
+ const secondary_properties = axis === "y" ? ["top", "bottom"] : ["left", "right"];
+ const capitalized_secondary_properties = secondary_properties.map(
+ (e) => `${e[0].toUpperCase()}${e.slice(1)}`
+ );
+ const padding_start_value = parseFloat(style[`padding${capitalized_secondary_properties[0]}`]);
+ const padding_end_value = parseFloat(style[`padding${capitalized_secondary_properties[1]}`]);
+ const margin_start_value = parseFloat(style[`margin${capitalized_secondary_properties[0]}`]);
+ const margin_end_value = parseFloat(style[`margin${capitalized_secondary_properties[1]}`]);
+ const border_width_start_value = parseFloat(
+ style[`border${capitalized_secondary_properties[0]}Width`]
+ );
+ const border_width_end_value = parseFloat(
+ style[`border${capitalized_secondary_properties[1]}Width`]
+ );
return {
delay: delay2,
duration,
easing,
- css: (t) => `overflow: hidden;opacity: ${Math.min(t * 20, 1) * opacity};height: ${t * height}px;padding-top: ${t * padding_top}px;padding-bottom: ${t * padding_bottom}px;margin-top: ${t * margin_top}px;margin-bottom: ${t * margin_bottom}px;border-top-width: ${t * border_top_width}px;border-bottom-width: ${t * border_bottom_width}px;`
+ css: (t) => `overflow: hidden;opacity: ${Math.min(t * 20, 1) * opacity};${primary_property}: ${t * primary_property_value}px;padding-${secondary_properties[0]}: ${t * padding_start_value}px;padding-${secondary_properties[1]}: ${t * padding_end_value}px;margin-${secondary_properties[0]}: ${t * margin_start_value}px;margin-${secondary_properties[1]}: ${t * margin_end_value}px;border-${secondary_properties[0]}-width: ${t * border_width_start_value}px;border-${secondary_properties[1]}-width: ${t * border_width_end_value}px;`
};
}
+// src/ui/history/components/logFileComponent.svelte
+init_polyfill_buffer();
+var import_obsidian18 = require("obsidian");
+function add_css(target) {
+ append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}");
+}
+function create_if_block(ctx) {
+ let div;
+ let mounted;
+ let dispose;
+ return {
+ c() {
+ div = element("div");
+ attr(div, "data-icon", "go-to-file");
+ attr(div, "aria-label", "Open File");
+ attr(div, "class", "clickable-icon");
+ },
+ m(target, anchor) {
+ insert(target, div, anchor);
+ ctx[7](div);
+ if (!mounted) {
+ dispose = [
+ listen(div, "auxclick", stop_propagation(
+ /*open*/
+ ctx[4]
+ )),
+ listen(div, "click", stop_propagation(
+ /*open*/
+ ctx[4]
+ ))
+ ];
+ mounted = true;
+ }
+ },
+ p: noop,
+ d(detaching) {
+ if (detaching) {
+ detach(div);
+ }
+ ctx[7](null);
+ mounted = false;
+ run_all(dispose);
+ }
+ };
+}
+function create_fragment(ctx) {
+ let main;
+ let div3;
+ let div0;
+ let t0_value = getDisplayPath(
+ /*diff*/
+ ctx[0].vault_path
+ ) + "";
+ let t0;
+ let t1;
+ let div2;
+ let div1;
+ let show_if = (
+ /*view*/
+ ctx[1].app.vault.getAbstractFileByPath(
+ /*diff*/
+ ctx[0].vault_path
+ )
+ );
+ let t2;
+ let span;
+ let t3_value = (
+ /*diff*/
+ ctx[0].status + ""
+ );
+ let t3;
+ let span_data_type_value;
+ let div3_data_path_value;
+ let div3_aria_label_value;
+ let mounted;
+ let dispose;
+ let if_block = show_if && create_if_block(ctx);
+ return {
+ c() {
+ var _a2, _b;
+ main = element("main");
+ div3 = element("div");
+ div0 = element("div");
+ t0 = text(t0_value);
+ t1 = space();
+ div2 = element("div");
+ div1 = element("div");
+ if (if_block)
+ if_block.c();
+ t2 = space();
+ span = element("span");
+ t3 = text(t3_value);
+ attr(div0, "class", "tree-item-inner nav-file-title-content");
+ attr(div1, "class", "buttons");
+ attr(span, "class", "type");
+ attr(span, "data-type", span_data_type_value = /*diff*/
+ ctx[0].status);
+ attr(div2, "class", "git-tools");
+ attr(div3, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp");
+ attr(div3, "data-path", div3_data_path_value = /*diff*/
+ ctx[0].vault_path);
+ attr(
+ div3,
+ "aria-label-position",
+ /*side*/
+ ctx[3]
+ );
+ attr(
+ div3,
+ "data-tooltip-position",
+ /*side*/
+ ctx[3]
+ );
+ attr(div3, "aria-label", div3_aria_label_value = /*diff*/
+ ctx[0].vault_path);
+ toggle_class(
+ div3,
+ "is-active",
+ /*view*/
+ ((_a2 = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*diff*/
+ ctx[0].vault_path && /*view*/
+ ((_b = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash)
+ );
+ attr(main, "class", "tree-item nav-file svelte-1wbh8tp");
+ },
+ m(target, anchor) {
+ insert(target, main, anchor);
+ append2(main, div3);
+ append2(div3, div0);
+ append2(div0, t0);
+ append2(div3, t1);
+ append2(div3, div2);
+ append2(div2, div1);
+ if (if_block)
+ if_block.m(div1, null);
+ append2(div2, t2);
+ append2(div2, span);
+ append2(span, t3);
+ if (!mounted) {
+ dispose = [
+ listen(main, "click", stop_propagation(
+ /*showDiff*/
+ ctx[5]
+ )),
+ listen(main, "auxclick", stop_propagation(
+ /*showDiff*/
+ ctx[5]
+ )),
+ listen(
+ main,
+ "focus",
+ /*focus_handler*/
+ ctx[6]
+ )
+ ];
+ mounted = true;
+ }
+ },
+ p(ctx2, [dirty]) {
+ var _a2, _b;
+ if (dirty & /*diff*/
+ 1 && t0_value !== (t0_value = getDisplayPath(
+ /*diff*/
+ ctx2[0].vault_path
+ ) + ""))
+ set_data(t0, t0_value);
+ if (dirty & /*view, diff*/
+ 3)
+ show_if = /*view*/
+ ctx2[1].app.vault.getAbstractFileByPath(
+ /*diff*/
+ ctx2[0].vault_path
+ );
+ if (show_if) {
+ if (if_block) {
+ if_block.p(ctx2, dirty);
+ } else {
+ if_block = create_if_block(ctx2);
+ if_block.c();
+ if_block.m(div1, null);
+ }
+ } else if (if_block) {
+ if_block.d(1);
+ if_block = null;
+ }
+ if (dirty & /*diff*/
+ 1 && t3_value !== (t3_value = /*diff*/
+ ctx2[0].status + ""))
+ set_data(t3, t3_value);
+ if (dirty & /*diff*/
+ 1 && span_data_type_value !== (span_data_type_value = /*diff*/
+ ctx2[0].status)) {
+ attr(span, "data-type", span_data_type_value);
+ }
+ if (dirty & /*diff*/
+ 1 && div3_data_path_value !== (div3_data_path_value = /*diff*/
+ ctx2[0].vault_path)) {
+ attr(div3, "data-path", div3_data_path_value);
+ }
+ if (dirty & /*side*/
+ 8) {
+ attr(
+ div3,
+ "aria-label-position",
+ /*side*/
+ ctx2[3]
+ );
+ }
+ if (dirty & /*side*/
+ 8) {
+ attr(
+ div3,
+ "data-tooltip-position",
+ /*side*/
+ ctx2[3]
+ );
+ }
+ if (dirty & /*diff*/
+ 1 && div3_aria_label_value !== (div3_aria_label_value = /*diff*/
+ ctx2[0].vault_path)) {
+ attr(div3, "aria-label", div3_aria_label_value);
+ }
+ if (dirty & /*view, diff*/
+ 3) {
+ toggle_class(
+ div3,
+ "is-active",
+ /*view*/
+ ((_a2 = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*diff*/
+ ctx2[0].vault_path && /*view*/
+ ((_b = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash)
+ );
+ }
+ },
+ i: noop,
+ o: noop,
+ d(detaching) {
+ if (detaching) {
+ detach(main);
+ }
+ if (if_block)
+ if_block.d();
+ mounted = false;
+ run_all(dispose);
+ }
+ };
+}
+function instance($$self, $$props, $$invalidate) {
+ let side;
+ let { diff: diff2 } = $$props;
+ let { view } = $$props;
+ let buttons = [];
+ window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian18.setIcon)(b, b.getAttr("data-icon"))), 0);
+ function open(event) {
+ var _a2;
+ const file = view.app.vault.getAbstractFileByPath(diff2.vault_path);
+ if (file instanceof import_obsidian18.TFile) {
+ (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file);
+ }
+ }
+ function showDiff(event) {
+ var _a2;
+ (_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.setViewState({
+ type: DIFF_VIEW_CONFIG.type,
+ active: true,
+ state: {
+ file: diff2.path,
+ staged: false,
+ hash: diff2.hash
+ }
+ });
+ }
+ function focus_handler(event) {
+ bubble.call(this, $$self, event);
+ }
+ function div_binding($$value) {
+ binding_callbacks[$$value ? "unshift" : "push"](() => {
+ buttons[0] = $$value;
+ $$invalidate(2, buttons);
+ });
+ }
+ $$self.$$set = ($$props2) => {
+ if ("diff" in $$props2)
+ $$invalidate(0, diff2 = $$props2.diff);
+ if ("view" in $$props2)
+ $$invalidate(1, view = $$props2.view);
+ };
+ $$self.$$.update = () => {
+ if ($$self.$$.dirty & /*view*/
+ 2) {
+ $:
+ $$invalidate(3, side = view.leaf.getRoot().side == "left" ? "right" : "left");
+ }
+ };
+ return [diff2, view, buttons, side, open, showDiff, focus_handler, div_binding];
+}
+var LogFileComponent = class extends SvelteComponent {
+ constructor(options) {
+ super();
+ init2(this, options, instance, create_fragment, safe_not_equal, { diff: 0, view: 1 }, add_css);
+ }
+};
+var logFileComponent_default = LogFileComponent;
+
+// src/ui/history/components/logTreeComponent.svelte
+init_polyfill_buffer();
+function add_css2(target) {
+ append_styles(target, "svelte-1lnl15d", "main.svelte-1lnl15d .nav-folder-title-content.svelte-1lnl15d{display:flex;align-items:center}");
+}
+function get_each_context(ctx, list, i) {
+ const child_ctx = ctx.slice();
+ child_ctx[8] = list[i];
+ return child_ctx;
+}
+function create_else_block(ctx) {
+ let div4;
+ let div3;
+ let div0;
+ let t0;
+ let div1;
+ let t1;
+ let div2;
+ let t2_value = (
+ /*entity*/
+ ctx[8].title + ""
+ );
+ let t2;
+ let div3_aria_label_value;
+ let t3;
+ let t4;
+ let current;
+ let mounted;
+ let dispose;
+ function click_handler() {
+ return (
+ /*click_handler*/
+ ctx[7](
+ /*entity*/
+ ctx[8]
+ )
+ );
+ }
+ let if_block = !/*closed*/
+ ctx[4][
+ /*entity*/
+ ctx[8].title
+ ] && create_if_block_1(ctx);
+ return {
+ c() {
+ div4 = element("div");
+ div3 = element("div");
+ div0 = element("div");
+ t0 = space();
+ div1 = element("div");
+ div1.innerHTML = ``;
+ t1 = space();
+ div2 = element("div");
+ t2 = text(t2_value);
+ t3 = space();
+ if (if_block)
+ if_block.c();
+ t4 = space();
+ attr(div0, "data-icon", "folder");
+ set_style(div0, "padding-right", "5px");
+ set_style(div0, "display", "flex");
+ attr(div1, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon");
+ toggle_class(
+ div1,
+ "is-collapsed",
+ /*closed*/
+ ctx[4][
+ /*entity*/
+ ctx[8].title
+ ]
+ );
+ attr(div2, "class", "tree-item-inner nav-folder-title-content svelte-1lnl15d");
+ attr(div3, "class", "tree-item-self is-clickable nav-folder-title");
+ attr(
+ div3,
+ "aria-label-position",
+ /*side*/
+ ctx[5]
+ );
+ attr(
+ div3,
+ "data-tooltip-position",
+ /*side*/
+ ctx[5]
+ );
+ attr(div3, "aria-label", div3_aria_label_value = /*entity*/
+ ctx[8].vaultPath);
+ attr(div4, "class", "tree-item nav-folder");
+ toggle_class(
+ div4,
+ "is-collapsed",
+ /*closed*/
+ ctx[4][
+ /*entity*/
+ ctx[8].title
+ ]
+ );
+ },
+ m(target, anchor) {
+ insert(target, div4, anchor);
+ append2(div4, div3);
+ append2(div3, div0);
+ append2(div3, t0);
+ append2(div3, div1);
+ append2(div3, t1);
+ append2(div3, div2);
+ append2(div2, t2);
+ append2(div4, t3);
+ if (if_block)
+ if_block.m(div4, null);
+ append2(div4, t4);
+ current = true;
+ if (!mounted) {
+ dispose = listen(div3, "click", click_handler);
+ mounted = true;
+ }
+ },
+ p(new_ctx, dirty) {
+ ctx = new_ctx;
+ if (!current || dirty & /*closed, hierarchy*/
+ 17) {
+ toggle_class(
+ div1,
+ "is-collapsed",
+ /*closed*/
+ ctx[4][
+ /*entity*/
+ ctx[8].title
+ ]
+ );
+ }
+ if ((!current || dirty & /*hierarchy*/
+ 1) && t2_value !== (t2_value = /*entity*/
+ ctx[8].title + ""))
+ set_data(t2, t2_value);
+ if (!current || dirty & /*side*/
+ 32) {
+ attr(
+ div3,
+ "aria-label-position",
+ /*side*/
+ ctx[5]
+ );
+ }
+ if (!current || dirty & /*side*/
+ 32) {
+ attr(
+ div3,
+ "data-tooltip-position",
+ /*side*/
+ ctx[5]
+ );
+ }
+ if (!current || dirty & /*hierarchy*/
+ 1 && div3_aria_label_value !== (div3_aria_label_value = /*entity*/
+ ctx[8].vaultPath)) {
+ attr(div3, "aria-label", div3_aria_label_value);
+ }
+ if (!/*closed*/
+ ctx[4][
+ /*entity*/
+ ctx[8].title
+ ]) {
+ if (if_block) {
+ if_block.p(ctx, dirty);
+ if (dirty & /*closed, hierarchy*/
+ 17) {
+ transition_in(if_block, 1);
+ }
+ } else {
+ if_block = create_if_block_1(ctx);
+ if_block.c();
+ transition_in(if_block, 1);
+ if_block.m(div4, t4);
+ }
+ } else if (if_block) {
+ group_outros();
+ transition_out(if_block, 1, 1, () => {
+ if_block = null;
+ });
+ check_outros();
+ }
+ if (!current || dirty & /*closed, hierarchy*/
+ 17) {
+ toggle_class(
+ div4,
+ "is-collapsed",
+ /*closed*/
+ ctx[4][
+ /*entity*/
+ ctx[8].title
+ ]
+ );
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(if_block);
+ current = true;
+ },
+ o(local) {
+ transition_out(if_block);
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(div4);
+ }
+ if (if_block)
+ if_block.d();
+ mounted = false;
+ dispose();
+ }
+ };
+}
+function create_if_block2(ctx) {
+ let div;
+ let logfilecomponent;
+ let t;
+ let current;
+ logfilecomponent = new logFileComponent_default({
+ props: {
+ diff: (
+ /*entity*/
+ ctx[8].data
+ ),
+ view: (
+ /*view*/
+ ctx[2]
+ )
+ }
+ });
+ return {
+ c() {
+ div = element("div");
+ create_component(logfilecomponent.$$.fragment);
+ t = space();
+ },
+ m(target, anchor) {
+ insert(target, div, anchor);
+ mount_component(logfilecomponent, div, null);
+ append2(div, t);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ const logfilecomponent_changes = {};
+ if (dirty & /*hierarchy*/
+ 1)
+ logfilecomponent_changes.diff = /*entity*/
+ ctx2[8].data;
+ if (dirty & /*view*/
+ 4)
+ logfilecomponent_changes.view = /*view*/
+ ctx2[2];
+ logfilecomponent.$set(logfilecomponent_changes);
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(logfilecomponent.$$.fragment, local);
+ current = true;
+ },
+ o(local) {
+ transition_out(logfilecomponent.$$.fragment, local);
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(div);
+ }
+ destroy_component(logfilecomponent);
+ }
+ };
+}
+function create_if_block_1(ctx) {
+ let div;
+ let logtreecomponent;
+ let div_transition;
+ let current;
+ logtreecomponent = new LogTreeComponent({
+ props: {
+ hierarchy: (
+ /*entity*/
+ ctx[8]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[1]
+ ),
+ view: (
+ /*view*/
+ ctx[2]
+ )
+ }
+ });
+ return {
+ c() {
+ div = element("div");
+ create_component(logtreecomponent.$$.fragment);
+ attr(div, "class", "tree-item-children nav-folder-children");
+ },
+ m(target, anchor) {
+ insert(target, div, anchor);
+ mount_component(logtreecomponent, div, null);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ const logtreecomponent_changes = {};
+ if (dirty & /*hierarchy*/
+ 1)
+ logtreecomponent_changes.hierarchy = /*entity*/
+ ctx2[8];
+ if (dirty & /*plugin*/
+ 2)
+ logtreecomponent_changes.plugin = /*plugin*/
+ ctx2[1];
+ if (dirty & /*view*/
+ 4)
+ logtreecomponent_changes.view = /*view*/
+ ctx2[2];
+ logtreecomponent.$set(logtreecomponent_changes);
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(logtreecomponent.$$.fragment, local);
+ if (local) {
+ add_render_callback(() => {
+ if (!current)
+ return;
+ if (!div_transition)
+ div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true);
+ div_transition.run(1);
+ });
+ }
+ current = true;
+ },
+ o(local) {
+ transition_out(logtreecomponent.$$.fragment, local);
+ if (local) {
+ if (!div_transition)
+ div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false);
+ div_transition.run(0);
+ }
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(div);
+ }
+ destroy_component(logtreecomponent);
+ if (detaching && div_transition)
+ div_transition.end();
+ }
+ };
+}
+function create_each_block(ctx) {
+ let current_block_type_index;
+ let if_block;
+ let if_block_anchor;
+ let current;
+ const if_block_creators = [create_if_block2, create_else_block];
+ const if_blocks = [];
+ function select_block_type(ctx2, dirty) {
+ if (
+ /*entity*/
+ ctx2[8].data
+ )
+ return 0;
+ return 1;
+ }
+ current_block_type_index = select_block_type(ctx, -1);
+ if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
+ return {
+ c() {
+ if_block.c();
+ if_block_anchor = empty();
+ },
+ m(target, anchor) {
+ if_blocks[current_block_type_index].m(target, anchor);
+ insert(target, if_block_anchor, anchor);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ let previous_block_index = current_block_type_index;
+ current_block_type_index = select_block_type(ctx2, dirty);
+ if (current_block_type_index === previous_block_index) {
+ if_blocks[current_block_type_index].p(ctx2, dirty);
+ } else {
+ group_outros();
+ transition_out(if_blocks[previous_block_index], 1, 1, () => {
+ if_blocks[previous_block_index] = null;
+ });
+ check_outros();
+ if_block = if_blocks[current_block_type_index];
+ if (!if_block) {
+ if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
+ if_block.c();
+ } else {
+ if_block.p(ctx2, dirty);
+ }
+ transition_in(if_block, 1);
+ if_block.m(if_block_anchor.parentNode, if_block_anchor);
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(if_block);
+ current = true;
+ },
+ o(local) {
+ transition_out(if_block);
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(if_block_anchor);
+ }
+ if_blocks[current_block_type_index].d(detaching);
+ }
+ };
+}
+function create_fragment2(ctx) {
+ let main;
+ let current;
+ let each_value = ensure_array_like(
+ /*hierarchy*/
+ ctx[0].children
+ );
+ let each_blocks = [];
+ for (let i = 0; i < each_value.length; i += 1) {
+ each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
+ }
+ const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
+ each_blocks[i] = null;
+ });
+ return {
+ c() {
+ main = element("main");
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ each_blocks[i].c();
+ }
+ attr(main, "class", "svelte-1lnl15d");
+ toggle_class(
+ main,
+ "topLevel",
+ /*topLevel*/
+ ctx[3]
+ );
+ },
+ m(target, anchor) {
+ insert(target, main, anchor);
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ if (each_blocks[i]) {
+ each_blocks[i].m(main, null);
+ }
+ }
+ current = true;
+ },
+ p(ctx2, [dirty]) {
+ if (dirty & /*hierarchy, view, closed, plugin, side, fold*/
+ 119) {
+ each_value = ensure_array_like(
+ /*hierarchy*/
+ ctx2[0].children
+ );
+ let i;
+ for (i = 0; i < each_value.length; i += 1) {
+ const child_ctx = get_each_context(ctx2, each_value, i);
+ if (each_blocks[i]) {
+ each_blocks[i].p(child_ctx, dirty);
+ transition_in(each_blocks[i], 1);
+ } else {
+ each_blocks[i] = create_each_block(child_ctx);
+ each_blocks[i].c();
+ transition_in(each_blocks[i], 1);
+ each_blocks[i].m(main, null);
+ }
+ }
+ group_outros();
+ for (i = each_value.length; i < each_blocks.length; i += 1) {
+ out(i);
+ }
+ check_outros();
+ }
+ if (!current || dirty & /*topLevel*/
+ 8) {
+ toggle_class(
+ main,
+ "topLevel",
+ /*topLevel*/
+ ctx2[3]
+ );
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ for (let i = 0; i < each_value.length; i += 1) {
+ transition_in(each_blocks[i]);
+ }
+ current = true;
+ },
+ o(local) {
+ each_blocks = each_blocks.filter(Boolean);
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ transition_out(each_blocks[i]);
+ }
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(main);
+ }
+ destroy_each(each_blocks, detaching);
+ }
+ };
+}
+function instance2($$self, $$props, $$invalidate) {
+ let side;
+ let { hierarchy } = $$props;
+ let { plugin } = $$props;
+ let { view } = $$props;
+ let { topLevel = false } = $$props;
+ const closed = {};
+ function fold(item) {
+ $$invalidate(4, closed[item.title] = !closed[item.title], closed);
+ }
+ const click_handler = (entity) => fold(entity);
+ $$self.$$set = ($$props2) => {
+ if ("hierarchy" in $$props2)
+ $$invalidate(0, hierarchy = $$props2.hierarchy);
+ if ("plugin" in $$props2)
+ $$invalidate(1, plugin = $$props2.plugin);
+ if ("view" in $$props2)
+ $$invalidate(2, view = $$props2.view);
+ if ("topLevel" in $$props2)
+ $$invalidate(3, topLevel = $$props2.topLevel);
+ };
+ $$self.$$.update = () => {
+ if ($$self.$$.dirty & /*view*/
+ 4) {
+ $:
+ $$invalidate(5, side = view.leaf.getRoot().side == "left" ? "right" : "left");
+ }
+ };
+ return [hierarchy, plugin, view, topLevel, closed, side, fold, click_handler];
+}
+var LogTreeComponent = class extends SvelteComponent {
+ constructor(options) {
+ super();
+ init2(
+ this,
+ options,
+ instance2,
+ create_fragment2,
+ safe_not_equal,
+ {
+ hierarchy: 0,
+ plugin: 1,
+ view: 2,
+ topLevel: 3
+ },
+ add_css2
+ );
+ }
+};
+var logTreeComponent_default = LogTreeComponent;
+
+// src/ui/history/components/logComponent.svelte
+function add_css3(target) {
+ append_styles(target, "svelte-1t6egnt", ".git-ref.svelte-1t6egnt{color:var(--text-accent)}");
+}
+function get_each_context2(ctx, list, i) {
+ const child_ctx = ctx.slice();
+ child_ctx[8] = list[i];
+ return child_ctx;
+}
+function create_if_block_2(ctx) {
+ let div;
+ let t_value = (
+ /*log*/
+ ctx[0].refs.join(", ") + ""
+ );
+ let t;
+ return {
+ c() {
+ div = element("div");
+ t = text(t_value);
+ attr(div, "class", "git-ref svelte-1t6egnt");
+ },
+ m(target, anchor) {
+ insert(target, div, anchor);
+ append2(div, t);
+ },
+ p(ctx2, dirty) {
+ if (dirty & /*log*/
+ 1 && t_value !== (t_value = /*log*/
+ ctx2[0].refs.join(", ") + ""))
+ set_data(t, t_value);
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(div);
+ }
+ }
+ };
+}
+function create_if_block3(ctx) {
+ let div;
+ let current_block_type_index;
+ let if_block;
+ let div_transition;
+ let current;
+ const if_block_creators = [create_if_block_12, create_else_block2];
+ const if_blocks = [];
+ function select_block_type(ctx2, dirty) {
+ if (
+ /*showTree*/
+ ctx2[2]
+ )
+ return 0;
+ return 1;
+ }
+ current_block_type_index = select_block_type(ctx, -1);
+ if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
+ return {
+ c() {
+ div = element("div");
+ if_block.c();
+ attr(div, "class", "tree-item-children nav-folder-children");
+ },
+ m(target, anchor) {
+ insert(target, div, anchor);
+ if_blocks[current_block_type_index].m(div, null);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ let previous_block_index = current_block_type_index;
+ current_block_type_index = select_block_type(ctx2, dirty);
+ if (current_block_type_index === previous_block_index) {
+ if_blocks[current_block_type_index].p(ctx2, dirty);
+ } else {
+ group_outros();
+ transition_out(if_blocks[previous_block_index], 1, 1, () => {
+ if_blocks[previous_block_index] = null;
+ });
+ check_outros();
+ if_block = if_blocks[current_block_type_index];
+ if (!if_block) {
+ if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
+ if_block.c();
+ } else {
+ if_block.p(ctx2, dirty);
+ }
+ transition_in(if_block, 1);
+ if_block.m(div, null);
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(if_block);
+ if (local) {
+ add_render_callback(() => {
+ if (!current)
+ return;
+ if (!div_transition)
+ div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true);
+ div_transition.run(1);
+ });
+ }
+ current = true;
+ },
+ o(local) {
+ transition_out(if_block);
+ if (local) {
+ if (!div_transition)
+ div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, false);
+ div_transition.run(0);
+ }
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(div);
+ }
+ if_blocks[current_block_type_index].d();
+ if (detaching && div_transition)
+ div_transition.end();
+ }
+ };
+}
+function create_else_block2(ctx) {
+ let each_1_anchor;
+ let current;
+ let each_value = ensure_array_like(
+ /*log*/
+ ctx[0].diff.files
+ );
+ let each_blocks = [];
+ for (let i = 0; i < each_value.length; i += 1) {
+ each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i));
+ }
+ const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
+ each_blocks[i] = null;
+ });
+ return {
+ c() {
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ each_blocks[i].c();
+ }
+ each_1_anchor = empty();
+ },
+ m(target, anchor) {
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ if (each_blocks[i]) {
+ each_blocks[i].m(target, anchor);
+ }
+ }
+ insert(target, each_1_anchor, anchor);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ if (dirty & /*view, log*/
+ 3) {
+ each_value = ensure_array_like(
+ /*log*/
+ ctx2[0].diff.files
+ );
+ let i;
+ for (i = 0; i < each_value.length; i += 1) {
+ const child_ctx = get_each_context2(ctx2, each_value, i);
+ if (each_blocks[i]) {
+ each_blocks[i].p(child_ctx, dirty);
+ transition_in(each_blocks[i], 1);
+ } else {
+ each_blocks[i] = create_each_block2(child_ctx);
+ each_blocks[i].c();
+ transition_in(each_blocks[i], 1);
+ each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
+ }
+ }
+ group_outros();
+ for (i = each_value.length; i < each_blocks.length; i += 1) {
+ out(i);
+ }
+ check_outros();
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ for (let i = 0; i < each_value.length; i += 1) {
+ transition_in(each_blocks[i]);
+ }
+ current = true;
+ },
+ o(local) {
+ each_blocks = each_blocks.filter(Boolean);
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ transition_out(each_blocks[i]);
+ }
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(each_1_anchor);
+ }
+ destroy_each(each_blocks, detaching);
+ }
+ };
+}
+function create_if_block_12(ctx) {
+ let logtreecomponent;
+ let current;
+ logtreecomponent = new logTreeComponent_default({
+ props: {
+ hierarchy: (
+ /*logsHierarchy*/
+ ctx[6]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[3]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ topLevel: true
+ }
+ });
+ return {
+ c() {
+ create_component(logtreecomponent.$$.fragment);
+ },
+ m(target, anchor) {
+ mount_component(logtreecomponent, target, anchor);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ const logtreecomponent_changes = {};
+ if (dirty & /*logsHierarchy*/
+ 64)
+ logtreecomponent_changes.hierarchy = /*logsHierarchy*/
+ ctx2[6];
+ if (dirty & /*plugin*/
+ 8)
+ logtreecomponent_changes.plugin = /*plugin*/
+ ctx2[3];
+ if (dirty & /*view*/
+ 2)
+ logtreecomponent_changes.view = /*view*/
+ ctx2[1];
+ logtreecomponent.$set(logtreecomponent_changes);
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(logtreecomponent.$$.fragment, local);
+ current = true;
+ },
+ o(local) {
+ transition_out(logtreecomponent.$$.fragment, local);
+ current = false;
+ },
+ d(detaching) {
+ destroy_component(logtreecomponent, detaching);
+ }
+ };
+}
+function create_each_block2(ctx) {
+ let logfilecomponent;
+ let current;
+ logfilecomponent = new logFileComponent_default({
+ props: {
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ diff: (
+ /*file*/
+ ctx[8]
+ )
+ }
+ });
+ return {
+ c() {
+ create_component(logfilecomponent.$$.fragment);
+ },
+ m(target, anchor) {
+ mount_component(logfilecomponent, target, anchor);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ const logfilecomponent_changes = {};
+ if (dirty & /*view*/
+ 2)
+ logfilecomponent_changes.view = /*view*/
+ ctx2[1];
+ if (dirty & /*log*/
+ 1)
+ logfilecomponent_changes.diff = /*file*/
+ ctx2[8];
+ logfilecomponent.$set(logfilecomponent_changes);
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(logfilecomponent.$$.fragment, local);
+ current = true;
+ },
+ o(local) {
+ transition_out(logfilecomponent.$$.fragment, local);
+ current = false;
+ },
+ d(detaching) {
+ destroy_component(logfilecomponent, detaching);
+ }
+ };
+}
+function create_fragment3(ctx) {
+ let main;
+ let div4;
+ let div3;
+ let div0;
+ let t0;
+ let div2;
+ let t1;
+ let div1;
+ let t2_value = (
+ /*log*/
+ ctx[0].message + ""
+ );
+ let t2;
+ let div1_aria_label_value;
+ let t3;
+ let current;
+ let mounted;
+ let dispose;
+ let if_block0 = (
+ /*log*/
+ ctx[0].refs.length > 0 && create_if_block_2(ctx)
+ );
+ let if_block1 = !/*isCollapsed*/
+ ctx[4] && create_if_block3(ctx);
+ return {
+ c() {
+ main = element("main");
+ div4 = element("div");
+ div3 = element("div");
+ div0 = element("div");
+ div0.innerHTML = ``;
+ t0 = space();
+ div2 = element("div");
+ if (if_block0)
+ if_block0.c();
+ t1 = space();
+ div1 = element("div");
+ t2 = text(t2_value);
+ t3 = space();
+ if (if_block1)
+ if_block1.c();
+ attr(div0, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon");
+ toggle_class(
+ div0,
+ "is-collapsed",
+ /*isCollapsed*/
+ ctx[4]
+ );
+ attr(div1, "class", "tree-item-inner nav-folder-title-content");
+ attr(div1, "aria-label", div1_aria_label_value = /*log*/
+ ctx[0].message);
+ attr(
+ div1,
+ "aria-label-position",
+ /*side*/
+ ctx[5]
+ );
+ attr(
+ div1,
+ "data-tooltip-position",
+ /*side*/
+ ctx[5]
+ );
+ attr(div3, "class", "tree-item-self is-clickable nav-folder-title");
+ attr(div4, "class", "tree-item nav-folder");
+ toggle_class(
+ div4,
+ "is-collapsed",
+ /*isCollapsed*/
+ ctx[4]
+ );
+ },
+ m(target, anchor) {
+ insert(target, main, anchor);
+ append2(main, div4);
+ append2(div4, div3);
+ append2(div3, div0);
+ append2(div3, t0);
+ append2(div3, div2);
+ if (if_block0)
+ if_block0.m(div2, null);
+ append2(div2, t1);
+ append2(div2, div1);
+ append2(div1, t2);
+ append2(div4, t3);
+ if (if_block1)
+ if_block1.m(div4, null);
+ current = true;
+ if (!mounted) {
+ dispose = listen(
+ div3,
+ "click",
+ /*click_handler*/
+ ctx[7]
+ );
+ mounted = true;
+ }
+ },
+ p(ctx2, [dirty]) {
+ if (!current || dirty & /*isCollapsed*/
+ 16) {
+ toggle_class(
+ div0,
+ "is-collapsed",
+ /*isCollapsed*/
+ ctx2[4]
+ );
+ }
+ if (
+ /*log*/
+ ctx2[0].refs.length > 0
+ ) {
+ if (if_block0) {
+ if_block0.p(ctx2, dirty);
+ } else {
+ if_block0 = create_if_block_2(ctx2);
+ if_block0.c();
+ if_block0.m(div2, t1);
+ }
+ } else if (if_block0) {
+ if_block0.d(1);
+ if_block0 = null;
+ }
+ if ((!current || dirty & /*log*/
+ 1) && t2_value !== (t2_value = /*log*/
+ ctx2[0].message + ""))
+ set_data(t2, t2_value);
+ if (!current || dirty & /*log*/
+ 1 && div1_aria_label_value !== (div1_aria_label_value = /*log*/
+ ctx2[0].message)) {
+ attr(div1, "aria-label", div1_aria_label_value);
+ }
+ if (!current || dirty & /*side*/
+ 32) {
+ attr(
+ div1,
+ "aria-label-position",
+ /*side*/
+ ctx2[5]
+ );
+ }
+ if (!current || dirty & /*side*/
+ 32) {
+ attr(
+ div1,
+ "data-tooltip-position",
+ /*side*/
+ ctx2[5]
+ );
+ }
+ if (!/*isCollapsed*/
+ ctx2[4]) {
+ if (if_block1) {
+ if_block1.p(ctx2, dirty);
+ if (dirty & /*isCollapsed*/
+ 16) {
+ transition_in(if_block1, 1);
+ }
+ } else {
+ if_block1 = create_if_block3(ctx2);
+ if_block1.c();
+ transition_in(if_block1, 1);
+ if_block1.m(div4, null);
+ }
+ } else if (if_block1) {
+ group_outros();
+ transition_out(if_block1, 1, 1, () => {
+ if_block1 = null;
+ });
+ check_outros();
+ }
+ if (!current || dirty & /*isCollapsed*/
+ 16) {
+ toggle_class(
+ div4,
+ "is-collapsed",
+ /*isCollapsed*/
+ ctx2[4]
+ );
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(if_block1);
+ current = true;
+ },
+ o(local) {
+ transition_out(if_block1);
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(main);
+ }
+ if (if_block0)
+ if_block0.d();
+ if (if_block1)
+ if_block1.d();
+ mounted = false;
+ dispose();
+ }
+ };
+}
+function instance3($$self, $$props, $$invalidate) {
+ let logsHierarchy;
+ let side;
+ let { log: log2 } = $$props;
+ let { view } = $$props;
+ let { showTree } = $$props;
+ let { plugin } = $$props;
+ let isCollapsed = true;
+ const click_handler = () => $$invalidate(4, isCollapsed = !isCollapsed);
+ $$self.$$set = ($$props2) => {
+ if ("log" in $$props2)
+ $$invalidate(0, log2 = $$props2.log);
+ if ("view" in $$props2)
+ $$invalidate(1, view = $$props2.view);
+ if ("showTree" in $$props2)
+ $$invalidate(2, showTree = $$props2.showTree);
+ if ("plugin" in $$props2)
+ $$invalidate(3, plugin = $$props2.plugin);
+ };
+ $$self.$$.update = () => {
+ if ($$self.$$.dirty & /*plugin, log*/
+ 9) {
+ $:
+ $$invalidate(6, logsHierarchy = {
+ title: "",
+ path: "",
+ vaultPath: "",
+ children: plugin.gitManager.getTreeStructure(log2.diff.files)
+ });
+ }
+ if ($$self.$$.dirty & /*view*/
+ 2) {
+ $:
+ $$invalidate(5, side = view.leaf.getRoot().side == "left" ? "right" : "left");
+ }
+ };
+ return [log2, view, showTree, plugin, isCollapsed, side, logsHierarchy, click_handler];
+}
+var LogComponent = class extends SvelteComponent {
+ constructor(options) {
+ super();
+ init2(this, options, instance3, create_fragment3, safe_not_equal, { log: 0, view: 1, showTree: 2, plugin: 3 }, add_css3);
+ }
+};
+var logComponent_default = LogComponent;
+
+// src/ui/history/historyView.svelte
+function get_each_context3(ctx, list, i) {
+ const child_ctx = ctx.slice();
+ child_ctx[11] = list[i];
+ return child_ctx;
+}
+function create_if_block4(ctx) {
+ let div1;
+ let div0;
+ let current;
+ let each_value = ensure_array_like(
+ /*logs*/
+ ctx[6]
+ );
+ let each_blocks = [];
+ for (let i = 0; i < each_value.length; i += 1) {
+ each_blocks[i] = create_each_block3(get_each_context3(ctx, each_value, i));
+ }
+ const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
+ each_blocks[i] = null;
+ });
+ return {
+ c() {
+ div1 = element("div");
+ div0 = element("div");
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ each_blocks[i].c();
+ }
+ attr(div0, "class", "tree-item-children nav-folder-children");
+ attr(div1, "class", "tree-item nav-folder mod-root");
+ },
+ m(target, anchor) {
+ insert(target, div1, anchor);
+ append2(div1, div0);
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ if (each_blocks[i]) {
+ each_blocks[i].m(div0, null);
+ }
+ }
+ current = true;
+ },
+ p(ctx2, dirty) {
+ if (dirty & /*view, showTree, logs, plugin*/
+ 71) {
+ each_value = ensure_array_like(
+ /*logs*/
+ ctx2[6]
+ );
+ let i;
+ for (i = 0; i < each_value.length; i += 1) {
+ const child_ctx = get_each_context3(ctx2, each_value, i);
+ if (each_blocks[i]) {
+ each_blocks[i].p(child_ctx, dirty);
+ transition_in(each_blocks[i], 1);
+ } else {
+ each_blocks[i] = create_each_block3(child_ctx);
+ each_blocks[i].c();
+ transition_in(each_blocks[i], 1);
+ each_blocks[i].m(div0, null);
+ }
+ }
+ group_outros();
+ for (i = each_value.length; i < each_blocks.length; i += 1) {
+ out(i);
+ }
+ check_outros();
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ for (let i = 0; i < each_value.length; i += 1) {
+ transition_in(each_blocks[i]);
+ }
+ current = true;
+ },
+ o(local) {
+ each_blocks = each_blocks.filter(Boolean);
+ for (let i = 0; i < each_blocks.length; i += 1) {
+ transition_out(each_blocks[i]);
+ }
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(div1);
+ }
+ destroy_each(each_blocks, detaching);
+ }
+ };
+}
+function create_each_block3(ctx) {
+ let logcomponent;
+ let current;
+ logcomponent = new logComponent_default({
+ props: {
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ showTree: (
+ /*showTree*/
+ ctx[2]
+ ),
+ log: (
+ /*log*/
+ ctx[11]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[0]
+ )
+ }
+ });
+ return {
+ c() {
+ create_component(logcomponent.$$.fragment);
+ },
+ m(target, anchor) {
+ mount_component(logcomponent, target, anchor);
+ current = true;
+ },
+ p(ctx2, dirty) {
+ const logcomponent_changes = {};
+ if (dirty & /*view*/
+ 2)
+ logcomponent_changes.view = /*view*/
+ ctx2[1];
+ if (dirty & /*showTree*/
+ 4)
+ logcomponent_changes.showTree = /*showTree*/
+ ctx2[2];
+ if (dirty & /*logs*/
+ 64)
+ logcomponent_changes.log = /*log*/
+ ctx2[11];
+ if (dirty & /*plugin*/
+ 1)
+ logcomponent_changes.plugin = /*plugin*/
+ ctx2[0];
+ logcomponent.$set(logcomponent_changes);
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(logcomponent.$$.fragment, local);
+ current = true;
+ },
+ o(local) {
+ transition_out(logcomponent.$$.fragment, local);
+ current = false;
+ },
+ d(detaching) {
+ destroy_component(logcomponent, detaching);
+ }
+ };
+}
+function create_fragment4(ctx) {
+ let main;
+ let div3;
+ let div2;
+ let div0;
+ let t0;
+ let div1;
+ let t1;
+ let div4;
+ let current;
+ let mounted;
+ let dispose;
+ let if_block = (
+ /*logs*/
+ ctx[6] && create_if_block4(ctx)
+ );
+ return {
+ c() {
+ main = element("main");
+ div3 = element("div");
+ div2 = element("div");
+ div0 = element("div");
+ t0 = space();
+ div1 = element("div");
+ t1 = space();
+ div4 = element("div");
+ if (if_block)
+ if_block.c();
+ attr(div0, "id", "layoutChange");
+ attr(div0, "class", "clickable-icon nav-action-button");
+ attr(div0, "aria-label", "Change Layout");
+ attr(div1, "id", "refresh");
+ attr(div1, "class", "clickable-icon nav-action-button");
+ attr(div1, "data-icon", "refresh-cw");
+ attr(div1, "aria-label", "Refresh");
+ set_style(div1, "margin", "1px");
+ toggle_class(
+ div1,
+ "loading",
+ /*loading*/
+ ctx[4]
+ );
+ attr(div2, "class", "nav-buttons-container");
+ attr(div3, "class", "nav-header");
+ attr(div4, "class", "nav-files-container");
+ set_style(div4, "position", "relative");
+ },
+ m(target, anchor) {
+ insert(target, main, anchor);
+ append2(main, div3);
+ append2(div3, div2);
+ append2(div2, div0);
+ ctx[7](div0);
+ append2(div2, t0);
+ append2(div2, div1);
+ ctx[9](div1);
+ append2(main, t1);
+ append2(main, div4);
+ if (if_block)
+ if_block.m(div4, null);
+ current = true;
+ if (!mounted) {
+ dispose = [
+ listen(
+ div0,
+ "click",
+ /*click_handler*/
+ ctx[8]
+ ),
+ listen(div1, "click", triggerRefresh)
+ ];
+ mounted = true;
+ }
+ },
+ p(ctx2, [dirty]) {
+ if (!current || dirty & /*loading*/
+ 16) {
+ toggle_class(
+ div1,
+ "loading",
+ /*loading*/
+ ctx2[4]
+ );
+ }
+ if (
+ /*logs*/
+ ctx2[6]
+ ) {
+ if (if_block) {
+ if_block.p(ctx2, dirty);
+ if (dirty & /*logs*/
+ 64) {
+ transition_in(if_block, 1);
+ }
+ } else {
+ if_block = create_if_block4(ctx2);
+ if_block.c();
+ transition_in(if_block, 1);
+ if_block.m(div4, null);
+ }
+ } else if (if_block) {
+ group_outros();
+ transition_out(if_block, 1, 1, () => {
+ if_block = null;
+ });
+ check_outros();
+ }
+ },
+ i(local) {
+ if (current)
+ return;
+ transition_in(if_block);
+ current = true;
+ },
+ o(local) {
+ transition_out(if_block);
+ current = false;
+ },
+ d(detaching) {
+ if (detaching) {
+ detach(main);
+ }
+ ctx[7](null);
+ ctx[9](null);
+ if (if_block)
+ if_block.d();
+ mounted = false;
+ run_all(dispose);
+ }
+ };
+}
+function triggerRefresh() {
+ dispatchEvent(new CustomEvent("git-refresh"));
+}
+function instance4($$self, $$props, $$invalidate) {
+ let { plugin } = $$props;
+ let { view } = $$props;
+ let loading;
+ let buttons = [];
+ let logs;
+ let showTree = plugin.settings.treeStructure;
+ let layoutBtn;
+ addEventListener("git-view-refresh", refresh);
+ plugin.app.workspace.onLayoutReady(() => {
+ window.setTimeout(
+ () => {
+ buttons.forEach((btn) => (0, import_obsidian19.setIcon)(btn, btn.getAttr("data-icon"), 16));
+ (0, import_obsidian19.setIcon)(layoutBtn, showTree ? "list" : "folder", 16);
+ },
+ 0
+ );
+ });
+ onDestroy(() => {
+ removeEventListener("git-view-refresh", refresh);
+ });
+ function refresh() {
+ return __awaiter(this, void 0, void 0, function* () {
+ $$invalidate(4, loading = true);
+ const isSimpleGit = plugin.gitManager instanceof SimpleGit;
+ $$invalidate(6, logs = yield plugin.gitManager.log(void 0, false, isSimpleGit ? 50 : 10));
+ $$invalidate(4, loading = false);
+ });
+ }
+ function div0_binding($$value) {
+ binding_callbacks[$$value ? "unshift" : "push"](() => {
+ layoutBtn = $$value;
+ $$invalidate(3, layoutBtn);
+ });
+ }
+ const click_handler = () => {
+ $$invalidate(2, showTree = !showTree);
+ $$invalidate(0, plugin.settings.treeStructure = showTree, plugin);
+ plugin.saveSettings();
+ };
+ function div1_binding($$value) {
+ binding_callbacks[$$value ? "unshift" : "push"](() => {
+ buttons[6] = $$value;
+ $$invalidate(5, buttons);
+ });
+ }
+ $$self.$$set = ($$props2) => {
+ if ("plugin" in $$props2)
+ $$invalidate(0, plugin = $$props2.plugin);
+ if ("view" in $$props2)
+ $$invalidate(1, view = $$props2.view);
+ };
+ $$self.$$.update = () => {
+ if ($$self.$$.dirty & /*layoutBtn, showTree*/
+ 12) {
+ $: {
+ if (layoutBtn) {
+ layoutBtn.empty();
+ (0, import_obsidian19.setIcon)(layoutBtn, showTree ? "list" : "folder", 16);
+ }
+ }
+ }
+ };
+ return [
+ plugin,
+ view,
+ showTree,
+ layoutBtn,
+ loading,
+ buttons,
+ logs,
+ div0_binding,
+ click_handler,
+ div1_binding
+ ];
+}
+var HistoryView = class extends SvelteComponent {
+ constructor(options) {
+ super();
+ init2(this, options, instance4, create_fragment4, safe_not_equal, { plugin: 0, view: 1 });
+ }
+};
+var historyView_default = HistoryView;
+
+// src/ui/history/historyView.ts
+var HistoryView2 = class extends import_obsidian20.ItemView {
+ constructor(leaf, plugin) {
+ super(leaf);
+ this.plugin = plugin;
+ this.hoverPopover = null;
+ }
+ getViewType() {
+ return HISTORY_VIEW_CONFIG.type;
+ }
+ getDisplayText() {
+ return HISTORY_VIEW_CONFIG.name;
+ }
+ getIcon() {
+ return HISTORY_VIEW_CONFIG.icon;
+ }
+ onClose() {
+ return super.onClose();
+ }
+ onOpen() {
+ this._view = new historyView_default({
+ target: this.contentEl,
+ props: {
+ plugin: this.plugin,
+ view: this
+ }
+ });
+ return super.onOpen();
+ }
+};
+
+// src/ui/modals/branchModal.ts
+init_polyfill_buffer();
+var import_obsidian21 = require("obsidian");
+var BranchModal = class extends import_obsidian21.FuzzySuggestModal {
+ constructor(branches) {
+ super(app);
+ this.branches = branches;
+ this.setPlaceholder("Select branch to checkout");
+ }
+ getItems() {
+ return this.branches;
+ }
+ getItemText(item) {
+ return item;
+ }
+ onChooseItem(item, evt) {
+ this.resolve(item);
+ }
+ open() {
+ super.open();
+ return new Promise((resolve) => {
+ this.resolve = resolve;
+ });
+ }
+ async onClose() {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ if (this.resolve)
+ this.resolve(void 0);
+ }
+};
+
+// src/ui/modals/ignoreModal.ts
+init_polyfill_buffer();
+var import_obsidian22 = require("obsidian");
+var IgnoreModal = class extends import_obsidian22.Modal {
+ constructor(app2, content) {
+ super(app2);
+ this.content = content;
+ this.resolve = null;
+ }
+ open() {
+ super.open();
+ return new Promise((resolve) => {
+ this.resolve = resolve;
+ });
+ }
+ onOpen() {
+ const { contentEl, titleEl } = this;
+ titleEl.setText("Edit .gitignore");
+ const div = contentEl.createDiv();
+ const text2 = div.createEl("textarea", {
+ text: this.content,
+ cls: ["obsidian-git-textarea"],
+ attr: { rows: 10, cols: 30, wrap: "off" }
+ });
+ div.createEl("button", {
+ cls: ["mod-cta", "obsidian-git-center-button"],
+ text: "Save"
+ }).addEventListener("click", async () => {
+ this.resolve(text2.value);
+ this.close();
+ });
+ }
+ onClose() {
+ const { contentEl } = this;
+ this.resolve(void 0);
+ contentEl.empty();
+ }
+};
+
+// src/ui/sourceControl/sourceControl.ts
+init_polyfill_buffer();
+var import_obsidian29 = require("obsidian");
+
+// src/ui/sourceControl/sourceControl.svelte
+init_polyfill_buffer();
+var import_obsidian28 = require("obsidian");
+
// src/ui/modals/discardModal.ts
init_polyfill_buffer();
-var import_obsidian16 = __toModule(require("obsidian"));
-var DiscardModal = class extends import_obsidian16.Modal {
+var import_obsidian23 = require("obsidian");
+var DiscardModal = class extends import_obsidian23.Modal {
constructor(app2, deletion, filename) {
super(app2);
this.deletion = deletion;
@@ -27344,29 +38936,36 @@ var DiscardModal = class extends import_obsidian16.Modal {
onOpen() {
const { contentEl, titleEl } = this;
titleEl.setText(`${this.deletion ? "Delete" : "Discard"} this file?`);
- contentEl.createEl("h4").setText(`Do you really want to ${this.deletion ? "delete" : "discard the changes of"} "${this.filename}"`);
- const div = contentEl.createDiv();
- div.addClass("obsidian-git-center");
- div.createEl("button", {
- text: "Cancel",
- attr: {
- style: "margin: 0 10px"
- }
- }).addEventListener("click", () => {
+ contentEl.createEl("p").setText(
+ `Do you really want to ${this.deletion ? "delete" : "discard the changes of"} "${this.filename}"`
+ );
+ const div = contentEl.createDiv({ cls: "modal-button-container" });
+ const discard = div.createEl("button", {
+ cls: "mod-warning",
+ text: this.deletion ? "Delete" : "Discard"
+ });
+ discard.addEventListener("click", async () => {
+ if (this.resolve)
+ this.resolve(true);
+ this.close();
+ });
+ discard.addEventListener("keypress", async () => {
+ if (this.resolve)
+ this.resolve(true);
+ this.close();
+ });
+ const close = div.createEl("button", {
+ text: "Cancel"
+ });
+ close.addEventListener("click", () => {
if (this.resolve)
this.resolve(false);
return this.close();
});
- div.createEl("button", {
- cls: "mod-cta",
- text: "Confirm",
- attr: {
- style: "margin: 0 10px"
- }
- }).addEventListener("click", async () => {
+ close.addEventListener("keypress", () => {
if (this.resolve)
- this.resolve(true);
- this.close();
+ this.resolve(false);
+ return this.close();
});
}
onClose() {
@@ -27375,17 +38974,17 @@ var DiscardModal = class extends import_obsidian16.Modal {
}
};
-// src/ui/sidebar/components/fileComponent.svelte
+// src/ui/sourceControl/components/fileComponent.svelte
init_polyfill_buffer();
-var import_obsidian18 = __toModule(require("obsidian"));
+var import_obsidian25 = require("obsidian");
-// node_modules/obsidian-community-lib/dist/index.js
+// node_modules/.pnpm/github.com+Vinzent03+obsidian-community-lib@e663de4f95c879b40613090da78ea599ff621d24_@codemir_kbfcpig3uak7df3ohthcqq53p4/node_modules/obsidian-community-lib/dist/index.js
init_polyfill_buffer();
-// node_modules/obsidian-community-lib/dist/utils.js
+// node_modules/.pnpm/github.com+Vinzent03+obsidian-community-lib@e663de4f95c879b40613090da78ea599ff621d24_@codemir_kbfcpig3uak7df3ohthcqq53p4/node_modules/obsidian-community-lib/dist/utils.js
init_polyfill_buffer();
-var feather = __toModule(require_feather());
-var import_obsidian17 = __toModule(require("obsidian"));
+var feather = __toESM(require_feather());
+var import_obsidian24 = require("obsidian");
function hoverPreview(event, view, to) {
const targetEl = event.target;
app.workspace.trigger("hover-link", {
@@ -27397,11 +38996,11 @@ function hoverPreview(event, view, to) {
});
}
-// src/ui/sidebar/components/fileComponent.svelte
-function add_css(target) {
- append_styles(target, "svelte-wn85nz", "main.svelte-wn85nz .nav-file-title-content.svelte-wn85nz.svelte-wn85nz{display:flex;align-items:center}main.svelte-wn85nz .tools.svelte-wn85nz.svelte-wn85nz{display:flex;margin-left:auto}main.svelte-wn85nz .tools .type.svelte-wn85nz.svelte-wn85nz{padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center}main.svelte-wn85nz .tools .type[data-type=M].svelte-wn85nz.svelte-wn85nz{color:orange}main.svelte-wn85nz .tools .type[data-type=D].svelte-wn85nz.svelte-wn85nz{color:red}main.svelte-wn85nz .tools .buttons.svelte-wn85nz.svelte-wn85nz{display:flex}main.svelte-wn85nz .tools .buttons.svelte-wn85nz>.svelte-wn85nz{padding:0 0;height:auto}");
+// src/ui/sourceControl/components/fileComponent.svelte
+function add_css4(target) {
+ append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}");
}
-function create_if_block(ctx) {
+function create_if_block5(ctx) {
let div;
let mounted;
let dispose;
@@ -27410,55 +39009,75 @@ function create_if_block(ctx) {
div = element("div");
attr(div, "data-icon", "go-to-file");
attr(div, "aria-label", "Open File");
- attr(div, "class", "clickable-icon svelte-wn85nz");
+ attr(div, "class", "clickable-icon");
},
m(target, anchor) {
insert(target, div, anchor);
ctx[11](div);
if (!mounted) {
dispose = [
- listen(div, "auxclick", ctx[5]),
- listen(div, "click", ctx[5])
+ listen(div, "auxclick", stop_propagation(
+ /*open*/
+ ctx[5]
+ )),
+ listen(div, "click", stop_propagation(
+ /*open*/
+ ctx[5]
+ ))
];
mounted = true;
}
},
p: noop,
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
ctx[11](null);
mounted = false;
run_all(dispose);
}
};
}
-function create_fragment(ctx) {
- var _a2;
+function create_fragment5(ctx) {
let main;
let div6;
let div0;
- let t0_value = ((_a2 = ctx[0].vault_path.split("/").last()) == null ? void 0 : _a2.replace(".md", "")) + "";
+ let t0_value = getDisplayPath(
+ /*change*/
+ ctx[0].vault_path
+ ) + "";
let t0;
let t1;
let div5;
let div3;
- let show_if = ctx[1].app.vault.getAbstractFileByPath(ctx[0].vault_path);
+ let show_if = (
+ /*view*/
+ ctx[1].app.vault.getAbstractFileByPath(
+ /*change*/
+ ctx[0].vault_path
+ )
+ );
let t2;
let div1;
let t3;
let div2;
let t4;
let div4;
- let t5_value = ctx[0].working_dir + "";
+ let t5_value = (
+ /*change*/
+ ctx[0].working_dir + ""
+ );
let t5;
let div4_data_type_value;
+ let div6_data_path_value;
let div6_aria_label_value;
let mounted;
let dispose;
- let if_block = show_if && create_if_block(ctx);
+ let if_block = show_if && create_if_block5(ctx);
return {
c() {
+ var _a2, _b, _c;
main = element("main");
div6 = element("div");
div0 = element("div");
@@ -27475,21 +39094,45 @@ function create_fragment(ctx) {
t4 = space();
div4 = element("div");
t5 = text(t5_value);
- attr(div0, "class", "nav-file-title-content svelte-wn85nz");
+ attr(div0, "class", "tree-item-inner nav-file-title-content");
attr(div1, "data-icon", "undo");
attr(div1, "aria-label", "Discard");
- attr(div1, "class", "clickable-icon svelte-wn85nz");
+ attr(div1, "class", "clickable-icon");
attr(div2, "data-icon", "plus");
attr(div2, "aria-label", "Stage");
- attr(div2, "class", "clickable-icon svelte-wn85nz");
- attr(div3, "class", "buttons svelte-wn85nz");
- attr(div4, "class", "type svelte-wn85nz");
- attr(div4, "data-type", div4_data_type_value = ctx[0].working_dir);
- attr(div5, "class", "tools svelte-wn85nz");
- attr(div6, "class", "nav-file-title");
- attr(div6, "aria-label-position", ctx[3]);
- attr(div6, "aria-label", div6_aria_label_value = ctx[0].vault_path.split("/").last() != ctx[0].vault_path ? ctx[0].vault_path : "");
- attr(main, "class", "nav-file svelte-wn85nz");
+ attr(div2, "class", "clickable-icon");
+ attr(div3, "class", "buttons");
+ attr(div4, "class", "type");
+ attr(div4, "data-type", div4_data_type_value = /*change*/
+ ctx[0].working_dir);
+ attr(div5, "class", "git-tools");
+ attr(div6, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp");
+ attr(div6, "data-path", div6_data_path_value = /*change*/
+ ctx[0].vault_path);
+ attr(
+ div6,
+ "aria-label-position",
+ /*side*/
+ ctx[3]
+ );
+ attr(
+ div6,
+ "data-tooltip-position",
+ /*side*/
+ ctx[3]
+ );
+ attr(div6, "aria-label", div6_aria_label_value = /*change*/
+ ctx[0].vault_path);
+ toggle_class(
+ div6,
+ "is-active",
+ /*view*/
+ ((_a2 = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/
+ ctx[0].vault_path && !/*view*/
+ ((_b = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && !/*view*/
+ ((_c = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged)
+ );
+ attr(main, "class", "tree-item nav-file svelte-1wbh8tp");
},
m(target, anchor) {
insert(target, main, anchor);
@@ -27512,30 +39155,58 @@ function create_fragment(ctx) {
append2(div4, t5);
if (!mounted) {
dispose = [
- listen(div0, "click", ctx[7]),
- listen(div0, "auxclick", ctx[7]),
- listen(div1, "click", ctx[8]),
- listen(div2, "click", ctx[6]),
- listen(div6, "click", self2(ctx[7])),
- listen(div6, "auxclick", self2(ctx[7])),
- listen(main, "mouseover", ctx[4]),
- listen(main, "click", self2(ctx[7])),
- listen(main, "focus", ctx[10])
+ listen(div1, "click", stop_propagation(
+ /*discard*/
+ ctx[8]
+ )),
+ listen(div2, "click", stop_propagation(
+ /*stage*/
+ ctx[6]
+ )),
+ listen(
+ main,
+ "mouseover",
+ /*hover*/
+ ctx[4]
+ ),
+ listen(main, "click", stop_propagation(
+ /*showDiff*/
+ ctx[7]
+ )),
+ listen(main, "auxclick", stop_propagation(
+ /*showDiff*/
+ ctx[7]
+ )),
+ listen(
+ main,
+ "focus",
+ /*focus_handler*/
+ ctx[10]
+ )
];
mounted = true;
}
},
p(ctx2, [dirty]) {
- var _a3;
- if (dirty & 1 && t0_value !== (t0_value = ((_a3 = ctx2[0].vault_path.split("/").last()) == null ? void 0 : _a3.replace(".md", "")) + ""))
+ var _a2, _b, _c;
+ if (dirty & /*change*/
+ 1 && t0_value !== (t0_value = getDisplayPath(
+ /*change*/
+ ctx2[0].vault_path
+ ) + ""))
set_data(t0, t0_value);
- if (dirty & 3)
- show_if = ctx2[1].app.vault.getAbstractFileByPath(ctx2[0].vault_path);
+ if (dirty & /*view, change*/
+ 3)
+ show_if = /*view*/
+ ctx2[1].app.vault.getAbstractFileByPath(
+ /*change*/
+ ctx2[0].vault_path
+ );
if (show_if) {
if (if_block) {
if_block.p(ctx2, dirty);
} else {
- if_block = create_if_block(ctx2);
+ if_block = create_if_block5(ctx2);
if_block.c();
if_block.m(div3, t2);
}
@@ -27543,23 +39214,62 @@ function create_fragment(ctx) {
if_block.d(1);
if_block = null;
}
- if (dirty & 1 && t5_value !== (t5_value = ctx2[0].working_dir + ""))
+ if (dirty & /*change*/
+ 1 && t5_value !== (t5_value = /*change*/
+ ctx2[0].working_dir + ""))
set_data(t5, t5_value);
- if (dirty & 1 && div4_data_type_value !== (div4_data_type_value = ctx2[0].working_dir)) {
+ if (dirty & /*change*/
+ 1 && div4_data_type_value !== (div4_data_type_value = /*change*/
+ ctx2[0].working_dir)) {
attr(div4, "data-type", div4_data_type_value);
}
- if (dirty & 8) {
- attr(div6, "aria-label-position", ctx2[3]);
+ if (dirty & /*change*/
+ 1 && div6_data_path_value !== (div6_data_path_value = /*change*/
+ ctx2[0].vault_path)) {
+ attr(div6, "data-path", div6_data_path_value);
}
- if (dirty & 1 && div6_aria_label_value !== (div6_aria_label_value = ctx2[0].vault_path.split("/").last() != ctx2[0].vault_path ? ctx2[0].vault_path : "")) {
+ if (dirty & /*side*/
+ 8) {
+ attr(
+ div6,
+ "aria-label-position",
+ /*side*/
+ ctx2[3]
+ );
+ }
+ if (dirty & /*side*/
+ 8) {
+ attr(
+ div6,
+ "data-tooltip-position",
+ /*side*/
+ ctx2[3]
+ );
+ }
+ if (dirty & /*change*/
+ 1 && div6_aria_label_value !== (div6_aria_label_value = /*change*/
+ ctx2[0].vault_path)) {
attr(div6, "aria-label", div6_aria_label_value);
}
+ if (dirty & /*view, change*/
+ 3) {
+ toggle_class(
+ div6,
+ "is-active",
+ /*view*/
+ ((_a2 = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/
+ ctx2[0].vault_path && !/*view*/
+ ((_b = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && !/*view*/
+ ((_c = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged)
+ );
+ }
},
i: noop,
o: noop,
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(main);
+ }
if (if_block)
if_block.d();
ctx[12](null);
@@ -27569,23 +39279,23 @@ function create_fragment(ctx) {
}
};
}
-function instance($$self, $$props, $$invalidate) {
+function instance5($$self, $$props, $$invalidate) {
let side;
let { change } = $$props;
let { view } = $$props;
let { manager } = $$props;
let buttons = [];
- window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian18.setIcon)(b, b.getAttr("data-icon"))), 0);
+ window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian25.setIcon)(b, b.getAttr("data-icon"))), 0);
function hover(event) {
- if (!change.path.startsWith(view.app.vault.configDir) || !change.path.startsWith(".")) {
- hoverPreview(event, view, change.vault_path.split("/").last().replace(".md", ""));
+ if (app.vault.getAbstractFileByPath(change.vault_path)) {
+ hoverPreview(event, view, change.vault_path);
}
}
function open(event) {
var _a2;
const file = view.app.vault.getAbstractFileByPath(change.vault_path);
console.log(event);
- if (file instanceof import_obsidian18.TFile) {
+ if (file instanceof import_obsidian25.TFile) {
(_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file);
}
}
@@ -27648,7 +39358,8 @@ function instance($$self, $$props, $$invalidate) {
$$invalidate(9, manager = $$props2.manager);
};
$$self.$$.update = () => {
- if ($$self.$$.dirty & 2) {
+ if ($$self.$$.dirty & /*view*/
+ 2) {
$:
$$invalidate(3, side = view.leaf.getRoot().side == "left" ? "right" : "left");
}
@@ -27673,30 +39384,36 @@ function instance($$self, $$props, $$invalidate) {
var FileComponent = class extends SvelteComponent {
constructor(options) {
super();
- init2(this, options, instance, create_fragment, safe_not_equal, { change: 0, view: 1, manager: 9 }, add_css);
+ init2(this, options, instance5, create_fragment5, safe_not_equal, { change: 0, view: 1, manager: 9 }, add_css4);
}
};
var fileComponent_default = FileComponent;
-// src/ui/sidebar/components/pulledFileComponent.svelte
+// src/ui/sourceControl/components/pulledFileComponent.svelte
init_polyfill_buffer();
-var import_obsidian19 = __toModule(require("obsidian"));
-function add_css2(target) {
- append_styles(target, "svelte-sajhpp", "main.svelte-sajhpp .nav-file-title-content.svelte-sajhpp{display:flex;align-items:center}main.svelte-sajhpp .tools.svelte-sajhpp{display:flex;margin-left:auto}main.svelte-sajhpp .tools .type.svelte-sajhpp{padding-left:var(--size-2-1);display:flex;align-items:center;justify-content:center}main.svelte-sajhpp .tools .type[data-type=M].svelte-sajhpp{color:orange}main.svelte-sajhpp .tools .type[data-type=D].svelte-sajhpp{color:red}");
+var import_obsidian26 = require("obsidian");
+function add_css5(target) {
+ append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}");
}
-function create_fragment2(ctx) {
- var _a2;
+function create_fragment6(ctx) {
let main;
let div2;
let div0;
- let t0_value = ((_a2 = ctx[0].vault_path.split("/").last()) == null ? void 0 : _a2.replace(".md", "")) + "";
+ let t0_value = getDisplayPath(
+ /*change*/
+ ctx[0].vault_path
+ ) + "";
let t0;
let t1;
let div1;
let span;
- let t2_value = ctx[0].working_dir + "";
+ let t2_value = (
+ /*change*/
+ ctx[0].working_dir + ""
+ );
let t2;
let span_data_type_value;
+ let div2_data_path_value;
let div2_aria_label_value;
let mounted;
let dispose;
@@ -27710,14 +39427,29 @@ function create_fragment2(ctx) {
div1 = element("div");
span = element("span");
t2 = text(t2_value);
- attr(div0, "class", "nav-file-title-content svelte-sajhpp");
- attr(span, "class", "type svelte-sajhpp");
- attr(span, "data-type", span_data_type_value = ctx[0].working_dir);
- attr(div1, "class", "tools svelte-sajhpp");
- attr(div2, "class", "nav-file-title");
- attr(div2, "aria-label-position", ctx[1]);
- attr(div2, "aria-label", div2_aria_label_value = ctx[0].vault_path.split("/").last() != ctx[0].vault_path ? ctx[0].vault_path : "");
- attr(main, "class", "nav-file svelte-sajhpp");
+ attr(div0, "class", "tree-item-inner nav-file-title-content");
+ attr(span, "class", "type");
+ attr(span, "data-type", span_data_type_value = /*change*/
+ ctx[0].working_dir);
+ attr(div1, "class", "git-tools");
+ attr(div2, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp");
+ attr(div2, "data-path", div2_data_path_value = /*change*/
+ ctx[0].vault_path);
+ attr(
+ div2,
+ "aria-label-position",
+ /*side*/
+ ctx[1]
+ );
+ attr(
+ div2,
+ "data-tooltip-position",
+ /*side*/
+ ctx[1]
+ );
+ attr(div2, "aria-label", div2_aria_label_value = /*change*/
+ ctx[0].vault_path);
+ attr(main, "class", "tree-item nav-file svelte-1wbh8tp");
},
m(target, anchor) {
insert(target, main, anchor);
@@ -27730,52 +39462,99 @@ function create_fragment2(ctx) {
append2(span, t2);
if (!mounted) {
dispose = [
- listen(main, "mouseover", ctx[2]),
- listen(main, "click", ctx[3]),
- listen(main, "focus", ctx[5])
+ listen(
+ main,
+ "mouseover",
+ /*hover*/
+ ctx[2]
+ ),
+ listen(main, "click", stop_propagation(
+ /*open*/
+ ctx[3]
+ )),
+ listen(main, "auxclick", stop_propagation(
+ /*open*/
+ ctx[3]
+ )),
+ listen(
+ main,
+ "focus",
+ /*focus_handler*/
+ ctx[5]
+ )
];
mounted = true;
}
},
p(ctx2, [dirty]) {
- var _a3;
- if (dirty & 1 && t0_value !== (t0_value = ((_a3 = ctx2[0].vault_path.split("/").last()) == null ? void 0 : _a3.replace(".md", "")) + ""))
+ if (dirty & /*change*/
+ 1 && t0_value !== (t0_value = getDisplayPath(
+ /*change*/
+ ctx2[0].vault_path
+ ) + ""))
set_data(t0, t0_value);
- if (dirty & 1 && t2_value !== (t2_value = ctx2[0].working_dir + ""))
+ if (dirty & /*change*/
+ 1 && t2_value !== (t2_value = /*change*/
+ ctx2[0].working_dir + ""))
set_data(t2, t2_value);
- if (dirty & 1 && span_data_type_value !== (span_data_type_value = ctx2[0].working_dir)) {
+ if (dirty & /*change*/
+ 1 && span_data_type_value !== (span_data_type_value = /*change*/
+ ctx2[0].working_dir)) {
attr(span, "data-type", span_data_type_value);
}
- if (dirty & 2) {
- attr(div2, "aria-label-position", ctx2[1]);
+ if (dirty & /*change*/
+ 1 && div2_data_path_value !== (div2_data_path_value = /*change*/
+ ctx2[0].vault_path)) {
+ attr(div2, "data-path", div2_data_path_value);
}
- if (dirty & 1 && div2_aria_label_value !== (div2_aria_label_value = ctx2[0].vault_path.split("/").last() != ctx2[0].vault_path ? ctx2[0].vault_path : "")) {
+ if (dirty & /*side*/
+ 2) {
+ attr(
+ div2,
+ "aria-label-position",
+ /*side*/
+ ctx2[1]
+ );
+ }
+ if (dirty & /*side*/
+ 2) {
+ attr(
+ div2,
+ "data-tooltip-position",
+ /*side*/
+ ctx2[1]
+ );
+ }
+ if (dirty & /*change*/
+ 1 && div2_aria_label_value !== (div2_aria_label_value = /*change*/
+ ctx2[0].vault_path)) {
attr(div2, "aria-label", div2_aria_label_value);
}
},
i: noop,
o: noop,
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(main);
+ }
mounted = false;
run_all(dispose);
}
};
}
-function instance2($$self, $$props, $$invalidate) {
+function instance6($$self, $$props, $$invalidate) {
let side;
let { change } = $$props;
let { view } = $$props;
function hover(event) {
- if (!change.path.startsWith(view.app.vault.configDir) || !change.path.startsWith(".")) {
- hoverPreview(event, view, change.vault_path.split("/").last().replace(".md", ""));
+ if (app.vault.getAbstractFileByPath(change.vault_path)) {
+ hoverPreview(event, view, change.vault_path);
}
}
function open(event) {
var _a2;
const file = view.app.vault.getAbstractFileByPath(change.vault_path);
- if (file instanceof import_obsidian19.TFile) {
+ if (file instanceof import_obsidian26.TFile) {
(_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file);
}
}
@@ -27789,7 +39568,8 @@ function instance2($$self, $$props, $$invalidate) {
$$invalidate(4, view = $$props2.view);
};
$$self.$$.update = () => {
- if ($$self.$$.dirty & 16) {
+ if ($$self.$$.dirty & /*view*/
+ 16) {
$:
$$invalidate(1, side = view.leaf.getRoot().side == "left" ? "right" : "left");
}
@@ -27799,18 +39579,18 @@ function instance2($$self, $$props, $$invalidate) {
var PulledFileComponent = class extends SvelteComponent {
constructor(options) {
super();
- init2(this, options, instance2, create_fragment2, safe_not_equal, { change: 0, view: 4 }, add_css2);
+ init2(this, options, instance6, create_fragment6, safe_not_equal, { change: 0, view: 4 }, add_css5);
}
};
var pulledFileComponent_default = PulledFileComponent;
-// src/ui/sidebar/components/stagedFileComponent.svelte
+// src/ui/sourceControl/components/stagedFileComponent.svelte
init_polyfill_buffer();
-var import_obsidian20 = __toModule(require("obsidian"));
-function add_css3(target) {
- append_styles(target, "svelte-wn85nz", "main.svelte-wn85nz .nav-file-title-content.svelte-wn85nz.svelte-wn85nz{display:flex;align-items:center}main.svelte-wn85nz .tools.svelte-wn85nz.svelte-wn85nz{display:flex;margin-left:auto}main.svelte-wn85nz .tools .type.svelte-wn85nz.svelte-wn85nz{padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center}main.svelte-wn85nz .tools .type[data-type=M].svelte-wn85nz.svelte-wn85nz{color:orange}main.svelte-wn85nz .tools .type[data-type=D].svelte-wn85nz.svelte-wn85nz{color:red}main.svelte-wn85nz .tools .buttons.svelte-wn85nz.svelte-wn85nz{display:flex}main.svelte-wn85nz .tools .buttons.svelte-wn85nz>.svelte-wn85nz{padding:0 0;height:auto}");
+var import_obsidian27 = require("obsidian");
+function add_css6(target) {
+ append_styles(target, "svelte-1wbh8tp", "main.svelte-1wbh8tp .nav-file-title.svelte-1wbh8tp{align-items:center}");
}
-function create_if_block2(ctx) {
+function create_if_block6(ctx) {
let div;
let mounted;
let dispose;
@@ -27819,50 +39599,67 @@ function create_if_block2(ctx) {
div = element("div");
attr(div, "data-icon", "go-to-file");
attr(div, "aria-label", "Open File");
- attr(div, "class", "clickable-icon svelte-wn85nz");
+ attr(div, "class", "clickable-icon");
},
m(target, anchor) {
insert(target, div, anchor);
- ctx[11](div);
+ ctx[10](div);
if (!mounted) {
- dispose = listen(div, "click", ctx[6]);
+ dispose = listen(div, "click", stop_propagation(
+ /*open*/
+ ctx[5]
+ ));
mounted = true;
}
},
p: noop,
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
- ctx[11](null);
+ }
+ ctx[10](null);
mounted = false;
dispose();
}
};
}
-function create_fragment3(ctx) {
- var _a2;
+function create_fragment7(ctx) {
let main;
let div5;
let div0;
- let t0_value = ((_a2 = ctx[3].split("/").last()) == null ? void 0 : _a2.replace(".md", "")) + "";
+ let t0_value = getDisplayPath(
+ /*change*/
+ ctx[0].vault_path
+ ) + "";
let t0;
let t1;
let div4;
let div2;
- let show_if = ctx[1].app.vault.getAbstractFileByPath(ctx[3]);
+ let show_if = (
+ /*view*/
+ ctx[1].app.vault.getAbstractFileByPath(
+ /*change*/
+ ctx[0].vault_path
+ )
+ );
let t2;
let div1;
let t3;
let div3;
- let t4_value = ctx[0].index + "";
+ let t4_value = (
+ /*change*/
+ ctx[0].index + ""
+ );
let t4;
let div3_data_type_value;
+ let div5_data_path_value;
let div5_aria_label_value;
let mounted;
let dispose;
- let if_block = show_if && create_if_block2(ctx);
+ let if_block = show_if && create_if_block6(ctx);
return {
c() {
+ var _a2, _b, _c;
main = element("main");
div5 = element("div");
div0 = element("div");
@@ -27877,18 +39674,42 @@ function create_fragment3(ctx) {
t3 = space();
div3 = element("div");
t4 = text(t4_value);
- attr(div0, "class", "nav-file-title-content svelte-wn85nz");
+ attr(div0, "class", "tree-item-inner nav-file-title-content");
attr(div1, "data-icon", "minus");
attr(div1, "aria-label", "Unstage");
- attr(div1, "class", "clickable-icon svelte-wn85nz");
- attr(div2, "class", "buttons svelte-wn85nz");
- attr(div3, "class", "type svelte-wn85nz");
- attr(div3, "data-type", div3_data_type_value = ctx[0].index);
- attr(div4, "class", "tools svelte-wn85nz");
- attr(div5, "class", "nav-file-title");
- attr(div5, "aria-label-position", ctx[4]);
- attr(div5, "aria-label", div5_aria_label_value = ctx[3].split("/").last() != ctx[3] ? ctx[3] : "");
- attr(main, "class", "nav-file svelte-wn85nz");
+ attr(div1, "class", "clickable-icon");
+ attr(div2, "class", "buttons");
+ attr(div3, "class", "type");
+ attr(div3, "data-type", div3_data_type_value = /*change*/
+ ctx[0].index);
+ attr(div4, "class", "git-tools");
+ attr(div5, "class", "tree-item-self is-clickable nav-file-title svelte-1wbh8tp");
+ attr(div5, "data-path", div5_data_path_value = /*change*/
+ ctx[0].vault_path);
+ attr(
+ div5,
+ "aria-label-position",
+ /*side*/
+ ctx[3]
+ );
+ attr(
+ div5,
+ "data-tooltip-position",
+ /*side*/
+ ctx[3]
+ );
+ attr(div5, "aria-label", div5_aria_label_value = /*change*/
+ ctx[0].vault_path);
+ toggle_class(
+ div5,
+ "is-active",
+ /*view*/
+ ((_a2 = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/
+ ctx[0].vault_path && !/*view*/
+ ((_b = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && /*view*/
+ ((_c = ctx[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged)
+ );
+ attr(main, "class", "tree-item nav-file svelte-1wbh8tp");
},
m(target, anchor) {
insert(target, main, anchor);
@@ -27902,34 +39723,60 @@ function create_fragment3(ctx) {
if_block.m(div2, null);
append2(div2, t2);
append2(div2, div1);
- ctx[12](div1);
+ ctx[11](div1);
append2(div4, t3);
append2(div4, div3);
append2(div3, t4);
if (!mounted) {
dispose = [
- listen(div0, "click", ctx[7]),
- listen(div0, "auxclick", ctx[7]),
- listen(div1, "click", ctx[8]),
- listen(div5, "click", self2(ctx[7])),
- listen(main, "mouseover", ctx[5]),
- listen(main, "focus", ctx[10]),
- listen(main, "click", self2(ctx[7]))
+ listen(div1, "click", stop_propagation(
+ /*unstage*/
+ ctx[7]
+ )),
+ listen(
+ main,
+ "mouseover",
+ /*hover*/
+ ctx[4]
+ ),
+ listen(
+ main,
+ "focus",
+ /*focus_handler*/
+ ctx[9]
+ ),
+ listen(main, "click", stop_propagation(
+ /*showDiff*/
+ ctx[6]
+ )),
+ listen(main, "auxclick", stop_propagation(
+ /*showDiff*/
+ ctx[6]
+ ))
];
mounted = true;
}
},
p(ctx2, [dirty]) {
- var _a3;
- if (dirty & 8 && t0_value !== (t0_value = ((_a3 = ctx2[3].split("/").last()) == null ? void 0 : _a3.replace(".md", "")) + ""))
+ var _a2, _b, _c;
+ if (dirty & /*change*/
+ 1 && t0_value !== (t0_value = getDisplayPath(
+ /*change*/
+ ctx2[0].vault_path
+ ) + ""))
set_data(t0, t0_value);
- if (dirty & 10)
- show_if = ctx2[1].app.vault.getAbstractFileByPath(ctx2[3]);
+ if (dirty & /*view, change*/
+ 3)
+ show_if = /*view*/
+ ctx2[1].app.vault.getAbstractFileByPath(
+ /*change*/
+ ctx2[0].vault_path
+ );
if (show_if) {
if (if_block) {
if_block.p(ctx2, dirty);
} else {
- if_block = create_if_block2(ctx2);
+ if_block = create_if_block6(ctx2);
if_block.c();
if_block.m(div2, t2);
}
@@ -27937,48 +39784,86 @@ function create_fragment3(ctx) {
if_block.d(1);
if_block = null;
}
- if (dirty & 1 && t4_value !== (t4_value = ctx2[0].index + ""))
+ if (dirty & /*change*/
+ 1 && t4_value !== (t4_value = /*change*/
+ ctx2[0].index + ""))
set_data(t4, t4_value);
- if (dirty & 1 && div3_data_type_value !== (div3_data_type_value = ctx2[0].index)) {
+ if (dirty & /*change*/
+ 1 && div3_data_type_value !== (div3_data_type_value = /*change*/
+ ctx2[0].index)) {
attr(div3, "data-type", div3_data_type_value);
}
- if (dirty & 16) {
- attr(div5, "aria-label-position", ctx2[4]);
+ if (dirty & /*change*/
+ 1 && div5_data_path_value !== (div5_data_path_value = /*change*/
+ ctx2[0].vault_path)) {
+ attr(div5, "data-path", div5_data_path_value);
}
- if (dirty & 8 && div5_aria_label_value !== (div5_aria_label_value = ctx2[3].split("/").last() != ctx2[3] ? ctx2[3] : "")) {
+ if (dirty & /*side*/
+ 8) {
+ attr(
+ div5,
+ "aria-label-position",
+ /*side*/
+ ctx2[3]
+ );
+ }
+ if (dirty & /*side*/
+ 8) {
+ attr(
+ div5,
+ "data-tooltip-position",
+ /*side*/
+ ctx2[3]
+ );
+ }
+ if (dirty & /*change*/
+ 1 && div5_aria_label_value !== (div5_aria_label_value = /*change*/
+ ctx2[0].vault_path)) {
attr(div5, "aria-label", div5_aria_label_value);
}
+ if (dirty & /*view, change*/
+ 3) {
+ toggle_class(
+ div5,
+ "is-active",
+ /*view*/
+ ((_a2 = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _a2.file) == /*change*/
+ ctx2[0].vault_path && !/*view*/
+ ((_b = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _b.hash) && /*view*/
+ ((_c = ctx2[1].plugin.lastDiffViewState) == null ? void 0 : _c.staged)
+ );
+ }
},
i: noop,
o: noop,
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(main);
+ }
if (if_block)
if_block.d();
- ctx[12](null);
+ ctx[11](null);
mounted = false;
run_all(dispose);
}
};
}
-function instance3($$self, $$props, $$invalidate) {
- let formattedPath;
+function instance7($$self, $$props, $$invalidate) {
let side;
let { change } = $$props;
let { view } = $$props;
let { manager } = $$props;
let buttons = [];
- window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian20.setIcon)(b, b.getAttr("data-icon"), 16)), 0);
+ window.setTimeout(() => buttons.forEach((b) => (0, import_obsidian27.setIcon)(b, b.getAttr("data-icon"), 16)), 0);
function hover(event) {
- if (!change.path.startsWith(view.app.vault.configDir) || !change.path.startsWith(".")) {
- hoverPreview(event, view, formattedPath.split("/").last().replace(".md", ""));
+ if (app.vault.getAbstractFileByPath(change.vault_path)) {
+ hoverPreview(event, view, change.vault_path);
}
}
function open(event) {
var _a2;
const file = view.app.vault.getAbstractFileByPath(change.vault_path);
- if (file instanceof import_obsidian20.TFile) {
+ if (file instanceof import_obsidian27.TFile) {
(_a2 = getNewLeaf(event)) === null || _a2 === void 0 ? void 0 : _a2.openFile(file);
}
}
@@ -28016,23 +39901,19 @@ function instance3($$self, $$props, $$invalidate) {
if ("view" in $$props2)
$$invalidate(1, view = $$props2.view);
if ("manager" in $$props2)
- $$invalidate(9, manager = $$props2.manager);
+ $$invalidate(8, manager = $$props2.manager);
};
$$self.$$.update = () => {
- if ($$self.$$.dirty & 1) {
+ if ($$self.$$.dirty & /*view*/
+ 2) {
$:
- $$invalidate(3, formattedPath = change.vault_path);
- }
- if ($$self.$$.dirty & 2) {
- $:
- $$invalidate(4, side = view.leaf.getRoot().side == "left" ? "right" : "left");
+ $$invalidate(3, side = view.leaf.getRoot().side == "left" ? "right" : "left");
}
};
return [
change,
view,
buttons,
- formattedPath,
side,
hover,
open,
@@ -28047,22 +39928,22 @@ function instance3($$self, $$props, $$invalidate) {
var StagedFileComponent = class extends SvelteComponent {
constructor(options) {
super();
- init2(this, options, instance3, create_fragment3, safe_not_equal, { change: 0, view: 1, manager: 9 }, add_css3);
+ init2(this, options, instance7, create_fragment7, safe_not_equal, { change: 0, view: 1, manager: 8 }, add_css6);
}
};
var stagedFileComponent_default = StagedFileComponent;
-// src/ui/sidebar/components/treeComponent.svelte
+// src/ui/sourceControl/components/treeComponent.svelte
init_polyfill_buffer();
-function add_css4(target) {
- append_styles(target, "svelte-148wteu", "main.svelte-148wteu .nav-folder-title-content.svelte-148wteu.svelte-148wteu{display:flex;align-items:center}main.svelte-148wteu .tools.svelte-148wteu.svelte-148wteu{display:flex;margin-left:auto}main.svelte-148wteu .tools .buttons.svelte-148wteu.svelte-148wteu{display:flex}main.svelte-148wteu .tools .buttons.svelte-148wteu>.svelte-148wteu{padding:0 0;height:auto}");
+function add_css7(target) {
+ append_styles(target, "svelte-hup5mn", "main.svelte-hup5mn .nav-folder-title.svelte-hup5mn{align-items:center}");
}
-function get_each_context(ctx, list, i) {
+function get_each_context4(ctx, list, i) {
const child_ctx = ctx.slice();
- child_ctx[17] = list[i];
+ child_ctx[15] = list[i];
return child_ctx;
}
-function create_else_block(ctx) {
+function create_else_block3(ctx) {
let div7;
let div6;
let div0;
@@ -28070,7 +39951,10 @@ function create_else_block(ctx) {
let div1;
let t1;
let div2;
- let t2_value = ctx[17].title + "";
+ let t2_value = (
+ /*entity*/
+ ctx[15].title + ""
+ );
let t2;
let t3;
let div5;
@@ -28083,23 +39967,30 @@ function create_else_block(ctx) {
let current;
let mounted;
let dispose;
- function click_handler() {
- return ctx[11](ctx[17]);
- }
- function click_handler_1() {
- return ctx[12](ctx[17]);
- }
function select_block_type_2(ctx2, dirty) {
- if (ctx2[3] == FileType.staged)
+ if (
+ /*fileType*/
+ ctx2[3] == 0 /* staged */
+ )
return create_if_block_5;
return create_else_block_1;
}
let current_block_type = select_block_type_2(ctx, -1);
let if_block0 = current_block_type(ctx);
- function click_handler_5() {
- return ctx[16](ctx[17]);
+ let if_block1 = !/*closed*/
+ ctx[5][
+ /*entity*/
+ ctx[15].title
+ ] && create_if_block_4(ctx);
+ function click_handler_3() {
+ return (
+ /*click_handler_3*/
+ ctx[14](
+ /*entity*/
+ ctx[15]
+ )
+ );
}
- let if_block1 = !ctx[5][ctx[17].title] && create_if_block_4(ctx);
return {
c() {
div7 = element("div");
@@ -28124,17 +40015,45 @@ function create_else_block(ctx) {
attr(div0, "data-icon", "folder");
set_style(div0, "padding-right", "5px");
set_style(div0, "display", "flex");
- attr(div1, "class", "nav-folder-collapse-indicator collapse-icon");
- attr(div2, "class", "nav-folder-title-content svelte-148wteu");
+ attr(div1, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon");
+ toggle_class(
+ div1,
+ "is-collapsed",
+ /*closed*/
+ ctx[5][
+ /*entity*/
+ ctx[15].title
+ ]
+ );
+ attr(div2, "class", "tree-item-inner nav-folder-title-content");
set_style(div3, "width", "11px");
- attr(div3, "class", "svelte-148wteu");
- attr(div4, "class", "buttons svelte-148wteu");
- attr(div5, "class", "tools svelte-148wteu");
- attr(div6, "class", "nav-folder-title");
- attr(div6, "aria-label-position", ctx[6]);
- attr(div6, "aria-label", div6_aria_label_value = ctx[17].vaultPath.split("/").last() != ctx[17].vaultPath ? ctx[17].vaultPath : "");
- attr(div7, "class", "nav-folder");
- toggle_class(div7, "is-collapsed", ctx[5][ctx[17].title]);
+ attr(div4, "class", "buttons");
+ attr(div5, "class", "git-tools");
+ attr(div6, "class", "tree-item-self is-clickable nav-folder-title svelte-hup5mn");
+ attr(
+ div6,
+ "aria-label-position",
+ /*side*/
+ ctx[6]
+ );
+ attr(
+ div6,
+ "data-tooltip-position",
+ /*side*/
+ ctx[6]
+ );
+ attr(div6, "aria-label", div6_aria_label_value = /*entity*/
+ ctx[15].vaultPath);
+ attr(div7, "class", "tree-item nav-folder");
+ toggle_class(
+ div7,
+ "is-collapsed",
+ /*closed*/
+ ctx[5][
+ /*entity*/
+ ctx[15].title
+ ]
+ );
},
m(target, anchor) {
insert(target, div7, anchor);
@@ -28157,17 +40076,27 @@ function create_else_block(ctx) {
append2(div7, t6);
current = true;
if (!mounted) {
- dispose = [
- listen(div1, "click", click_handler),
- listen(div2, "click", click_handler_1),
- listen(div6, "click", self2(click_handler_5))
- ];
+ dispose = listen(div7, "click", stop_propagation(click_handler_3));
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
- if ((!current || dirty & 1) && t2_value !== (t2_value = ctx[17].title + ""))
+ if (!current || dirty & /*closed, hierarchy*/
+ 33) {
+ toggle_class(
+ div1,
+ "is-collapsed",
+ /*closed*/
+ ctx[5][
+ /*entity*/
+ ctx[15].title
+ ]
+ );
+ }
+ if ((!current || dirty & /*hierarchy*/
+ 1) && t2_value !== (t2_value = /*entity*/
+ ctx[15].title + ""))
set_data(t2, t2_value);
if (current_block_type === (current_block_type = select_block_type_2(ctx, dirty)) && if_block0) {
if_block0.p(ctx, dirty);
@@ -28179,16 +40108,38 @@ function create_else_block(ctx) {
if_block0.m(div4, t4);
}
}
- if (!current || dirty & 64) {
- attr(div6, "aria-label-position", ctx[6]);
+ if (!current || dirty & /*side*/
+ 64) {
+ attr(
+ div6,
+ "aria-label-position",
+ /*side*/
+ ctx[6]
+ );
}
- if (!current || dirty & 1 && div6_aria_label_value !== (div6_aria_label_value = ctx[17].vaultPath.split("/").last() != ctx[17].vaultPath ? ctx[17].vaultPath : "")) {
+ if (!current || dirty & /*side*/
+ 64) {
+ attr(
+ div6,
+ "data-tooltip-position",
+ /*side*/
+ ctx[6]
+ );
+ }
+ if (!current || dirty & /*hierarchy*/
+ 1 && div6_aria_label_value !== (div6_aria_label_value = /*entity*/
+ ctx[15].vaultPath)) {
attr(div6, "aria-label", div6_aria_label_value);
}
- if (!ctx[5][ctx[17].title]) {
+ if (!/*closed*/
+ ctx[5][
+ /*entity*/
+ ctx[15].title
+ ]) {
if (if_block1) {
if_block1.p(ctx, dirty);
- if (dirty & 33) {
+ if (dirty & /*closed, hierarchy*/
+ 33) {
transition_in(if_block1, 1);
}
} else {
@@ -28204,8 +40155,17 @@ function create_else_block(ctx) {
});
check_outros();
}
- if (!current || dirty & 33) {
- toggle_class(div7, "is-collapsed", ctx[5][ctx[17].title]);
+ if (!current || dirty & /*closed, hierarchy*/
+ 33) {
+ toggle_class(
+ div7,
+ "is-collapsed",
+ /*closed*/
+ ctx[5][
+ /*entity*/
+ ctx[15].title
+ ]
+ );
}
},
i(local) {
@@ -28219,30 +40179,40 @@ function create_else_block(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div7);
+ }
if_block0.d();
if (if_block1)
if_block1.d();
mounted = false;
- run_all(dispose);
+ dispose();
}
};
}
-function create_if_block3(ctx) {
+function create_if_block7(ctx) {
let div;
let current_block_type_index;
let if_block;
let t;
let current;
- const if_block_creators = [create_if_block_1, create_if_block_2, create_if_block_3];
+ const if_block_creators = [create_if_block_13, create_if_block_22, create_if_block_3];
const if_blocks = [];
function select_block_type_1(ctx2, dirty) {
- if (ctx2[3] == FileType.staged)
+ if (
+ /*fileType*/
+ ctx2[3] == 0 /* staged */
+ )
return 0;
- if (ctx2[3] == FileType.changed)
+ if (
+ /*fileType*/
+ ctx2[3] == 1 /* changed */
+ )
return 1;
- if (ctx2[3] == FileType.pulled)
+ if (
+ /*fileType*/
+ ctx2[3] == 2 /* pulled */
+ )
return 2;
return -1;
}
@@ -28305,8 +40275,9 @@ function create_if_block3(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
if (~current_block_type_index) {
if_blocks[current_block_type_index].d();
}
@@ -28319,11 +40290,23 @@ function create_else_block_1(ctx) {
let div1;
let mounted;
let dispose;
- function click_handler_3() {
- return ctx[14](ctx[17]);
+ function click_handler_1() {
+ return (
+ /*click_handler_1*/
+ ctx[12](
+ /*entity*/
+ ctx[15]
+ )
+ );
}
- function click_handler_4() {
- return ctx[15](ctx[17]);
+ function click_handler_2() {
+ return (
+ /*click_handler_2*/
+ ctx[13](
+ /*entity*/
+ ctx[15]
+ )
+ );
}
return {
c() {
@@ -28334,10 +40317,10 @@ function create_else_block_1(ctx) {
div1.innerHTML = ``;
attr(div0, "data-icon", "undo");
attr(div0, "aria-label", "Discard");
- attr(div0, "class", "clickable-icon svelte-148wteu");
+ attr(div0, "class", "clickable-icon");
attr(div1, "data-icon", "plus");
attr(div1, "aria-label", "Stage");
- attr(div1, "class", "clickable-icon svelte-148wteu");
+ attr(div1, "class", "clickable-icon");
},
m(target, anchor) {
insert(target, div0, anchor);
@@ -28345,8 +40328,8 @@ function create_else_block_1(ctx) {
insert(target, div1, anchor);
if (!mounted) {
dispose = [
- listen(div0, "click", click_handler_3),
- listen(div1, "click", click_handler_4)
+ listen(div0, "click", stop_propagation(click_handler_1)),
+ listen(div1, "click", stop_propagation(click_handler_2))
];
mounted = true;
}
@@ -28355,12 +40338,11 @@ function create_else_block_1(ctx) {
ctx = new_ctx;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div0);
- if (detaching)
detach(t);
- if (detaching)
detach(div1);
+ }
mounted = false;
run_all(dispose);
}
@@ -28370,8 +40352,14 @@ function create_if_block_5(ctx) {
let div;
let mounted;
let dispose;
- function click_handler_2() {
- return ctx[13](ctx[17]);
+ function click_handler() {
+ return (
+ /*click_handler*/
+ ctx[11](
+ /*entity*/
+ ctx[15]
+ )
+ );
}
return {
c() {
@@ -28379,12 +40367,12 @@ function create_if_block_5(ctx) {
div.innerHTML = ``;
attr(div, "data-icon", "minus");
attr(div, "aria-label", "Unstage");
- attr(div, "class", "clickable-icon svelte-148wteu");
+ attr(div, "class", "clickable-icon");
},
m(target, anchor) {
insert(target, div, anchor);
if (!mounted) {
- dispose = listen(div, "click", click_handler_2);
+ dispose = listen(div, "click", stop_propagation(click_handler));
mounted = true;
}
},
@@ -28392,8 +40380,9 @@ function create_if_block_5(ctx) {
ctx = new_ctx;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
mounted = false;
dispose();
}
@@ -28406,17 +40395,29 @@ function create_if_block_4(ctx) {
let current;
treecomponent = new TreeComponent({
props: {
- hierarchy: ctx[17],
- plugin: ctx[1],
- view: ctx[2],
- fileType: ctx[3]
+ hierarchy: (
+ /*entity*/
+ ctx[15]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[1]
+ ),
+ view: (
+ /*view*/
+ ctx[2]
+ ),
+ fileType: (
+ /*fileType*/
+ ctx[3]
+ )
}
});
return {
c() {
div = element("div");
create_component(treecomponent.$$.fragment);
- attr(div, "class", "nav-folder-children");
+ attr(div, "class", "tree-item-children nav-folder-children");
},
m(target, anchor) {
insert(target, div, anchor);
@@ -28425,14 +40426,22 @@ function create_if_block_4(ctx) {
},
p(ctx2, dirty) {
const treecomponent_changes = {};
- if (dirty & 1)
- treecomponent_changes.hierarchy = ctx2[17];
- if (dirty & 2)
- treecomponent_changes.plugin = ctx2[1];
- if (dirty & 4)
- treecomponent_changes.view = ctx2[2];
- if (dirty & 8)
- treecomponent_changes.fileType = ctx2[3];
+ if (dirty & /*hierarchy*/
+ 1)
+ treecomponent_changes.hierarchy = /*entity*/
+ ctx2[15];
+ if (dirty & /*plugin*/
+ 2)
+ treecomponent_changes.plugin = /*plugin*/
+ ctx2[1];
+ if (dirty & /*view*/
+ 4)
+ treecomponent_changes.view = /*view*/
+ ctx2[2];
+ if (dirty & /*fileType*/
+ 8)
+ treecomponent_changes.fileType = /*fileType*/
+ ctx2[3];
treecomponent.$set(treecomponent_changes);
},
i(local) {
@@ -28441,6 +40450,8 @@ function create_if_block_4(ctx) {
transition_in(treecomponent.$$.fragment, local);
if (local) {
add_render_callback(() => {
+ if (!current)
+ return;
if (!div_transition)
div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true);
div_transition.run(1);
@@ -28458,8 +40469,9 @@ function create_if_block_4(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
destroy_component(treecomponent);
if (detaching && div_transition)
div_transition.end();
@@ -28471,8 +40483,14 @@ function create_if_block_3(ctx) {
let current;
pulledfilecomponent = new pulledFileComponent_default({
props: {
- change: ctx[17].statusResult,
- view: ctx[2]
+ change: (
+ /*entity*/
+ ctx[15].data
+ ),
+ view: (
+ /*view*/
+ ctx[2]
+ )
}
});
return {
@@ -28485,10 +40503,14 @@ function create_if_block_3(ctx) {
},
p(ctx2, dirty) {
const pulledfilecomponent_changes = {};
- if (dirty & 1)
- pulledfilecomponent_changes.change = ctx2[17].statusResult;
- if (dirty & 4)
- pulledfilecomponent_changes.view = ctx2[2];
+ if (dirty & /*hierarchy*/
+ 1)
+ pulledfilecomponent_changes.change = /*entity*/
+ ctx2[15].data;
+ if (dirty & /*view*/
+ 4)
+ pulledfilecomponent_changes.view = /*view*/
+ ctx2[2];
pulledfilecomponent.$set(pulledfilecomponent_changes);
},
i(local) {
@@ -28506,14 +40528,23 @@ function create_if_block_3(ctx) {
}
};
}
-function create_if_block_2(ctx) {
+function create_if_block_22(ctx) {
let filecomponent;
let current;
filecomponent = new fileComponent_default({
props: {
- change: ctx[17].statusResult,
- manager: ctx[1].gitManager,
- view: ctx[2]
+ change: (
+ /*entity*/
+ ctx[15].data
+ ),
+ manager: (
+ /*plugin*/
+ ctx[1].gitManager
+ ),
+ view: (
+ /*view*/
+ ctx[2]
+ )
}
});
return {
@@ -28526,12 +40557,18 @@ function create_if_block_2(ctx) {
},
p(ctx2, dirty) {
const filecomponent_changes = {};
- if (dirty & 1)
- filecomponent_changes.change = ctx2[17].statusResult;
- if (dirty & 2)
- filecomponent_changes.manager = ctx2[1].gitManager;
- if (dirty & 4)
- filecomponent_changes.view = ctx2[2];
+ if (dirty & /*hierarchy*/
+ 1)
+ filecomponent_changes.change = /*entity*/
+ ctx2[15].data;
+ if (dirty & /*plugin*/
+ 2)
+ filecomponent_changes.manager = /*plugin*/
+ ctx2[1].gitManager;
+ if (dirty & /*view*/
+ 4)
+ filecomponent_changes.view = /*view*/
+ ctx2[2];
filecomponent.$set(filecomponent_changes);
},
i(local) {
@@ -28549,14 +40586,23 @@ function create_if_block_2(ctx) {
}
};
}
-function create_if_block_1(ctx) {
+function create_if_block_13(ctx) {
let stagedfilecomponent;
let current;
stagedfilecomponent = new stagedFileComponent_default({
props: {
- change: ctx[17].statusResult,
- manager: ctx[1].gitManager,
- view: ctx[2]
+ change: (
+ /*entity*/
+ ctx[15].data
+ ),
+ manager: (
+ /*plugin*/
+ ctx[1].gitManager
+ ),
+ view: (
+ /*view*/
+ ctx[2]
+ )
}
});
return {
@@ -28569,12 +40615,18 @@ function create_if_block_1(ctx) {
},
p(ctx2, dirty) {
const stagedfilecomponent_changes = {};
- if (dirty & 1)
- stagedfilecomponent_changes.change = ctx2[17].statusResult;
- if (dirty & 2)
- stagedfilecomponent_changes.manager = ctx2[1].gitManager;
- if (dirty & 4)
- stagedfilecomponent_changes.view = ctx2[2];
+ if (dirty & /*hierarchy*/
+ 1)
+ stagedfilecomponent_changes.change = /*entity*/
+ ctx2[15].data;
+ if (dirty & /*plugin*/
+ 2)
+ stagedfilecomponent_changes.manager = /*plugin*/
+ ctx2[1].gitManager;
+ if (dirty & /*view*/
+ 4)
+ stagedfilecomponent_changes.view = /*view*/
+ ctx2[2];
stagedfilecomponent.$set(stagedfilecomponent_changes);
},
i(local) {
@@ -28592,15 +40644,18 @@ function create_if_block_1(ctx) {
}
};
}
-function create_each_block(ctx) {
+function create_each_block4(ctx) {
let current_block_type_index;
let if_block;
let if_block_anchor;
let current;
- const if_block_creators = [create_if_block3, create_else_block];
+ const if_block_creators = [create_if_block7, create_else_block3];
const if_blocks = [];
function select_block_type(ctx2, dirty) {
- if (ctx2[17].statusResult)
+ if (
+ /*entity*/
+ ctx2[15].data
+ )
return 0;
return 1;
}
@@ -28649,19 +40704,23 @@ function create_each_block(ctx) {
current = false;
},
d(detaching) {
- if_blocks[current_block_type_index].d(detaching);
- if (detaching)
+ if (detaching) {
detach(if_block_anchor);
+ }
+ if_blocks[current_block_type_index].d(detaching);
}
};
}
-function create_fragment4(ctx) {
+function create_fragment8(ctx) {
let main;
let current;
- let each_value = ctx[0].children;
+ let each_value = ensure_array_like(
+ /*hierarchy*/
+ ctx[0].children
+ );
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
- each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
+ each_blocks[i] = create_each_block4(get_each_context4(ctx, each_value, i));
}
const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
@@ -28672,27 +40731,38 @@ function create_fragment4(ctx) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
- attr(main, "class", "svelte-148wteu");
- toggle_class(main, "topLevel", ctx[4]);
+ attr(main, "class", "svelte-hup5mn");
+ toggle_class(
+ main,
+ "topLevel",
+ /*topLevel*/
+ ctx[4]
+ );
},
m(target, anchor) {
insert(target, main, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
- each_blocks[i].m(main, null);
+ if (each_blocks[i]) {
+ each_blocks[i].m(main, null);
+ }
}
current = true;
},
p(ctx2, [dirty]) {
- if (dirty & 2031) {
- each_value = ctx2[0].children;
+ if (dirty & /*hierarchy, plugin, view, fileType, closed, fold, side, unstage, stage, discard*/
+ 2031) {
+ each_value = ensure_array_like(
+ /*hierarchy*/
+ ctx2[0].children
+ );
let i;
for (i = 0; i < each_value.length; i += 1) {
- const child_ctx = get_each_context(ctx2, each_value, i);
+ const child_ctx = get_each_context4(ctx2, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
- each_blocks[i] = create_each_block(child_ctx);
+ each_blocks[i] = create_each_block4(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(main, null);
@@ -28704,8 +40774,14 @@ function create_fragment4(ctx) {
}
check_outros();
}
- if (!current || dirty & 16) {
- toggle_class(main, "topLevel", ctx2[4]);
+ if (!current || dirty & /*topLevel*/
+ 16) {
+ toggle_class(
+ main,
+ "topLevel",
+ /*topLevel*/
+ ctx2[4]
+ );
}
},
i(local) {
@@ -28724,13 +40800,14 @@ function create_fragment4(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(main);
+ }
destroy_each(each_blocks, detaching);
}
};
}
-function instance4($$self, $$props, $$invalidate) {
+function instance8($$self, $$props, $$invalidate) {
let side;
let { hierarchy } = $$props;
let { plugin } = $$props;
@@ -28763,12 +40840,10 @@ function instance4($$self, $$props, $$invalidate) {
function fold(item) {
$$invalidate(5, closed[item.title] = !closed[item.title], closed);
}
- const click_handler = (entity) => fold(entity);
- const click_handler_1 = (entity) => fold(entity);
- const click_handler_2 = (entity) => unstage(entity.path);
- const click_handler_3 = (entity) => discard(entity);
- const click_handler_4 = (entity) => stage(entity.path);
- const click_handler_5 = (entity) => fold(entity);
+ const click_handler = (entity) => unstage(entity.path);
+ const click_handler_1 = (entity) => discard(entity);
+ const click_handler_2 = (entity) => stage(entity.path);
+ const click_handler_3 = (entity) => fold(entity);
$$self.$$set = ($$props2) => {
if ("hierarchy" in $$props2)
$$invalidate(0, hierarchy = $$props2.hierarchy);
@@ -28782,7 +40857,8 @@ function instance4($$self, $$props, $$invalidate) {
$$invalidate(4, topLevel = $$props2.topLevel);
};
$$self.$$.update = () => {
- if ($$self.$$.dirty & 4) {
+ if ($$self.$$.dirty & /*view*/
+ 4) {
$:
$$invalidate(6, side = view.leaf.getRoot().side == "left" ? "right" : "left");
}
@@ -28802,42 +40878,48 @@ function instance4($$self, $$props, $$invalidate) {
click_handler,
click_handler_1,
click_handler_2,
- click_handler_3,
- click_handler_4,
- click_handler_5
+ click_handler_3
];
}
var TreeComponent = class extends SvelteComponent {
constructor(options) {
super();
- init2(this, options, instance4, create_fragment4, safe_not_equal, {
- hierarchy: 0,
- plugin: 1,
- view: 2,
- fileType: 3,
- topLevel: 4
- }, add_css4);
+ init2(
+ this,
+ options,
+ instance8,
+ create_fragment8,
+ safe_not_equal,
+ {
+ hierarchy: 0,
+ plugin: 1,
+ view: 2,
+ fileType: 3,
+ topLevel: 4
+ },
+ add_css7
+ );
}
};
var treeComponent_default = TreeComponent;
-// src/ui/sidebar/gitView.svelte
-function add_css5(target) {
- append_styles(target, "svelte-fnxzfa", `.commit-msg-input.svelte-fnxzfa.svelte-fnxzfa.svelte-fnxzfa{width:100%;overflow:hidden;resize:none;padding:7px 5px;background-color:var(--background-modifier-form-field)}.git-commit-msg.svelte-fnxzfa.svelte-fnxzfa.svelte-fnxzfa{position:relative;padding:0;width:calc(100% - var(--size-4-8));margin:4px auto}main.svelte-fnxzfa .tools.svelte-fnxzfa.svelte-fnxzfa{display:flex;margin-left:auto}main.svelte-fnxzfa .tools .buttons.svelte-fnxzfa.svelte-fnxzfa{display:flex}main.svelte-fnxzfa .tools .buttons.svelte-fnxzfa>.svelte-fnxzfa{padding:0 0;height:auto}main.svelte-fnxzfa .tools .files-count.svelte-fnxzfa.svelte-fnxzfa{padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center}.git-commit-msg-clear-button.svelte-fnxzfa.svelte-fnxzfa.svelte-fnxzfa{position:absolute;background:transparent;border-radius:50%;color:var(--search-clear-button-color);cursor:var(--cursor);top:-4px;right:2px;bottom:0px;line-height:0;height:var(--input-height);width:28px;margin:auto;padding:0 0;text-align:center;display:flex;justify-content:center;align-items:center;transition:color 0.15s ease-in-out}.git-commit-msg-clear-button.svelte-fnxzfa.svelte-fnxzfa.svelte-fnxzfa:after{content:"";height:var(--search-clear-button-size);width:var(--search-clear-button-size);display:block;background-color:currentColor;-webkit-mask-image:url("data:image/svg+xml,");-webkit-mask-repeat:no-repeat}.tree-item-flair.svelte-fnxzfa.svelte-fnxzfa.svelte-fnxzfa{margin-left:auto;align-items:center}`);
+// src/ui/sourceControl/sourceControl.svelte
+function add_css8(target) {
+ append_styles(target, "svelte-1bvmxec", `.commit-msg-input.svelte-1bvmxec.svelte-1bvmxec{width:100%;overflow:hidden;resize:none;padding:7px 5px;background-color:var(--background-modifier-form-field)}.git-commit-msg.svelte-1bvmxec.svelte-1bvmxec{position:relative;padding:0;width:calc(100% - var(--size-4-8));margin:4px auto}main.svelte-1bvmxec .git-tools .files-count.svelte-1bvmxec{padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center}.nav-folder-title.svelte-1bvmxec.svelte-1bvmxec{align-items:center}.git-commit-msg-clear-button.svelte-1bvmxec.svelte-1bvmxec{position:absolute;background:transparent;border-radius:50%;color:var(--search-clear-button-color);cursor:var(--cursor);top:-4px;right:2px;bottom:0px;line-height:0;height:var(--input-height);width:28px;margin:auto;padding:0 0;text-align:center;display:flex;justify-content:center;align-items:center;transition:color 0.15s ease-in-out}.git-commit-msg-clear-button.svelte-1bvmxec.svelte-1bvmxec:after{content:"";height:var(--search-clear-button-size);width:var(--search-clear-button-size);display:block;background-color:currentColor;-webkit-mask-image:url("data:image/svg+xml,");-webkit-mask-repeat:no-repeat}`);
}
-function get_each_context2(ctx, list, i) {
+function get_each_context5(ctx, list, i) {
const child_ctx = ctx.slice();
- child_ctx[43] = list[i];
+ child_ctx[40] = list[i];
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
- child_ctx[43] = list[i];
+ child_ctx[40] = list[i];
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
- child_ctx[48] = list[i];
+ child_ctx[45] = list[i];
return child_ctx;
}
function create_if_block_8(ctx) {
@@ -28848,26 +40930,32 @@ function create_if_block_8(ctx) {
return {
c() {
div = element("div");
- attr(div, "class", "git-commit-msg-clear-button svelte-fnxzfa");
+ attr(div, "class", "git-commit-msg-clear-button svelte-1bvmxec");
attr(div, "aria-label", div_aria_label_value = "Clear");
},
m(target, anchor) {
insert(target, div, anchor);
if (!mounted) {
- dispose = listen(div, "click", ctx[31]);
+ dispose = listen(
+ div,
+ "click",
+ /*click_handler_1*/
+ ctx[33]
+ );
mounted = true;
}
},
p: noop,
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
mounted = false;
dispose();
}
};
}
-function create_if_block4(ctx) {
+function create_if_block8(ctx) {
let div18;
let div17;
let div7;
@@ -28881,7 +40969,10 @@ function create_if_block4(ctx) {
let div2;
let t3;
let div4;
- let t4_value = ctx[6].staged.length + "";
+ let t4_value = (
+ /*status*/
+ ctx[6].staged.length + ""
+ );
let t4;
let t5;
let t6;
@@ -28898,16 +40989,28 @@ function create_if_block4(ctx) {
let div11;
let t11;
let div13;
- let t12_value = ctx[6].changed.length + "";
+ let t12_value = (
+ /*status*/
+ ctx[6].changed.length + ""
+ );
let t12;
let t13;
let t14;
let current;
let mounted;
let dispose;
- let if_block0 = ctx[13] && create_if_block_6(ctx);
- let if_block1 = ctx[12] && create_if_block_42(ctx);
- let if_block2 = ctx[7].length > 0 && create_if_block_12(ctx);
+ let if_block0 = (
+ /*stagedOpen*/
+ ctx[13] && create_if_block_6(ctx)
+ );
+ let if_block1 = (
+ /*changesOpen*/
+ ctx[12] && create_if_block_42(ctx)
+ );
+ let if_block2 = (
+ /*lastPulledFiles*/
+ ctx[7].length > 0 && create_if_block_14(ctx)
+ );
return {
c() {
div18 = element("div");
@@ -28955,33 +41058,39 @@ function create_if_block4(ctx) {
t14 = space();
if (if_block2)
if_block2.c();
- attr(div0, "class", "nav-folder-collapse-indicator collapse-icon");
- attr(div1, "class", "nav-folder-title-content");
+ attr(div0, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon");
+ toggle_class(div0, "is-collapsed", !/*stagedOpen*/
+ ctx[13]);
+ attr(div1, "class", "tree-item-inner nav-folder-title-content");
attr(div2, "data-icon", "minus");
attr(div2, "aria-label", "Unstage");
- attr(div2, "class", "clickable-icon svelte-fnxzfa");
- attr(div3, "class", "buttons svelte-fnxzfa");
- attr(div4, "class", "files-count svelte-fnxzfa");
- attr(div5, "class", "tools svelte-fnxzfa");
- attr(div6, "class", "nav-folder-title");
- attr(div7, "class", "staged nav-folder");
- toggle_class(div7, "is-collapsed", !ctx[13]);
- attr(div8, "class", "nav-folder-collapse-indicator collapse-icon");
- attr(div9, "class", "nav-folder-title-content");
+ attr(div2, "class", "clickable-icon");
+ attr(div3, "class", "buttons");
+ attr(div4, "class", "files-count svelte-1bvmxec");
+ attr(div5, "class", "git-tools");
+ attr(div6, "class", "tree-item-self is-clickable nav-folder-title svelte-1bvmxec");
+ attr(div7, "class", "staged tree-item nav-folder");
+ toggle_class(div7, "is-collapsed", !/*stagedOpen*/
+ ctx[13]);
+ attr(div8, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon");
+ toggle_class(div8, "is-collapsed", !/*changesOpen*/
+ ctx[12]);
+ attr(div9, "class", "tree-item-inner nav-folder-title-content");
attr(div10, "data-icon", "undo");
attr(div10, "aria-label", "Discard");
- attr(div10, "class", "clickable-icon svelte-fnxzfa");
+ attr(div10, "class", "clickable-icon");
attr(div11, "data-icon", "plus");
attr(div11, "aria-label", "Stage");
- attr(div11, "class", "clickable-icon svelte-fnxzfa");
- attr(div12, "class", "buttons svelte-fnxzfa");
- attr(div13, "class", "files-count svelte-fnxzfa");
- attr(div14, "class", "tools svelte-fnxzfa");
- attr(div15, "class", "nav-folder-title");
- attr(div16, "class", "changes nav-folder");
- toggle_class(div16, "is-collapsed", !ctx[12]);
- attr(div17, "class", "nav-folder-children");
- attr(div18, "class", "nav-folder mod-root");
+ attr(div11, "class", "clickable-icon");
+ attr(div12, "class", "buttons");
+ attr(div13, "class", "files-count svelte-1bvmxec");
+ attr(div14, "class", "git-tools");
+ attr(div15, "class", "tree-item-self is-clickable nav-folder-title svelte-1bvmxec");
+ attr(div16, "class", "changes tree-item nav-folder");
+ toggle_class(div16, "is-collapsed", !/*changesOpen*/
+ ctx[12]);
+ attr(div17, "class", "tree-item-children nav-folder-children");
+ attr(div18, "class", "tree-item nav-folder mod-root");
},
m(target, anchor) {
insert(target, div18, anchor);
@@ -29014,7 +41123,7 @@ function create_if_block4(ctx) {
append2(div12, div10);
append2(div12, t10);
append2(div12, div11);
- ctx[39](div11);
+ ctx[36](div11);
append2(div14, t11);
append2(div14, div13);
append2(div13, t12);
@@ -29027,26 +41136,52 @@ function create_if_block4(ctx) {
current = true;
if (!mounted) {
dispose = [
- listen(div0, "click", ctx[32]),
- listen(div1, "click", ctx[33]),
- listen(div2, "click", ctx[18]),
- listen(div6, "click", self2(ctx[35])),
- listen(div8, "click", ctx[36]),
- listen(div9, "click", ctx[37]),
- listen(div10, "click", ctx[38]),
- listen(div11, "click", ctx[17]),
- listen(div15, "click", self2(ctx[40]))
+ listen(div2, "click", stop_propagation(
+ /*unstageAll*/
+ ctx[19]
+ )),
+ listen(
+ div6,
+ "click",
+ /*click_handler_2*/
+ ctx[35]
+ ),
+ listen(div10, "click", stop_propagation(
+ /*discard*/
+ ctx[22]
+ )),
+ listen(div11, "click", stop_propagation(
+ /*stageAll*/
+ ctx[18]
+ )),
+ listen(
+ div15,
+ "click",
+ /*click_handler_3*/
+ ctx[37]
+ )
];
mounted = true;
}
},
p(ctx2, dirty) {
- if ((!current || dirty[0] & 64) && t4_value !== (t4_value = ctx2[6].staged.length + ""))
+ if (!current || dirty[0] & /*stagedOpen*/
+ 8192) {
+ toggle_class(div0, "is-collapsed", !/*stagedOpen*/
+ ctx2[13]);
+ }
+ if ((!current || dirty[0] & /*status*/
+ 64) && t4_value !== (t4_value = /*status*/
+ ctx2[6].staged.length + ""))
set_data(t4, t4_value);
- if (ctx2[13]) {
+ if (
+ /*stagedOpen*/
+ ctx2[13]
+ ) {
if (if_block0) {
if_block0.p(ctx2, dirty);
- if (dirty[0] & 8192) {
+ if (dirty[0] & /*stagedOpen*/
+ 8192) {
transition_in(if_block0, 1);
}
} else {
@@ -29062,15 +41197,28 @@ function create_if_block4(ctx) {
});
check_outros();
}
- if (!current || dirty[0] & 8192) {
- toggle_class(div7, "is-collapsed", !ctx2[13]);
+ if (!current || dirty[0] & /*stagedOpen*/
+ 8192) {
+ toggle_class(div7, "is-collapsed", !/*stagedOpen*/
+ ctx2[13]);
}
- if ((!current || dirty[0] & 64) && t12_value !== (t12_value = ctx2[6].changed.length + ""))
+ if (!current || dirty[0] & /*changesOpen*/
+ 4096) {
+ toggle_class(div8, "is-collapsed", !/*changesOpen*/
+ ctx2[12]);
+ }
+ if ((!current || dirty[0] & /*status*/
+ 64) && t12_value !== (t12_value = /*status*/
+ ctx2[6].changed.length + ""))
set_data(t12, t12_value);
- if (ctx2[12]) {
+ if (
+ /*changesOpen*/
+ ctx2[12]
+ ) {
if (if_block1) {
if_block1.p(ctx2, dirty);
- if (dirty[0] & 4096) {
+ if (dirty[0] & /*changesOpen*/
+ 4096) {
transition_in(if_block1, 1);
}
} else {
@@ -29086,17 +41234,23 @@ function create_if_block4(ctx) {
});
check_outros();
}
- if (!current || dirty[0] & 4096) {
- toggle_class(div16, "is-collapsed", !ctx2[12]);
+ if (!current || dirty[0] & /*changesOpen*/
+ 4096) {
+ toggle_class(div16, "is-collapsed", !/*changesOpen*/
+ ctx2[12]);
}
- if (ctx2[7].length > 0) {
+ if (
+ /*lastPulledFiles*/
+ ctx2[7].length > 0
+ ) {
if (if_block2) {
if_block2.p(ctx2, dirty);
- if (dirty[0] & 128) {
+ if (dirty[0] & /*lastPulledFiles*/
+ 128) {
transition_in(if_block2, 1);
}
} else {
- if_block2 = create_if_block_12(ctx2);
+ if_block2 = create_if_block_14(ctx2);
if_block2.c();
transition_in(if_block2, 1);
if_block2.m(div17, null);
@@ -29124,12 +41278,13 @@ function create_if_block4(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div18);
+ }
ctx[34](null);
if (if_block0)
if_block0.d();
- ctx[39](null);
+ ctx[36](null);
if (if_block1)
if_block1.d();
if (if_block2)
@@ -29148,7 +41303,10 @@ function create_if_block_6(ctx) {
const if_block_creators = [create_if_block_7, create_else_block_2];
const if_blocks = [];
function select_block_type(ctx2, dirty) {
- if (ctx2[3])
+ if (
+ /*showTree*/
+ ctx2[3]
+ )
return 0;
return 1;
}
@@ -29158,7 +41316,7 @@ function create_if_block_6(ctx) {
c() {
div = element("div");
if_block.c();
- attr(div, "class", "nav-folder-children");
+ attr(div, "class", "tree-item-children nav-folder-children");
},
m(target, anchor) {
insert(target, div, anchor);
@@ -29193,6 +41351,8 @@ function create_if_block_6(ctx) {
transition_in(if_block);
if (local) {
add_render_callback(() => {
+ if (!current)
+ return;
if (!div_transition)
div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true);
div_transition.run(1);
@@ -29210,8 +41370,9 @@ function create_if_block_6(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
if_blocks[current_block_type_index].d();
if (detaching && div_transition)
div_transition.end();
@@ -29221,7 +41382,10 @@ function create_if_block_6(ctx) {
function create_else_block_2(ctx) {
let each_1_anchor;
let current;
- let each_value_2 = ctx[6].staged;
+ let each_value_2 = ensure_array_like(
+ /*status*/
+ ctx[6].staged
+ );
let each_blocks = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
@@ -29238,14 +41402,20 @@ function create_else_block_2(ctx) {
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
- each_blocks[i].m(target, anchor);
+ if (each_blocks[i]) {
+ each_blocks[i].m(target, anchor);
+ }
}
insert(target, each_1_anchor, anchor);
current = true;
},
p(ctx2, dirty) {
- if (dirty[0] & 67) {
- each_value_2 = ctx2[6].staged;
+ if (dirty[0] & /*status, view, plugin*/
+ 67) {
+ each_value_2 = ensure_array_like(
+ /*status*/
+ ctx2[6].staged
+ );
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx2, each_value_2, i);
@@ -29282,9 +41452,10 @@ function create_else_block_2(ctx) {
current = false;
},
d(detaching) {
- destroy_each(each_blocks, detaching);
- if (detaching)
+ if (detaching) {
detach(each_1_anchor);
+ }
+ destroy_each(each_blocks, detaching);
}
};
}
@@ -29293,10 +41464,19 @@ function create_if_block_7(ctx) {
let current;
treecomponent = new treeComponent_default({
props: {
- hierarchy: ctx[10],
- plugin: ctx[0],
- view: ctx[1],
- fileType: FileType.staged,
+ hierarchy: (
+ /*stagedHierarchy*/
+ ctx[10]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[0]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ fileType: 0 /* staged */,
topLevel: true
}
});
@@ -29310,12 +41490,18 @@ function create_if_block_7(ctx) {
},
p(ctx2, dirty) {
const treecomponent_changes = {};
- if (dirty[0] & 1024)
- treecomponent_changes.hierarchy = ctx2[10];
- if (dirty[0] & 1)
- treecomponent_changes.plugin = ctx2[0];
- if (dirty[0] & 2)
- treecomponent_changes.view = ctx2[1];
+ if (dirty[0] & /*stagedHierarchy*/
+ 1024)
+ treecomponent_changes.hierarchy = /*stagedHierarchy*/
+ ctx2[10];
+ if (dirty[0] & /*plugin*/
+ 1)
+ treecomponent_changes.plugin = /*plugin*/
+ ctx2[0];
+ if (dirty[0] & /*view*/
+ 2)
+ treecomponent_changes.view = /*view*/
+ ctx2[1];
treecomponent.$set(treecomponent_changes);
},
i(local) {
@@ -29338,9 +41524,18 @@ function create_each_block_2(ctx) {
let current;
stagedfilecomponent = new stagedFileComponent_default({
props: {
- change: ctx[48],
- view: ctx[1],
- manager: ctx[0].gitManager
+ change: (
+ /*stagedFile*/
+ ctx[45]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ manager: (
+ /*plugin*/
+ ctx[0].gitManager
+ )
}
});
return {
@@ -29353,12 +41548,18 @@ function create_each_block_2(ctx) {
},
p(ctx2, dirty) {
const stagedfilecomponent_changes = {};
- if (dirty[0] & 64)
- stagedfilecomponent_changes.change = ctx2[48];
- if (dirty[0] & 2)
- stagedfilecomponent_changes.view = ctx2[1];
- if (dirty[0] & 1)
- stagedfilecomponent_changes.manager = ctx2[0].gitManager;
+ if (dirty[0] & /*status*/
+ 64)
+ stagedfilecomponent_changes.change = /*stagedFile*/
+ ctx2[45];
+ if (dirty[0] & /*view*/
+ 2)
+ stagedfilecomponent_changes.view = /*view*/
+ ctx2[1];
+ if (dirty[0] & /*plugin*/
+ 1)
+ stagedfilecomponent_changes.manager = /*plugin*/
+ ctx2[0].gitManager;
stagedfilecomponent.$set(stagedfilecomponent_changes);
},
i(local) {
@@ -29385,7 +41586,10 @@ function create_if_block_42(ctx) {
const if_block_creators = [create_if_block_52, create_else_block_12];
const if_blocks = [];
function select_block_type_1(ctx2, dirty) {
- if (ctx2[3])
+ if (
+ /*showTree*/
+ ctx2[3]
+ )
return 0;
return 1;
}
@@ -29395,7 +41599,7 @@ function create_if_block_42(ctx) {
c() {
div = element("div");
if_block.c();
- attr(div, "class", "nav-folder-children");
+ attr(div, "class", "tree-item-children nav-folder-children");
},
m(target, anchor) {
insert(target, div, anchor);
@@ -29430,6 +41634,8 @@ function create_if_block_42(ctx) {
transition_in(if_block);
if (local) {
add_render_callback(() => {
+ if (!current)
+ return;
if (!div_transition)
div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true);
div_transition.run(1);
@@ -29447,8 +41653,9 @@ function create_if_block_42(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
if_blocks[current_block_type_index].d();
if (detaching && div_transition)
div_transition.end();
@@ -29458,7 +41665,10 @@ function create_if_block_42(ctx) {
function create_else_block_12(ctx) {
let each_1_anchor;
let current;
- let each_value_1 = ctx[6].changed;
+ let each_value_1 = ensure_array_like(
+ /*status*/
+ ctx[6].changed
+ );
let each_blocks = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
@@ -29475,14 +41685,20 @@ function create_else_block_12(ctx) {
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
- each_blocks[i].m(target, anchor);
+ if (each_blocks[i]) {
+ each_blocks[i].m(target, anchor);
+ }
}
insert(target, each_1_anchor, anchor);
current = true;
},
p(ctx2, dirty) {
- if (dirty[0] & 67) {
- each_value_1 = ctx2[6].changed;
+ if (dirty[0] & /*status, view, plugin*/
+ 67) {
+ each_value_1 = ensure_array_like(
+ /*status*/
+ ctx2[6].changed
+ );
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx2, each_value_1, i);
@@ -29519,9 +41735,10 @@ function create_else_block_12(ctx) {
current = false;
},
d(detaching) {
- destroy_each(each_blocks, detaching);
- if (detaching)
+ if (detaching) {
detach(each_1_anchor);
+ }
+ destroy_each(each_blocks, detaching);
}
};
}
@@ -29530,10 +41747,19 @@ function create_if_block_52(ctx) {
let current;
treecomponent = new treeComponent_default({
props: {
- hierarchy: ctx[9],
- plugin: ctx[0],
- view: ctx[1],
- fileType: FileType.changed,
+ hierarchy: (
+ /*changeHierarchy*/
+ ctx[9]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[0]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ fileType: 1 /* changed */,
topLevel: true
}
});
@@ -29547,12 +41773,18 @@ function create_if_block_52(ctx) {
},
p(ctx2, dirty) {
const treecomponent_changes = {};
- if (dirty[0] & 512)
- treecomponent_changes.hierarchy = ctx2[9];
- if (dirty[0] & 1)
- treecomponent_changes.plugin = ctx2[0];
- if (dirty[0] & 2)
- treecomponent_changes.view = ctx2[1];
+ if (dirty[0] & /*changeHierarchy*/
+ 512)
+ treecomponent_changes.hierarchy = /*changeHierarchy*/
+ ctx2[9];
+ if (dirty[0] & /*plugin*/
+ 1)
+ treecomponent_changes.plugin = /*plugin*/
+ ctx2[0];
+ if (dirty[0] & /*view*/
+ 2)
+ treecomponent_changes.view = /*view*/
+ ctx2[1];
treecomponent.$set(treecomponent_changes);
},
i(local) {
@@ -29575,12 +41807,21 @@ function create_each_block_1(ctx) {
let current;
filecomponent = new fileComponent_default({
props: {
- change: ctx[43],
- view: ctx[1],
- manager: ctx[0].gitManager
+ change: (
+ /*change*/
+ ctx[40]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ manager: (
+ /*plugin*/
+ ctx[0].gitManager
+ )
}
});
- filecomponent.$on("git-refresh", triggerRefresh);
+ filecomponent.$on("git-refresh", triggerRefresh2);
return {
c() {
create_component(filecomponent.$$.fragment);
@@ -29591,12 +41832,18 @@ function create_each_block_1(ctx) {
},
p(ctx2, dirty) {
const filecomponent_changes = {};
- if (dirty[0] & 64)
- filecomponent_changes.change = ctx2[43];
- if (dirty[0] & 2)
- filecomponent_changes.view = ctx2[1];
- if (dirty[0] & 1)
- filecomponent_changes.manager = ctx2[0].gitManager;
+ if (dirty[0] & /*status*/
+ 64)
+ filecomponent_changes.change = /*change*/
+ ctx2[40];
+ if (dirty[0] & /*view*/
+ 2)
+ filecomponent_changes.view = /*view*/
+ ctx2[1];
+ if (dirty[0] & /*plugin*/
+ 1)
+ filecomponent_changes.manager = /*plugin*/
+ ctx2[0].gitManager;
filecomponent.$set(filecomponent_changes);
},
i(local) {
@@ -29614,7 +41861,7 @@ function create_each_block_1(ctx) {
}
};
}
-function create_if_block_12(ctx) {
+function create_if_block_14(ctx) {
let div3;
let div2;
let div0;
@@ -29622,13 +41869,19 @@ function create_if_block_12(ctx) {
let div1;
let t2;
let span;
- let t3_value = ctx[7].length + "";
+ let t3_value = (
+ /*lastPulledFiles*/
+ ctx[7].length + ""
+ );
let t3;
let t4;
let current;
let mounted;
let dispose;
- let if_block = ctx[14] && create_if_block_22(ctx);
+ let if_block = (
+ /*lastPulledFilesOpen*/
+ ctx[14] && create_if_block_23(ctx)
+ );
return {
c() {
div3 = element("div");
@@ -29644,12 +41897,13 @@ function create_if_block_12(ctx) {
t4 = space();
if (if_block)
if_block.c();
- attr(div0, "class", "nav-folder-collapse-indicator collapse-icon");
- attr(div1, "class", "nav-folder-title-content");
- attr(span, "class", "tree-item-flair svelte-fnxzfa");
- attr(div2, "class", "nav-folder-title");
+ attr(div0, "class", "tree-item-icon nav-folder-collapse-indicator collapse-icon");
+ attr(div1, "class", "tree-item-inner nav-folder-title-content");
+ attr(span, "class", "tree-item-flair");
+ attr(div2, "class", "tree-item-self is-clickable nav-folder-title svelte-1bvmxec");
attr(div3, "class", "pulled nav-folder");
- toggle_class(div3, "is-collapsed", !ctx[14]);
+ toggle_class(div3, "is-collapsed", !/*lastPulledFilesOpen*/
+ ctx[14]);
},
m(target, anchor) {
insert(target, div3, anchor);
@@ -29665,21 +41919,32 @@ function create_if_block_12(ctx) {
if_block.m(div3, null);
current = true;
if (!mounted) {
- dispose = listen(div2, "click", ctx[41]);
+ dispose = listen(
+ div2,
+ "click",
+ /*click_handler_4*/
+ ctx[38]
+ );
mounted = true;
}
},
p(ctx2, dirty) {
- if ((!current || dirty[0] & 128) && t3_value !== (t3_value = ctx2[7].length + ""))
+ if ((!current || dirty[0] & /*lastPulledFiles*/
+ 128) && t3_value !== (t3_value = /*lastPulledFiles*/
+ ctx2[7].length + ""))
set_data(t3, t3_value);
- if (ctx2[14]) {
+ if (
+ /*lastPulledFilesOpen*/
+ ctx2[14]
+ ) {
if (if_block) {
if_block.p(ctx2, dirty);
- if (dirty[0] & 16384) {
+ if (dirty[0] & /*lastPulledFilesOpen*/
+ 16384) {
transition_in(if_block, 1);
}
} else {
- if_block = create_if_block_22(ctx2);
+ if_block = create_if_block_23(ctx2);
if_block.c();
transition_in(if_block, 1);
if_block.m(div3, null);
@@ -29691,8 +41956,10 @@ function create_if_block_12(ctx) {
});
check_outros();
}
- if (!current || dirty[0] & 16384) {
- toggle_class(div3, "is-collapsed", !ctx2[14]);
+ if (!current || dirty[0] & /*lastPulledFilesOpen*/
+ 16384) {
+ toggle_class(div3, "is-collapsed", !/*lastPulledFilesOpen*/
+ ctx2[14]);
}
},
i(local) {
@@ -29706,8 +41973,9 @@ function create_if_block_12(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div3);
+ }
if (if_block)
if_block.d();
mounted = false;
@@ -29715,16 +41983,19 @@ function create_if_block_12(ctx) {
}
};
}
-function create_if_block_22(ctx) {
+function create_if_block_23(ctx) {
let div;
let current_block_type_index;
let if_block;
let div_transition;
let current;
- const if_block_creators = [create_if_block_32, create_else_block2];
+ const if_block_creators = [create_if_block_32, create_else_block4];
const if_blocks = [];
function select_block_type_2(ctx2, dirty) {
- if (ctx2[3])
+ if (
+ /*showTree*/
+ ctx2[3]
+ )
return 0;
return 1;
}
@@ -29734,7 +42005,7 @@ function create_if_block_22(ctx) {
c() {
div = element("div");
if_block.c();
- attr(div, "class", "nav-folder-children");
+ attr(div, "class", "tree-item-children nav-folder-children");
},
m(target, anchor) {
insert(target, div, anchor);
@@ -29769,6 +42040,8 @@ function create_if_block_22(ctx) {
transition_in(if_block);
if (local) {
add_render_callback(() => {
+ if (!current)
+ return;
if (!div_transition)
div_transition = create_bidirectional_transition(div, slide, { duration: 150 }, true);
div_transition.run(1);
@@ -29786,21 +42059,25 @@ function create_if_block_22(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(div);
+ }
if_blocks[current_block_type_index].d();
if (detaching && div_transition)
div_transition.end();
}
};
}
-function create_else_block2(ctx) {
+function create_else_block4(ctx) {
let each_1_anchor;
let current;
- let each_value = ctx[7];
+ let each_value = ensure_array_like(
+ /*lastPulledFiles*/
+ ctx[7]
+ );
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
- each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i));
+ each_blocks[i] = create_each_block5(get_each_context5(ctx, each_value, i));
}
const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
@@ -29814,22 +42091,28 @@ function create_else_block2(ctx) {
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
- each_blocks[i].m(target, anchor);
+ if (each_blocks[i]) {
+ each_blocks[i].m(target, anchor);
+ }
}
insert(target, each_1_anchor, anchor);
current = true;
},
p(ctx2, dirty) {
- if (dirty[0] & 130) {
- each_value = ctx2[7];
+ if (dirty[0] & /*lastPulledFiles, view*/
+ 130) {
+ each_value = ensure_array_like(
+ /*lastPulledFiles*/
+ ctx2[7]
+ );
let i;
for (i = 0; i < each_value.length; i += 1) {
- const child_ctx = get_each_context2(ctx2, each_value, i);
+ const child_ctx = get_each_context5(ctx2, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
- each_blocks[i] = create_each_block2(child_ctx);
+ each_blocks[i] = create_each_block5(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
@@ -29858,9 +42141,10 @@ function create_else_block2(ctx) {
current = false;
},
d(detaching) {
- destroy_each(each_blocks, detaching);
- if (detaching)
+ if (detaching) {
detach(each_1_anchor);
+ }
+ destroy_each(each_blocks, detaching);
}
};
}
@@ -29869,10 +42153,19 @@ function create_if_block_32(ctx) {
let current;
treecomponent = new treeComponent_default({
props: {
- hierarchy: ctx[11],
- plugin: ctx[0],
- view: ctx[1],
- fileType: FileType.pulled,
+ hierarchy: (
+ /*lastPulledFilesHierarchy*/
+ ctx[11]
+ ),
+ plugin: (
+ /*plugin*/
+ ctx[0]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ ),
+ fileType: 2 /* pulled */,
topLevel: true
}
});
@@ -29886,12 +42179,18 @@ function create_if_block_32(ctx) {
},
p(ctx2, dirty) {
const treecomponent_changes = {};
- if (dirty[0] & 2048)
- treecomponent_changes.hierarchy = ctx2[11];
- if (dirty[0] & 1)
- treecomponent_changes.plugin = ctx2[0];
- if (dirty[0] & 2)
- treecomponent_changes.view = ctx2[1];
+ if (dirty[0] & /*lastPulledFilesHierarchy*/
+ 2048)
+ treecomponent_changes.hierarchy = /*lastPulledFilesHierarchy*/
+ ctx2[11];
+ if (dirty[0] & /*plugin*/
+ 1)
+ treecomponent_changes.plugin = /*plugin*/
+ ctx2[0];
+ if (dirty[0] & /*view*/
+ 2)
+ treecomponent_changes.view = /*view*/
+ ctx2[1];
treecomponent.$set(treecomponent_changes);
},
i(local) {
@@ -29909,16 +42208,22 @@ function create_if_block_32(ctx) {
}
};
}
-function create_each_block2(ctx) {
+function create_each_block5(ctx) {
let pulledfilecomponent;
let current;
pulledfilecomponent = new pulledFileComponent_default({
props: {
- change: ctx[43],
- view: ctx[1]
+ change: (
+ /*change*/
+ ctx[40]
+ ),
+ view: (
+ /*view*/
+ ctx[1]
+ )
}
});
- pulledfilecomponent.$on("git-refresh", triggerRefresh);
+ pulledfilecomponent.$on("git-refresh", triggerRefresh2);
return {
c() {
create_component(pulledfilecomponent.$$.fragment);
@@ -29929,10 +42234,14 @@ function create_each_block2(ctx) {
},
p(ctx2, dirty) {
const pulledfilecomponent_changes = {};
- if (dirty[0] & 128)
- pulledfilecomponent_changes.change = ctx2[43];
- if (dirty[0] & 2)
- pulledfilecomponent_changes.view = ctx2[1];
+ if (dirty[0] & /*lastPulledFiles*/
+ 128)
+ pulledfilecomponent_changes.change = /*change*/
+ ctx2[40];
+ if (dirty[0] & /*view*/
+ 2)
+ pulledfilecomponent_changes.view = /*view*/
+ ctx2[1];
pulledfilecomponent.$set(pulledfilecomponent_changes);
},
i(local) {
@@ -29950,10 +42259,10 @@ function create_each_block2(ctx) {
}
};
}
-function create_fragment5(ctx) {
+function create_fragment9(ctx) {
let main;
+ let div9;
let div8;
- let div7;
let div0;
let t0;
let div1;
@@ -29968,21 +42277,32 @@ function create_fragment5(ctx) {
let t5;
let div6;
let t6;
- let div9;
- let textarea;
+ let div7;
let t7;
- let t8;
let div10;
+ let textarea;
+ let t8;
+ let t9;
+ let div11;
+ let main_data_type_value;
let current;
let mounted;
let dispose;
- let if_block0 = ctx[2] && create_if_block_8(ctx);
- let if_block1 = ctx[6] && ctx[10] && ctx[9] && create_if_block4(ctx);
+ let if_block0 = (
+ /*commitMessage*/
+ ctx[2] && create_if_block_8(ctx)
+ );
+ let if_block1 = (
+ /*status*/
+ ctx[6] && /*stagedHierarchy*/
+ ctx[10] && /*changeHierarchy*/
+ ctx[9] && create_if_block8(ctx)
+ );
return {
c() {
main = element("main");
+ div9 = element("div");
div8 = element("div");
- div7 = element("div");
div0 = element("div");
t0 = space();
div1 = element("div");
@@ -29997,139 +42317,229 @@ function create_fragment5(ctx) {
t5 = space();
div6 = element("div");
t6 = space();
- div9 = element("div");
- textarea = element("textarea");
+ div7 = element("div");
t7 = space();
+ div10 = element("div");
+ textarea = element("textarea");
+ t8 = space();
if (if_block0)
if_block0.c();
- t8 = space();
- div10 = element("div");
+ t9 = space();
+ div11 = element("div");
if (if_block1)
if_block1.c();
- attr(div0, "id", "commit-btn");
- attr(div0, "data-icon", "check");
+ attr(div0, "id", "backup-btn");
+ attr(div0, "data-icon", "arrow-up-circle");
attr(div0, "class", "clickable-icon nav-action-button");
- attr(div0, "aria-label", "Commit");
- attr(div1, "id", "stage-all");
+ attr(div0, "aria-label", "Backup");
+ attr(div1, "id", "commit-btn");
+ attr(div1, "data-icon", "check");
attr(div1, "class", "clickable-icon nav-action-button");
- attr(div1, "data-icon", "plus-circle");
- attr(div1, "aria-label", "Stage all");
- attr(div2, "id", "unstage-all");
+ attr(div1, "aria-label", "Commit");
+ attr(div2, "id", "stage-all");
attr(div2, "class", "clickable-icon nav-action-button");
- attr(div2, "data-icon", "minus-circle");
- attr(div2, "aria-label", "Unstage all");
- attr(div3, "id", "push");
+ attr(div2, "data-icon", "plus-circle");
+ attr(div2, "aria-label", "Stage all");
+ attr(div3, "id", "unstage-all");
attr(div3, "class", "clickable-icon nav-action-button");
- attr(div3, "data-icon", "upload");
- attr(div3, "aria-label", "Push");
- attr(div4, "id", "pull");
+ attr(div3, "data-icon", "minus-circle");
+ attr(div3, "aria-label", "Unstage all");
+ attr(div4, "id", "push");
attr(div4, "class", "clickable-icon nav-action-button");
- attr(div4, "data-icon", "download");
- attr(div4, "aria-label", "Pull");
- attr(div5, "id", "layoutChange");
+ attr(div4, "data-icon", "upload");
+ attr(div4, "aria-label", "Push");
+ attr(div5, "id", "pull");
attr(div5, "class", "clickable-icon nav-action-button");
- attr(div5, "aria-label", "Change Layout");
- attr(div6, "id", "refresh");
+ attr(div5, "data-icon", "download");
+ attr(div5, "aria-label", "Pull");
+ attr(div6, "id", "layoutChange");
attr(div6, "class", "clickable-icon nav-action-button");
- attr(div6, "data-icon", "refresh-cw");
- attr(div6, "aria-label", "Refresh");
- set_style(div6, "margin", "1px");
- toggle_class(div6, "loading", ctx[5]);
- attr(div7, "class", "nav-buttons-container");
- attr(div8, "class", "nav-header");
- attr(textarea, "rows", ctx[15]);
- attr(textarea, "class", "commit-msg-input svelte-fnxzfa");
- attr(textarea, "type", "text");
+ attr(div6, "aria-label", "Change Layout");
+ attr(div7, "id", "refresh");
+ attr(div7, "class", "clickable-icon nav-action-button");
+ attr(div7, "data-icon", "refresh-cw");
+ attr(div7, "aria-label", "Refresh");
+ set_style(div7, "margin", "1px");
+ toggle_class(
+ div7,
+ "loading",
+ /*loading*/
+ ctx[5]
+ );
+ attr(div8, "class", "nav-buttons-container");
+ attr(div9, "class", "nav-header");
+ attr(
+ textarea,
+ "rows",
+ /*rows*/
+ ctx[15]
+ );
+ attr(textarea, "class", "commit-msg-input svelte-1bvmxec");
attr(textarea, "spellcheck", "true");
attr(textarea, "placeholder", "Commit Message");
- attr(div9, "class", "git-commit-msg svelte-fnxzfa");
- attr(div10, "class", "nav-files-container");
- set_style(div10, "position", "relative");
- attr(main, "class", "svelte-fnxzfa");
+ attr(div10, "class", "git-commit-msg svelte-1bvmxec");
+ attr(div11, "class", "nav-files-container");
+ set_style(div11, "position", "relative");
+ attr(main, "data-type", main_data_type_value = SOURCE_CONTROL_VIEW_CONFIG.type);
+ attr(main, "class", "svelte-1bvmxec");
},
m(target, anchor) {
insert(target, main, anchor);
- append2(main, div8);
- append2(div8, div7);
- append2(div7, div0);
- ctx[22](div0);
- append2(div7, t0);
- append2(div7, div1);
- ctx[23](div1);
- append2(div7, t1);
- append2(div7, div2);
- ctx[24](div2);
- append2(div7, t2);
- append2(div7, div3);
- ctx[25](div3);
- append2(div7, t3);
- append2(div7, div4);
- ctx[26](div4);
- append2(div7, t4);
- append2(div7, div5);
- ctx[27](div5);
- append2(div7, t5);
- append2(div7, div6);
- ctx[29](div6);
- append2(main, t6);
append2(main, div9);
- append2(div9, textarea);
- set_input_value(textarea, ctx[2]);
- append2(div9, t7);
- if (if_block0)
- if_block0.m(div9, null);
- append2(main, t8);
+ append2(div9, div8);
+ append2(div8, div0);
+ ctx[23](div0);
+ append2(div8, t0);
+ append2(div8, div1);
+ ctx[24](div1);
+ append2(div8, t1);
+ append2(div8, div2);
+ ctx[25](div2);
+ append2(div8, t2);
+ append2(div8, div3);
+ ctx[26](div3);
+ append2(div8, t3);
+ append2(div8, div4);
+ ctx[27](div4);
+ append2(div8, t4);
+ append2(div8, div5);
+ ctx[28](div5);
+ append2(div8, t5);
+ append2(div8, div6);
+ ctx[29](div6);
+ append2(div8, t6);
+ append2(div8, div7);
+ ctx[31](div7);
+ append2(main, t7);
append2(main, div10);
+ append2(div10, textarea);
+ set_input_value(
+ textarea,
+ /*commitMessage*/
+ ctx[2]
+ );
+ append2(div10, t8);
+ if (if_block0)
+ if_block0.m(div10, null);
+ append2(main, t9);
+ append2(main, div11);
if (if_block1)
- if_block1.m(div10, null);
+ if_block1.m(div11, null);
current = true;
if (!mounted) {
dispose = [
- listen(div0, "click", ctx[16]),
- listen(div1, "click", ctx[17]),
- listen(div2, "click", ctx[18]),
- listen(div3, "click", ctx[19]),
- listen(div4, "click", ctx[20]),
- listen(div5, "click", ctx[28]),
- listen(div6, "click", triggerRefresh),
- listen(textarea, "input", ctx[30])
+ listen(
+ div0,
+ "click",
+ /*backup*/
+ ctx[17]
+ ),
+ listen(
+ div1,
+ "click",
+ /*commit*/
+ ctx[16]
+ ),
+ listen(
+ div2,
+ "click",
+ /*stageAll*/
+ ctx[18]
+ ),
+ listen(
+ div3,
+ "click",
+ /*unstageAll*/
+ ctx[19]
+ ),
+ listen(
+ div4,
+ "click",
+ /*push*/
+ ctx[20]
+ ),
+ listen(
+ div5,
+ "click",
+ /*pull*/
+ ctx[21]
+ ),
+ listen(
+ div6,
+ "click",
+ /*click_handler*/
+ ctx[30]
+ ),
+ listen(div7, "click", triggerRefresh2),
+ listen(
+ textarea,
+ "input",
+ /*textarea_input_handler*/
+ ctx[32]
+ )
];
mounted = true;
}
},
p(ctx2, dirty) {
- if (!current || dirty[0] & 32) {
- toggle_class(div6, "loading", ctx2[5]);
+ if (!current || dirty[0] & /*loading*/
+ 32) {
+ toggle_class(
+ div7,
+ "loading",
+ /*loading*/
+ ctx2[5]
+ );
}
- if (!current || dirty[0] & 32768) {
- attr(textarea, "rows", ctx2[15]);
+ if (!current || dirty[0] & /*rows*/
+ 32768) {
+ attr(
+ textarea,
+ "rows",
+ /*rows*/
+ ctx2[15]
+ );
}
- if (dirty[0] & 4) {
- set_input_value(textarea, ctx2[2]);
+ if (dirty[0] & /*commitMessage*/
+ 4) {
+ set_input_value(
+ textarea,
+ /*commitMessage*/
+ ctx2[2]
+ );
}
- if (ctx2[2]) {
+ if (
+ /*commitMessage*/
+ ctx2[2]
+ ) {
if (if_block0) {
if_block0.p(ctx2, dirty);
} else {
if_block0 = create_if_block_8(ctx2);
if_block0.c();
- if_block0.m(div9, null);
+ if_block0.m(div10, null);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
- if (ctx2[6] && ctx2[10] && ctx2[9]) {
+ if (
+ /*status*/
+ ctx2[6] && /*stagedHierarchy*/
+ ctx2[10] && /*changeHierarchy*/
+ ctx2[9]
+ ) {
if (if_block1) {
if_block1.p(ctx2, dirty);
- if (dirty[0] & 1600) {
+ if (dirty[0] & /*status, stagedHierarchy, changeHierarchy*/
+ 1600) {
transition_in(if_block1, 1);
}
} else {
- if_block1 = create_if_block4(ctx2);
+ if_block1 = create_if_block8(ctx2);
if_block1.c();
transition_in(if_block1, 1);
- if_block1.m(div10, null);
+ if_block1.m(div11, null);
}
} else if (if_block1) {
group_outros();
@@ -30150,15 +42560,17 @@ function create_fragment5(ctx) {
current = false;
},
d(detaching) {
- if (detaching)
+ if (detaching) {
detach(main);
- ctx[22](null);
+ }
ctx[23](null);
ctx[24](null);
ctx[25](null);
ctx[26](null);
ctx[27](null);
+ ctx[28](null);
ctx[29](null);
+ ctx[31](null);
if (if_block0)
if_block0.d();
if (if_block1)
@@ -30168,10 +42580,10 @@ function create_fragment5(ctx) {
}
};
}
-function triggerRefresh() {
+function triggerRefresh2() {
dispatchEvent(new CustomEvent("git-refresh"));
}
-function instance5($$self, $$props, $$invalidate) {
+function instance9($$self, $$props, $$invalidate) {
let rows;
let { plugin } = $$props;
let { view } = $$props;
@@ -30190,130 +42602,171 @@ function instance5($$self, $$props, $$invalidate) {
let layoutBtn;
addEventListener("git-view-refresh", refresh);
plugin.app.workspace.onLayoutReady(() => {
- window.setTimeout(() => {
- buttons.forEach((btn) => (0, import_obsidian21.setIcon)(btn, btn.getAttr("data-icon"), 16));
- (0, import_obsidian21.setIcon)(layoutBtn, showTree ? "list" : "folder", 16);
- }, 0);
+ window.setTimeout(
+ () => {
+ buttons.forEach((btn) => (0, import_obsidian28.setIcon)(btn, btn.getAttr("data-icon")));
+ (0, import_obsidian28.setIcon)(layoutBtn, showTree ? "list" : "folder");
+ },
+ 0
+ );
});
onDestroy(() => {
removeEventListener("git-view-refresh", refresh);
});
- async function commit2() {
- $$invalidate(5, loading = true);
- if (status2) {
- if (await plugin.hasTooBigFiles(status2.staged)) {
- plugin.setState(PluginState.idle);
- return false;
- }
- plugin.gitManager.commit(commitMessage).then(() => {
- if (commitMessage !== plugin.settings.commitMessage) {
- $$invalidate(2, commitMessage = "");
+ function commit2() {
+ return __awaiter(this, void 0, void 0, function* () {
+ $$invalidate(5, loading = true);
+ if (status2) {
+ if (yield plugin.hasTooBigFiles(status2.staged)) {
+ plugin.setState(0 /* idle */);
+ return false;
}
- }).finally(triggerRefresh);
- }
+ plugin.promiseQueue.addTask(() => plugin.gitManager.commit({ message: commitMessage }).then(() => {
+ if (commitMessage !== plugin.settings.commitMessage) {
+ $$invalidate(2, commitMessage = "");
+ }
+ plugin.setUpAutoBackup();
+ }).finally(triggerRefresh2));
+ }
+ });
}
- async function refresh() {
- if (!plugin.gitReady) {
- $$invalidate(6, status2 = void 0);
- return;
- }
- $$invalidate(6, status2 = plugin.cachedStatus);
- if (plugin.lastPulledFiles && plugin.lastPulledFiles != lastPulledFiles) {
- $$invalidate(7, lastPulledFiles = plugin.lastPulledFiles);
- $$invalidate(11, lastPulledFilesHierarchy = {
- title: "",
- path: "",
- vaultPath: "",
- children: plugin.gitManager.getTreeStructure(lastPulledFiles)
- });
- }
- if (status2) {
- const sort = (a, b) => {
- return a.vault_path.split("/").last().localeCompare(b.vault_path.split("/").last());
- };
- status2.changed.sort(sort);
- status2.staged.sort(sort);
- if (status2.changed.length + status2.staged.length > 500) {
+ function backup() {
+ return __awaiter(this, void 0, void 0, function* () {
+ $$invalidate(5, loading = true);
+ if (status2) {
+ plugin.promiseQueue.addTask(() => plugin.createBackup(false, false, commitMessage).then(() => {
+ if (commitMessage !== plugin.settings.commitMessage) {
+ $$invalidate(2, commitMessage = "");
+ }
+ }).finally(triggerRefresh2));
+ }
+ });
+ }
+ function refresh() {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (!plugin.gitReady) {
$$invalidate(6, status2 = void 0);
- if (!plugin.loading) {
- plugin.displayError("Too many changes to display");
+ return;
+ }
+ const unPushedCommits = yield plugin.gitManager.getUnpushedCommits();
+ buttons.forEach((btn) => {
+ var _a2, _b;
+ if (import_obsidian28.Platform.isMobile) {
+ btn.removeClass("button-border");
+ if (btn.id == "push" && unPushedCommits > 0) {
+ btn.addClass("button-border");
+ }
+ } else {
+ (_a2 = btn.firstElementChild) === null || _a2 === void 0 ? void 0 : _a2.removeAttribute("color");
+ if (btn.id == "push" && unPushedCommits > 0) {
+ (_b = btn.firstElementChild) === null || _b === void 0 ? void 0 : _b.setAttr("color", "var(--text-accent)");
+ }
+ }
+ });
+ $$invalidate(6, status2 = plugin.cachedStatus);
+ if (plugin.lastPulledFiles && plugin.lastPulledFiles != lastPulledFiles) {
+ $$invalidate(7, lastPulledFiles = plugin.lastPulledFiles);
+ $$invalidate(11, lastPulledFilesHierarchy = {
+ title: "",
+ path: "",
+ vaultPath: "",
+ children: plugin.gitManager.getTreeStructure(lastPulledFiles)
+ });
+ }
+ if (status2) {
+ const sort = (a, b) => {
+ return a.vault_path.split("/").last().localeCompare(getDisplayPath(b.vault_path));
+ };
+ status2.changed.sort(sort);
+ status2.staged.sort(sort);
+ if (status2.changed.length + status2.staged.length > 500) {
+ $$invalidate(6, status2 = void 0);
+ if (!plugin.loading) {
+ plugin.displayError("Too many changes to display");
+ }
+ } else {
+ $$invalidate(9, changeHierarchy = {
+ title: "",
+ path: "",
+ vaultPath: "",
+ children: plugin.gitManager.getTreeStructure(status2.changed)
+ });
+ $$invalidate(10, stagedHierarchy = {
+ title: "",
+ path: "",
+ vaultPath: "",
+ children: plugin.gitManager.getTreeStructure(status2.staged)
+ });
}
} else {
- $$invalidate(9, changeHierarchy = {
- title: "",
- path: "",
- vaultPath: "",
- children: plugin.gitManager.getTreeStructure(status2.changed)
- });
- $$invalidate(10, stagedHierarchy = {
- title: "",
- path: "",
- vaultPath: "",
- children: plugin.gitManager.getTreeStructure(status2.staged)
- });
+ $$invalidate(9, changeHierarchy = void 0);
+ $$invalidate(10, stagedHierarchy = void 0);
}
- } else {
- $$invalidate(9, changeHierarchy = void 0);
- $$invalidate(10, stagedHierarchy = void 0);
- }
- $$invalidate(5, loading = plugin.loading);
+ $$invalidate(5, loading = plugin.loading);
+ });
}
function stageAll() {
$$invalidate(5, loading = true);
- plugin.gitManager.stageAll({ status: status2 }).finally(triggerRefresh);
+ plugin.promiseQueue.addTask(() => plugin.gitManager.stageAll({ status: status2 }).finally(triggerRefresh2));
}
function unstageAll() {
$$invalidate(5, loading = true);
- plugin.gitManager.unstageAll({ status: status2 }).finally(triggerRefresh);
+ plugin.promiseQueue.addTask(() => plugin.gitManager.unstageAll({ status: status2 }).finally(triggerRefresh2));
}
function push2() {
$$invalidate(5, loading = true);
- plugin.push().finally(triggerRefresh);
+ plugin.promiseQueue.addTask(() => plugin.push().finally(triggerRefresh2));
}
function pull2() {
$$invalidate(5, loading = true);
- plugin.pullChangesFromRemote().finally(triggerRefresh);
+ plugin.promiseQueue.addTask(() => plugin.pullChangesFromRemote().finally(triggerRefresh2));
}
function discard() {
new DiscardModal(view.app, false, plugin.gitManager.getVaultPath("/")).myOpen().then((shouldDiscard) => {
if (shouldDiscard === true) {
- plugin.gitManager.discardAll({ status: plugin.cachedStatus }).finally(() => {
+ plugin.promiseQueue.addTask(() => plugin.gitManager.discardAll({ status: plugin.cachedStatus }).finally(() => {
dispatchEvent(new CustomEvent("git-refresh"));
- });
+ }));
}
});
}
function div0_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
- buttons[0] = $$value;
+ buttons[5] = $$value;
$$invalidate(8, buttons);
});
}
function div1_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
- buttons[1] = $$value;
+ buttons[0] = $$value;
$$invalidate(8, buttons);
});
}
function div2_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
- buttons[2] = $$value;
+ buttons[1] = $$value;
$$invalidate(8, buttons);
});
}
function div3_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
- buttons[3] = $$value;
+ buttons[2] = $$value;
$$invalidate(8, buttons);
});
}
function div4_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
- buttons[4] = $$value;
+ buttons[3] = $$value;
$$invalidate(8, buttons);
});
}
function div5_binding($$value) {
+ binding_callbacks[$$value ? "unshift" : "push"](() => {
+ buttons[4] = $$value;
+ $$invalidate(8, buttons);
+ });
+ }
+ function div6_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
layoutBtn = $$value;
$$invalidate(4, layoutBtn);
@@ -30324,7 +42777,7 @@ function instance5($$self, $$props, $$invalidate) {
$$invalidate(0, plugin.settings.treeStructure = showTree, plugin);
plugin.saveSettings();
};
- function div6_binding($$value) {
+ function div7_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
buttons[6] = $$value;
$$invalidate(8, buttons);
@@ -30335,26 +42788,21 @@ function instance5($$self, $$props, $$invalidate) {
$$invalidate(2, commitMessage);
}
const click_handler_1 = () => $$invalidate(2, commitMessage = "");
- const click_handler_2 = () => $$invalidate(13, stagedOpen = !stagedOpen);
- const click_handler_3 = () => $$invalidate(13, stagedOpen = !stagedOpen);
function div2_binding_1($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
buttons[8] = $$value;
$$invalidate(8, buttons);
});
}
- const click_handler_4 = () => $$invalidate(13, stagedOpen = !stagedOpen);
- const click_handler_5 = () => $$invalidate(12, changesOpen = !changesOpen);
- const click_handler_6 = () => $$invalidate(12, changesOpen = !changesOpen);
- const click_handler_7 = () => discard();
+ const click_handler_2 = () => $$invalidate(13, stagedOpen = !stagedOpen);
function div11_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
buttons[9] = $$value;
$$invalidate(8, buttons);
});
}
- const click_handler_8 = () => $$invalidate(12, changesOpen = !changesOpen);
- const click_handler_9 = () => $$invalidate(14, lastPulledFilesOpen = !lastPulledFilesOpen);
+ const click_handler_3 = () => $$invalidate(12, changesOpen = !changesOpen);
+ const click_handler_4 = () => $$invalidate(14, lastPulledFilesOpen = !lastPulledFilesOpen);
$$self.$$set = ($$props2) => {
if ("plugin" in $$props2)
$$invalidate(0, plugin = $$props2.plugin);
@@ -30362,15 +42810,17 @@ function instance5($$self, $$props, $$invalidate) {
$$invalidate(1, view = $$props2.view);
};
$$self.$$.update = () => {
- if ($$self.$$.dirty[0] & 24) {
+ if ($$self.$$.dirty[0] & /*layoutBtn, showTree*/
+ 24) {
$: {
if (layoutBtn) {
layoutBtn.empty();
- (0, import_obsidian21.setIcon)(layoutBtn, showTree ? "list" : "folder", 16);
+ (0, import_obsidian28.setIcon)(layoutBtn, showTree ? "list" : "folder");
}
}
}
- if ($$self.$$.dirty[0] & 4) {
+ if ($$self.$$.dirty[0] & /*commitMessage*/
+ 4) {
$:
$$invalidate(15, rows = (commitMessage.match(/\n/g) || []).length + 1 || 1);
}
@@ -30393,6 +42843,7 @@ function instance5($$self, $$props, $$invalidate) {
lastPulledFilesOpen,
rows,
commit2,
+ backup,
stageAll,
unstageAll,
push2,
@@ -30404,51 +42855,47 @@ function instance5($$self, $$props, $$invalidate) {
div3_binding,
div4_binding,
div5_binding,
- click_handler,
div6_binding,
+ click_handler,
+ div7_binding,
textarea_input_handler,
click_handler_1,
- click_handler_2,
- click_handler_3,
div2_binding_1,
- click_handler_4,
- click_handler_5,
- click_handler_6,
- click_handler_7,
+ click_handler_2,
div11_binding,
- click_handler_8,
- click_handler_9
+ click_handler_3,
+ click_handler_4
];
}
-var GitView = class extends SvelteComponent {
+var SourceControl = class extends SvelteComponent {
constructor(options) {
super();
- init2(this, options, instance5, create_fragment5, safe_not_equal, { plugin: 0, view: 1 }, add_css5, [-1, -1]);
+ init2(this, options, instance9, create_fragment9, safe_not_equal, { plugin: 0, view: 1 }, add_css8, [-1, -1]);
}
};
-var gitView_default = GitView;
+var sourceControl_default = SourceControl;
-// src/ui/sidebar/sidebarView.ts
-var GitView2 = class extends import_obsidian22.ItemView {
+// src/ui/sourceControl/sourceControl.ts
+var GitView = class extends import_obsidian29.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.plugin = plugin;
this.hoverPopover = null;
}
getViewType() {
- return GIT_VIEW_CONFIG.type;
+ return SOURCE_CONTROL_VIEW_CONFIG.type;
}
getDisplayText() {
- return GIT_VIEW_CONFIG.name;
+ return SOURCE_CONTROL_VIEW_CONFIG.name;
}
getIcon() {
- return GIT_VIEW_CONFIG.icon;
+ return SOURCE_CONTROL_VIEW_CONFIG.icon;
}
onClose() {
return super.onClose();
}
onOpen() {
- this._view = new gitView_default({
+ this._view = new sourceControl_default({
target: this.contentEl,
props: {
plugin: this.plugin,
@@ -30485,7 +42932,7 @@ var BranchStatusBar = class {
};
// src/main.ts
-var ObsidianGit = class extends import_obsidian23.Plugin {
+var ObsidianGit = class extends import_obsidian30.Plugin {
constructor() {
super(...arguments);
this.gitReady = false;
@@ -30493,6 +42940,7 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.conflictOutputFile = "conflict-files-obsidian-git.md";
this.offlineMode = false;
this.loading = false;
+ this.lineAuthoringFeature = new LineAuthoringFeature(this);
}
setState(state) {
var _a2;
@@ -30504,8 +42952,13 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
return this.cachedStatus;
}
async refresh() {
- const gitView = this.app.workspace.getLeavesOfType(GIT_VIEW_CONFIG.type);
- if (this.settings.changedFilesInStatusBar || gitView.length > 0) {
+ const gitView = this.app.workspace.getLeavesOfType(
+ SOURCE_CONTROL_VIEW_CONFIG.type
+ );
+ const historyView = this.app.workspace.getLeavesOfType(
+ HISTORY_VIEW_CONFIG.type
+ );
+ if (this.settings.changedFilesInStatusBar || gitView.length > 0 || historyView.length > 0) {
this.loading = true;
dispatchEvent(new CustomEvent("git-view-refresh"));
await this.updateCachedStatus();
@@ -30513,29 +42966,42 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
dispatchEvent(new CustomEvent("git-view-refresh"));
}
}
+ async refreshUpdatedHead() {
+ this.lineAuthoringFeature.refreshLineAuthorViews();
+ }
async onload() {
console.log("loading " + this.manifest.name + " plugin");
+ pluginRef.plugin = this;
this.localStorage = new LocalStorageSettings(this);
this.localStorage.migrate();
await this.loadSettings();
this.migrateSettings();
- this.addSettingTab(new ObsidianGitSettingsTab(this.app, this));
+ this.settingsTab = new ObsidianGitSettingsTab(this.app, this);
+ this.addSettingTab(this.settingsTab);
if (!this.localStorage.getPluginDisabled()) {
this.loadPlugin();
}
}
async loadPlugin() {
addEventListener("git-refresh", this.refresh.bind(this));
- this.registerView(GIT_VIEW_CONFIG.type, (leaf) => {
- return new GitView2(leaf, this);
+ addEventListener("git-head-update", this.refreshUpdatedHead.bind(this));
+ this.registerView(SOURCE_CONTROL_VIEW_CONFIG.type, (leaf) => {
+ return new GitView(leaf, this);
+ });
+ this.registerView(HISTORY_VIEW_CONFIG.type, (leaf) => {
+ return new HistoryView2(leaf, this);
});
this.registerView(DIFF_VIEW_CONFIG.type, (leaf) => {
return new DiffView(leaf, this);
});
- this.app.workspace.registerHoverLinkSource(GIT_VIEW_CONFIG.type, {
- display: "Git View",
- defaultMod: true
- });
+ this.lineAuthoringFeature.onLoadPlugin();
+ this.app.workspace.registerHoverLinkSource(
+ SOURCE_CONTROL_VIEW_CONFIG.type,
+ {
+ display: "Git View",
+ defaultMod: true
+ }
+ );
this.setRefreshDebouncer();
this.addCommand({
id: "edit-gitignore",
@@ -30558,12 +43024,34 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
id: "open-git-view",
name: "Open source control view",
callback: async () => {
- const leafs = this.app.workspace.getLeavesOfType(GIT_VIEW_CONFIG.type);
+ const leafs = this.app.workspace.getLeavesOfType(
+ SOURCE_CONTROL_VIEW_CONFIG.type
+ );
let leaf;
if (leafs.length === 0) {
leaf = this.app.workspace.getRightLeaf(false);
await leaf.setViewState({
- type: GIT_VIEW_CONFIG.type
+ type: SOURCE_CONTROL_VIEW_CONFIG.type
+ });
+ } else {
+ leaf = leafs.first();
+ }
+ this.app.workspace.revealLeaf(leaf);
+ dispatchEvent(new CustomEvent("git-refresh"));
+ }
+ });
+ this.addCommand({
+ id: "open-history-view",
+ name: "Open history view",
+ callback: async () => {
+ const leafs = this.app.workspace.getLeavesOfType(
+ HISTORY_VIEW_CONFIG.type
+ );
+ let leaf;
+ if (leafs.length === 0) {
+ leaf = this.app.workspace.getRightLeaf(false);
+ await leaf.setViewState({
+ type: HISTORY_VIEW_CONFIG.type
});
} else {
leaf = leafs.first();
@@ -30581,34 +43069,66 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (checking) {
return file !== null;
} else {
- (_a2 = getNewLeaf()) == null ? void 0 : _a2.setViewState({ type: DIFF_VIEW_CONFIG.type, state: { staged: false, file: file.path } });
+ (_a2 = getNewLeaf()) == null ? void 0 : _a2.setViewState({
+ type: DIFF_VIEW_CONFIG.type,
+ active: true,
+ state: {
+ staged: false,
+ file: this.gitManager.asRepositoryRelativePath(
+ file.path,
+ true
+ )
+ }
+ });
}
}
});
this.addCommand({
id: "view-file-on-github",
name: "Open file on GitHub",
- editorCallback: (editor, { file }) => openLineInGitHub(editor, file, this.gitManager)
+ editorCallback: (editor, { file }) => {
+ if (file)
+ return openLineInGitHub(editor, file, this.gitManager);
+ }
});
this.addCommand({
id: "view-history-on-github",
name: "Open file history on GitHub",
- editorCallback: (_, { file }) => openHistoryInGitHub(file, this.gitManager)
+ editorCallback: (_, { file }) => {
+ if (file)
+ return openHistoryInGitHub(file, this.gitManager);
+ }
});
this.addCommand({
id: "pull",
name: "Pull",
callback: () => this.promiseQueue.addTask(() => this.pullChangesFromRemote())
});
+ this.addCommand({
+ id: "fetch",
+ name: "fetch",
+ callback: () => this.promiseQueue.addTask(() => this.fetch())
+ });
+ this.addCommand({
+ id: "switch-to-remote-branch",
+ name: "Switch to remote branch",
+ callback: () => this.promiseQueue.addTask(() => this.switchRemoteBranch())
+ });
this.addCommand({
id: "add-to-gitignore",
name: "Add file to gitignore",
checkCallback: (checking) => {
- const file = app.workspace.getActiveFile();
+ const file = this.app.workspace.getActiveFile();
if (checking) {
return file !== null;
} else {
- app.vault.adapter.append(this.gitManager.getVaultPath(".gitignore"), "\n" + this.gitManager.getPath(file.path, true)).then(() => {
+ this.app.vault.adapter.append(
+ this.gitManager.getVaultPath(".gitignore"),
+ "\n" + this.gitManager.asRepositoryRelativePath(
+ file.path,
+ true
+ )
+ ).then(() => {
this.refresh();
});
}
@@ -30635,22 +43155,55 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.addCommand({
id: "commit",
name: "Commit all changes",
- callback: () => this.promiseQueue.addTask(() => this.commit(false))
+ callback: () => this.promiseQueue.addTask(
+ () => this.commit({ fromAutoBackup: false })
+ )
});
this.addCommand({
id: "commit-specified-message",
name: "Commit all changes with specific message",
- callback: () => this.promiseQueue.addTask(() => this.commit(false, true))
+ callback: () => this.promiseQueue.addTask(
+ () => this.commit({
+ fromAutoBackup: false,
+ requestCustomMessage: true
+ })
+ )
});
this.addCommand({
id: "commit-staged",
name: "Commit staged",
- callback: () => this.promiseQueue.addTask(() => this.commit(false, false, true))
+ callback: () => this.promiseQueue.addTask(
+ () => this.commit({
+ fromAutoBackup: false,
+ requestCustomMessage: false,
+ onlyStaged: true
+ })
+ )
});
+ if (import_obsidian30.Platform.isDesktopApp) {
+ this.addCommand({
+ id: "commit-amend-staged-specified-message",
+ name: "Commit Amend",
+ callback: () => this.promiseQueue.addTask(
+ () => this.commit({
+ fromAutoBackup: false,
+ requestCustomMessage: true,
+ onlyStaged: true,
+ amend: true
+ })
+ )
+ });
+ }
this.addCommand({
id: "commit-staged-specified-message",
name: "Commit staged with specific message",
- callback: () => this.promiseQueue.addTask(() => this.commit(false, true, true))
+ callback: () => this.promiseQueue.addTask(
+ () => this.commit({
+ fromAutoBackup: false,
+ requestCustomMessage: true,
+ onlyStaged: true
+ })
+ )
});
this.addCommand({
id: "push2",
@@ -30695,18 +43248,29 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
id: "delete-repo",
name: "CAUTION: Delete repository",
callback: async () => {
- const repoExists = await this.app.vault.adapter.exists(`${this.settings.basePath}/.git`);
+ const repoExists = await this.app.vault.adapter.exists(
+ `${this.settings.basePath}/.git`
+ );
if (repoExists) {
- const modal = new GeneralModal({ options: ["NO", "YES"], placeholder: "Do you really want to delete the repository (.git directory)? This action cannot be undone.", onlySelection: true });
+ const modal = new GeneralModal({
+ options: ["NO", "YES"],
+ placeholder: "Do you really want to delete the repository (.git directory)? This action cannot be undone.",
+ onlySelection: true
+ });
const shouldDelete = await modal.open() === "YES";
if (shouldDelete) {
- await this.app.vault.adapter.rmdir(`${this.settings.basePath}/.git`, true);
- new import_obsidian23.Notice("Successfully deleted repository. Reloading plugin...");
+ await this.app.vault.adapter.rmdir(
+ `${this.settings.basePath}/.git`,
+ true
+ );
+ new import_obsidian30.Notice(
+ "Successfully deleted repository. Reloading plugin..."
+ );
this.unloadPlugin();
this.init();
}
} else {
- new import_obsidian23.Notice("No repository found");
+ new import_obsidian30.Notice("No repository found");
}
}
});
@@ -30727,12 +43291,13 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (!await this.isAllInitialized())
return;
const status2 = await this.gitManager.status();
- this.setState(PluginState.idle);
+ console.log(status2);
+ this.setState(0 /* idle */);
if (status2.changed.length + status2.staged.length > 500) {
this.displayError("Too many changes to display");
return;
}
- new ChangedFilesModal(this, status2.changed).open();
+ new ChangedFilesModal(this, status2.all).open();
}
});
this.addCommand({
@@ -30756,48 +43321,93 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.deleteBranch();
}
});
- this.registerEvent(this.app.workspace.on("file-menu", (menu, file, source) => {
- this.handleFileMenu(menu, file, source);
- }));
+ this.addCommand({
+ id: "discard-all",
+ name: "CAUTION: Discard all changes",
+ callback: async () => {
+ if (!await this.isAllInitialized())
+ return false;
+ const modal = new GeneralModal({
+ options: ["NO", "YES"],
+ placeholder: "Do you want to discard all changes to tracked files? This action cannot be undone.",
+ onlySelection: true
+ });
+ const shouldDiscardAll = await modal.open() === "YES";
+ if (shouldDiscardAll) {
+ this.promiseQueue.addTask(() => this.discardAll());
+ }
+ }
+ });
+ this.addCommand({
+ id: "toggle-line-author-info",
+ name: "Toggle line author information",
+ callback: () => {
+ var _a2;
+ return (_a2 = this.settingsTab) == null ? void 0 : _a2.configureLineAuthorShowStatus(
+ !this.settings.lineAuthor.show
+ );
+ }
+ });
+ this.registerEvent(
+ this.app.workspace.on("file-menu", (menu, file, source) => {
+ this.handleFileMenu(menu, file, source);
+ })
+ );
if (this.settings.showStatusBar) {
const statusBarEl = this.addStatusBarItem();
this.statusBar = new StatusBar(statusBarEl, this);
- this.registerInterval(window.setInterval(() => {
- var _a2;
- return (_a2 = this.statusBar) == null ? void 0 : _a2.display();
- }, 1e3));
+ this.registerInterval(
+ window.setInterval(() => {
+ var _a2;
+ return (_a2 = this.statusBar) == null ? void 0 : _a2.display();
+ }, 1e3)
+ );
}
- if (import_obsidian23.Platform.isDesktop && this.settings.showBranchStatusBar) {
+ if (import_obsidian30.Platform.isDesktop && this.settings.showBranchStatusBar) {
const branchStatusBarEl = this.addStatusBarItem();
this.branchBar = new BranchStatusBar(branchStatusBarEl, this);
- this.registerInterval(window.setInterval(() => {
- var _a2;
- return (_a2 = this.branchBar) == null ? void 0 : _a2.display();
- }, 6e4));
+ this.registerInterval(
+ window.setInterval(() => {
+ var _a2;
+ return (_a2 = this.branchBar) == null ? void 0 : _a2.display();
+ }, 6e4)
+ );
}
this.app.workspace.onLayoutReady(() => this.init());
}
setRefreshDebouncer() {
var _a2;
(_a2 = this.debRefresh) == null ? void 0 : _a2.cancel();
- this.debRefresh = (0, import_obsidian23.debounce)(() => {
- if (this.settings.refreshSourceControl) {
- this.refresh();
- }
- }, this.settings.refreshSourceControlTimer, true);
+ this.debRefresh = (0, import_obsidian30.debounce)(
+ () => {
+ if (this.settings.refreshSourceControl) {
+ this.refresh();
+ }
+ },
+ this.settings.refreshSourceControlTimer,
+ true
+ );
}
async showNotices() {
const length = 1e4;
- if (this.manifest.id === "obsidian-git" && import_obsidian23.Platform.isDesktopApp && !this.settings.showedMobileNotice) {
- new import_obsidian23.Notice("Obsidian Git is now available on mobile! Please read the plugin's README for more information.", length);
+ if (this.manifest.id === "obsidian-git" && import_obsidian30.Platform.isDesktopApp && !this.settings.showedMobileNotice) {
+ new import_obsidian30.Notice(
+ "Git is now available on mobile! Please read the plugin's README for more information.",
+ length
+ );
this.settings.showedMobileNotice = true;
await this.saveSettings();
}
if (this.manifest.id === "obsidian-git-isomorphic") {
- new import_obsidian23.Notice("Obsidian Git Mobile is now deprecated. Please uninstall it and install Obsidian Git instead.", length);
+ new import_obsidian30.Notice(
+ "Git Mobile is now deprecated. Please uninstall it and install Git instead.",
+ length
+ );
}
}
handleFileMenu(menu, file, source) {
+ if (!this.settings.showFileMenu)
+ return;
if (source !== "file-explorer-context-menu") {
return;
}
@@ -30809,10 +43419,15 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
menu.addItem((item) => {
item.setTitle(`Git: Stage`).setIcon("plus-circle").setSection("action").onClick((_) => {
this.promiseQueue.addTask(async () => {
- if (file instanceof import_obsidian23.TFile) {
+ if (file instanceof import_obsidian30.TFile) {
await this.gitManager.stage(file.path, true);
} else {
- await this.gitManager.stageAll({ dir: this.gitManager.getPath(file.path, true) });
+ await this.gitManager.stageAll({
+ dir: this.gitManager.asRepositoryRelativePath(
+ file.path,
+ true
+ )
+ });
}
this.displayMessage(`Staged ${file.path}`);
});
@@ -30821,10 +43436,15 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
menu.addItem((item) => {
item.setTitle(`Git: Unstage`).setIcon("minus-circle").setSection("action").onClick((_) => {
this.promiseQueue.addTask(async () => {
- if (file instanceof import_obsidian23.TFile) {
+ if (file instanceof import_obsidian30.TFile) {
await this.gitManager.unstage(file.path, true);
} else {
- await this.gitManager.unstageAll({ dir: this.gitManager.getPath(file.path, true) });
+ await this.gitManager.unstageAll({
+ dir: this.gitManager.asRepositoryRelativePath(
+ file.path,
+ true
+ )
+ });
}
this.displayMessage(`Unstaged ${file.path}`);
});
@@ -30846,14 +43466,25 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.settings.gitPath = void 0;
await this.saveSettings();
}
+ if (this.settings.username != void 0) {
+ this.localStorage.setPassword(this.settings.username);
+ this.settings.username = void 0;
+ await this.saveSettings();
+ }
}
unloadPlugin() {
this.gitReady = false;
dispatchEvent(new CustomEvent("git-refresh"));
+ this.lineAuthoringFeature.deactivateFeature();
this.clearAutoPull();
this.clearAutoPush();
this.clearAutoBackup();
removeEventListener("git-refresh", this.refresh.bind(this));
+ removeEventListener(
+ "git-head-update",
+ this.refreshUpdatedHead.bind(this)
+ );
+ this.app.workspace.offref(this.openEvent);
this.app.metadataCache.offref(this.modifyEvent);
this.app.metadataCache.offref(this.deleteEvent);
this.app.metadataCache.offref(this.createEvent);
@@ -30861,7 +43492,9 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.debRefresh.cancel();
}
async onunload() {
- this.app.workspace.unregisterHoverLinkSource(GIT_VIEW_CONFIG.type);
+ this.app.workspace.unregisterHoverLinkSource(
+ SOURCE_CONTROL_VIEW_CONFIG.type
+ );
this.unloadPlugin();
console.log("unloading " + this.manifest.name + " plugin");
}
@@ -30870,12 +43503,14 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (data == void 0) {
data = { showedMobileNotice: true };
}
- this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
+ this.settings = mergeSettingsByPriority(DEFAULT_SETTINGS, data);
}
async saveSettings() {
+ var _a2;
+ (_a2 = this.settingsTab) == null ? void 0 : _a2.beforeSaveSettings();
await this.saveData(this.settings);
}
- async saveLastAuto(date, mode) {
+ saveLastAuto(date, mode) {
if (mode === "backup") {
this.localStorage.setLastAutoBackup(date.toString());
} else if (mode === "pull") {
@@ -30884,19 +43519,22 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.localStorage.setLastAutoPush(date.toString());
}
}
- async loadLastAuto() {
+ loadLastAuto() {
var _a2, _b, _c;
return {
- "backup": new Date((_a2 = this.localStorage.getLastAutoBackup()) != null ? _a2 : ""),
- "pull": new Date((_b = this.localStorage.getLastAutoPull()) != null ? _b : ""),
- "push": new Date((_c = this.localStorage.getLastAutoPush()) != null ? _c : "")
+ backup: new Date((_a2 = this.localStorage.getLastAutoBackup()) != null ? _a2 : ""),
+ pull: new Date((_b = this.localStorage.getLastAutoPull()) != null ? _b : ""),
+ push: new Date((_c = this.localStorage.getLastAutoPush()) != null ? _c : "")
};
}
+ get useSimpleGit() {
+ return import_obsidian30.Platform.isDesktopApp;
+ }
async init() {
var _a2;
this.showNotices();
try {
- if (import_obsidian23.Platform.isDesktopApp) {
+ if (this.useSimpleGit) {
this.gitManager = new SimpleGit(this);
await this.gitManager.setGitInstance();
} else {
@@ -30908,11 +43546,18 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.displayError("Cannot run git command");
break;
case "missing-repo":
- new import_obsidian23.Notice("Can't find a valid git repository. Please create one via the given command or clone an existing repo.");
+ new import_obsidian30.Notice(
+ "Can't find a valid git repository. Please create one via the given command or clone an existing repo.",
+ 1e4
+ );
break;
case "valid":
this.gitReady = true;
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
+ this.openEvent = this.app.workspace.on(
+ "active-leaf-change",
+ (leaf) => this.handleViewActiveState(leaf)
+ );
this.modifyEvent = this.app.vault.on("modify", () => {
this.debRefresh();
});
@@ -30930,29 +43575,19 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.registerEvent(this.createEvent);
this.registerEvent(this.renameEvent);
(_a2 = this.branchBar) == null ? void 0 : _a2.display();
+ this.lineAuthoringFeature.conditionallyActivateBySettings();
dispatchEvent(new CustomEvent("git-refresh"));
if (this.settings.autoPullOnBoot) {
- this.promiseQueue.addTask(() => this.pullChangesFromRemote());
- }
- const lastAutos = await this.loadLastAuto();
- if (this.settings.autoSaveInterval > 0) {
- const now2 = new Date();
- const diff2 = this.settings.autoSaveInterval - Math.round((now2.getTime() - lastAutos.backup.getTime()) / 1e3 / 60);
- this.startAutoBackup(diff2 <= 0 ? 0 : diff2);
- }
- if (this.settings.differentIntervalCommitAndPush && this.settings.autoPushInterval > 0) {
- const now2 = new Date();
- const diff2 = this.settings.autoPushInterval - Math.round((now2.getTime() - lastAutos.push.getTime()) / 1e3 / 60);
- this.startAutoPush(diff2 <= 0 ? 0 : diff2);
- }
- if (this.settings.autoPullInterval > 0) {
- const now2 = new Date();
- const diff2 = this.settings.autoPullInterval - Math.round((now2.getTime() - lastAutos.pull.getTime()) / 1e3 / 60);
- this.startAutoPull(diff2 <= 0 ? 0 : diff2);
+ this.promiseQueue.addTask(
+ () => this.pullChangesFromRemote()
+ );
}
+ this.setUpAutos();
break;
default:
- console.log("Something weird happened. The 'checkRequirements' result is " + result);
+ console.log(
+ "Something weird happened. The 'checkRequirements' result is " + result
+ );
}
} catch (error) {
this.displayError(error);
@@ -30961,7 +43596,7 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
}
async createNewRepo() {
await this.gitManager.init();
- new import_obsidian23.Notice("Initialized new repo");
+ new import_obsidian30.Notice("Initialized new repo");
await this.init();
}
async cloneNewRepo() {
@@ -30970,7 +43605,7 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (url) {
const confirmOption = "Vault Root";
let dir = await new GeneralModal({
- options: [confirmOption],
+ options: this.gitManager instanceof IsomorphicGit ? [confirmOption] : [],
placeholder: "Enter directory for clone. It needs to be empty or not existent.",
allowEmpty: this.gitManager instanceof IsomorphicGit
}).open();
@@ -30978,70 +43613,114 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (dir === confirmOption) {
dir = ".";
}
- dir = (0, import_obsidian23.normalizePath)(dir);
+ dir = (0, import_obsidian30.normalizePath)(dir);
if (dir === "/") {
dir = ".";
}
if (dir === ".") {
- const modal2 = new GeneralModal({ options: ["NO", "YES"], placeholder: `Does your remote repo contain a ${app.vault.configDir} directory at the root?`, onlySelection: true });
+ const modal2 = new GeneralModal({
+ options: ["NO", "YES"],
+ placeholder: `Does your remote repo contain a ${app.vault.configDir} directory at the root?`,
+ onlySelection: true
+ });
const containsConflictDir = await modal2.open();
if (containsConflictDir === void 0) {
- new import_obsidian23.Notice("Aborted clone");
+ new import_obsidian30.Notice("Aborted clone");
return;
} else if (containsConflictDir === "YES") {
const confirmOption2 = "DELETE ALL YOUR LOCAL CONFIG AND PLUGINS";
- const modal3 = new GeneralModal({ options: ["Abort clone", confirmOption2], placeholder: `To avoid conflicts, the local ${app.vault.configDir} directory needs to be deleted.`, onlySelection: true });
+ const modal3 = new GeneralModal({
+ options: ["Abort clone", confirmOption2],
+ placeholder: `To avoid conflicts, the local ${app.vault.configDir} directory needs to be deleted.`,
+ onlySelection: true
+ });
const shouldDelete = await modal3.open() === confirmOption2;
if (shouldDelete) {
- await this.app.vault.adapter.rmdir(app.vault.configDir, true);
+ await this.app.vault.adapter.rmdir(
+ app.vault.configDir,
+ true
+ );
} else {
- new import_obsidian23.Notice("Aborted clone");
+ new import_obsidian30.Notice("Aborted clone");
return;
}
}
}
- new import_obsidian23.Notice(`Cloning new repo into "${dir}"`);
- await this.gitManager.clone(url, dir);
- new import_obsidian23.Notice("Cloned new repo.");
- new import_obsidian23.Notice("Please restart Obsidian");
- if (dir && dir !== ".") {
+ const depth = await new GeneralModal({
+ placeholder: "Specify depth of clone. Leave empty for full clone.",
+ allowEmpty: true
+ }).open();
+ let depthInt = void 0;
+ if (depth !== "") {
+ depthInt = parseInt(depth);
+ if (isNaN(depthInt)) {
+ new import_obsidian30.Notice("Invalid depth. Aborting clone.");
+ return;
+ }
+ }
+ new import_obsidian30.Notice(`Cloning new repo into "${dir}"`);
+ const oldBase = this.settings.basePath;
+ const customDir = dir && dir !== ".";
+ if (customDir) {
this.settings.basePath = dir;
+ }
+ try {
+ await this.gitManager.clone(url, dir, depthInt);
+ } catch (error) {
+ this.settings.basePath = oldBase;
+ this.saveSettings();
+ throw error;
+ }
+ new import_obsidian30.Notice("Cloned new repo.");
+ new import_obsidian30.Notice("Please restart Obsidian");
+ if (customDir) {
this.saveSettings();
}
}
}
}
+ /**
+ * Retries to call `this.init()` if necessary, otherwise returns directly
+ * @returns true if `this.gitManager` is ready to be used, false if not.
+ */
async isAllInitialized() {
if (!this.gitReady) {
await this.init();
}
return this.gitReady;
}
+ ///Used for command
async pullChangesFromRemote() {
if (!await this.isAllInitialized())
return;
const filesUpdated = await this.pull();
+ this.setUpAutoBackup();
if (!filesUpdated) {
this.displayMessage("Everything is up-to-date");
}
if (this.gitManager instanceof SimpleGit) {
const status2 = await this.gitManager.status();
if (status2.conflicted.length > 0) {
- this.displayError(`You have ${status2.conflicted.length} conflict ${status2.conflicted.length > 1 ? "files" : "file"}`);
+ this.displayError(
+ `You have conflicts in ${status2.conflicted.length} ${status2.conflicted.length == 1 ? "file" : "files"}`
+ );
this.handleConflict(status2.conflicted);
}
}
dispatchEvent(new CustomEvent("git-refresh"));
- this.lastUpdate = Date.now();
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
}
- async createBackup(fromAutoBackup, requestCustomMessage = false) {
+ async createBackup(fromAutoBackup, requestCustomMessage = false, commitMessage) {
if (!await this.isAllInitialized())
return;
if (this.settings.syncMethod == "reset" && this.settings.pullBeforePush) {
await this.pull();
}
- if (!await this.commit(fromAutoBackup, requestCustomMessage))
+ if (!await this.commit({
+ fromAutoBackup,
+ requestCustomMessage,
+ commitMessage
+ }))
return;
if (!this.settings.disablePush) {
if (await this.gitManager.canPush()) {
@@ -31053,34 +43732,45 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.displayMessage("No changes to push");
}
}
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
}
- async commit(fromAutoBackup, requestCustomMessage = false, onlyStaged = false) {
+ // Returns true if commit was successfully
+ async commit({
+ fromAutoBackup,
+ requestCustomMessage = false,
+ onlyStaged = false,
+ commitMessage,
+ amend = false
+ }) {
if (!await this.isAllInitialized())
return false;
- const hadConflict = this.localStorage.getConflict() === "true";
+ let hadConflict = this.localStorage.getConflict();
let changedFiles;
let status2;
let unstagedFiles;
if (this.gitManager instanceof SimpleGit) {
- const file = this.app.vault.getAbstractFileByPath(this.conflictOutputFile);
- if (file != null)
- await this.app.vault.delete(file);
+ this.mayDeleteConflictFile();
status2 = await this.updateCachedStatus();
+ if (status2.conflicted.length == 0) {
+ this.localStorage.setConflict(false);
+ hadConflict = false;
+ }
if (fromAutoBackup && status2.conflicted.length > 0) {
- this.displayError(`Did not commit, because you have ${status2.conflicted.length} conflict ${status2.conflicted.length > 1 ? "files" : "file"}. Please resolve them and commit per command.`);
+ this.displayError(
+ `Did not commit, because you have conflicts in ${status2.conflicted.length} ${status2.conflicted.length == 1 ? "file" : "files"}. Please resolve them and commit per command.`
+ );
this.handleConflict(status2.conflicted);
return false;
}
changedFiles = [...status2.changed, ...status2.staged];
} else if (fromAutoBackup && hadConflict) {
- this.setState(PluginState.conflicted);
- this.displayError(`Did not commit, because you have conflict files. Please resolve them and commit per command.`);
+ this.setState(6 /* conflicted */);
+ this.displayError(
+ `Did not commit, because you have conflicts. Please resolve them and commit per command.`
+ );
return false;
} else if (hadConflict) {
- const file = this.app.vault.getAbstractFileByPath(this.conflictOutputFile);
- if (file != null)
- await this.app.vault.delete(file);
+ await this.mayDeleteConflictFile();
status2 = await this.updateCachedStatus();
changedFiles = [...status2.changed, ...status2.staged];
} else {
@@ -31088,62 +43778,90 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
changedFiles = await this.gitManager.getStagedFiles();
} else {
unstagedFiles = await this.gitManager.getUnstagedFiles();
- changedFiles = unstagedFiles.map(({ filepath }) => ({ vault_path: this.gitManager.getVaultPath(filepath) }));
+ changedFiles = unstagedFiles.map(({ filepath }) => ({
+ vault_path: this.gitManager.getVaultPath(filepath)
+ }));
}
}
if (await this.hasTooBigFiles(changedFiles)) {
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
return false;
}
if (changedFiles.length !== 0 || hadConflict) {
- let commitMessage = fromAutoBackup ? this.settings.autoCommitMessage : this.settings.commitMessage;
+ let cmtMessage = commitMessage != null ? commitMessage : commitMessage = fromAutoBackup ? this.settings.autoCommitMessage : this.settings.commitMessage;
if (fromAutoBackup && this.settings.customMessageOnAutoBackup || requestCustomMessage) {
if (!this.settings.disablePopups && fromAutoBackup) {
- new import_obsidian23.Notice("Auto backup: Please enter a custom commit message. Leave empty to abort");
+ new import_obsidian30.Notice(
+ "Auto backup: Please enter a custom commit message. Leave empty to abort"
+ );
}
- const tempMessage = await new CustomMessageModal(this, true).open();
+ const tempMessage = await new CustomMessageModal(
+ this,
+ true
+ ).open();
if (tempMessage != void 0 && tempMessage != "" && tempMessage != "...") {
- commitMessage = tempMessage;
+ cmtMessage = tempMessage;
} else {
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
return false;
}
}
let committedFiles;
if (onlyStaged) {
- committedFiles = await this.gitManager.commit(commitMessage);
+ committedFiles = await this.gitManager.commit({
+ message: cmtMessage,
+ amend
+ });
} else {
- committedFiles = await this.gitManager.commitAll({ message: commitMessage, status: status2, unstagedFiles });
+ committedFiles = await this.gitManager.commitAll({
+ message: cmtMessage,
+ status: status2,
+ unstagedFiles,
+ amend
+ });
+ }
+ if (this.gitManager instanceof SimpleGit) {
+ if ((await this.updateCachedStatus()).conflicted.length == 0) {
+ this.localStorage.setConflict(false);
+ }
}
let roughly = false;
if (committedFiles === void 0) {
roughly = true;
committedFiles = changedFiles.length;
}
- this.displayMessage(`Committed${roughly ? " approx." : ""} ${committedFiles} ${committedFiles > 1 ? "files" : "file"}`);
+ this.setUpAutoBackup();
+ this.displayMessage(
+ `Committed${roughly ? " approx." : ""} ${committedFiles} ${committedFiles == 1 ? "file" : "files"}`
+ );
} else {
this.displayMessage("No changes to commit");
}
dispatchEvent(new CustomEvent("git-refresh"));
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
return true;
}
async hasTooBigFiles(files) {
- var _a2;
const branchInfo = await this.gitManager.branchInfo();
- const remote = (_a2 = branchInfo.tracking) == null ? void 0 : _a2.split("/")[0];
+ const remote = branchInfo.tracking ? splitRemoteBranch(branchInfo.tracking)[0] : null;
if (remote) {
const remoteUrl = await this.gitManager.getRemoteUrl(remote);
if (remoteUrl == null ? void 0 : remoteUrl.includes("github.com")) {
const tooBigFiles = files.filter((f) => {
- const file = this.app.vault.getAbstractFileByPath(f.vault_path);
- if (file instanceof import_obsidian23.TFile) {
+ const file = this.app.vault.getAbstractFileByPath(
+ f.vault_path
+ );
+ if (file instanceof import_obsidian30.TFile) {
return file.stat.size >= 1e8;
}
return false;
});
if (tooBigFiles.length > 0) {
- this.displayError(`Did not commit, because following files are too big: ${tooBigFiles.map((e) => e.vault_path)}. Please remove them.`);
+ this.displayError(
+ `Did not commit, because following files are too big: ${tooBigFiles.map(
+ (e) => e.vault_path
+ )}. Please remove them.`
+ );
return true;
}
}
@@ -31156,35 +43874,40 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (!await this.remotesAreSet()) {
return false;
}
- const file = this.app.vault.getAbstractFileByPath(this.conflictOutputFile);
- const hadConflict = this.localStorage.getConflict() === "true";
- if (this.gitManager instanceof SimpleGit && file)
- await this.app.vault.delete(file);
+ const hadConflict = this.localStorage.getConflict();
+ if (this.gitManager instanceof SimpleGit)
+ await this.mayDeleteConflictFile();
let status2;
if (this.gitManager instanceof SimpleGit && (status2 = await this.updateCachedStatus()).conflicted.length > 0) {
- this.displayError(`Cannot push. You have ${status2.conflicted.length} conflict ${status2.conflicted.length > 1 ? "files" : "file"}`);
+ this.displayError(
+ `Cannot push. You have conflicts in ${status2.conflicted.length} ${status2.conflicted.length == 1 ? "file" : "files"}`
+ );
this.handleConflict(status2.conflicted);
return false;
} else if (this.gitManager instanceof IsomorphicGit && hadConflict) {
- this.displayError(`Cannot push. You have conflict files`);
- this.setState(PluginState.conflicted);
+ this.displayError(`Cannot push. You have conflicts`);
+ this.setState(6 /* conflicted */);
return false;
}
{
console.log("Pushing....");
const pushedFiles = await this.gitManager.push();
console.log("Pushed!", pushedFiles);
- this.lastUpdate = Date.now();
if (pushedFiles > 0) {
- this.displayMessage(`Pushed ${pushedFiles} ${pushedFiles > 1 ? "files" : "file"} to remote`);
+ this.displayMessage(
+ `Pushed ${pushedFiles} ${pushedFiles == 1 ? "file" : "files"} to remote`
+ );
} else {
this.displayMessage(`No changes to push`);
}
this.offlineMode = false;
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
+ dispatchEvent(new CustomEvent("git-refresh"));
return true;
}
}
+ /// Used for internals
+ /// Returns whether the pull added a commit or not.
async pull() {
if (!await this.remotesAreSet()) {
return false;
@@ -31192,18 +43915,43 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
const pulledFiles = await this.gitManager.pull() || [];
this.offlineMode = false;
if (pulledFiles.length > 0) {
- this.displayMessage(`Pulled ${pulledFiles.length} ${pulledFiles.length > 1 ? "files" : "file"} from remote`);
+ this.displayMessage(
+ `Pulled ${pulledFiles.length} ${pulledFiles.length == 1 ? "file" : "files"} from remote`
+ );
this.lastPulledFiles = pulledFiles;
}
return pulledFiles.length != 0;
}
+ async fetch() {
+ if (!await this.remotesAreSet()) {
+ return;
+ }
+ await this.gitManager.fetch();
+ this.displayMessage(`Fetched from remote`);
+ this.offlineMode = false;
+ dispatchEvent(new CustomEvent("git-refresh"));
+ }
+ async mayDeleteConflictFile() {
+ const file = this.app.vault.getAbstractFileByPath(
+ this.conflictOutputFile
+ );
+ if (file) {
+ this.app.workspace.iterateAllLeaves((leaf) => {
+ var _a2;
+ if (leaf.view instanceof import_obsidian30.MarkdownView && ((_a2 = leaf.view.file) == null ? void 0 : _a2.path) == file.path) {
+ leaf.detach();
+ }
+ });
+ await this.app.vault.delete(file);
+ }
+ }
async stageFile(file) {
if (!await this.isAllInitialized())
return false;
await this.gitManager.stage(file.path, true);
this.displayMessage(`Staged ${file.path}`);
dispatchEvent(new CustomEvent("git-refresh"));
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
return true;
}
async unstageFile(file) {
@@ -31212,7 +43960,7 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
await this.gitManager.unstage(file.path, true);
this.displayMessage(`Unstaged ${file.path}`);
dispatchEvent(new CustomEvent("git-refresh"));
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
return true;
}
async switchBranch() {
@@ -31220,7 +43968,9 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (!await this.isAllInitialized())
return;
const branchInfo = await this.gitManager.branchInfo();
- const selectedBranch = await new BranchModal(branchInfo.branches).open();
+ const selectedBranch = await new BranchModal(
+ branchInfo.branches
+ ).open();
if (selectedBranch != void 0) {
await this.gitManager.checkout(selectedBranch);
this.displayMessage(`Switched to ${selectedBranch}`);
@@ -31228,11 +43978,26 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
return selectedBranch;
}
}
+ async switchRemoteBranch() {
+ var _a2;
+ if (!await this.isAllInitialized())
+ return;
+ const selectedBranch = await this.selectRemoteBranch() || "";
+ const [remote, branch2] = splitRemoteBranch(selectedBranch);
+ if (branch2 != void 0 && remote != void 0) {
+ await this.gitManager.checkout(branch2, remote);
+ this.displayMessage(`Switched to ${selectedBranch}`);
+ (_a2 = this.branchBar) == null ? void 0 : _a2.display();
+ return selectedBranch;
+ }
+ }
async createBranch() {
var _a2;
if (!await this.isAllInitialized())
return;
- const newBranch = await new GeneralModal({ placeholder: "Create new branch" }).open();
+ const newBranch = await new GeneralModal({
+ placeholder: "Create new branch"
+ }).open();
if (newBranch != void 0) {
await this.gitManager.createBranch(newBranch);
this.displayMessage(`Created new branch ${newBranch}`);
@@ -31247,11 +44012,20 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
const branchInfo = await this.gitManager.branchInfo();
if (branchInfo.current)
branchInfo.branches.remove(branchInfo.current);
- const branch2 = await new GeneralModal({ options: branchInfo.branches, placeholder: "Delete branch", onlySelection: true }).open();
+ const branch2 = await new GeneralModal({
+ options: branchInfo.branches,
+ placeholder: "Delete branch",
+ onlySelection: true
+ }).open();
if (branch2 != void 0) {
let force = false;
- if (!await this.gitManager.branchIsMerged(branch2)) {
- const forceAnswer = await new GeneralModal({ options: ["YES", "NO"], placeholder: "This branch isn't merged into HEAD. Force delete?", onlySelection: true }).open();
+ const merged = await this.gitManager.branchIsMerged(branch2);
+ if (!merged) {
+ const forceAnswer = await new GeneralModal({
+ options: ["YES", "NO"],
+ placeholder: "This branch isn't merged into HEAD. Force delete?",
+ onlySelection: true
+ }).open();
if (forceAnswer !== "YES") {
return;
}
@@ -31265,11 +44039,11 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
}
async remotesAreSet() {
if (!(await this.gitManager.branchInfo()).tracking) {
- new import_obsidian23.Notice("No upstream branch is set. Please select one.");
+ new import_obsidian30.Notice("No upstream branch is set. Please select one.");
const remoteBranch = await this.selectRemoteBranch();
if (remoteBranch == void 0) {
this.displayError("Aborted. No upstream-branch is set!", 1e4);
- this.setState(PluginState.idle);
+ this.setState(0 /* idle */);
return false;
} else {
await this.gitManager.updateUpstreamBranch(remoteBranch);
@@ -31278,46 +44052,115 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
}
return true;
}
+ async setUpAutoBackup() {
+ if (this.settings.setLastSaveToLastCommit) {
+ this.clearAutoBackup();
+ const lastCommitDate = await this.gitManager.getLastCommitTime();
+ if (lastCommitDate) {
+ this.localStorage.setLastAutoBackup(lastCommitDate.toString());
+ }
+ }
+ if (!this.timeoutIDBackup && !this.onFileModifyEventRef) {
+ const lastAutos = this.loadLastAuto();
+ if (this.settings.autoSaveInterval > 0) {
+ const now2 = /* @__PURE__ */ new Date();
+ const diff2 = this.settings.autoSaveInterval - Math.round(
+ (now2.getTime() - lastAutos.backup.getTime()) / 1e3 / 60
+ );
+ this.startAutoBackup(diff2 <= 0 ? 0 : diff2);
+ }
+ }
+ }
+ async setUpAutos() {
+ this.setUpAutoBackup();
+ const lastAutos = this.loadLastAuto();
+ if (this.settings.differentIntervalCommitAndPush && this.settings.autoPushInterval > 0) {
+ const now2 = /* @__PURE__ */ new Date();
+ const diff2 = this.settings.autoPushInterval - Math.round(
+ (now2.getTime() - lastAutos.push.getTime()) / 1e3 / 60
+ );
+ this.startAutoPush(diff2 <= 0 ? 0 : diff2);
+ }
+ if (this.settings.autoPullInterval > 0) {
+ const now2 = /* @__PURE__ */ new Date();
+ const diff2 = this.settings.autoPullInterval - Math.round(
+ (now2.getTime() - lastAutos.pull.getTime()) / 1e3 / 60
+ );
+ this.startAutoPull(diff2 <= 0 ? 0 : diff2);
+ }
+ }
+ async discardAll() {
+ await this.gitManager.discardAll({
+ status: this.cachedStatus
+ });
+ new import_obsidian30.Notice(
+ "All local changes have been discarded. New files remain untouched."
+ );
+ }
+ clearAutos() {
+ this.clearAutoBackup();
+ this.clearAutoPush();
+ this.clearAutoPull();
+ }
startAutoBackup(minutes) {
- const time = (minutes != null ? minutes : this.settings.autoSaveInterval) * 6e4;
+ let time = (minutes != null ? minutes : this.settings.autoSaveInterval) * 6e4;
if (this.settings.autoBackupAfterFileChange) {
if (minutes === 0) {
this.doAutoBackup();
} else {
- this.onFileModifyEventRef = this.app.vault.on("modify", () => this.autoBackupDebouncer());
- this.autoBackupDebouncer = (0, import_obsidian23.debounce)(() => this.doAutoBackup(), time, true);
+ this.onFileModifyEventRef = this.app.vault.on(
+ "modify",
+ () => this.autoBackupDebouncer()
+ );
+ this.autoBackupDebouncer = (0, import_obsidian30.debounce)(
+ () => this.doAutoBackup(),
+ time,
+ true
+ );
}
} else {
- this.timeoutIDBackup = window.setTimeout(() => this.doAutoBackup(), time);
+ if (time > 2147483647)
+ time = 2147483647;
+ this.timeoutIDBackup = window.setTimeout(
+ () => this.doAutoBackup(),
+ time
+ );
}
}
+ // This is used for both auto backup and commit
doAutoBackup() {
this.promiseQueue.addTask(() => {
if (this.settings.differentIntervalCommitAndPush) {
- return this.commit(true);
+ return this.commit({ fromAutoBackup: true });
} else {
return this.createBackup(true);
}
});
- this.saveLastAuto(new Date(), "backup");
+ this.saveLastAuto(/* @__PURE__ */ new Date(), "backup");
this.saveSettings();
this.startAutoBackup();
}
startAutoPull(minutes) {
+ let time = (minutes != null ? minutes : this.settings.autoPullInterval) * 6e4;
+ if (time > 2147483647)
+ time = 2147483647;
this.timeoutIDPull = window.setTimeout(() => {
this.promiseQueue.addTask(() => this.pullChangesFromRemote());
- this.saveLastAuto(new Date(), "pull");
+ this.saveLastAuto(/* @__PURE__ */ new Date(), "pull");
this.saveSettings();
this.startAutoPull();
- }, (minutes != null ? minutes : this.settings.autoPullInterval) * 6e4);
+ }, time);
}
startAutoPush(minutes) {
+ let time = (minutes != null ? minutes : this.settings.autoPushInterval) * 6e4;
+ if (time > 2147483647)
+ time = 2147483647;
this.timeoutIDPush = window.setTimeout(() => {
this.promiseQueue.addTask(() => this.push());
- this.saveLastAuto(new Date(), "push");
+ this.saveLastAuto(/* @__PURE__ */ new Date(), "push");
this.saveSettings();
this.startAutoPush();
- }, (minutes != null ? minutes : this.settings.autoPushInterval) * 6e4);
+ }, time);
}
clearAutoBackup() {
var _a2;
@@ -31352,22 +44195,39 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
return false;
}
async handleConflict(conflicted) {
- this.setState(PluginState.conflicted);
- this.localStorage.setConflict("true");
+ this.setState(6 /* conflicted */);
+ this.localStorage.setConflict(true);
let lines;
if (conflicted !== void 0) {
lines = [
- "# Conflict files",
- "Please resolve them and commit per command (This file will be deleted before the commit).",
+ "# Conflicts",
+ "Please resolve them and commit them using the commands `Git: Commit all changes` followed by `Git: Push`",
+ "(This file will automatically be deleted before commit)",
+ "[[#Additional Instructions]] available below file list",
+ "",
...conflicted.map((e) => {
const file = this.app.vault.getAbstractFileByPath(e);
- if (file instanceof import_obsidian23.TFile) {
- const link = this.app.metadataCache.fileToLinktext(file, "/");
+ if (file instanceof import_obsidian30.TFile) {
+ const link = this.app.metadataCache.fileToLinktext(
+ file,
+ "/"
+ );
return `- [[${link}]]`;
} else {
return `- Not a file: ${e}`;
}
- })
+ }),
+ `
+# Additional Instructions
+I strongly recommend to use "Source mode" for viewing the conflicted files. For simple conflicts, in each file listed above replace every occurrence of the following text blocks with the desired text.
+
+\`\`\`diff
+<<<<<<< HEAD
+ File changes in local repository
+=======
+ File changes in remote repository
+>>>>>>> origin/main
+\`\`\``
];
}
this.writeAndOpenFile(lines == null ? void 0 : lines.join("\n"));
@@ -31400,13 +44260,19 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
remotes = await this.gitManager.getRemotes();
}
}
- const nameModal = new GeneralModal({ options: remotes, placeholder: "Select or create a new remote by typing its name and selecting it" });
+ const nameModal = new GeneralModal({
+ options: remotes,
+ placeholder: "Select or create a new remote by typing its name and selecting it"
+ });
const remoteName = selectedRemote != null ? selectedRemote : await nameModal.open();
if (remoteName) {
this.displayMessage("Fetching remote branches");
await this.gitManager.fetch(remoteName);
const branches = await this.gitManager.getRemoteBranches(remoteName);
- const branchModal = new GeneralModal({ options: branches, placeholder: "Select or create a new remote branch by typing its name and selecting it" });
+ const branchModal = new GeneralModal({
+ options: branches,
+ placeholder: "Select or create a new remote branch by typing its name and selecting it"
+ });
return await branchModal.open();
}
}
@@ -31414,7 +44280,10 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
if (!await this.isAllInitialized())
return;
const remotes = await this.gitManager.getRemotes();
- const nameModal = new GeneralModal({ options: remotes, placeholder: "Select a remote" });
+ const nameModal = new GeneralModal({
+ options: remotes,
+ placeholder: "Select a remote"
+ });
const remoteName = await nameModal.open();
if (remoteName) {
this.gitManager.removeRemote(remoteName);
@@ -31434,51 +44303,92 @@ var ObsidianGit = class extends import_obsidian23.Plugin {
this.app.workspace.openLinkText(this.conflictOutputFile, "/", true);
}
}
+ handleViewActiveState(leaf) {
+ var _a2, _b;
+ if (!(leaf == null ? void 0 : leaf.view.getState().file))
+ return;
+ const sourceControlLeaf = this.app.workspace.getLeavesOfType(SOURCE_CONTROL_VIEW_CONFIG.type).first();
+ const historyLeaf = this.app.workspace.getLeavesOfType(HISTORY_VIEW_CONFIG.type).first();
+ (_a2 = sourceControlLeaf == null ? void 0 : sourceControlLeaf.view.containerEl.querySelector(`div.nav-file-title.is-active`)) == null ? void 0 : _a2.removeClass("is-active");
+ (_b = historyLeaf == null ? void 0 : historyLeaf.view.containerEl.querySelector(`div.nav-file-title.is-active`)) == null ? void 0 : _b.removeClass("is-active");
+ if ((leaf == null ? void 0 : leaf.view) instanceof DiffView) {
+ const path2 = leaf.view.state.file;
+ this.lastDiffViewState = leaf.view.getState();
+ let el;
+ if (sourceControlLeaf && leaf.view.state.staged) {
+ el = sourceControlLeaf.view.containerEl.querySelector(
+ `div.staged div.nav-file-title[data-path='${path2}']`
+ );
+ } else if (sourceControlLeaf && leaf.view.state.staged === false && !leaf.view.state.hash) {
+ el = sourceControlLeaf.view.containerEl.querySelector(
+ `div.changes div.nav-file-title[data-path='${path2}']`
+ );
+ } else if (historyLeaf && leaf.view.state.hash) {
+ el = historyLeaf.view.containerEl.querySelector(
+ `div.nav-file-title[data-path='${path2}']`
+ );
+ }
+ el == null ? void 0 : el.addClass("is-active");
+ } else {
+ this.lastDiffViewState = void 0;
+ }
+ }
+ // region: displaying / formatting messages
displayMessage(message, timeout = 4 * 1e3) {
var _a2;
(_a2 = this.statusBar) == null ? void 0 : _a2.displayMessage(message.toLowerCase(), timeout);
if (!this.settings.disablePopups) {
- new import_obsidian23.Notice(message, 5 * 1e3);
+ if (!this.settings.disablePopupsForNoChanges || !message.startsWith("No changes")) {
+ new import_obsidian30.Notice(message, 5 * 1e3);
+ }
}
console.log(`git obsidian message: ${message}`);
}
displayError(message, timeout = 10 * 1e3) {
var _a2;
if (message instanceof Errors.UserCanceledError) {
- new import_obsidian23.Notice("Aborted");
+ new import_obsidian30.Notice("Aborted");
return;
}
message = message.toString();
- new import_obsidian23.Notice(message, timeout);
+ new import_obsidian30.Notice(message, timeout);
console.log(`git obsidian error: ${message}`);
(_a2 = this.statusBar) == null ? void 0 : _a2.displayMessage(message.toLowerCase(), timeout);
}
};
-/*!
- Copyright (c) 2016 Jed Watson.
- Licensed under the MIT License (MIT), see
- http://jedwatson.github.io/classnames
+/*! Bundled license information:
+
+ieee754/index.js:
+ (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *)
+
+buffer/index.js:
+ (*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ *)
+
+safe-buffer/index.js:
+ (*! safe-buffer. MIT License. Feross Aboukhadijeh *)
+
+crc-32/crc32.js:
+ (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *)
+
+js-sha256/src/sha256.js:
+ (**
+ * [js-sha256]{@link https://github.com/emn178/js-sha256}
+ *
+ * @version 0.9.0
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
+ * @copyright Chen, Yi-Cyuan 2014-2017
+ * @license MIT
+ *)
+
+feather-icons/dist/feather.js:
+ (*!
+ Copyright (c) 2016 Jed Watson.
+ Licensed under the MIT License (MIT), see
+ http://jedwatson.github.io/classnames
+ *)
*/
-/*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-/*! *****************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
-/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */
-/*! safe-buffer. MIT License. Feross Aboukhadijeh */
diff --git a/.obsidian/plugins/obsidian-git/manifest.json b/.obsidian/plugins/obsidian-git/manifest.json
index 949c98e..3491a21 100644
--- a/.obsidian/plugins/obsidian-git/manifest.json
+++ b/.obsidian/plugins/obsidian-git/manifest.json
@@ -1,8 +1,9 @@
{
"id": "obsidian-git",
- "name": "Obsidian Git",
+ "name": "Git",
"description": "Backup your vault with Git.",
"isDesktopOnly": false,
+ "fundingUrl": "https://ko-fi.com/vinzent",
"js": "main.js",
- "version": "2.8.0"
+ "version": "2.23.2"
}
diff --git a/.obsidian/plugins/obsidian-git/styles.css b/.obsidian/plugins/obsidian-git/styles.css
index e496c17..c1d5065 100644
--- a/.obsidian/plugins/obsidian-git/styles.css
+++ b/.obsidian/plugins/obsidian-git/styles.css
@@ -8,10 +8,19 @@
}
}
+.workspace-leaf-content[data-type='git-view'] .button-border {
+ border: 2px solid var(--interactive-accent);
+ border-radius: var(--radius-s);
+}
+
.workspace-leaf-content[data-type='git-view'] .view-content {
padding: 0;
}
+.workspace-leaf-content[data-type='git-history-view'] .view-content {
+ padding: 0;
+}
+
.loading>svg {
animation: 2s linear infinite loading;
transform-origin: 50% 50%;
@@ -42,21 +51,30 @@
.tooltip.mod-right {
overflow-wrap: break-word;
}
-
-.obsidian-git-shortcuts {
- margin: 10px;
-}
-
-.diff-err {
- height: 100%;
+.git-tools {
+ display: flex;
+ margin-left: auto;
+}
+.git-tools .type {
+ padding-left: var(--size-2-1);
display: flex;
- justify-content: center;
- flex-direction: column;
align-items: center;
+ justify-content: center;
+ width: 11px;
}
-.diff-err-sign {
- font-size: 2em;
+.git-tools .type[data-type="M"] {
+ color: orange;
+}
+.git-tools .type[data-type="D"] {
+ color: red;
+}
+.git-tools .buttons {
+ display: flex;
+}
+.git-tools .buttons > * {
+ padding: 0 0;
+ height: auto;
}
.workspace-leaf-content[data-type="diff-view"] .d2h-d-none {
@@ -471,4 +489,24 @@
.workspace-leaf-content[data-type="diff-view"] .d2h-moved-tag {
border: 1px solid #3572b0;
-}
\ No newline at end of file
+}
+
+/* ====================== Line Authoring Information ====================== */
+
+.cm-gutterElement.obs-git-blame-gutter {
+ /* Add background color to spacing inbetween and around the gutter for better aesthetics */
+ border-width: 0px 2px 0.2px 2px;
+ border-style: solid;
+ border-color: var(--background-secondary);
+ background-color: var(--background-secondary);
+}
+
+.cm-gutterElement.obs-git-blame-gutter > div, .line-author-settings-preview {
+ /* delegate text color to settings */
+ color: var(--obs-git-gutter-text);
+ font-family: monospace;
+ height: 100%; /* ensure, that age-based background color occupies entire parent */
+ text-align: right;
+ padding: 0px 6px 0px 6px;
+ white-space: pre; /* Keep spaces and do not collapse them. */
+}