file object. let curFile = templateFile.clone().QueryInterface(Ci.nsIFile); let [base, ext] = DownloadPaths.splitBaseNameAndExtension(curFile.leafName); // Try other file names, for example "base(1).txt" or "base(1).tar.gz", // only if the file name initially set already exists. for (let i = 1; i < 10000 && curFile.exists(); i++) { curFile.leafName = base + "(" + i + ")" + ext; } // At this point we hand off control to createUnique, which will create the // file with the name we chose, if it is valid. If not, createUnique will // attempt to modify it again, for example it will shorten very long names // that can't be created on some platforms, and for which a normal call to // nsIFile.create would result in NS_ERROR_FILE_NOT_FOUND. This can result // very rarely in strange names like "base(9999).tar-1.gz" or "ba-1.gz". curFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o644); return curFile; }, /** * Separates the base name from the extension in a file name, recognizing some * double extensions like ".tar.gz". * * @param leafName * The full leaf name to be parsed. Be careful when processing names * containing leading or trailing dots or spaces. * * @return [base, ext] * The base name of the file, which can be empty, and its extension, * which always includes the leading dot unless it's an empty string. * Concatenating the two items always results in the original name. */ splitBaseNameAndExtension(leafName) { // The following regular expression is built from these key parts: // .*? Matches the base name non-greedily. // \.[A-Z0-9]{1,3} Up to three letters or numbers preceding a // double extension. // \.(?:gz|bz2|Z) The second part of common double extensions. // \.[^.]* Matches any extension or a single trailing dot. let [, base, ext] = /(.*?)(\.[A-Z0-9]{1,3}\.(?:gz|bz2|Z)|\.[^.]*)?$/i.exec( leafName ); // Return an empty string instead of undefined if no extension is found. return [base, ext || ""]; }, }; PK