Created
February 20, 2017 16:04
-
-
Save onnimonni/8cf6bac9331bbb1ddbe7fea97845a579 to your computer and use it in GitHub Desktop.
Slightly edited version from https://www.cabbages-and-kings.net/2015/04/22/launching_gpg_agent_at_login_on_os_x.html
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
#!/usr/bin/env python | |
import os | |
import re | |
import subprocess | |
import sys | |
def main(): | |
# If necessary, run gpg-agent | |
if not is_running(): | |
subprocess.check_output(["/usr/local/bin/gpg-agent", "--daemon"]) | |
# Once it is running, parse its environment file | |
env_file = find_environment_file() | |
environment = parse_environment_file(env_file) | |
# Set environment for later processes | |
for name, value in environment.items(): | |
subprocess.check_call(["launchctl", "setenv", name, value]) | |
def find_environment_file(): | |
config_file = os.path.join(os.path.expanduser("~"), ".gnupg", "gpg-agent.conf") | |
env_file = None | |
try: | |
with open(config_file) as fd: | |
for line in fd.readlines(): | |
line = line.strip() | |
match = re.match(r"([^ ]+) ([^ ]+)", line) | |
if match and match.group(1) == "write-env-file": | |
env_file = match.group(2) | |
except IOError as e: | |
raise Exception("Could not open configuration file: {}".format(e)) | |
# Use default path if no config was mentioned | |
if env_file is None: | |
env_file = os.path.join(os.path.expanduser("~"), ".gpg-agent-info") | |
return env_file | |
def parse_environment_file(environment_file): | |
environment = {} | |
try: | |
with open(environment_file) as fd: | |
for line in fd.readlines(): | |
line = line.strip() | |
match = re.match(r"([^=]+)=(.*)", line) | |
if match: | |
name, value = match.groups() | |
environment[name] = value | |
except IOError as e: | |
raise Exception("Could not open environment file: {}".format(e)) | |
return environment | |
def is_running(): | |
env_file = find_environment_file() | |
environment = parse_environment_file(env_file) | |
gpg_agent_info = environment.get("GPG_AGENT_INFO", "") | |
running = True | |
match = re.match(r"([^:]+):([^:]+):([^:]+)", gpg_agent_info) | |
if match: | |
pid = int(match.group(2)) | |
try: | |
os.kill(pid, 0) | |
except OSError: | |
running = False | |
else: | |
running = False | |
return running | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment