from django.core.exceptions import ObjectDoesNotExist

from db.models.repos import CodeReference


def get_project_code_reference(project, commit=None):
    if not project.has_code:
        return None

    repo = project.repo

    if commit:
        try:
            return CodeReference.objects.get(repo=repo, commit=commit)
        except ObjectDoesNotExist:
            return None

    # If no commit is provided we get the last commit, and save new ref if not found
    last_commit = repo.last_commit
    if not last_commit:
        return None

    code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
    return code_reference


def get_code_reference(instance, commit):
    return get_project_code_reference(instance.project, commit=commit)


def assign_code_reference(instance, commit=None):
    if instance.code_reference is not None:
        return
    if not commit and instance.specification and instance.specification.build:
        commit = instance.specification.build.commit
    code_reference = get_code_reference(instance=instance, commit=commit)
    if code_reference:
        instance.code_reference = code_reference

    return instance

@@ -96,32 +96,24 @@
 e%0A%0A%0Adef get_
-project_
 code_referen
@@ -115,23 +115,24 @@
 ference(
-project
+instance
 , commit
@@ -140,84 +140,163 @@
 None
-):%0A    if not project.has_code:%0A        return None%0A%0A    repo = project.repo
+, external_repo=None):%0A    project = instance.project%0A%0A    repo = project.repo if project.has_code else external_repo%0A%0A    if not repo:%0A        return None
 %0A%0A  
@@ -743,123 +743,8 @@
 e%0A%0A%0A
-def get_code_reference(instance, commit):%0A    return get_project_code_reference(instance.project, commit=commit)%0A%0A%0A
 def 
@@ -856,25 +856,15 @@
     
-if not commit and
+build =
  ins
@@ -882,20 +882,25 @@
 fication
- and
+.build if
  instanc
@@ -918,141 +918,322 @@
 tion
-.build:%0A        commit = instance.specification.build.commit%0A    code_reference = get_code_reference(instance=instance, commit=commit
+ else None%0A    if not commit and build:%0A        commit = build.commit%0A    external_repo = build.git if build and build.git else None%0A    code_reference = get_code_reference(instance=instance,%0A                                        commit=commit,%0A                                        external_repo=external_repo
 )%0A  

Extend code references with external repos