markdown/src/composables/useGit.js

106 lines
2.4 KiB
JavaScript

import { reactive } from 'vue';
const state = reactive({
isGitRepo: false,
statusOutput: '',
statusFiles: [],
remoteUrl: '',
loading: false
});
export function useGit() {
const checkGitRepo = async (rootDir) => {
if (!window.services?.isGitRepository) return;
state.isGitRepo = await window.services.isGitRepository(rootDir);
if (state.isGitRepo) {
// 自动获取一次状态
await getStatus(rootDir);
await getRemoteUrl(rootDir);
}
};
const getRemoteUrl = async (rootDir) => {
try {
const res = await window.services.gitRemoteUrl(rootDir);
if (res.success) {
state.remoteUrl = res.stdout.trim();
}
} catch (e) {
console.error("Failed to get remote url", e);
}
};
const openRemoteUrl = () => {
if (state.remoteUrl) {
window.services.openExternal(state.remoteUrl);
}
};
const getStatus = async (rootDir) => {
state.loading = true;
try {
const res = await window.services.gitStatus(rootDir);
if (res.success) {
state.statusOutput = res.stdout;
// 解析状态文件列表
state.statusFiles = res.stdout
.split('\n')
.filter(line => line.trim())
.map(line => {
// git status --short 格式: XY PATH
// 前两个字符是状态,后面是路径
const status = line.substring(0, 2);
const path = line.substring(3);
return { status, path };
});
}
} finally {
state.loading = false;
}
};
const commit = async (rootDir, message) => {
state.loading = true;
try {
await window.services.gitAdd(rootDir); // 默认 add .
const res = await window.services.gitCommit(rootDir, message);
return res;
} finally {
state.loading = false;
await getStatus(rootDir);
}
};
const push = async (rootDir) => {
state.loading = true;
try {
return await window.services.gitPush(rootDir);
} finally {
state.loading = false;
await getStatus(rootDir);
}
};
const pull = async (rootDir) => {
state.loading = true;
try {
return await window.services.gitPull(rootDir);
} finally {
state.loading = false;
await getStatus(rootDir);
}
};
return {
state,
checkGitRepo,
getStatus,
getRemoteUrl,
openRemoteUrl,
commit,
push,
pull
};
}