mirror of
https://github.com/silvanocerza/github-gitless-sync.git
synced 2026-07-22 12:10:28 +00:00
Compare commits
29 commits
1.0.7-beta
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ebd201da9 | ||
|
|
ee9c2ee236 | ||
|
|
b6eb9ed62d | ||
|
|
59f951f2b8 | ||
|
|
c62afe938b | ||
|
|
69841aa574 | ||
|
|
345826443f | ||
|
|
e33de48075 | ||
|
|
b2f3db6050 | ||
|
|
be547d8691 | ||
|
|
4fa2526322 | ||
|
|
786cefaf4d | ||
|
|
654fa6b455 | ||
|
|
1e16d01adf | ||
|
|
56bd6dee4c | ||
|
|
b6be53ca16 | ||
|
|
53651f5b88 | ||
|
|
263623dad7 | ||
|
|
13383dc65c | ||
|
|
15cc51014c | ||
|
|
96da957f18 | ||
|
|
457a0b6d24 | ||
|
|
1a2eb64959 | ||
|
|
5ab20cf482 | ||
|
|
d0f04d5217 | ||
|
|
7e7eddaec3 | ||
|
|
6c9b8625c3 | ||
|
|
271d90b7f9 | ||
|
|
de1c814260 |
23 changed files with 787 additions and 344 deletions
7
.github/workflows/release.yml
vendored
7
.github/workflows/release.yml
vendored
|
|
@ -20,14 +20,15 @@ jobs:
|
||||||
|
|
||||||
- name: Build plugin
|
- name: Build plugin
|
||||||
run: |
|
run: |
|
||||||
npm install
|
npm install -g pnpm@latest-10
|
||||||
npm run build
|
pnpm install
|
||||||
|
pnpm build
|
||||||
|
|
||||||
- name: Create release
|
- name: Create release
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
if [[ "${{ github.ref_name }}" == *-beta ]]; then
|
if [[ "${{ github.ref_name }}" == *-beta* ]]; then
|
||||||
gh release create "${{ github.ref_name }}" \
|
gh release create "${{ github.ref_name }}" \
|
||||||
--title="${{ github.ref_name }}" \
|
--title="${{ github.ref_name }}" \
|
||||||
--prerelease \
|
--prerelease \
|
||||||
|
|
|
||||||
26
README.md
26
README.md
|
|
@ -28,9 +28,9 @@ The plugin is available as a community plugin, you can easily search for it in O
|
||||||
|
|
||||||
If you find any problem please open an issue with as many details as possible.
|
If you find any problem please open an issue with as many details as possible.
|
||||||
|
|
||||||
Please also provide logs if possible, you can find the `github-sync.log` file in your config directory. Remember to enable logging first.
|
Please also provide logs if possible, you can copy them from the settings page. Remember to enable logging first.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
|
@ -102,7 +102,9 @@ If you need to reset the plugin settings and metadata you can easily do that in
|
||||||
|
|
||||||
That will completely wipe all the sync metadata so you'll have to repeat the first sync as if you just enabled the plugin for the first time.
|
That will completely wipe all the sync metadata so you'll have to repeat the first sync as if you just enabled the plugin for the first time.
|
||||||
|
|
||||||
## What's different from other sync plugins?
|
## FAQs
|
||||||
|
|
||||||
|
### What's different from other sync plugins?
|
||||||
|
|
||||||
There are obviously other plugins that let you sync your vault with GitHub or other git hosts, like [`obsidian-git`](https://github.com/Vinzent03/obsidian-git) and [`Obsidian-GitHub-Sync`](https://github.com/kevinmkchin/Obsidian-GitHub-Sync) just to name a couple.
|
There are obviously other plugins that let you sync your vault with GitHub or other git hosts, like [`obsidian-git`](https://github.com/Vinzent03/obsidian-git) and [`Obsidian-GitHub-Sync`](https://github.com/kevinmkchin/Obsidian-GitHub-Sync) just to name a couple.
|
||||||
|
|
||||||
|
|
@ -116,6 +118,24 @@ This obviously comes with some limitations. Since `git` is not used you can't in
|
||||||
|
|
||||||
Also since this relies only on the GitHub APIs you can only sync with GitHub and no other host.
|
Also since this relies only on the GitHub APIs you can only sync with GitHub and no other host.
|
||||||
|
|
||||||
|
### Can I use this with other sync plugins?
|
||||||
|
|
||||||
|
No.
|
||||||
|
|
||||||
|
To work correctly this plugin uses a custom metadata file that is updated every time we sync, if you commit changes outside the plugin that file is not updated properly.
|
||||||
|
|
||||||
|
Other plugins don't know about that file, so if you sync with others too you risk losing data.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Contributions are obviously accepted.
|
||||||
|
|
||||||
|
Bug fixes are always welcome, new feature must be discussed first. Open a [discussion](https://github.com/silvanocerza/github-gitless-sync/discussions) and let's talk in that case.
|
||||||
|
|
||||||
|
Keep PRs as small as possible, I won't review PRs with hundreds of lines if it's mostly code.
|
||||||
|
|
||||||
|
Low quality or vibe coded PRs are not welcome. Put some effort in it please.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
The project is licensed under the [AGPLv3](https://www.gnu.org/licenses/agpl-3.0.en.html) license.
|
The project is licensed under the [AGPLv3](https://www.gnu.org/licenses/agpl-3.0.en.html) license.
|
||||||
|
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 12 KiB |
BIN
assets/logs_settings.png
Normal file
BIN
assets/logs_settings.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
45
benchmark.ts
45
benchmark.ts
|
|
@ -12,10 +12,6 @@ const LoggerModule = proxyquireNonStrict("./src/logger", {
|
||||||
obsidian: obsidianMocks,
|
obsidian: obsidianMocks,
|
||||||
});
|
});
|
||||||
|
|
||||||
const GithubClientModule = proxyquireNonStrict("./src/github/client", {
|
|
||||||
obsidian: obsidianMocks,
|
|
||||||
});
|
|
||||||
|
|
||||||
const MetadataStoreModule = proxyquireNonStrict("./src/metadata-store", {
|
const MetadataStoreModule = proxyquireNonStrict("./src/metadata-store", {
|
||||||
obsidian: obsidianMocks,
|
obsidian: obsidianMocks,
|
||||||
});
|
});
|
||||||
|
|
@ -29,6 +25,11 @@ const UtilsModule = proxyquireNonStrict("./src/utils", {
|
||||||
obsidian: obsidianMocks,
|
obsidian: obsidianMocks,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const GithubClientModule = proxyquireNonStrict("./src/github/client", {
|
||||||
|
obsidian: obsidianMocks,
|
||||||
|
"src/utils": UtilsModule,
|
||||||
|
});
|
||||||
|
|
||||||
const SyncManagerModule = proxyquireNonStrict("./src/sync-manager", {
|
const SyncManagerModule = proxyquireNonStrict("./src/sync-manager", {
|
||||||
obsidian: obsidianMocks,
|
obsidian: obsidianMocks,
|
||||||
"./metadata-store": MetadataStoreModule,
|
"./metadata-store": MetadataStoreModule,
|
||||||
|
|
@ -143,14 +144,22 @@ const generateRandomFiles = (
|
||||||
fs.writeFileSync(metadataFilePath, JSON.stringify(metadata), { flag: "w" });
|
fs.writeFileSync(metadataFilePath, JSON.stringify(metadata), { flag: "w" });
|
||||||
};
|
};
|
||||||
|
|
||||||
const cleanupRemote = async () => {
|
const cleanupRemote = () => {
|
||||||
const url = `git@github.com:${process.env.REPO_OWNER}/${process.env.REPO_NAME}.git`;
|
const url = `git@github.com:${process.env.REPO_OWNER}/${process.env.REPO_NAME}.git`;
|
||||||
const clonedDir = path.join(os.tmpdir(), "temp-clone");
|
const clonedDir = path.join(os.tmpdir(), "temp-clone");
|
||||||
|
|
||||||
|
// Remove the folder in case it already exists
|
||||||
|
fs.rmSync(clonedDir, { recursive: true, force: true });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Clone the repository
|
// Clone the repository
|
||||||
execSync(`git clone ${url} ${clonedDir}`, { stdio: "ignore" });
|
execSync(`git clone ${url} ${clonedDir}`, { stdio: "ignore" });
|
||||||
|
|
||||||
|
const repoExists = fs.existsSync(clonedDir);
|
||||||
|
if (!repoExists) {
|
||||||
|
throw Error("Failed to clone repo");
|
||||||
|
}
|
||||||
|
|
||||||
// Remove all files except .git
|
// Remove all files except .git
|
||||||
execSync('find . -type f -not -path "./.git*" -delete', {
|
execSync('find . -type f -not -path "./.git*" -delete', {
|
||||||
stdio: "ignore",
|
stdio: "ignore",
|
||||||
|
|
@ -166,16 +175,12 @@ const cleanupRemote = async () => {
|
||||||
|
|
||||||
// Push changes
|
// Push changes
|
||||||
execSync("git push", { stdio: "ignore", cwd: clonedDir });
|
execSync("git push", { stdio: "ignore", cwd: clonedDir });
|
||||||
|
|
||||||
// Remove the folder
|
|
||||||
fs.rm(clonedDir, { recursive: true, force: true }, (err) => {
|
|
||||||
if (err) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Error: ${error.message}`);
|
console.error(`Error: ${error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove the folder when everything is done
|
||||||
|
fs.rmSync(clonedDir, { recursive: true, force: true });
|
||||||
};
|
};
|
||||||
|
|
||||||
const BENCHMARK_DATA = [
|
const BENCHMARK_DATA = [
|
||||||
|
|
@ -224,7 +229,7 @@ const BENCHMARK_DATA = [
|
||||||
const results = [];
|
const results = [];
|
||||||
for (const data of BENCHMARK_DATA) {
|
for (const data of BENCHMARK_DATA) {
|
||||||
console.log(
|
console.log(
|
||||||
`Running benchmark for ${data.files} files of ${data.fileSize} bytes`,
|
`Running benchmark with ${data.files} files totaling ${data.fileSize} bytes`,
|
||||||
);
|
);
|
||||||
const vaultRootDir = path.join(
|
const vaultRootDir = path.join(
|
||||||
benchmarkRootDir,
|
benchmarkRootDir,
|
||||||
|
|
@ -239,16 +244,18 @@ const BENCHMARK_DATA = [
|
||||||
);
|
);
|
||||||
|
|
||||||
// Run first sync by uploading all local files
|
// Run first sync by uploading all local files
|
||||||
|
console.log("First sync from local");
|
||||||
const uploadTime = await runBenchmark(vaultRootDir);
|
const uploadTime = await runBenchmark(vaultRootDir);
|
||||||
|
|
||||||
// Cleanup vault dir completely
|
// Cleanup vault dir completely
|
||||||
fs.rmSync(vaultRootDir, { recursive: true, force: true });
|
fs.rmSync(vaultRootDir, { recursive: true, force: true });
|
||||||
|
|
||||||
// Run first sync again, this time we download the files we just uploaded
|
// Run first sync again, this time we download the files we just uploaded
|
||||||
|
console.log("Second sync from remote");
|
||||||
const downloadTime = await runBenchmark(vaultRootDir);
|
const downloadTime = await runBenchmark(vaultRootDir);
|
||||||
|
|
||||||
// Cleanup the remote repo so it's ready for another benchmark
|
// Cleanup the remote repo so it's ready for another benchmark
|
||||||
await cleanupRemote();
|
cleanupRemote();
|
||||||
|
|
||||||
results.push({
|
results.push({
|
||||||
data,
|
data,
|
||||||
|
|
@ -258,6 +265,10 @@ const BENCHMARK_DATA = [
|
||||||
|
|
||||||
// Cleanup vault dir again, it's not necessary to keep it around
|
// Cleanup vault dir again, it's not necessary to keep it around
|
||||||
fs.rmSync(vaultRootDir, { recursive: true, force: true });
|
fs.rmSync(vaultRootDir, { recursive: true, force: true });
|
||||||
|
|
||||||
|
// Wait 2 seconds between each run just to avoid annoying Github
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
console.log("");
|
||||||
}
|
}
|
||||||
fs.writeFileSync("benchmark_result.json", JSON.stringify(results), {
|
fs.writeFileSync("benchmark_result.json", JSON.stringify(results), {
|
||||||
flag: "w",
|
flag: "w",
|
||||||
|
|
@ -265,9 +276,5 @@ const BENCHMARK_DATA = [
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Benchmark failed:", error);
|
console.error("Benchmark failed:", error);
|
||||||
}
|
}
|
||||||
fs.rm(benchmarkRootDir, { recursive: true, force: true }, (err) => {
|
fs.rmSync(benchmarkRootDir, { recursive: true, force: true });
|
||||||
if (err) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})();
|
})();
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"id": "github-gitless-sync",
|
"id": "github-gitless-sync",
|
||||||
"name": "GitHub Gitless Sync",
|
"name": "GitHub Gitless Sync",
|
||||||
"version": "1.0.6",
|
"version": "1.0.7",
|
||||||
"minAppVersion": "1.7.7",
|
"minAppVersion": "1.7.7",
|
||||||
"description": "Sync a GitHub repository with vaults on different platforms without requiring git installation",
|
"description": "Sync a GitHub repository with vaults on different platforms without requiring git installation",
|
||||||
"author": "Silvano Cerza",
|
"author": "Silvano Cerza",
|
||||||
|
|
|
||||||
|
|
@ -128,11 +128,22 @@ export async function requestUrl(options: RequestUrlParam) {
|
||||||
body: options.body,
|
body: options.body,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const isJsonResponse = response.headers
|
||||||
|
.get("content-type")
|
||||||
|
?.includes("application/json");
|
||||||
|
|
||||||
// Convert to expected Obsidian response format
|
// Convert to expected Obsidian response format
|
||||||
return {
|
if (isJsonResponse) {
|
||||||
status: response.status,
|
return {
|
||||||
json: await response.json(),
|
status: response.status,
|
||||||
};
|
json: await response.json(),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
status: response.status,
|
||||||
|
arrayBuffer: await response.arrayBuffer(),
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mock utility functions
|
// Mock utility functions
|
||||||
|
|
@ -150,6 +161,3 @@ export function base64ToArrayBuffer(base64: string): ArrayBuffer {
|
||||||
|
|
||||||
// Mock Event reference
|
// Mock Event reference
|
||||||
export type EventRef = string;
|
export type EventRef = string;
|
||||||
|
|
||||||
// Re-export the fileTypeFromBuffer function
|
|
||||||
export { fileTypeFromBuffer } from "file-type";
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "github-gitless-sync",
|
"name": "github-gitless-sync",
|
||||||
"version": "1.0.6",
|
"version": "1.0.7",
|
||||||
"description": "Sync a GitHub repository with vaults on different platforms without requiring git installation",
|
"description": "Sync a GitHub repository with vaults on different platforms without requiring git installation",
|
||||||
"main": "main.js",
|
"main": "main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|
@ -34,8 +34,8 @@
|
||||||
"@codemirror/state": "^6.5.2",
|
"@codemirror/state": "^6.5.2",
|
||||||
"@codemirror/view": "^6.36.2",
|
"@codemirror/view": "^6.36.2",
|
||||||
"@uiw/react-codemirror": "^4.23.8",
|
"@uiw/react-codemirror": "^4.23.8",
|
||||||
|
"@zip.js/zip.js": "^2.7.60",
|
||||||
"codemirror": "^6.0.1",
|
"codemirror": "^6.0.1",
|
||||||
"file-type": "^20.4.1",
|
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0"
|
"react-dom": "^19.0.0"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -20,12 +20,12 @@ importers:
|
||||||
'@uiw/react-codemirror':
|
'@uiw/react-codemirror':
|
||||||
specifier: ^4.23.8
|
specifier: ^4.23.8
|
||||||
version: 4.23.8(@babel/runtime@7.26.9)(@codemirror/autocomplete@6.18.6)(@codemirror/language@6.10.8)(@codemirror/lint@6.8.4)(@codemirror/search@6.5.9)(@codemirror/state@6.5.2)(@codemirror/theme-one-dark@6.1.2)(@codemirror/view@6.36.2)(codemirror@6.0.1)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
|
version: 4.23.8(@babel/runtime@7.26.9)(@codemirror/autocomplete@6.18.6)(@codemirror/language@6.10.8)(@codemirror/lint@6.8.4)(@codemirror/search@6.5.9)(@codemirror/state@6.5.2)(@codemirror/theme-one-dark@6.1.2)(@codemirror/view@6.36.2)(codemirror@6.0.1)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
|
||||||
|
'@zip.js/zip.js':
|
||||||
|
specifier: ^2.7.60
|
||||||
|
version: 2.7.60
|
||||||
codemirror:
|
codemirror:
|
||||||
specifier: ^6.0.1
|
specifier: ^6.0.1
|
||||||
version: 6.0.1
|
version: 6.0.1
|
||||||
file-type:
|
|
||||||
specifier: ^20.4.1
|
|
||||||
version: 20.4.1
|
|
||||||
react:
|
react:
|
||||||
specifier: ^19.0.0
|
specifier: ^19.0.0
|
||||||
version: 19.0.0
|
version: 19.0.0
|
||||||
|
|
@ -534,13 +534,6 @@ packages:
|
||||||
'@sinonjs/samsam@8.0.2':
|
'@sinonjs/samsam@8.0.2':
|
||||||
resolution: {integrity: sha512-v46t/fwnhejRSFTGqbpn9u+LQ9xJDse10gNnPgAcxgdoCDMXj/G2asWAC/8Qs+BAZDicX+MNZouXT1A7c83kVw==}
|
resolution: {integrity: sha512-v46t/fwnhejRSFTGqbpn9u+LQ9xJDse10gNnPgAcxgdoCDMXj/G2asWAC/8Qs+BAZDicX+MNZouXT1A7c83kVw==}
|
||||||
|
|
||||||
'@tokenizer/inflate@0.2.7':
|
|
||||||
resolution: {integrity: sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==}
|
|
||||||
engines: {node: '>=18'}
|
|
||||||
|
|
||||||
'@tokenizer/token@0.3.0':
|
|
||||||
resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==}
|
|
||||||
|
|
||||||
'@types/codemirror@5.60.8':
|
'@types/codemirror@5.60.8':
|
||||||
resolution: {integrity: sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==}
|
resolution: {integrity: sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==}
|
||||||
|
|
||||||
|
|
@ -645,6 +638,10 @@ packages:
|
||||||
react: '>=16.8.0'
|
react: '>=16.8.0'
|
||||||
react-dom: '>=16.8.0'
|
react-dom: '>=16.8.0'
|
||||||
|
|
||||||
|
'@zip.js/zip.js@2.7.60':
|
||||||
|
resolution: {integrity: sha512-vA3rLyqdxBrVo1FWSsbyoecaqWTV+vgPRf0QKeM7kVDG0r+lHUqd7zQDv1TO9k4BcAoNzNDSNrrel24Mk6addA==}
|
||||||
|
engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=16.5.0'}
|
||||||
|
|
||||||
acorn-jsx@5.3.2:
|
acorn-jsx@5.3.2:
|
||||||
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
|
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
|
|
@ -805,17 +802,10 @@ packages:
|
||||||
fastq@1.18.0:
|
fastq@1.18.0:
|
||||||
resolution: {integrity: sha512-QKHXPW0hD8g4UET03SdOdunzSouc9N4AuHdsX8XNcTsuz+yYFILVNIX4l9yHABMhiEI9Db0JTTIpu0wB+Y1QQw==}
|
resolution: {integrity: sha512-QKHXPW0hD8g4UET03SdOdunzSouc9N4AuHdsX8XNcTsuz+yYFILVNIX4l9yHABMhiEI9Db0JTTIpu0wB+Y1QQw==}
|
||||||
|
|
||||||
fflate@0.8.2:
|
|
||||||
resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==}
|
|
||||||
|
|
||||||
file-entry-cache@8.0.0:
|
file-entry-cache@8.0.0:
|
||||||
resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}
|
resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}
|
||||||
engines: {node: '>=16.0.0'}
|
engines: {node: '>=16.0.0'}
|
||||||
|
|
||||||
file-type@20.4.1:
|
|
||||||
resolution: {integrity: sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==}
|
|
||||||
engines: {node: '>=18'}
|
|
||||||
|
|
||||||
fill-keys@1.0.2:
|
fill-keys@1.0.2:
|
||||||
resolution: {integrity: sha512-tcgI872xXjwFF4xgQmLxi76GnwJG3g/3isB1l4/G5Z4zrbddGpBjqZCO9oEAcB5wX0Hj/5iQB3toxfO7in1hHA==}
|
resolution: {integrity: sha512-tcgI872xXjwFF4xgQmLxi76GnwJG3g/3isB1l4/G5Z4zrbddGpBjqZCO9oEAcB5wX0Hj/5iQB3toxfO7in1hHA==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
|
|
@ -869,9 +859,6 @@ packages:
|
||||||
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
|
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
|
|
||||||
ieee754@1.2.1:
|
|
||||||
resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
|
|
||||||
|
|
||||||
ignore@5.3.2:
|
ignore@5.3.2:
|
||||||
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
||||||
engines: {node: '>= 4'}
|
engines: {node: '>= 4'}
|
||||||
|
|
@ -1006,10 +993,6 @@ packages:
|
||||||
path-parse@1.0.7:
|
path-parse@1.0.7:
|
||||||
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
|
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
|
||||||
|
|
||||||
peek-readable@7.0.0:
|
|
||||||
resolution: {integrity: sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==}
|
|
||||||
engines: {node: '>=18'}
|
|
||||||
|
|
||||||
picocolors@1.1.1:
|
picocolors@1.1.1:
|
||||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||||
|
|
||||||
|
|
@ -1097,10 +1080,6 @@ packages:
|
||||||
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
|
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
strtok3@10.2.2:
|
|
||||||
resolution: {integrity: sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==}
|
|
||||||
engines: {node: '>=18'}
|
|
||||||
|
|
||||||
style-mod@4.1.2:
|
style-mod@4.1.2:
|
||||||
resolution: {integrity: sha512-wnD1HyVqpJUI2+eKZ+eo1UwghftP6yuFheBqqe+bWCotBjC2K1YnteJILRMs3SM4V/0dLEW1SC27MWP5y+mwmw==}
|
resolution: {integrity: sha512-wnD1HyVqpJUI2+eKZ+eo1UwghftP6yuFheBqqe+bWCotBjC2K1YnteJILRMs3SM4V/0dLEW1SC27MWP5y+mwmw==}
|
||||||
|
|
||||||
|
|
@ -1116,10 +1095,6 @@ packages:
|
||||||
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
|
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
|
||||||
engines: {node: '>=8.0'}
|
engines: {node: '>=8.0'}
|
||||||
|
|
||||||
token-types@6.0.0:
|
|
||||||
resolution: {integrity: sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==}
|
|
||||||
engines: {node: '>=14.16'}
|
|
||||||
|
|
||||||
ts-api-utils@1.4.3:
|
ts-api-utils@1.4.3:
|
||||||
resolution: {integrity: sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==}
|
resolution: {integrity: sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==}
|
||||||
engines: {node: '>=16'}
|
engines: {node: '>=16'}
|
||||||
|
|
@ -1151,10 +1126,6 @@ packages:
|
||||||
engines: {node: '>=14.17'}
|
engines: {node: '>=14.17'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
uint8array-extras@1.4.0:
|
|
||||||
resolution: {integrity: sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==}
|
|
||||||
engines: {node: '>=18'}
|
|
||||||
|
|
||||||
undici-types@6.20.0:
|
undici-types@6.20.0:
|
||||||
resolution: {integrity: sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==}
|
resolution: {integrity: sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==}
|
||||||
|
|
||||||
|
|
@ -1562,16 +1533,6 @@ snapshots:
|
||||||
lodash.get: 4.4.2
|
lodash.get: 4.4.2
|
||||||
type-detect: 4.1.0
|
type-detect: 4.1.0
|
||||||
|
|
||||||
'@tokenizer/inflate@0.2.7':
|
|
||||||
dependencies:
|
|
||||||
debug: 4.4.0
|
|
||||||
fflate: 0.8.2
|
|
||||||
token-types: 6.0.0
|
|
||||||
transitivePeerDependencies:
|
|
||||||
- supports-color
|
|
||||||
|
|
||||||
'@tokenizer/token@0.3.0': {}
|
|
||||||
|
|
||||||
'@types/codemirror@5.60.8':
|
'@types/codemirror@5.60.8':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/tern': 0.23.9
|
'@types/tern': 0.23.9
|
||||||
|
|
@ -1710,6 +1671,8 @@ snapshots:
|
||||||
- '@codemirror/lint'
|
- '@codemirror/lint'
|
||||||
- '@codemirror/search'
|
- '@codemirror/search'
|
||||||
|
|
||||||
|
'@zip.js/zip.js@2.7.60': {}
|
||||||
|
|
||||||
acorn-jsx@5.3.2(acorn@8.14.0):
|
acorn-jsx@5.3.2(acorn@8.14.0):
|
||||||
dependencies:
|
dependencies:
|
||||||
acorn: 8.14.0
|
acorn: 8.14.0
|
||||||
|
|
@ -1935,21 +1898,10 @@ snapshots:
|
||||||
dependencies:
|
dependencies:
|
||||||
reusify: 1.0.4
|
reusify: 1.0.4
|
||||||
|
|
||||||
fflate@0.8.2: {}
|
|
||||||
|
|
||||||
file-entry-cache@8.0.0:
|
file-entry-cache@8.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
flat-cache: 4.0.1
|
flat-cache: 4.0.1
|
||||||
|
|
||||||
file-type@20.4.1:
|
|
||||||
dependencies:
|
|
||||||
'@tokenizer/inflate': 0.2.7
|
|
||||||
strtok3: 10.2.2
|
|
||||||
token-types: 6.0.0
|
|
||||||
uint8array-extras: 1.4.0
|
|
||||||
transitivePeerDependencies:
|
|
||||||
- supports-color
|
|
||||||
|
|
||||||
fill-keys@1.0.2:
|
fill-keys@1.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
is-object: 1.0.2
|
is-object: 1.0.2
|
||||||
|
|
@ -1998,8 +1950,6 @@ snapshots:
|
||||||
dependencies:
|
dependencies:
|
||||||
function-bind: 1.1.2
|
function-bind: 1.1.2
|
||||||
|
|
||||||
ieee754@1.2.1: {}
|
|
||||||
|
|
||||||
ignore@5.3.2: {}
|
ignore@5.3.2: {}
|
||||||
|
|
||||||
import-fresh@3.3.0:
|
import-fresh@3.3.0:
|
||||||
|
|
@ -2118,8 +2068,6 @@ snapshots:
|
||||||
|
|
||||||
path-parse@1.0.7: {}
|
path-parse@1.0.7: {}
|
||||||
|
|
||||||
peek-readable@7.0.0: {}
|
|
||||||
|
|
||||||
picocolors@1.1.1:
|
picocolors@1.1.1:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
|
@ -2194,11 +2142,6 @@ snapshots:
|
||||||
|
|
||||||
strip-json-comments@3.1.1: {}
|
strip-json-comments@3.1.1: {}
|
||||||
|
|
||||||
strtok3@10.2.2:
|
|
||||||
dependencies:
|
|
||||||
'@tokenizer/token': 0.3.0
|
|
||||||
peek-readable: 7.0.0
|
|
||||||
|
|
||||||
style-mod@4.1.2: {}
|
style-mod@4.1.2: {}
|
||||||
|
|
||||||
supports-color@7.2.0:
|
supports-color@7.2.0:
|
||||||
|
|
@ -2211,11 +2154,6 @@ snapshots:
|
||||||
dependencies:
|
dependencies:
|
||||||
is-number: 7.0.0
|
is-number: 7.0.0
|
||||||
|
|
||||||
token-types@6.0.0:
|
|
||||||
dependencies:
|
|
||||||
'@tokenizer/token': 0.3.0
|
|
||||||
ieee754: 1.2.1
|
|
||||||
|
|
||||||
ts-api-utils@1.4.3(typescript@5.7.2):
|
ts-api-utils@1.4.3(typescript@5.7.2):
|
||||||
dependencies:
|
dependencies:
|
||||||
typescript: 5.7.2
|
typescript: 5.7.2
|
||||||
|
|
@ -2239,8 +2177,6 @@ snapshots:
|
||||||
|
|
||||||
typescript@5.7.2: {}
|
typescript@5.7.2: {}
|
||||||
|
|
||||||
uint8array-extras@1.4.0: {}
|
|
||||||
|
|
||||||
undici-types@6.20.0: {}
|
undici-types@6.20.0: {}
|
||||||
|
|
||||||
uri-js@4.4.1:
|
uri-js@4.4.1:
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Vault, TAbstractFile, TFolder, EventRef } from "obsidian";
|
import { Vault, TAbstractFile, TFolder } from "obsidian";
|
||||||
import MetadataStore, { MANIFEST_FILE_NAME } from "./metadata-store";
|
import MetadataStore, { MANIFEST_FILE_NAME } from "./metadata-store";
|
||||||
import { GitHubSyncSettings } from "./settings/settings";
|
import { GitHubSyncSettings } from "./settings/settings";
|
||||||
import Logger from "./logger";
|
import Logger, { LOG_FILE_NAME } from "./logger";
|
||||||
import GitHubSyncPlugin from "./main";
|
import GitHubSyncPlugin from "./main";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -145,6 +145,9 @@ export default class EventsListener {
|
||||||
) {
|
) {
|
||||||
// Obsidian recommends not syncing the workspace files
|
// Obsidian recommends not syncing the workspace files
|
||||||
return false;
|
return false;
|
||||||
|
} else if (filePath === `${this.vault.configDir}/${LOG_FILE_NAME}`) {
|
||||||
|
// Don't sync the log file, doesn't make sense
|
||||||
|
return false;
|
||||||
} else if (
|
} else if (
|
||||||
this.settings.syncConfigDir &&
|
this.settings.syncConfigDir &&
|
||||||
filePath.startsWith(this.vault.configDir)
|
filePath.startsWith(this.vault.configDir)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { requestUrl } from "obsidian";
|
import { requestUrl } from "obsidian";
|
||||||
import Logger from "src/logger";
|
import Logger from "src/logger";
|
||||||
import { GitHubSyncSettings } from "src/settings/settings";
|
import { GitHubSyncSettings } from "src/settings/settings";
|
||||||
|
import { retryUntil } from "src/utils";
|
||||||
|
|
||||||
export type RepoContent = {
|
export type RepoContent = {
|
||||||
files: { [key: string]: GetTreeResponseItem };
|
files: { [key: string]: GetTreeResponseItem };
|
||||||
|
|
@ -75,22 +76,35 @@ export default class GithubClient {
|
||||||
/**
|
/**
|
||||||
* Gets the content of the repo.
|
* Gets the content of the repo.
|
||||||
*
|
*
|
||||||
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
* @returns Array of files in the directory in the remote repo
|
* @returns Array of files in the directory in the remote repo
|
||||||
*/
|
*/
|
||||||
async getRepoContent(): Promise<RepoContent> {
|
async getRepoContent({
|
||||||
const res = await requestUrl({
|
retry = false,
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/trees/${this.settings.githubBranch}?recursive=1`,
|
maxRetries = 5,
|
||||||
headers: this.headers(),
|
} = {}): Promise<RepoContent> {
|
||||||
throw: false,
|
const response = await retryUntil(
|
||||||
});
|
async () => {
|
||||||
if (res.status < 200 || res.status >= 400) {
|
return requestUrl({
|
||||||
await this.logger.error("Failed to get repo content", res);
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/trees/${this.settings.githubBranch}?recursive=1`,
|
||||||
|
headers: this.headers(),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422, // Retry condition: only retry on 422 status
|
||||||
|
retry ? maxRetries : 0, // Use 0 retries if retry is false
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to get repo content", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to get repo content, status ${res.status}`,
|
`Failed to get repo content, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const files = res.json.tree
|
|
||||||
|
const files = response.json.tree
|
||||||
.filter((file: GetTreeResponseItem) => file.type === "blob")
|
.filter((file: GetTreeResponseItem) => file.type === "blob")
|
||||||
.reduce(
|
.reduce(
|
||||||
(
|
(
|
||||||
|
|
@ -99,80 +113,168 @@ export default class GithubClient {
|
||||||
) => ({ ...acc, [file.path]: file }),
|
) => ({ ...acc, [file.path]: file }),
|
||||||
{},
|
{},
|
||||||
);
|
);
|
||||||
return { files, sha: res.json.sha };
|
return { files, sha: response.json.sha };
|
||||||
}
|
}
|
||||||
|
|
||||||
async createTree(tree: { tree: NewTreeRequestItem[]; base_tree: string }) {
|
/**
|
||||||
const res = await requestUrl({
|
* Creates a new tree in the GitHub repository.
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/trees`,
|
*
|
||||||
headers: this.headers(),
|
* @param tree The tree object to create
|
||||||
method: "POST",
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
body: JSON.stringify(tree),
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
throw: false,
|
* @returns The SHA of the created tree
|
||||||
});
|
*/
|
||||||
if (res.status < 200 || res.status >= 400) {
|
async createTree({
|
||||||
await this.logger.error("Failed to create tree", res);
|
tree,
|
||||||
|
retry = false,
|
||||||
|
maxRetries = 5,
|
||||||
|
}: {
|
||||||
|
tree: { tree: NewTreeRequestItem[]; base_tree: string };
|
||||||
|
retry?: boolean;
|
||||||
|
maxRetries?: number;
|
||||||
|
}) {
|
||||||
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/trees`,
|
||||||
|
headers: this.headers(),
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(tree),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to create tree", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to create tree, status ${res.status}`,
|
`Failed to create tree, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return res.json.sha;
|
return response.json.sha;
|
||||||
}
|
}
|
||||||
|
|
||||||
async createCommit(message: string, treeSha: string, parent: string) {
|
/**
|
||||||
const res = await requestUrl({
|
* Creates a new commit in the repository.
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/commits`,
|
*
|
||||||
headers: this.headers(),
|
* @param message The commit message
|
||||||
method: "POST",
|
* @param treeSha The SHA of the tree
|
||||||
body: JSON.stringify({
|
* @param parent The SHA of the parent commit
|
||||||
message: message,
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
tree: treeSha,
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
parents: [parent],
|
* @returns The SHA of the created commit
|
||||||
}),
|
*/
|
||||||
throw: false,
|
async createCommit({
|
||||||
});
|
message,
|
||||||
if (res.status < 200 || res.status >= 400) {
|
treeSha,
|
||||||
await this.logger.error("Failed to create commit", res);
|
parent,
|
||||||
|
retry = false,
|
||||||
|
maxRetries = 5,
|
||||||
|
}: {
|
||||||
|
message: string;
|
||||||
|
treeSha: string;
|
||||||
|
parent: string;
|
||||||
|
retry?: boolean;
|
||||||
|
maxRetries?: number;
|
||||||
|
}): Promise<string> {
|
||||||
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/commits`,
|
||||||
|
headers: this.headers(),
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: message,
|
||||||
|
tree: treeSha,
|
||||||
|
parents: [parent],
|
||||||
|
}),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to create commit", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to create commit, status ${res.status}`,
|
`Failed to create commit, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return res.json.sha;
|
return response.json.sha;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getBranchHeadSha() {
|
/**
|
||||||
const res = await requestUrl({
|
* Gets the SHA of the branch head.
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/refs/heads/${this.settings.githubBranch}`,
|
*
|
||||||
headers: this.headers(),
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
throw: false,
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
});
|
* @returns The SHA of the branch head
|
||||||
if (res.status < 200 || res.status >= 400) {
|
*/
|
||||||
await this.logger.error("Failed to get branch head sha", res);
|
async getBranchHeadSha({ retry = false, maxRetries = 5 } = {}) {
|
||||||
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/refs/heads/${this.settings.githubBranch}`,
|
||||||
|
headers: this.headers(),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to get branch head sha", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to get branch head sha, status ${res.status}`,
|
`Failed to get branch head sha, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return res.json.object.sha;
|
return response.json.object.sha;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateBranchHead(sha: string) {
|
/**
|
||||||
const res = await requestUrl({
|
* Updates the branch head to point to a new commit.
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/refs/heads/${this.settings.githubBranch}`,
|
*
|
||||||
headers: this.headers(),
|
* @param sha The SHA of the commit to point to
|
||||||
method: "PATCH",
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
body: JSON.stringify({
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
sha: sha,
|
*/
|
||||||
}),
|
async updateBranchHead({
|
||||||
throw: false,
|
sha,
|
||||||
});
|
retry = false,
|
||||||
if (res.status < 200 || res.status >= 400) {
|
maxRetries = 5,
|
||||||
await this.logger.error("Failed to update branch head sha", res);
|
}: {
|
||||||
|
sha: string;
|
||||||
|
retry?: boolean;
|
||||||
|
maxRetries?: number;
|
||||||
|
}) {
|
||||||
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/refs/heads/${this.settings.githubBranch}`,
|
||||||
|
headers: this.headers(),
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({
|
||||||
|
sha: sha,
|
||||||
|
}),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to update branch head sha", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to update branch head sha, status ${res.status}`,
|
`Failed to update branch head sha, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -182,76 +284,166 @@ export default class GithubClient {
|
||||||
*
|
*
|
||||||
* @param content The content of the blob to upload
|
* @param content The content of the blob to upload
|
||||||
* @param encoding Content encoding, can be "utf-8" or "base64". Defaults to "base64"
|
* @param encoding Content encoding, can be "utf-8" or "base64". Defaults to "base64"
|
||||||
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
* @returns The SHA of the newly uploaded blob
|
* @returns The SHA of the newly uploaded blob
|
||||||
*/
|
*/
|
||||||
async createBlob(
|
async createBlob({
|
||||||
content: string,
|
content,
|
||||||
encoding: "utf-8" | "base64" = "base64",
|
encoding = "base64",
|
||||||
): Promise<CreatedBlob> {
|
retry = false,
|
||||||
const res = await requestUrl({
|
maxRetries = 5,
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/blobs`,
|
}: {
|
||||||
headers: this.headers(),
|
content: string;
|
||||||
method: "POST",
|
encoding?: "utf-8" | "base64";
|
||||||
body: JSON.stringify({ content, encoding }),
|
retry?: boolean;
|
||||||
throw: false,
|
maxRetries?: number;
|
||||||
});
|
}): Promise<CreatedBlob> {
|
||||||
if (res.status < 200 || res.status >= 400) {
|
const response = await retryUntil(
|
||||||
await this.logger.error("Failed to create blob", res);
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/blobs`,
|
||||||
|
headers: this.headers(),
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ content, encoding }),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to create blob", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to create blob, status ${res.status}`,
|
`Failed to create blob, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
sha: res.json["sha"],
|
sha: response.json["sha"],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a blob from its sha
|
* Gets a blob from its sha
|
||||||
* @param url blob sha
|
*
|
||||||
|
* @param sha The SHA of the blob
|
||||||
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
|
* @returns The blob file
|
||||||
*/
|
*/
|
||||||
async getBlob(sha: string): Promise<BlobFile> {
|
async getBlob({
|
||||||
const res = await requestUrl({
|
sha,
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/blobs/${sha}`,
|
retry = false,
|
||||||
headers: this.headers(),
|
maxRetries = 5,
|
||||||
throw: false,
|
}: {
|
||||||
});
|
sha: string;
|
||||||
if (res.status < 200 || res.status >= 400) {
|
retry?: boolean;
|
||||||
await this.logger.error("Failed to get blob", res);
|
maxRetries?: number;
|
||||||
|
}): Promise<BlobFile> {
|
||||||
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/git/blobs/${sha}`,
|
||||||
|
headers: this.headers(),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to get blob", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to get blob, status ${res.status}`,
|
`Failed to get blob, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return res.json;
|
return response.json;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new file in the repo, the content must be base64 encoded or the request will fail.
|
* Create a new file in the repo, the content must be base64 encoded or the request will fail.
|
||||||
*
|
*
|
||||||
* @param message commit message
|
* @param path Path to create in the repo
|
||||||
* @param path path to create in the repo
|
* @param content Base64 encoded content of the file
|
||||||
* @param content base64 encoded content of the file
|
* @param message Commit message
|
||||||
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
*/
|
*/
|
||||||
async createFile(path: string, content: string, message: string) {
|
async createFile({
|
||||||
const res = await requestUrl({
|
path,
|
||||||
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/contents/${path}`,
|
content,
|
||||||
headers: this.headers(),
|
message,
|
||||||
method: "PUT",
|
retry = false,
|
||||||
body: JSON.stringify({
|
maxRetries = 5,
|
||||||
message: message,
|
}: {
|
||||||
content: content,
|
path: string;
|
||||||
branch: this.settings.githubBranch,
|
content: string;
|
||||||
}),
|
message: string;
|
||||||
throw: false,
|
retry?: boolean;
|
||||||
});
|
maxRetries?: number;
|
||||||
if (res.status < 200 || res.status >= 400) {
|
}) {
|
||||||
await this.logger.error("Failed to create file", res);
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/contents/${path}`,
|
||||||
|
headers: this.headers(),
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: message,
|
||||||
|
content: content,
|
||||||
|
branch: this.settings.githubBranch,
|
||||||
|
}),
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to create file", response);
|
||||||
throw new GithubAPIError(
|
throw new GithubAPIError(
|
||||||
res.status,
|
response.status,
|
||||||
`Failed to create file, status ${res.status}`,
|
`Failed to create file, status ${response.status}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Downloads the repository as a ZIP archive from GitHub.
|
||||||
|
*
|
||||||
|
* @param retry Whether to retry the request on failure (default: false)
|
||||||
|
* @param maxRetries Maximum number of retry attempts (default: 5)
|
||||||
|
* @returns The archive contents as an ArrayBuffer
|
||||||
|
*/
|
||||||
|
async downloadRepositoryArchive({
|
||||||
|
retry = false,
|
||||||
|
maxRetries = 5,
|
||||||
|
} = {}): Promise<ArrayBuffer> {
|
||||||
|
const response = await retryUntil(
|
||||||
|
async () => {
|
||||||
|
return requestUrl({
|
||||||
|
url: `https://api.github.com/repos/${this.settings.githubOwner}/${this.settings.githubRepo}/zipball/${this.settings.githubBranch}`,
|
||||||
|
headers: this.headers(),
|
||||||
|
method: "GET",
|
||||||
|
throw: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
(res) => res.status !== 422,
|
||||||
|
retry ? maxRetries : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.status < 200 || response.status >= 400) {
|
||||||
|
await this.logger.error("Failed to download zip archive", response);
|
||||||
|
throw new GithubAPIError(
|
||||||
|
response.status,
|
||||||
|
`Failed to download zip archive, status ${response.status}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return response.arrayBuffer;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { Vault, normalizePath } from "obsidian";
|
import { Vault, normalizePath } from "obsidian";
|
||||||
|
|
||||||
const LOG_FILE_NAME = "github-sync.log" as const;
|
export const LOG_FILE_NAME = "github-sync.log" as const;
|
||||||
|
|
||||||
export default class Logger {
|
export default class Logger {
|
||||||
private logFile: string;
|
private logFile: string;
|
||||||
|
|
@ -40,6 +40,14 @@ export default class Logger {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async read(): Promise<string> {
|
||||||
|
return await this.vault.adapter.read(this.logFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
async clean(): Promise<void> {
|
||||||
|
return await this.vault.adapter.write(this.logFile, "");
|
||||||
|
}
|
||||||
|
|
||||||
enable(): void {
|
enable(): void {
|
||||||
this.enabled = true;
|
this.enabled = true;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
16
src/main.ts
16
src/main.ts
|
|
@ -152,9 +152,19 @@ export default class GitHubSyncPlugin extends Plugin {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.settings.firstSync) {
|
if (this.settings.firstSync) {
|
||||||
await this.syncManager.firstSync();
|
const notice = new Notice("Syncing...");
|
||||||
this.settings.firstSync = false;
|
try {
|
||||||
this.saveSettings();
|
await this.syncManager.firstSync();
|
||||||
|
this.settings.firstSync = false;
|
||||||
|
this.saveSettings();
|
||||||
|
// Shown only if sync doesn't fail
|
||||||
|
new Notice("Sync successful", 5000);
|
||||||
|
} catch (err) {
|
||||||
|
// Show the error to the user, it's not automatically dismissed to make sure
|
||||||
|
// the user sees it.
|
||||||
|
new Notice(`Error syncing. ${err}`);
|
||||||
|
}
|
||||||
|
notice.hide();
|
||||||
} else {
|
} else {
|
||||||
await this.syncManager.sync();
|
await this.syncManager.sync();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,13 @@
|
||||||
import { PluginSettingTab, App, Setting, TextComponent, Modal } from "obsidian";
|
import {
|
||||||
|
PluginSettingTab,
|
||||||
|
App,
|
||||||
|
Setting,
|
||||||
|
TextComponent,
|
||||||
|
Modal,
|
||||||
|
Notice,
|
||||||
|
} from "obsidian";
|
||||||
import GitHubSyncPlugin from "src/main";
|
import GitHubSyncPlugin from "src/main";
|
||||||
|
import { copyToClipboard } from "src/utils";
|
||||||
|
|
||||||
export default class GitHubSyncSettingsTab extends PluginSettingTab {
|
export default class GitHubSyncSettingsTab extends PluginSettingTab {
|
||||||
plugin: GitHubSyncPlugin;
|
plugin: GitHubSyncPlugin;
|
||||||
|
|
@ -268,6 +276,30 @@ export default class GitHubSyncSettingsTab extends PluginSettingTab {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName("Copy logs")
|
||||||
|
.setDesc("Copy the log file content, this is useful to report bugs.")
|
||||||
|
.addButton((button) => {
|
||||||
|
button.setButtonText("Copy").onClick(async () => {
|
||||||
|
const logs: string = await this.plugin.logger.read();
|
||||||
|
try {
|
||||||
|
await copyToClipboard(logs);
|
||||||
|
new Notice("Logs copied", 5000);
|
||||||
|
} catch (err) {
|
||||||
|
new Notice(`Failed copying logs: ${err}`, 10000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
new Setting(containerEl)
|
||||||
|
.setName("Clean logs")
|
||||||
|
.setDesc("Delete all existing logs.")
|
||||||
|
.addButton((button) => {
|
||||||
|
button.setButtonText("Clean").onClick(async () => {
|
||||||
|
await this.plugin.logger.clean();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
new Setting(containerEl)
|
new Setting(containerEl)
|
||||||
.setName("Reset")
|
.setName("Reset")
|
||||||
.setDesc("Reset the plugin settings and metadata")
|
.setDesc("Reset the plugin settings and metadata")
|
||||||
|
|
|
||||||
|
|
@ -17,10 +17,10 @@ import MetadataStore, {
|
||||||
} from "./metadata-store";
|
} from "./metadata-store";
|
||||||
import EventsListener from "./events-listener";
|
import EventsListener from "./events-listener";
|
||||||
import { GitHubSyncSettings } from "./settings/settings";
|
import { GitHubSyncSettings } from "./settings/settings";
|
||||||
import Logger from "./logger";
|
import Logger, { LOG_FILE_NAME } from "./logger";
|
||||||
import { decodeBase64String } from "./utils";
|
import { decodeBase64String, hasTextExtension } from "./utils";
|
||||||
import GitHubSyncPlugin from "./main";
|
import GitHubSyncPlugin from "./main";
|
||||||
import { fileTypeFromBuffer } from "file-type";
|
import { BlobReader, Entry, Uint8ArrayWriter, ZipReader } from "@zip.js/zip.js";
|
||||||
|
|
||||||
interface SyncAction {
|
interface SyncAction {
|
||||||
type: "upload" | "download" | "delete_local" | "delete_remote";
|
type: "upload" | "download" | "delete_local" | "delete_remote";
|
||||||
|
|
@ -95,19 +95,14 @@ export default class SyncManager {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const notice = new Notice("Syncing...");
|
|
||||||
this.syncing = true;
|
this.syncing = true;
|
||||||
try {
|
try {
|
||||||
await this.firstSyncImpl();
|
await this.firstSyncImpl();
|
||||||
// Shown only if sync doesn't fail
|
|
||||||
new Notice("Sync successful", 5000);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Show the error to the user, it's not automatically dismissed to make sure
|
this.syncing = false;
|
||||||
// the user sees it.
|
throw err;
|
||||||
new Notice(`Error syncing. ${err}`);
|
|
||||||
}
|
}
|
||||||
this.syncing = false;
|
this.syncing = false;
|
||||||
notice.hide();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async firstSyncImpl() {
|
private async firstSyncImpl() {
|
||||||
|
|
@ -142,14 +137,18 @@ export default class SyncManager {
|
||||||
// API doesn't let us create a new tree when the repo is empty.
|
// API doesn't let us create a new tree when the repo is empty.
|
||||||
// So we create a the manifest file as the first commit, since we're going
|
// So we create a the manifest file as the first commit, since we're going
|
||||||
// to create that in any case right after this.
|
// to create that in any case right after this.
|
||||||
await this.client.createFile(
|
const buffer = await this.vault.adapter.readBinary(
|
||||||
`${this.vault.configDir}/${MANIFEST_FILE_NAME}`,
|
normalizePath(`${this.vault.configDir}/${MANIFEST_FILE_NAME}`),
|
||||||
"",
|
|
||||||
"First sync",
|
|
||||||
);
|
);
|
||||||
|
await this.client.createFile({
|
||||||
|
path: `${this.vault.configDir}/${MANIFEST_FILE_NAME}`,
|
||||||
|
content: arrayBufferToBase64(buffer),
|
||||||
|
message: "First sync",
|
||||||
|
retry: true,
|
||||||
|
});
|
||||||
// Now get the repo content again cause we know for sure it will return a
|
// Now get the repo content again cause we know for sure it will return a
|
||||||
// valid sha that we can use to create the first sync commit.
|
// valid sha that we can use to create the first sync commit.
|
||||||
res = await this.client.getRepoContent();
|
res = await this.client.getRepoContent({ retry: true });
|
||||||
files = res.files;
|
files = res.files;
|
||||||
treeSha = res.sha;
|
treeSha = res.sha;
|
||||||
}
|
}
|
||||||
|
|
@ -187,24 +186,98 @@ export default class SyncManager {
|
||||||
treeSha: string,
|
treeSha: string,
|
||||||
) {
|
) {
|
||||||
await this.logger.info("Starting first sync from remote files");
|
await this.logger.info("Starting first sync from remote files");
|
||||||
|
|
||||||
|
// We want to avoid getting throttled by GitHub, so instead of making a request for each
|
||||||
|
// file we download the whole repository as a ZIP file and extract it in the vault.
|
||||||
|
// We exclude config dir files if the user doesn't want to sync those.
|
||||||
|
const zipBuffer = await this.client.downloadRepositoryArchive();
|
||||||
|
const zipBlob = new Blob([zipBuffer]);
|
||||||
|
const reader = new ZipReader(new BlobReader(zipBlob));
|
||||||
|
const entries = await reader.getEntries();
|
||||||
|
|
||||||
|
await this.logger.info("Extracting files from ZIP", {
|
||||||
|
length: entries.length,
|
||||||
|
});
|
||||||
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
Object.keys(files)
|
entries.map(async (entry: Entry) => {
|
||||||
.filter((filePath: string) => {
|
// All repo ZIPs contain a root directory that contains all the content
|
||||||
if (
|
// of that repo, we need to ignore that directory so we strip the first
|
||||||
this.settings.syncConfigDir &&
|
// folder segment from the path
|
||||||
filePath.startsWith(this.vault.configDir) &&
|
const pathParts = entry.filename.split("/");
|
||||||
filePath !== `${this.vault.configDir}/${MANIFEST_FILE_NAME}`
|
const targetPath =
|
||||||
) {
|
pathParts.length > 1 ? pathParts.slice(1).join("/") : entry.filename;
|
||||||
// Include files in the config dir only if the user has enabled it.
|
|
||||||
// The metadata file must always be synced.
|
if (targetPath === "") {
|
||||||
return false;
|
// Must be the root folder, skip it.
|
||||||
}
|
// This is really important as that would lead us to try and
|
||||||
return true;
|
// create the folder "/" and crash Obsidian
|
||||||
})
|
return;
|
||||||
.map(async (filePath: string) => {
|
}
|
||||||
await this.downloadFile(files[filePath], Date.now());
|
|
||||||
}),
|
if (
|
||||||
|
this.settings.syncConfigDir &&
|
||||||
|
targetPath.startsWith(this.vault.configDir) &&
|
||||||
|
targetPath !== `${this.vault.configDir}/${MANIFEST_FILE_NAME}`
|
||||||
|
) {
|
||||||
|
await this.logger.info("Skipped config", { targetPath });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entry.directory) {
|
||||||
|
const normalizedPath = normalizePath(targetPath);
|
||||||
|
await this.vault.adapter.mkdir(normalizedPath);
|
||||||
|
await this.logger.info("Created directory", {
|
||||||
|
normalizedPath,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetPath === `${this.vault.configDir}/${LOG_FILE_NAME}`) {
|
||||||
|
// We don't want to download the log file if the user synced it in the past.
|
||||||
|
// This is necessary because in the past we forgot to ignore the log file
|
||||||
|
// from syncing if the user enabled configs sync.
|
||||||
|
// To avoid downloading it we ignore it if still present in the remote repo.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetPath.split("/").last()?.startsWith(".")) {
|
||||||
|
// We must skip hidden files as that creates issues with syncing.
|
||||||
|
// This is fine as users can't edit hidden files in Obsidian anyway.
|
||||||
|
await this.logger.info("Skipping hidden file", targetPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const writer = new Uint8ArrayWriter();
|
||||||
|
await entry.getData!(writer);
|
||||||
|
const data = await writer.getData();
|
||||||
|
const dir = targetPath.split("/").splice(0, -1).join("/");
|
||||||
|
if (dir !== "") {
|
||||||
|
const normalizedDir = normalizePath(dir);
|
||||||
|
await this.vault.adapter.mkdir(normalizedDir);
|
||||||
|
await this.logger.info("Created directory", {
|
||||||
|
normalizedDir,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedPath = normalizePath(targetPath);
|
||||||
|
await this.vault.adapter.writeBinary(normalizedPath, data);
|
||||||
|
await this.logger.info("Written file", {
|
||||||
|
normalizedPath,
|
||||||
|
});
|
||||||
|
this.metadataStore.data.files[normalizedPath] = {
|
||||||
|
path: normalizedPath,
|
||||||
|
sha: files[normalizedPath].sha,
|
||||||
|
dirty: false,
|
||||||
|
justDownloaded: true,
|
||||||
|
lastModified: Date.now(),
|
||||||
|
};
|
||||||
|
await this.metadataStore.save();
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
await this.logger.info("Extracted zip");
|
||||||
|
|
||||||
const newTreeFiles = Object.keys(files)
|
const newTreeFiles = Object.keys(files)
|
||||||
.map((filePath: string) => ({
|
.map((filePath: string) => ({
|
||||||
path: files[filePath].path,
|
path: files[filePath].path,
|
||||||
|
|
@ -221,18 +294,33 @@ export default class SyncManager {
|
||||||
);
|
);
|
||||||
// Add files that are in the manifest but not in the tree.
|
// Add files that are in the manifest but not in the tree.
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
Object.keys(this.metadataStore.data.files).map(
|
Object.keys(this.metadataStore.data.files)
|
||||||
async (filePath: string) => {
|
.filter((filePath: string) => {
|
||||||
|
return !Object.keys(files).contains(filePath);
|
||||||
|
})
|
||||||
|
.map(async (filePath: string) => {
|
||||||
const normalizedPath = normalizePath(filePath);
|
const normalizedPath = normalizePath(filePath);
|
||||||
const content = await this.vault.adapter.read(normalizedPath);
|
// We need to check whether the file is a text file or not before
|
||||||
|
// reading it here because trying to read a binary file as text fails
|
||||||
|
// on iOS, and probably on other mobile devices too, so we read the file
|
||||||
|
// content only if we're sure it contains text only.
|
||||||
|
//
|
||||||
|
// It's fine not reading the binary file in here and just setting some bogus
|
||||||
|
// content because when committing the sync we're going to read the binary
|
||||||
|
// file and upload its blob if it needs to be synced. The important thing is
|
||||||
|
// that some content is set so we know the file changed locally and needs to be
|
||||||
|
// uploaded.
|
||||||
|
let content = "binaryfile";
|
||||||
|
if (hasTextExtension(normalizedPath)) {
|
||||||
|
content = await this.vault.adapter.read(normalizedPath);
|
||||||
|
}
|
||||||
newTreeFiles[filePath] = {
|
newTreeFiles[filePath] = {
|
||||||
path: filePath,
|
path: filePath,
|
||||||
mode: "100644",
|
mode: "100644",
|
||||||
type: "blob",
|
type: "blob",
|
||||||
content: content,
|
content,
|
||||||
};
|
};
|
||||||
},
|
}),
|
||||||
),
|
|
||||||
);
|
);
|
||||||
await this.commitSync(newTreeFiles, treeSha);
|
await this.commitSync(newTreeFiles, treeSha);
|
||||||
}
|
}
|
||||||
|
|
@ -265,18 +353,36 @@ export default class SyncManager {
|
||||||
{},
|
{},
|
||||||
);
|
);
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
Object.keys(this.metadataStore.data.files).map(
|
Object.keys(this.metadataStore.data.files)
|
||||||
async (filePath: string) => {
|
.filter((filePath: string) => {
|
||||||
|
// We should not try to sync deleted files, this can happen when
|
||||||
|
// the user renames or deletes files after enabling the plugin but
|
||||||
|
// before syncing for the first time
|
||||||
|
return !this.metadataStore.data.files[filePath].deleted;
|
||||||
|
})
|
||||||
|
.map(async (filePath: string) => {
|
||||||
const normalizedPath = normalizePath(filePath);
|
const normalizedPath = normalizePath(filePath);
|
||||||
const content = await this.vault.adapter.read(normalizedPath);
|
// We need to check whether the file is a text file or not before
|
||||||
|
// reading it here because trying to read a binary file as text fails
|
||||||
|
// on iOS, and probably on other mobile devices too, so we read the file
|
||||||
|
// content only if we're sure it contains text only.
|
||||||
|
//
|
||||||
|
// It's fine not reading the binary file in here and just setting some bogus
|
||||||
|
// content because when committing the sync we're going to read the binary
|
||||||
|
// file and upload its blob if it needs to be synced. The important thing is
|
||||||
|
// that some content is set so we know the file changed locally and needs to be
|
||||||
|
// uploaded.
|
||||||
|
let content = "binaryfile";
|
||||||
|
if (hasTextExtension(normalizedPath)) {
|
||||||
|
content = await this.vault.adapter.read(normalizedPath);
|
||||||
|
}
|
||||||
newTreeFiles[filePath] = {
|
newTreeFiles[filePath] = {
|
||||||
path: filePath,
|
path: filePath,
|
||||||
mode: "100644",
|
mode: "100644",
|
||||||
type: "blob",
|
type: "blob",
|
||||||
content: content,
|
content,
|
||||||
};
|
};
|
||||||
},
|
}),
|
||||||
),
|
|
||||||
);
|
);
|
||||||
await this.commitSync(newTreeFiles, treeSha);
|
await this.commitSync(newTreeFiles, treeSha);
|
||||||
}
|
}
|
||||||
|
|
@ -309,7 +415,9 @@ export default class SyncManager {
|
||||||
|
|
||||||
private async syncImpl() {
|
private async syncImpl() {
|
||||||
await this.logger.info("Starting sync");
|
await this.logger.info("Starting sync");
|
||||||
const { files, sha: treeSha } = await this.client.getRepoContent();
|
const { files, sha: treeSha } = await this.client.getRepoContent({
|
||||||
|
retry: true,
|
||||||
|
});
|
||||||
const manifest = files[`${this.vault.configDir}/${MANIFEST_FILE_NAME}`];
|
const manifest = files[`${this.vault.configDir}/${MANIFEST_FILE_NAME}`];
|
||||||
|
|
||||||
if (manifest === undefined) {
|
if (manifest === undefined) {
|
||||||
|
|
@ -317,7 +425,17 @@ export default class SyncManager {
|
||||||
throw new Error("Remote manifest is missing");
|
throw new Error("Remote manifest is missing");
|
||||||
}
|
}
|
||||||
|
|
||||||
const blob = await this.client.getBlob(manifest.sha);
|
if (
|
||||||
|
Object.keys(files).contains(`${this.vault.configDir}/${LOG_FILE_NAME}`)
|
||||||
|
) {
|
||||||
|
// We don't want to download the log file if the user synced it in the past.
|
||||||
|
// This is necessary because in the past we forgot to ignore the log file
|
||||||
|
// from syncing if the user enabled configs sync.
|
||||||
|
// To avoid downloading it we delete it if still around.
|
||||||
|
delete files[`${this.vault.configDir}/${LOG_FILE_NAME}`];
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = await this.client.getBlob({ sha: manifest.sha });
|
||||||
const remoteMetadata: Metadata = JSON.parse(
|
const remoteMetadata: Metadata = JSON.parse(
|
||||||
decodeBase64String(blob.content),
|
decodeBase64String(blob.content),
|
||||||
);
|
);
|
||||||
|
|
@ -513,9 +631,11 @@ export default class SyncManager {
|
||||||
// Load contents in parallel
|
// Load contents in parallel
|
||||||
const [remoteContent, localContent] = await Promise.all([
|
const [remoteContent, localContent] = await Promise.all([
|
||||||
await (async () => {
|
await (async () => {
|
||||||
const res = await this.client.getBlob(
|
const res = await this.client.getBlob({
|
||||||
filesMetadata[filePath].sha!,
|
sha: filesMetadata[filePath].sha!,
|
||||||
);
|
retry: true,
|
||||||
|
maxRetries: 1,
|
||||||
|
});
|
||||||
return decodeBase64String(res.content);
|
return decodeBase64String(res.content);
|
||||||
})(),
|
})(),
|
||||||
await this.vault.adapter.read(normalizePath(filePath)),
|
await this.vault.adapter.read(normalizePath(filePath)),
|
||||||
|
|
@ -580,16 +700,19 @@ export default class SyncManager {
|
||||||
type: "delete_local",
|
type: "delete_local",
|
||||||
filePath: filePath,
|
filePath: filePath,
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
} else if (
|
} else if (
|
||||||
localFile.lastModified > (remoteFile.deletedAt as number)
|
localFile.lastModified > (remoteFile.deletedAt as number)
|
||||||
) {
|
) {
|
||||||
actions.push({ type: "upload", filePath: filePath });
|
actions.push({ type: "upload", filePath: filePath });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!remoteFile.deleted && localFile.deleted) {
|
if (!remoteFile.deleted && localFile.deleted) {
|
||||||
if (remoteFile.lastModified > (localFile.deletedAt as number)) {
|
if (remoteFile.lastModified > (localFile.deletedAt as number)) {
|
||||||
actions.push({ type: "download", filePath: filePath });
|
actions.push({ type: "download", filePath: filePath });
|
||||||
|
return;
|
||||||
} else if (
|
} else if (
|
||||||
(localFile.deletedAt as number) > remoteFile.lastModified
|
(localFile.deletedAt as number) > remoteFile.lastModified
|
||||||
) {
|
) {
|
||||||
|
|
@ -597,6 +720,7 @@ export default class SyncManager {
|
||||||
type: "delete_remote",
|
type: "delete_remote",
|
||||||
filePath: filePath,
|
filePath: filePath,
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -604,8 +728,10 @@ export default class SyncManager {
|
||||||
// Conflicts are already filtered out so we can make this decision easily
|
// Conflicts are already filtered out so we can make this decision easily
|
||||||
if (localSHA !== localFile.sha) {
|
if (localSHA !== localFile.sha) {
|
||||||
actions.push({ type: "upload", filePath: filePath });
|
actions.push({ type: "upload", filePath: filePath });
|
||||||
|
return;
|
||||||
} else {
|
} else {
|
||||||
actions.push({ type: "download", filePath: filePath });
|
actions.push({ type: "download", filePath: filePath });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
@ -664,9 +790,13 @@ export default class SyncManager {
|
||||||
* This is the same identical algoritm used by git to calculate
|
* This is the same identical algoritm used by git to calculate
|
||||||
* a blob's SHA.
|
* a blob's SHA.
|
||||||
* @param filePath normalized path to file
|
* @param filePath normalized path to file
|
||||||
* @returns String containing the file SHA1
|
* @returns String containing the file SHA1 or null in case the file doesn't exist
|
||||||
*/
|
*/
|
||||||
async calculateSHA(filePath: string): Promise<string> {
|
async calculateSHA(filePath: string): Promise<string | null> {
|
||||||
|
if (!(await this.vault.adapter.exists(filePath))) {
|
||||||
|
// The file doesn't exist, can't calculate any SHA
|
||||||
|
return null;
|
||||||
|
}
|
||||||
const contentBuffer = await this.vault.adapter.readBinary(filePath);
|
const contentBuffer = await this.vault.adapter.readBinary(filePath);
|
||||||
const contentBytes = new Uint8Array(contentBuffer);
|
const contentBytes = new Uint8Array(contentBuffer);
|
||||||
const header = new TextEncoder().encode(`blob ${contentBytes.length}\0`);
|
const header = new TextEncoder().encode(`blob ${contentBytes.length}\0`);
|
||||||
|
|
@ -723,45 +853,29 @@ export default class SyncManager {
|
||||||
Object.keys(treeFiles)
|
Object.keys(treeFiles)
|
||||||
.filter((filePath: string) => treeFiles[filePath].content)
|
.filter((filePath: string) => treeFiles[filePath].content)
|
||||||
.map(async (filePath: string) => {
|
.map(async (filePath: string) => {
|
||||||
// Some Markdown or JSON files might grow to be quite big, that makes it
|
|
||||||
// impossible for the file-type library to guess their file type.
|
|
||||||
// It also increases the amount of memory used by A LOT and might cause
|
|
||||||
// issues in devices with low memory if there are lots of files to check.
|
|
||||||
//
|
|
||||||
// I don't fully trust file extensions as they're not completely reliable
|
// I don't fully trust file extensions as they're not completely reliable
|
||||||
// to determine the file type, though I feel it's ok to compromise and rely
|
// to determine the file type, though I feel it's ok to compromise and rely
|
||||||
// on them if it makes the plugin handle upload better on certain devices.
|
// on them if it makes the plugin handle upload better on certain devices.
|
||||||
if (filePath.endsWith(".md") || filePath.endsWith(".json")) {
|
if (hasTextExtension(filePath)) {
|
||||||
this.metadataStore.data.files[filePath].sha =
|
const sha = await this.calculateSHA(filePath);
|
||||||
await this.calculateSHA(filePath);
|
this.metadataStore.data.files[filePath].sha = sha;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// We can't upload binary files by setting the content of a tree item,
|
||||||
|
// we first need to create a Git blob by uploading the file, then
|
||||||
|
// we must update the tree item to point the SHA to the blob we just created.
|
||||||
const buffer = await this.vault.adapter.readBinary(filePath);
|
const buffer = await this.vault.adapter.readBinary(filePath);
|
||||||
const fileType = await fileTypeFromBuffer(buffer);
|
const { sha } = await this.client.createBlob({
|
||||||
let newSha = "";
|
content: arrayBufferToBase64(buffer),
|
||||||
if (
|
retry: true,
|
||||||
// We can't determine the file type
|
maxRetries: 3,
|
||||||
fileType === undefined ||
|
});
|
||||||
// This is not a text file
|
await this.logger.info("Created blob", filePath);
|
||||||
!fileType.mime.startsWith("text/") ||
|
treeFiles[filePath].sha = sha;
|
||||||
// Neither a json file
|
// Can't have both sha and content set, so we delete it
|
||||||
fileType.mime !== "application/json"
|
delete treeFiles[filePath].content;
|
||||||
) {
|
this.metadataStore.data.files[filePath].sha = sha;
|
||||||
// We treat this file as a binary file. We can't upload these setting the content
|
|
||||||
// of a tree item, we first need to create a Git blob by uploading the file, then
|
|
||||||
// we must update the tree item to point the SHA to the blob we just created.
|
|
||||||
const hash = arrayBufferToBase64(buffer);
|
|
||||||
const { sha } = await this.client.createBlob(hash);
|
|
||||||
treeFiles[filePath].sha = sha;
|
|
||||||
// Can't have both sha and content set, so we delete it
|
|
||||||
delete treeFiles[filePath].content;
|
|
||||||
newSha = sha;
|
|
||||||
} else {
|
|
||||||
// File is text, we can upload the content directly
|
|
||||||
// so we just calculate the new SHA to keep track of it
|
|
||||||
newSha = await this.calculateSHA(filePath);
|
|
||||||
}
|
|
||||||
this.metadataStore.data.files[filePath].sha = newSha;
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -777,18 +891,21 @@ export default class SyncManager {
|
||||||
),
|
),
|
||||||
base_tree: baseTreeSha,
|
base_tree: baseTreeSha,
|
||||||
};
|
};
|
||||||
const newTreeSha = await this.client.createTree(newTree);
|
const newTreeSha = await this.client.createTree({
|
||||||
|
tree: newTree,
|
||||||
|
retry: true,
|
||||||
|
});
|
||||||
|
|
||||||
const branchHeadSha = await this.client.getBranchHeadSha();
|
const branchHeadSha = await this.client.getBranchHeadSha({ retry: true });
|
||||||
|
|
||||||
const commitSha = await this.client.createCommit(
|
const commitSha = await this.client.createCommit({
|
||||||
// TODO: Make this configurable or find a nicer commit message
|
// TODO: Make this configurable or find a nicer commit message
|
||||||
"Sync",
|
message: "Sync",
|
||||||
newTreeSha,
|
treeSha: newTreeSha,
|
||||||
branchHeadSha,
|
parent: branchHeadSha,
|
||||||
);
|
});
|
||||||
|
|
||||||
await this.client.updateBranchHead(commitSha);
|
await this.client.updateBranchHead({ sha: commitSha, retry: true });
|
||||||
|
|
||||||
// Update the local content of all files that had conflicts we resolved
|
// Update the local content of all files that had conflicts we resolved
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
|
|
@ -815,7 +932,7 @@ export default class SyncManager {
|
||||||
// File already exists and has the same SHA, no need to download it again.
|
// File already exists and has the same SHA, no need to download it again.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const blob = await this.client.getBlob(file.sha);
|
const blob = await this.client.getBlob({ sha: file.sha, retry: true });
|
||||||
const normalizedPath = normalizePath(file.path);
|
const normalizedPath = normalizePath(file.path);
|
||||||
const fileFolder = normalizePath(
|
const fileFolder = normalizePath(
|
||||||
normalizedPath.split("/").slice(0, -1).join("/"),
|
normalizedPath.split("/").slice(0, -1).join("/"),
|
||||||
|
|
|
||||||
85
src/utils.ts
85
src/utils.ts
|
|
@ -1,5 +1,15 @@
|
||||||
import { base64ToArrayBuffer } from "obsidian";
|
import { base64ToArrayBuffer } from "obsidian";
|
||||||
|
|
||||||
|
const TEXT_EXTENSIONS = [
|
||||||
|
".css",
|
||||||
|
".md",
|
||||||
|
".json",
|
||||||
|
".txt",
|
||||||
|
".csv",
|
||||||
|
".js",
|
||||||
|
".log",
|
||||||
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decodes a base64 encoded string, this properly
|
* Decodes a base64 encoded string, this properly
|
||||||
* handles emojis and other non ASCII chars.
|
* handles emojis and other non ASCII chars.
|
||||||
|
|
@ -12,3 +22,78 @@ export function decodeBase64String(s: string): string {
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
return decoder.decode(buffer);
|
return decoder.decode(buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copies the provided text to the system clipboard.
|
||||||
|
* Uses the modern Clipboard API with a fallback to older APIs.
|
||||||
|
*
|
||||||
|
* @param text The string to be copied to clipboard
|
||||||
|
* @returns A promise that resolves when the text has been copied
|
||||||
|
*/
|
||||||
|
export async function copyToClipboard(text: string) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} catch (err) {
|
||||||
|
// Fallback for devices like iOS that don't support Clipboard API
|
||||||
|
const textarea = document.createElement("textarea");
|
||||||
|
textarea.value = text;
|
||||||
|
textarea.setAttribute("readonly", "");
|
||||||
|
textarea.style.position = "absolute";
|
||||||
|
textarea.style.left = "-9999px";
|
||||||
|
document.body.appendChild(textarea);
|
||||||
|
|
||||||
|
textarea.select();
|
||||||
|
document.execCommand("copy");
|
||||||
|
document.body.removeChild(textarea);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a file path has one of the predefined text extensions.
|
||||||
|
* This is a best guess at best.
|
||||||
|
*
|
||||||
|
* @param filePath The path of the file to check
|
||||||
|
* @returns True if the file has a text extension, false otherwise
|
||||||
|
*/
|
||||||
|
export function hasTextExtension(filePath: string) {
|
||||||
|
for (const extension of TEXT_EXTENSIONS) {
|
||||||
|
if (filePath.endsWith(extension)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retries an async function until its return value satisfies a condition or max retries is reached.
|
||||||
|
* Uses exponential backoff between retry attempts.
|
||||||
|
*
|
||||||
|
* @param fn - The async function to execute and potentially retry
|
||||||
|
* @param condition - Function that evaluates if the result is acceptable
|
||||||
|
* @param maxRetries - Maximum number of retry attempts (default: 5)
|
||||||
|
* @param initialDelay - Initial delay in ms before first retry (default: 1000)
|
||||||
|
* @param backoffFactor - Multiplicative factor for delay between retries (default: 2)
|
||||||
|
* @returns The result of the function execution
|
||||||
|
*/
|
||||||
|
export async function retryUntil<T>(
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
condition: (result: T) => boolean,
|
||||||
|
maxRetries: number = 5,
|
||||||
|
initialDelay: number = 1000,
|
||||||
|
backoffFactor: number = 2,
|
||||||
|
): Promise<T> {
|
||||||
|
let retries = 0;
|
||||||
|
let delay = initialDelay;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const result = await fn();
|
||||||
|
|
||||||
|
if (condition(result) || retries >= maxRetries) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
retries++;
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||||
|
delay *= backoffFactor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -175,7 +175,6 @@ const ActionsGutter: React.FC<ActionsGutterProps> = ({
|
||||||
style={{
|
style={{
|
||||||
width: "100%",
|
width: "100%",
|
||||||
height: "100%",
|
height: "100%",
|
||||||
overflow: "hidden",
|
|
||||||
position: "relative",
|
position: "relative",
|
||||||
backgroundColor: "var(--background-secondary)",
|
backgroundColor: "var(--background-secondary)",
|
||||||
}}
|
}}
|
||||||
|
|
|
||||||
|
|
@ -36,13 +36,11 @@ const DiffView: React.FC<DiffViewProps> = ({
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
width: "100%",
|
|
||||||
height: "100%",
|
height: "100%",
|
||||||
display: "flex",
|
display: "flex",
|
||||||
overflow: "hidden",
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div style={{ flex: 1, overflow: "hidden" }}>
|
<div style={{ flex: 1 }}>
|
||||||
<EditorPane
|
<EditorPane
|
||||||
content={remoteText}
|
content={remoteText}
|
||||||
highlightPluginSpec={{
|
highlightPluginSpec={{
|
||||||
|
|
@ -142,7 +140,7 @@ const DiffView: React.FC<DiffViewProps> = ({
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ flex: 1, overflow: "hidden" }}>
|
<div style={{ flex: 1 }}>
|
||||||
<EditorPane
|
<EditorPane
|
||||||
content={localText}
|
content={localText}
|
||||||
highlightPluginSpec={{
|
highlightPluginSpec={{
|
||||||
|
|
|
||||||
|
|
@ -46,9 +46,9 @@ const SplitView = ({
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
height: "100%",
|
|
||||||
display: "flex",
|
display: "flex",
|
||||||
flexDirection: "column",
|
flexDirection: "column",
|
||||||
|
height: "100%",
|
||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|
@ -88,21 +88,28 @@ const SplitView = ({
|
||||||
currentFile={currentFile?.filePath || ""}
|
currentFile={currentFile?.filePath || ""}
|
||||||
setCurrentFileIndex={setCurrentFileIndex}
|
setCurrentFileIndex={setCurrentFileIndex}
|
||||||
/>
|
/>
|
||||||
<DiffView
|
<div
|
||||||
remoteText={currentFile?.remoteContent || ""}
|
style={{
|
||||||
localText={currentFile?.localContent || ""}
|
overflow: "auto",
|
||||||
onRemoteTextChange={(content: string) => {
|
flex: 1,
|
||||||
const tempFiles = [...files];
|
|
||||||
tempFiles[currentFileIndex].remoteContent = content;
|
|
||||||
setFiles(tempFiles);
|
|
||||||
}}
|
}}
|
||||||
onLocalTextChange={(content: string) => {
|
>
|
||||||
const tempFiles = [...files];
|
<DiffView
|
||||||
tempFiles[currentFileIndex].localContent = content;
|
remoteText={currentFile?.remoteContent || ""}
|
||||||
setFiles(tempFiles);
|
localText={currentFile?.localContent || ""}
|
||||||
}}
|
onRemoteTextChange={(content: string) => {
|
||||||
onConflictResolved={onConflictResolved}
|
const tempFiles = [...files];
|
||||||
/>
|
tempFiles[currentFileIndex].remoteContent = content;
|
||||||
|
setFiles(tempFiles);
|
||||||
|
}}
|
||||||
|
onLocalTextChange={(content: string) => {
|
||||||
|
const tempFiles = [...files];
|
||||||
|
tempFiles[currentFileIndex].localContent = content;
|
||||||
|
setFiles(tempFiles);
|
||||||
|
}}
|
||||||
|
onConflictResolved={onConflictResolved}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -183,7 +183,15 @@ const DiffView: React.FC<DiffViewProps> = ({
|
||||||
}, [initialRemoteText, initialLocalText]);
|
}, [initialRemoteText, initialLocalText]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ width: "100%", height: "100%", overflow: "hidden" }}>
|
<div
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
<CodeMirror
|
<CodeMirror
|
||||||
value={doc}
|
value={doc}
|
||||||
height="100%"
|
height="100%"
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,8 @@ const UnifiedView = ({
|
||||||
paddingTop: "var(--size-4-4)",
|
paddingTop: "var(--size-4-4)",
|
||||||
paddingBottom: "var(--size-4-4)",
|
paddingBottom: "var(--size-4-4)",
|
||||||
borderBottom: "1px solid var(--background-modifier-border)",
|
borderBottom: "1px solid var(--background-modifier-border)",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
|
|
@ -67,7 +69,14 @@ const UnifiedView = ({
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<div>
|
<div
|
||||||
|
style={{
|
||||||
|
height: "100%",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
overflow: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
{files.length === 0 ? (
|
{files.length === 0 ? (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
|
|
|
||||||
|
|
@ -4,4 +4,6 @@
|
||||||
|
|
||||||
.padless-conflicts-view-container {
|
.padless-conflicts-view-container {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
|
height: 100%;
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,5 +12,6 @@
|
||||||
"1.0.3": "1.7.7",
|
"1.0.3": "1.7.7",
|
||||||
"1.0.4": "1.7.7",
|
"1.0.4": "1.7.7",
|
||||||
"1.0.5": "1.7.7",
|
"1.0.5": "1.7.7",
|
||||||
"1.0.6": "1.7.7"
|
"1.0.6": "1.7.7",
|
||||||
|
"1.0.7": "1.7.7"
|
||||||
}
|
}
|
||||||
Loading…
Reference in a new issue