Last active
August 29, 2015 14:20
-
-
Save adriannier/bdfdcfd2a17db4e7d0ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uniqueFilePath('~/Library/Preferences/com.apple.finder.plist') | |
function uniqueFilePath(parentFolderPath, fileName, suffix) { | |
/* | |
Only for use with JavaScript for Automation (JXA) | |
Generates a unique path by appending a number | |
to the end of the file name. | |
If suffix is not specified it is extracted | |
from the file name. | |
If neither file name nor suffix is specified, | |
it is assumed that the first argument holds | |
the complete path to file. | |
*/ | |
if (!fileName) { | |
// Get the file name from the first argument | |
var components = $.NSString.alloc.initWithUTF8String(parentFolderPath).pathComponents.js // Return native array with NSStrings | |
// Get an array of native strings | |
var jsComponents = [] | |
components.forEach(function(component) { | |
jsComponents.push(component.js) | |
}) | |
// Get the file name | |
fileName = jsComponents[jsComponents.length - 1] | |
// Get the parent folder path | |
jsComponents.splice(-1, 1) | |
parentFolderPath = jsComponents.join('/') | |
} | |
if (!suffix) { | |
// Get suffix from file name | |
fileNameNSS = $.NSString.alloc.initWithUTF8String(fileName) | |
suffix = fileNameNSS.pathExtension.js | |
fileName = fileNameNSS.stringByDeletingPathExtension.js | |
} | |
if (suffix != '' && suffix.indexOf('.') != 0) { | |
// Add dot to beginning of suffix | |
suffix = '.' + suffix | |
} | |
// Clean up file name | |
fileName = fileName.replace(/[:\/\\]/gi,'-') | |
// Shorten file name if necessary | |
var availableFileNameLength = 255 - suffix.length | |
if (fileName.length > availableFileNameLength) { | |
fileName = fileName.substr(0, availableFileNameLength ) | |
} | |
// Expand tilde in parent folder path | |
parentFolderPath = $.NSString.alloc.initWithUTF8String(parentFolderPath).stringByExpandingTildeInPath.js | |
// Add trailing colon to parent folder path | |
if ( parentFolderPath.slice(-1) != '/') { parentFolderPath += '/' } | |
var loopNumber = 2 | |
var tempFilePath = parentFolderPath + fileName + suffix | |
while (Application('System Events').exists(Path(tempFilePath))) { | |
// Shorten file name if necessary | |
availableFileNameLength = 255 - suffix.length - loopNumber.toString().length - 1 | |
if (fileName.length > availableFileNameLength) { | |
fileName = fileName.substr(0, availableFileNameLength) | |
} | |
tempFilePath = parentFolderPath + fileName + ' ' + loopNumber + suffix | |
loopNumber++ | |
} | |
return tempFilePath | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment