| #!/usr/bin/python | |
| # Copyright (C) 2012 Google Inc. | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| """ | |
| Configures git to authenticate to *.googlesource.com. | |
| Adds a cookie to ~/.git-credential-cache/cookies and sets | |
| Git variable http.cookiefile to this path. | |
| """ | |
| from __future__ import print_function | |
| import os | |
| from subprocess import Popen, PIPE, check_call | |
| import sys | |
| if sys.version_info[0] > 2: | |
| # Python 3 imports | |
| import http.cookiejar as cookielib | |
| else: | |
| # Python 2 imports | |
| import cookielib | |
| try: | |
| # We want to use raw_input in Python 2. | |
| input = raw_input | |
| except NameError: | |
| # raw_input does not exist in in Python 3 and has been | |
| # renamed to input. | |
| pass | |
| def write_cookie(token): | |
| git_config = ['git', 'config', '--global', 'http.cookiefile'] | |
| set_config = False | |
| fn = Popen(git_config, stdout=PIPE).communicate()[0].decode('utf-8') | |
| if fn == '': | |
| home = os.environ['HOME'] | |
| fn = os.path.join(home, '.git-credential-cache', 'cookies') | |
| set_config = True | |
| elif fn[-1] == '\n': | |
| fn = fn[:-1] | |
| dir = os.path.dirname(fn) | |
| if os.path.exists(dir): | |
| os.chmod(dir, 0o700) | |
| else: | |
| os.mkdir(dir, 0o700) | |
| cj = cookielib.MozillaCookieJar(fn) | |
| if os.path.exists(cj.filename): | |
| cj.load() | |
| cj.set_cookie(cookielib.Cookie( | |
| version = 0, | |
| name = 'o', | |
| value = token, | |
| port = None, | |
| port_specified = False, | |
| domain = '.googlesource.com', | |
| domain_specified = True, | |
| domain_initial_dot = True, | |
| path = '/', | |
| path_specified = True, | |
| secure = True, | |
| expires = (1 << 31) - 1, | |
| discard = False, | |
| comment = None, | |
| comment_url = None, | |
| rest = {})) | |
| cj.save() | |
| os.chmod(cj.filename, 0o600) | |
| if set_config: | |
| check_call(git_config + [cj.filename]) | |
| return cj.filename | |
| def main(): | |
| print('Open https://www.googlesource.com/new-password ...') | |
| t = input("Password (under 'Login for Git'): ") | |
| p = write_cookie(t) | |
| print("Saved to %s" % (p,)) | |
| if __name__ == '__main__': | |
| main() |