Independent of this forum, I developed a solution in JavaScript for formatting a given date as an Australian Financial Year in the format "FY2020-21".
I'll post code below, but my question is around JavaScript in Rule Actions when using an external file. I consulted the
AppleScript/JavaScript in Rule Actions section in the Hazel User Guide:
https://www.noodlesoft.com/manual/hazel/attributes-actions/using-applescript-or-javascript/.
Here is the code:
- Code: Select all
function hazelProcessFile(theFile, inputAttributes)
{
var myDate = new Date(inputAttributes[0]);
// Get current year for usage below
var yearNumber = myDate.getFullYear();
var thisYearYYYY = yearNumber.toString();
// Construct YYYY-YY Australian Financial Year
var australianFinancialYear = "";
// Month is from 0 to 11
if (myDate.getMonth() + 1 > 6) {
var nextYearYYYY = (yearNumber + 1).toString();
var nextYearYY = nextYearYYYY.substr(
nextYearYYYY.length - 2,
nextYearYYYY.length
);
australianFinancialYear = "FY" + thisYearYYYY + "-" + nextYearYY;
} else {
var lastYearYYYY = (yearNumber - 1).toString();
var thisYearYY = thisYearYYYY.substr(
thisYearYYYY.length - 2,
thisYearYYYY.length
);
australianFinancialYear = "FY" + lastYearYYYY + "-" + thisYearYY;
}
return { hazelOutputAttributes: [australianFinancialYear] };
}
I have tested this code, it is valid JavaScript and returns the desired result. The below was attained by showing the browser console by hitting F12, pasting the function into the browser console and hitting return, so it is instantiated there, and then it was called it as follows:
- Code: Select all
hazelProcessFile("file",[new Date("2021-03-03")])
hazelOutputAttributes: ["FY2020-21"]
The problem is that when I put this exact code into a file called getAustralianFinancialYear.scpt, then in Hazel create a "Run JavaScript" Action, select "Other...", navigate to that file and click Open, Hazel displays a dialog with
Script is not validPlease fix the script or try another one.
Note that I can also embed this script in Hazel, without the function wrapper, and it works. The input attribute is date-type, and my script handles that. The output attribute is text and exactly what is required. I had the idea of using getAustralianFinancialYear.scpt in more than one Hazel rule, so it would be handy to be able to store it externally. How does Hazel validate JavaScript and why is it invalid in this instance? Is returning hazelPassesScript: true a requirement? This issue should be reproducible given the details above.