Skip to content

Instantly share code, notes, and snippets.

@james-howard
Last active August 18, 2017 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james-howard/4943f23bef7363f68884c7eb7aa107bb to your computer and use it in GitHub Desktop.
Save james-howard/4943f23bef7363f68884c7eb7aa107bb to your computer and use it in GitHub Desktop.
OSAScript to copy GitHub link from currently selected line in Xcode
function run() {
xcode = Application('Xcode')
var app = Application.currentApplication()
app.includeStandardAdditions = true;
docs = xcode.sourceDocuments()
for (var i = docs.length-1; i >= 0; i--) {
var doc = docs[i];
var range = doc.selectedParagraphRange();
if (!range) {
continue;
}
var start = range[0];
var end = range[1];
if (start > end) {
var tmp = start;
start = end;
end = tmp;
}
var path = doc.path();
var basename = path.substring(path.lastIndexOf('/')+1);
var gitinfo = app.doShellScript(
`cd \`dirname '${path}'\`\n` +
`git remote -v | head -1\n` +
`git rev-parse --show-toplevel\n` +
`git rev-parse HEAD\n`
).split('\r');
var remote = gitinfo[0];
var gitroot = gitinfo[1];
var branch = gitinfo[2];
var relativePath = path.substring(gitroot.length+1);
var m = remote.match(/.*github.com\/(.*?)\/(.*?)\.git.*/);
if (m) {
var owner = m[1];
var repo = m[2];
var lineAnchor = `L${start}`;
if (end != start) {
lineAnchor += `-L${end}`;
}
var cb = `https://github.com/${owner}/${repo}/blob/${branch}/${relativePath}#${lineAnchor}`;
app.setTheClipboardTo(cb);
app.displayNotification(cb, {withTitle:'Clipboard Updated'});
}
break;
}
}
@james-howard
Copy link
Author

james-howard commented Jan 17, 2017

I use this with FastScripts, but you could probably also use it with Script Menu.

Put this at ~/Library/Scripts/Applications/Xcode/

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