Skip to content

Instantly share code, notes, and snippets.

@kalupas226
Last active October 27, 2023 15:52
Show Gist options
  • Save kalupas226/bdc42bcab39e60c1451115aa94c97041 to your computer and use it in GitHub Desktop.
Save kalupas226/bdc42bcab39e60c1451115aa94c97041 to your computer and use it in GitHub Desktop.
AppleScript that allows you to switch to GitHub web page from code on Xcode
-- ref
-- - https://github.com/wojteklu/xcode-open-on-github
-- - http://tonbi.jp/AppleScript/Tips/Scripting/Debug.html
-- - https://developer.apple.com/library/archive/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/CallCommandLineUtilities.html
on run {input, parameters}
tell application "Xcode-14.0.0"
set activeDocument to document 1 whose name ends with (word -1 of (get name of window 1))
set activeDocumentPath to path of activeDocument
set currentLines to selected paragraph range of activeDocument
set startLine to get item 1 of currentLines
set endLine to get item 2 of currentLines
end tell
set upstreamUrl to do shell script "cd $(dirname '" & activeDocumentPath & "'); git config --get remote.upstream.url || echo ''"
if upstreamUrl = "" then
set repositoryUrl to do shell script "cd $(dirname '" & activeDocumentPath & "'); git config --get remote.origin.url"
else
set repositoryUrl to upstreamUrl
end if
set repositoryUrl to do shell script "echo '" & repositoryUrl & "' | sed 's/ssh:\\/\\/git@/https:\\/\\//' | sed 's/git@/https:\\/\\//' | sed 's/com:/com\\//' | sed 's/co:/co\\//' | sed 's/\\.git//'"
set pathToRepositoryDirLocation to do shell script "cd $(dirname '" & activeDocumentPath & "'); git rev-parse --show-toplevel "
set activeFilePathInRepository to replace_text(activeDocumentPath, pathToRepositoryDirLocation, "")
set currentFileLatestCommit to do shell script "cd $(dirname '" & activeDocumentPath & "'); git log --pretty=format:'%H' -- '" & activeDocumentPath & "' -L | head -n 1 | awk '{print $1}'"
set githubUrl to repositoryUrl & "/blob/" & currentFileLatestCommit & activeFilePathInRepository & "#L" & startLine & "-L" & endLine
do shell script "open " & replace_text(githubUrl, " ", "%20")
return input
end run
on replace_text(this_text, search_string, replacement_string)
set prevTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to prevTIDs
return this_text
end replace_text
@kalupas226
Copy link
Author

2022-09-19.18.19.23.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment