Skip to content

Commit 7f30ee1

Browse files
committed
feat(path):use uniformed path handler for windows.
1 parent b9b1208 commit 7f30ee1

File tree

7 files changed

+51
-36
lines changed

7 files changed

+51
-36
lines changed

src/exporter.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,10 @@ export const publishFiles = async (
116116

117117
const exportedFile = await exportFile(file, new Path(path), htmlFilePath, new Path(client.getUseHostSlug()), view, client);
118118
if (exportedFile) {
119+
log.info('exported file downloads: ', exportedFile.downloads);
119120
externalFiles.push(...exportedFile.downloads.map((d: Downloadable) => {
120121
const afterPath = exportedFile.exportToFolder.join(d.relativeDownloadPath);
121-
const fileKey = Path.localToWebPath((d.relativeDownloadPath.asString + '/' + d.filename).replace(/^\.\//, ''));
122+
const fileKey = (d.relativeDownloadPath.asString + '/' + d.filename).replace(/^\.\//, '');
122123

123124
const mdName = (file.path.endsWith('.md') && (fileKey?.replace(/\.html$/ig, '') === file.path.replace(/\.md$/igm, ''))) ? file.path : undefined
124125
Object.assign(d, {

src/main.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import {
3636
} from "./localdb";
3737
import { RemoteClient, ServerDomain } from "./remote";
3838
import { InvioSettingTab, DEFAULT_SETTINGS } from "./settings";
39-
import { fetchMetadataFile, parseRemoteItems, SyncStatusType, RemoteSrcPrefix, syncAttachment } from "./sync";
39+
import { fetchMetadataFile, parseRemoteItems, SyncStatusType, RemoteSrcPrefix, syncAttachment, LocalConflictPrefix, RemoteConflictPrefix } from "./sync";
4040
import { doActualSync, getSyncPlan, isPasswordOk } from "./sync";
4141
import { messyConfigToNormal, normalConfigToMessy } from "./configPersist";
4242
import { ObsConfigDirFileType, listFilesInObsFolder } from "./obsFolderLister";
@@ -282,8 +282,13 @@ export default class InvioPlugin extends Plugin {
282282
// this.app.vault.getAllLoadedFiles
283283
// TODO: List only concerned files, only source of truth
284284
// *.conflict.md files is for data backup when conflicts happened
285-
// const local = this.app.vault.getMarkdownFiles().filter(file => file.path.startsWith(this.settings.localWatchDir + '/') && !file.path.endsWith('.conflict.md'))
286-
const local = this.app.vault.getMarkdownFiles().filter(file => new Path(file.path).isInsideDir(this.settings.localWatchDir) && !file.path.endsWith('.conflict.md'))
285+
const local = this.app.vault.getMarkdownFiles().filter(file => {
286+
const p = new Path(file.path);
287+
return p.isInsideDir(this.settings.localWatchDir) &&
288+
!p.isInsideDir(RemoteConflictPrefix) &&
289+
!p.isInsideDir(LocalConflictPrefix) &&
290+
!file.path.endsWith('.conflict.md')
291+
});
287292
log.info('local file path list: ', local);
288293
// const local = this.app.vault.getAllLoadedFiles();
289294
const localHistory = await loadFileHistoryTableByVault(
@@ -372,11 +377,6 @@ export default class InvioPlugin extends Plugin {
372377
await insertSyncPlanRecordByVault(this.db, plan, this.vaultRandomID);
373378
let view: StatsView;
374379
if (triggerSource !== "dry") {
375-
// getNotice(
376-
// t("syncrun_step7", {
377-
// maxSteps: `${MAX_STEPS}`,
378-
// })
379-
// );
380380
let allFiles = this.app.vault.getMarkdownFiles();
381381
// if we are at the root path export all files, otherwise only export files in the folder we are exporting
382382
allFiles = allFiles.filter((file: TFile) => new Path(file.path).isInsideDir(this.settings.localWatchDir) && (file.extension === "md") && (!file.name.endsWith('.conflict.md')));

src/misc.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,18 @@ declare global {
1313
}
1414
}
1515

16+
function removePathDelimiters(filePath: string) {
17+
return filePath.replace(/^[/\\]+|[/\\]+$/g, '');
18+
}
19+
1620
export const trimPrefix = (key: string, prefix: string) => {
1721
if (!key) return key;
18-
if (key.startsWith(prefix)) {
19-
return key.slice(prefix.length)
22+
const prefixWithoutDel = removePathDelimiters(prefix);
23+
if (key.startsWith(prefixWithoutDel + '\\') || key.startsWith(prefixWithoutDel + '/')) {
24+
return key.slice(prefixWithoutDel.length + 1)
2025
}
21-
return key;
26+
const reg = new RegExp(`^${prefix}`);
27+
return key.replace(reg, '');
2228
}
2329

2430
/**

src/remote.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ export class RemoteClient {
9999
}
100100
}
101101

102-
return Path.localToWebPath(localPath);
102+
return localPath;
103103
}
104104

105105
getUseHostLocalPath(slug: string) {
@@ -130,7 +130,7 @@ export class RemoteClient {
130130
}
131131
}
132132

133-
return Path.webToLocalPath(webPath)
133+
return webPath
134134
}
135135

136136
uploadToRemote = async (

src/remoteForS3.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -340,9 +340,9 @@ export const uploadToRemote = async (
340340
rawContent: string | ArrayBuffer = "",
341341
remoteKey?: string
342342
) => {
343-
let uploadFileKey = Path.localToWebPath(prefix + fileOrFolderPath);
343+
let uploadFileKey = prefix + fileOrFolderPath;
344344
if (password !== "") {
345-
uploadFileKey = Path.localToWebPath(prefix + remoteEncryptedKey);
345+
uploadFileKey = prefix + remoteEncryptedKey;
346346
}
347347
const isFolder = Path.isFolderOrDir(fileOrFolderPath);
348348

@@ -537,9 +537,9 @@ export const downloadFromRemote = async (
537537
localContent = await decryptArrayBuffer(remoteContent, password);
538538
}
539539
if (!skipSaving) {
540-
await vault.adapter.writeBinary(Path.webToLocalPath(renamedTo || fileOrFolderPath), localContent, {
541-
mtime: mtime,
542-
});
540+
log.info('creating file: ', renamedTo || fileOrFolderPath);
541+
const option = mtime ? { mtime } : null;
542+
await vault.adapter.writeBinary(renamedTo || fileOrFolderPath, localContent, option);
543543
}
544544
return localContent;
545545
}

src/sync.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,14 @@ import {
5454
} from "./metadataOnRemote";
5555
import { isInsideObsFolder, ObsConfigDirFileType } from "./obsFolderLister";
5656
import { Utils } from './utils/utils';
57+
import { Path } from './utils/path';
5758
import { log } from "./moreOnLog";
59+
import { settings } from "assets/webworker.txt";
5860

5961
export const RemoteSrcPrefix = 'op-remote-source-raw/'
6062
export const RemoteAttPrefix = 'op-remote-attach-p/'
63+
export const LocalConflictPrefix = 'local.conflict'
64+
export const RemoteConflictPrefix = 'remote.conflict'
6165
// 影响到pub产物变动的decision
6266
const RemoteFileTouchedDecisions = ['uploadLocalDelHistToRemote', 'uploadLocalToRemote'];
6367
const LocalFileTouchedDecisions = ['downloadRemoteToLocal', 'keepRemoteDelHist'];
@@ -1254,7 +1258,10 @@ const dispatchOperationToActual = async (
12541258
if (r.remoteUnsync) {
12551259
// TODO: Add a hook to alert users the risk of data lost on the remote
12561260
log.info('download last changed version from remote for backup: ', r.key)
1257-
const renamed = r.key.replace(/\.md$/ig, '.conflict.md');
1261+
const conflictKey = () => '.' + Math.random().toFixed(4).slice(2) + '.conflict.md'
1262+
let renamed = r.key.replace(/\.md$/ig, conflictKey());
1263+
renamed = Path.insertSubPath(renamed, RemoteConflictPrefix)
1264+
await mkdirpInVault(renamed, vault);
12581265
await client.downloadFromRemote(
12591266
r.key,
12601267
RemoteSrcPrefix,
@@ -1295,10 +1302,8 @@ const dispatchOperationToActual = async (
12951302
log.info('rename last changed version from local for backup: ', r.key)
12961303
const conflictKey = () => '.' + Math.random().toFixed(4).slice(2) + '.conflict.md'
12971304
let renamed = r.key.replace(/\.md$/ig, conflictKey());
1298-
1299-
if (vault.adapter.exists(renamed)) {
1300-
renamed = renamed.replace('.conflict.md', conflictKey())
1301-
}
1305+
renamed = Path.insertSubPath(renamed, LocalConflictPrefix)
1306+
await mkdirpInVault(renamed, vault);
13021307
await vault.adapter.rename(r.key, renamed);
13031308
await Utils.appendFile(vault, renamed, ConflictDescriptionTxt);
13041309
}
@@ -1716,7 +1721,7 @@ export const syncAttachment = async (vault: Vault, client: RemoteClient, embeds:
17161721
link,
17171722
RemoteAttPrefix,
17181723
vault,
1719-
0,
1724+
Date.now(),
17201725
'',
17211726
'',
17221727
false,

src/utils/path.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ const isWindows: boolean = (typeof process.platform === 'string' ?
3636
process.platform :
3737
parseOSFromUA(navigator.userAgent)) === "win32";
3838

39-
export const PATH_SPLITER = isWindows ? '\\' : '/';
39+
export const PATH_SPLITER = '/';
4040
export const WEB_PATH_SPLITER = '/';
4141

4242
export class Path
@@ -244,16 +244,6 @@ export class Path
244244
return path.replaceAll(" ", "-").replaceAll(/-{2,}/g, "-").replace(".-", "-").toLowerCase();
245245
}
246246

247-
static localToWebPath(path: string): string {
248-
return path.replaceAll(PATH_SPLITER, '/')
249-
}
250-
251-
static webToLocalPath(path: string): string {
252-
if (isWindows) {
253-
return path.replaceAll('/', PATH_SPLITER);
254-
}
255-
return path;
256-
}
257247
static splitString(path: string): string[] {
258248
if (!path) return [];
259249
return path.split(PATH_SPLITER);
@@ -265,6 +255,19 @@ export class Path
265255
return path.endsWith(PATH_SPLITER) || path.endsWith(WEB_PATH_SPLITER);
266256
}
267257

258+
static getPathSpliter() {
259+
return PATH_SPLITER;
260+
}
261+
static removePathDelimiters(filePath: string) {
262+
return filePath.replace(/^[/\\]+|[/\\]+$/g, '');
263+
}
264+
static insertSubPath(path: string, subPath: string): string {
265+
if (!path || !subPath) return path;
266+
const pList = path.split(PATH_SPLITER);
267+
pList.splice(1, 0, Path.removePathDelimiters(subPath));
268+
return pList.filter(p => !!p).join('/');
269+
}
270+
268271
joinString(...paths: string[]): Path
269272
{
270273
return this.copy.reparse(Path.joinStringPaths(this.asString, ...paths));

0 commit comments

Comments
 (0)