Last active
July 13, 2017 22:09
-
-
Save nkmathew/418c3900263cb05680c9077d904cc835 to your computer and use it in GitHub Desktop.
git:// protocol scheme handler for Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Win32; | |
using System.Text.RegularExpressions; | |
using System; | |
/** | |
* @author nkmathew | |
* @date July 10, 2017 | |
* | |
* The program makes it possible to open "git://" like urls clicked from a console | |
* emulator like ConEmu in your default browser as Windows doesn't recognize that | |
* protocol scheme by default | |
* | |
* Build from the commandline or from an IDE. | |
* | |
* E.g | |
* | |
* C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe GitProtocolHandler.cs | |
*/ | |
class GitProtocolSchemeHandler { | |
/** | |
* Creates the registry key | |
*/ | |
static void RegisterAsHandler() { | |
string programPath = System.Diagnostics.Process. | |
GetCurrentProcess().MainModule.FileName; | |
const string keyPath = "Software\\Classes\\git\\shell\\open\\command"; | |
RegistryKey keyCommand = Registry.CurrentUser.OpenSubKey(keyPath, true); | |
if (keyCommand == null) { | |
RegistryKey keySoftware = Registry.CurrentUser.OpenSubKey("Software", true); | |
RegistryKey keyClasses = keySoftware.CreateSubKey("Classes"); | |
RegistryKey keyGit = keyClasses.CreateSubKey("git"); | |
RegistryKey keyShell = keyGit.CreateSubKey("shell"); | |
RegistryKey keyOpen = keyShell.CreateSubKey("open"); | |
keyCommand = keyOpen.CreateSubKey("command"); | |
} | |
keyCommand.SetValue("", programPath + " %1"); | |
keyCommand.Close(); | |
} | |
/** | |
* Returns the GitHub repo url given the a repo url starting with "git://" | |
*/ | |
static string ProcessGitUrl(string url) { | |
MatchCollection matches = Regex.Matches(url, "git://github.com/(.+)/(.+).git"); | |
int count = matches.Count; | |
if (matches.Count != 0) { | |
Group username = matches[0].Groups[1]; | |
Group reponame = matches[0].Groups[2]; | |
url = String.Format("https://github.com/{0}/{1}", username, reponame); | |
return url; | |
} else { | |
return ""; | |
} | |
} | |
static void Main(string[] args) { | |
RegisterAsHandler(); | |
if (args.Length > 0) { | |
string url = args[0]; | |
url = ProcessGitUrl(url); | |
if (url.Length != 0) { | |
Console.WriteLine("Opening {0} in browser", url); | |
System.Diagnostics.Process.Start(url); | |
} else { | |
Console.WriteLine("Error: Invalid github url found"); | |
} | |
} else { | |
Console.WriteLine("\nError: No url argument provided"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment