diff --git a/chrome/content/zotero/xpcom/file.js b/chrome/content/zotero/xpcom/file.js index 231b14a61d..59dc2e9850 100644 --- a/chrome/content/zotero/xpcom/file.js +++ b/chrome/content/zotero/xpcom/file.js @@ -894,6 +894,25 @@ Zotero.File = new function(){ } + /** + * @param {String} file + * @param {String} newFile + * @return {String} - Path of new file + */ + this.moveToUnique = async function (file, newFile) { + var targetDir = OS.Path.dirname(newFile); + + var newNSIFile = this.pathToFile(newFile); + newNSIFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0o644); + var newName = newNSIFile.leafName; + newNSIFile.remove(null); + + newFile = OS.Path.join(targetDir, newName); + await OS.File.move(file, newFile); + return newFile; + } + + this.copyToUnique = function (file, newFile) { file = this.pathToFile(file); newFile = this.pathToFile(newFile); diff --git a/chrome/content/zotero/xpcom/zotero.js b/chrome/content/zotero/xpcom/zotero.js index a0947cf36d..4c1471582a 100644 --- a/chrome/content/zotero/xpcom/zotero.js +++ b/chrome/content/zotero/xpcom/zotero.js @@ -49,7 +49,6 @@ Services.scriptloader.loadSubScript("resource://zotero/polyfill.js"); this.flattenArguments = flattenArguments; this.getAncestorByTagName = getAncestorByTagName; this.randomString = randomString; - this.moveToUnique = moveToUnique; this.reinit = reinit; // defined in zotero-service.js // Public properties @@ -1711,7 +1710,8 @@ Services.scriptloader.loadSubScript("resource://zotero/polyfill.js"); } - function moveToUnique(file, newFile){ + this.moveToUnique = function (file, newFile) { + Zotero.debug("Zotero.moveToUnique() is deprecated -- use Zotero.File.moveToUnique()", 2); newFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0o644); var newName = newFile.leafName; newFile.remove(null); diff --git a/test/tests/fileTest.js b/test/tests/fileTest.js index cb26ae072d..224d83afc7 100644 --- a/test/tests/fileTest.js +++ b/test/tests/fileTest.js @@ -158,6 +158,21 @@ describe("Zotero.File", function () { }); + describe("#moveToUnique", function () { + it("should move a file to a unique filename", async function () { + var tmpDir = Zotero.getTempDirectory().path; + var sourceFile = OS.Path.join(tmpDir, "1"); + var tmpTargetDir = OS.Path.join(tmpDir, "targetDirectory") + var targetFile = OS.Path.join(tmpTargetDir, "file.txt"); + await OS.File.makeDir(tmpTargetDir); + await Zotero.File.putContentsAsync(sourceFile, ""); + await Zotero.File.putContentsAsync(targetFile, ""); + var newFile = await Zotero.File.moveToUnique(sourceFile, targetFile); + assert.equal(OS.Path.join(tmpTargetDir, 'file-1.txt'), newFile); + }); + }); + + describe("#copyDirectory()", function () { it("should copy all files within a directory", function* () { var tmpDir = Zotero.getTempDirectory().path;