1# -*- coding: utf-8 -*- 2# Copyright 2020 The ChromiumOS Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Module for manipulating llvm-project-copy. Generally intended for tests.""" 7 8 9import datetime 10import os 11import subprocess 12import sys 13 14import get_llvm_hash 15import git_llvm_rev 16 17 18def get_location() -> str: 19 """Gets the absolute path for llvm-project-copy.""" 20 my_dir = os.path.dirname(os.path.abspath(__file__)) 21 return os.path.join(my_dir, "llvm-project-copy") 22 23 24def ensure_up_to_date(): 25 """Ensures that llvm-project-copy is checked out and semi-up-to-date.""" 26 27 checkout = get_location() 28 if not os.path.isdir(checkout): 29 print( 30 "No llvm-project exists locally; syncing it. This takes a while.", 31 file=sys.stderr, 32 ) 33 actual_checkout = get_llvm_hash.GetAndUpdateLLVMProjectInLLVMTools() 34 assert checkout == actual_checkout, "%s != %s" % ( 35 actual_checkout, 36 checkout, 37 ) 38 39 commit_timestamp = subprocess.check_output( 40 [ 41 "git", 42 "log", 43 "-n1", 44 "--format=%ct", 45 "origin/" + git_llvm_rev.MAIN_BRANCH, 46 ], 47 cwd=checkout, 48 encoding="utf-8", 49 ) 50 51 commit_time = datetime.datetime.fromtimestamp(int(commit_timestamp.strip())) 52 now = datetime.datetime.now() 53 54 time_since_last_commit = now - commit_time 55 56 # Arbitrary, but if it's been more than 2d since we've seen a commit, it's 57 # probably best to bring us up-to-date. 58 if time_since_last_commit <= datetime.timedelta(days=2): 59 return 60 61 print( 62 "%d days have elapsed since the last commit to %s; auto-syncing" 63 % (time_since_last_commit.days, checkout), 64 file=sys.stderr, 65 ) 66 67 result = subprocess.run( 68 ["git", "fetch", "origin"], check=False, cwd=checkout 69 ) 70 if result.returncode: 71 print( 72 "Sync failed somehow; hoping that things are fresh enough, then...", 73 file=sys.stderr, 74 ) 75