Scripting

RSS for tag

Scripting allows you to automate complex, repetitive, and time-consuming tasks by writing scripts that interact with apps, processes, and the operating system.

Posts under Scripting tag

22 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Modifying AAC/M4A audio file metadata with Shortcuts on macOS
I want to use the Shortcuts app on macOS Monterey to modify M4A/AAC audio file metadata for files that I have ripped from CD to my local Music app library. How can I use a regular expression on track titles to replace text that matches a certain regex pattern? I have already written the regex, I just need help with the Shortcuts app. I've started my shortcut with a "Find Music" action connected to a "Repeat with Each" loop action. Within the loop, I use a "Get Details of Music" action to get the title, which is passed to a "Replace Text" action using my regex. I just don't know how to write the correct new title into the music file's title/name metadata field. I tried a "Rename File" action with type "iTunes media" to try to set the "Title" field, but the field wasn't updated either in the Music app or in the M4A/AAC file itself. I couldn't find any other actions that seemed like they might be able to modify the field. I'd prefer a solution that goes through the Music app / its APIs, rather than directly modifying the M4A on the file system, because the latter would force me to have the Music app scan for changed files after the files we're modified.
0
0
149
3w
Moving file to a system folder
When making a custom System Settings panel, I want the project to automatically move the prefpane file to /Library/PreferencePanes/. With Run Script, the build fails because of denial to perform the operation. Sudo doesn't help, too. PREFPANE_SRC="${BUILT_PRODUCTS_DIR}/App.prefPane" PREFPANE_DST="$HOME/Library/PreferencePanes/" echo "PrefPane source path: $PREFPANE_SRC" echo "PrefPane destination path: $PREFPANE_DST" if [ -d "$PREFPANE_SRC" ]; then echo "Installing preference pane to ${PREFPANE_DST}" cp -R "${PREFPANE_SRC}" "${PREFPANE_DST}" else echo "Preference pane not found: ${PREFPANE_SRC}" exit 1 fi
8
0
355
Aug ’24
Changing Info.plist ATS value for Release archives
Hi, My company has an app that is communicating with local servers with self signed certificates, meaning in order to allow the app to have connection in the testing environment I had to add a few domains in NSExceptionDomains in App Transport Security Settings section of the Info.plist. The problem is, our Cyber department is not allowing us to upload the app with these domain in the app fearing a data leak. I had a Build Phase script using PlistBuddy that deleted those settings when archiving in Release but that no longer works as Apple recommended to set ”Generate Info.plist file” to true as a best practice. I tried to read about it and found out that info.plist is now generated after the build phases step so modifying it is impossible because it doesn’t exist yet in the $TARGET_BUILD_DIR when the script is running. Other than deleting it manually before each upload which is highly prone to mistakes, I need something like a script or some other automatic solution. Does Anyone have any suggestions to help me with this? Thanks
1
0
235
Aug ’24
How can I grant full disk access to a Node-RED instance?
I just updated to Sonoma on a Mac Mini that runs all my ad-hoc DIY home automations, and I have a bunch of custom self-made tools for triggering automations based in part on the state of reminders in the Reminders app. All of that stopped working immediately after the update. It took me a day to update my code for the new location of the sqlite reminders files and I made the changes to get my scripts working again, however one remaining problem is that I run an fswatch from node-red to monitor the database for changes to trigger my automations. Eventually, with help from stack and perlmonks, I found out that even though the permissions on the full path (via my home directory/Library) to the files is r*x to me and the node-red executable is running as me, I get an Operation not permitted error when I just try lsing the directories leading to the sqlite files. I read elsewhere that this sort of problem can be solved by granting full disk access to the executables(/processes) that are getting the Operation not permitted errors. However, I tried this, yet I still get the same error. Do I need to reboot? Is there some sort of documentation for casual users like myself that just code for themselves that can answer questions like this? The more aggressive Apple gets with security, the safer users are, but the more headaches and bewilderment it causes people like me.
9
0
467
Jul ’24
Is there any script that can detect Apple Submission to TestFlight errors early? like: ".framework contains disallowed nested bundles"
Some of the errors like ".framework contains disallowed nested bundles" we find out at later stage when uploading builds to TestFlight. It will be great if we can have similar script that apple uses or some custom script to verify it during the build time. So before I reinvent the wheel is there any script I can use at build time to detect this issue?
1
0
377
Jul ’24
tccd reports Apple Events entitlement check error, despite a process having it
HI! I am developing an application that should utilize ScriptingBridge.framework to interact with another process. Firstly, I created a separate test application for which I have added Apple Events entitlements via "Signing & Capabilities" section in Xcode and updated its Info.plist to have "Privacy - AppleEvents Sending Usage Description". While the test app works fine (I see an automation request popup and the process executes as expected) the main application where I want to integrate this functionality gets closed immediately after reaching the code interacting with Scripting Bridge. On its launch, I see the following error message from tccd in Console: Prompting policy for hardened runtime; service: kTCCServiceAppleEvents requires entitlement com.apple.security.automation.apple-events but it is missing for accessing={TCCDProcess: identifier=<app bundleID>, ..., binary_path=<path to the app's binary>} I had no such issues with the test app. Moreover, I should mention that the bundle I want to have with such functionality is stored in another bundle, both main and inner bundles aren't sandboxed, and the target app has Application is agent (UIElement) key set in Info.plist. Can you suggest any ideas as to why processes behave so differently despite having pretty much the same build configurations?
14
1
1k
Jun ’24
Seeking Assistance with Bulk Input of Pronunciation Corrections for iOS
Hello iOS Developer Community, I hope this message finds you healthy and happy. I am reaching out to seek your expertise and assistance with a particular challenge I’ve encountered while using the Speak Screen and Speak Selection features on iOS. As you may know, these features are incredibly useful for reading text aloud, but they sometimes struggle with the correct pronunciation of homographs—words that are spelled the same but have different meanings and pronunciations. An example of this is the word “live,” which can be pronounced differently based on the context of the sentence. To enhance my user experience, I am looking to input corrections for the pronunciation of “live” in its “happening now” context, such as in “live broadcast” or “live event.” However, the current process requires manual entry for each phrase, which is quite labor-intensive. I am wondering if there is a way to automate or streamline this process, perhaps through a shortcut or script that allows for bulk input of these corrections. Additionally, if anyone has already compiled a list of common phrases with homographs and their correct pronunciations, I would greatly appreciate it if you could share it or guide me on where to find such resources. Your insights and guidance on this matter would be invaluable, and I believe any solutions could benefit not just myself but many other users facing similar issues. Thank you for your time and consideration. I look forward to any suggestions or advice you may have. Best regards, Alec
0
0
429
Apr ’24
mailto: URL handling in MacOS Mail.app
Hi, I'm working on a series of scripts and utilities that process logs and generate pre-composed email reports as a consequence, and wanted to use the open "mailto:address?subject=my subject&amp;body=..." to do so from the scripting. to, cc, bcc, subject, and body are all obvious attributes, but what others are handled? Emails are typically sent from a joint mail address, not the user's primary (default) mail account (but one that is also locally provisioned in Mail.app). So I'd like to force the from=address attribute as well. And the messages should be text/plain, not multipart, and the charset of us-ascii. Where can I find the detailed handling on mailto: URL's in MacOS? RFC-6068 is unfortunately a guideline, and doesn't flesh out many requisites. Thanks
0
1
671
Mar ’24
updating the recovery partition with the latest OS & Updates
Is anyone familiar with the Sonoma 14.4 update file? I asked LLM to help me write a script to update the recovery partition. It keeps suggesting files that were in the old InstallAssistant.pkg, but Sonoma is different. Is anyone familiar with the Sonoma setup and its file structure? Is there a way to update the recovery partition with the latest OS? Because when I restore my computer back to factory reset, it always restores the macOS which came with the Mac. I have a Mac mini M2. Below is the script I used: #!/bin/bash Function to display an error message and exit function display_error { echo "Error: $1" exit 1 } Path to the directory containing InstallAssistant.pkg pkg_directory="/Users/colinp/Downloads" Check if InstallAssistant.pkg exists in the specified directory if [ ! -f "$pkg_directory/InstallAssistant.pkg" ]; then display_error "InstallAssistant.pkg not found in $pkg_directory." fi echo "InstallAssistant.pkg found in $pkg_directory." Prompt user to continue read -p "Do you want to continue? (y/n): " continue_response if [ "$continue_response" != "y" ]; then echo "Operation aborted by user." exit 0 fi Mount the InstallAssistant disk image echo "Mounting InstallAssistant disk image..." if ! hdiutil attach "$pkg_directory/InstallAssistant.pkg" -noverify -mountpoint /Volumes/InstallAssistant; then display_error "Failed to mount InstallAssistant disk image." fi Prompt user to continue read -p "Do you want to continue? (y/n): " continue_response if [ "$continue_response" != "y" ]; then echo "Operation aborted by user." hdiutil detach /Volumes/InstallAssistant >/dev/null 2>&1 exit 0 fi Find the BaseSystem.dmg within the InstallAssistant disk image basesystem_dmg=$(find /Volumes/InstallAssistant -name "BaseSystem.dmg" -print -quit) Check if BaseSystem.dmg is found if [ -z "$basesystem_dmg" ]; then display_error "BaseSystem.dmg not found within InstallAssistant.pkg." fi echo "BaseSystem.dmg found." Prompt user to continue read -p "Do you want to continue? (y/n): " continue_response if [ "$continue_response" != "y" ]; then echo "Operation aborted by user." hdiutil detach /Volumes/InstallAssistant >/dev/null 2>&1 exit 0 fi Determine the device identifier of the target disk recovery_partition=$(diskutil list | grep "Recovery HD" | awk '{print $NF}') if [ -z "$recovery_partition" ]; then display_error "Recovery partition not found." fi echo "Recovery partition found: $recovery_partition" Prompt user to continue read -p "Do you want to continue? (y/n): " continue_response if [ "$continue_response" != "y" ]; then echo "Operation aborted by user." hdiutil detach /Volumes/InstallAssistant >/dev/null 2>&1 exit 0 fi Unmount the recovery partition echo "Unmounting the recovery partition..." if ! diskutil unmountDisk "$recovery_partition"; then display_error "Failed to unmount the recovery partition." fi Prompt user to continue read -p "Do you want to continue? (y/n): " continue_response if [ "$continue_response" != "y" ]; then echo "Operation aborted by user." hdiutil detach /Volumes/InstallAssistant >/dev/null 2>&1 exit 0 fi Restore BaseSystem.dmg to the recovery partition echo "Updating the recovery partition. This may take a while..." if ! sudo asr restore --source "$basesystem_dmg" --target "$recovery_partition" --erase; then display_error "Failed to update the recovery partition." fi Detach the InstallAssistant disk image echo "Detaching InstallAssistant disk image..." if ! hdiutil detach /Volumes/InstallAssistant >/dev/null 2>&1; then display_error "Failed to detach InstallAssistant disk image." fi echo "Recovery partition update complete. any help is appreciated. Thanks in advance.
0
0
522
Mar ’24
Seeking ls functionality, wrap file names in quotes when there is an embedded space
I read on a webpage I can't cite that the Linux coreutils package at version 8.25 was modified so it, by default, the ls command puts single quotes around file names with spaces in them. Also that the ls -N option and the bash QUOTING_STYLE environment variable when set with the value of "literal" can be used to turn off the new behavior. I want to go the other direction in bash under MacOS. Is there a way to turn on wrapping of file names containing spaces in bash? I like not having to add single quotes all the time to the file names I copy and paste on Linux, so it'd be nice to have the same capability, at least optionally, on my Mac.
0
0
437
Mar ’24
Using Scriptable to pull text from an image and enter it into a database
Hi all. I'm a Software Engineer, but I've never done anything with iPhone. I have wanted to try Scriptable for a while but have not had any ideas, until now. I have a book of quotes - one quote on each page - no pictures or anything to get in the way, just a quote surrounded by white space. Ultimately I would like to set up an API for these quotes, but to do so I must enter them into a database. What I would like to do with Scriptable is to access the camera, take a photo of each quote, run OCR on it, and store it in some way so that I can turn around and automatically feed it into a noSQL database like MongoDB. First question: is this possible with Scriptable? I really don't want to create a whole app, because 1) I have too many things already to keep up on without taking on Swift, whereas Scriptable is basically just JavaScript, right? (I already know JavaScript), and 2) I just want this to be for my personal use. I'm not wanting to create something to put on the app store. I have too many things to do without having to deal with putting an app on the app store. Second Question: if it is possible with Scriptable, can you tell me in general terms an outline of how I would go about it? I am NOT looking for actual code - I want to code it myself. What I mean is, what tools on the iPhone will I need to be accessing, and what steps would I need to do this in? For example, I've come across mention of two things when it comes to recognizing text with an iPhone - Vision and LiveText. Now what I saw for Vision was in the context of Swift documentation. Is that only accessible via Swift? What about LiveText? Can I use that in a Scriptable script? If not, is there some sort of tool that Scriptable scripts can access that will convert the text from an image into text that I can save to eventually load into a database? And what tools would I use to access the camera and to store stuff into memory, and is there a specific section of memory I need to look into to save it? Basically, I just need the names of the things I need to read up on in order to accomplish my task. If I know the tools I need to use and have the Scriptable documentation, I'm pretty sure I can figure out the coding part myself. I appreciate any help on this.
1
0
507
Feb ’24
Custom UI and gracefully failing the .pkg installation
We have an app that is distributed in our .pkg installer (using pkgbuild and productbuild). Now we need to perform various system checks, eg. minimum macOS version and then continue or abort the installation, based on conditions. When we do that in the pre-install script, it works but the user experience is not what we need. The installation aborts with a generic message. What we want is to show the progress, eg. which checks have failed and why, a link to open the installation log, and to gracefully exit the installation. Is it possible to achieve all this without resorting to writing a custom installation mac app ?
0
1
655
Jan ’24
Launchctl agent errors
I am trying to automate a backup terminal script to mirror some directories to my NAS. The terminal script is working fine, so I want to automate them. The recommended path uses the launchctl agent, which, from the description, should be what I need. However, I have been running into two errors and looking for answers. I am using a M1 Mac mini with 8GB of memory (for reference). First, I get an error 23, which means too many files are open. If I reboot the machine, this error goes away. But why am I getting this message? I can run the script manually without a problem, and the system is running fine. The machine does little, so it should have almost nothing open. The second error, once the 23 is cleared, is error 12, cannot allocate memory. The machine is an 8GB machine but is reporting 3GB free. Again, the script runs fine in the terminal. I suspect the problem is the agent, but I am unsure how to diagnose or resolve these issues. I do not want to reboot the machine to run the backup, and so is the agent running under some system constraints that are too limiting. Can I change those limits for the job and make the recommended process to automate work? Any suggestions would be appreciated.
2
0
560
Jan ’24
Simple scriptable macOS Xcode Swift App example please
Does anyone have a simple example for a scriptable App in Swift in Xcode for macOS? I mean one that exposes objects and functions to applescript? I've checked all examples that I could find. But for me they get me confused about whether they are accessing the actual and already existing instance of a class or whether they are creating an instance with AppleScript, or just using the class definition to call some function. Also the way they are defined in the .sdef file does not help. It would be great if someone had a really simple example, stripped down to bare minimum that 1) defines a class with a single function, 2) creates an instance of the class inside appDelegate and then 3) the function of the specific instance is called using appleScript. 4) It would be great if the function could do something in the GUI, such as change a text of a Label.
0
0
615
Dec ’23
Run a python script as a quick action in finder on selected folder
Hi, not sure if this forum is the right place to ask, but it’s extremely difficult to search the web for answers about shortcuts.app (must be the name…). I’m learning python currently and I’m trying to automate recurring tasks on my Mac easily. I have a python script as a first test-case that works (It basically makes a bunch of named folders). I use Apples Shortcuts.app to execute the python-file with the shell-script action. I start this script in Finder from the Quick Actions menu. The script creates my folders, but not in the selected folder when executing it, but always in my users home folder /Users/markus/. I suspect I have to somehow tell the Shortcut to take the currently selected folder as a variable or something. I tried to read the help but I don’t find anything useful and don’t understand the options of the Shell-Script Action in Shortcuts.app. Any ideas how I can get this to work? Or does anyone have a link to a good forum to ask questions about Shortcuts.app and automation? Thanks! Regards Markus
5
1
2.5k
Mar ’24
Command PhaseScriptExecution failed with a nonzero exit code
I am working on a Unity IOS game. I keep getting this reoccurring issue. I downloaded XCODE via the app store, so it automatically is in my applications folder Here is the log: Showing Recent Messages WorkingDir: /Users/parkerbrandt/Library/Developer/Xcode/DerivedData/Unity-iPhone-gsxoxmhunhavroeddecygwafmdgn/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/artifacts/arm64/buildstate ExitCode: 4 Duration: 0s13ms ExitCode: 1 Duration: 0s1ms Build failed with 0 successful nodes and 0 failed ones Error: Internal build system error. BuildProgram exited with code 1. Unity.IL2CPP.Bee.BuildLogic.ToolchainNotFoundException: IL2CPP C++ code builder is unable to build C++ code. In order to build C++ code for Mac, you must have Xcode installed. Building for Apple Silicon requires Xcode 9.4 and Mac 10.12 SDK. Xcode needs to be installed in the /Applications directory and have a name matching Xcode*.app. Or be selected using xcode-select. It's also possible to use /Library/Developer/CommandLineTools if those match the listed requirements. More information and installation instructions can be found here: https://developer.apple.com/support/xcode/ Specific Xcode versions can be downloaded here: https://developer.apple.com/download/more/ Unable to detect any compatible iPhoneOS SDK! at Unity.IL2CPP.Bee.BuildLogic.iOS.iOSBuildLogic.GetCompatibleXcodeInstallation(Architecture architecture, Version xcodeMinVersion, Version platformSdkMinVersion, Identifier platformSdkIdentifier, XcodePlatformSdk&amp; compatiblePlatformSdk, XcodeInstallation&amp; compatibleXcodeInstallation) at Unity.IL2CPP.Bee.BuildLogic.iOS.iOSBuildLogic.UserAvailableToolchainFor(Architecture architecture, NPath toolChainPath, NPath sysRootPath) at Unity.IL2CPP.Bee.IL2CPPExeCompileCppBuildProgram.BuildProgram.Main(String[] args, String currentDirectory) at Unity.IL2CPP.Building.InProcessBuildProgram.StartImpl(String workingDirectory, String[] arguments) in /Users/bokken/build/output/unity/il2cpp/Unity.IL2CPP.Building/InProcessBuildProgram.cs:line 51 Error: Unity.IL2CPP.Building.BuilderFailedException: Build failed with 0 successful nodes and 0 failed ones Error: Internal build system error. BuildProgram exited with code 1. Unity.IL2CPP.Bee.BuildLogic.ToolchainNotFoundException: IL2CPP C++ code builder is unable to build C++ code. In order to build C++ code for Mac, you must have Xcode installed. Building for Apple Silicon requires Xcode 9.4 and Mac 10.12 SDK. Xcode needs to be installed in the /Applications directory and have a name matching Xcode*.app. Or be selected using xcode-select. It's also possible to use /Library/Developer/CommandLineTools if those match the listed requirements. More information and installation instructions can be found here: https://developer.apple.com/support/xcode/ Specific Xcode versions can be downloaded here: https://developer.apple.com/download/more/ Unable to detect any compatible iPhoneOS SDK! at Unity.IL2CPP.Bee.BuildLogic.iOS.iOSBuildLogic.GetCompatibleXcodeInstallation(Architecture architecture, Version xcodeMinVersion, Version platformSdkMinVersion, Identifier platformSdkIdentifier, XcodePlatformSdk&amp; compatiblePlatformSdk, XcodeInstallation&amp; compatibleXcodeInstallation) at Unity.IL2CPP.Bee.BuildLogic.iOS.iOSBuildLogic.UserAvailableToolchainFor(Architecture architecture, NPath toolChainPath, NPath sysRootPath) at Unity.IL2CPP.Bee.IL2CPPExeCompileCppBuildProgram.BuildProgram.Main(String[] args, String currentDirectory) at Unity.IL2CPP.Building.InProcessBuildProgram.StartImpl(String workingDirectory, String[] arguments) in /Users/bokken/build/output/unity/il2cpp/Unity.IL2CPP.Building/InProcessBuildProgram.cs:line 51 at il2cpp.Program.DoRun(TinyProfiler2 tinyProfiler, String[] args, RuntimePlatform platform, Il2CppCommandLineArguments il2CppCommandLineArguments, BuildingOptions buildingOptions, Boolean throwExceptions) in /Users/bokken/build/output/unity/il2cpp/il2cpp/Program.cs:line 319 Command PhaseScriptExecution failed with a nonzero exit code
2
1
1.4k
Oct ’23
Package pre build script execution
Hello, i am currently trying to implement a pre build script execution in a package. I am using this tutorial to implement it. But it only shows how to use the pre build feature with an already existing feature. I want to execute a skript on my pc every time i build the project. I can't use apples prebuild skript feature in the build settings because it is a package. Right now my code looks like this: import Foundation import OSLog import PackagePlugin @main struct GenerateLocalizer: BuildToolPlugin {     do {       let commandlineOutput = try shell("./testScript.sh")     } catch {     }     return [.prebuildCommand(displayName: "Generate Strings", executable: PackagePlugin.Path("./scrips/generate_strings.sh"), arguments: [], outputFilesDirectory: target.directory)]   }   func shell(_ command: String) throws -> String {     let task = Process()     let pipe = Pipe()     task.standardOutput = pipe     task.standardError = pipe     task.arguments = [command]     os_log("%{public}@", log: log, task.arguments?.joined(separator: " ") ?? "not found")     task.launchPath = "/bin/zsh"     task.standardInput = nil     try task.run()     let data = pipe.fileHandleForReading.readDataToEndOfFile()     let output = String(data: data, encoding: .utf8)!     return output   } } and my Package file looks something like that       name: "CustomSdk",       dependencies: ["CustomSdk-Objc"],       path: "CustomSdk",       exclude: ["Info.plist", "CustomSdk.podspec"],       plugins: [         .plugin(name: "GenerateLocalizer")       ]     ),     .plugin(name: "GenerateLocalizer",         capability: .buildTool(),         dependencies: ["CustomSdk-Objc"]     ) It gets called properly but when want to write files in my "testScript.sh" it only says: Operation not permitted. Anyone got any ideas how to fix this or is there another way to utitlize custom scripts with custom packages? Greetings Ben
2
1
2.9k
Oct ’23