Exemplo n.º 1
0
	def set_go_version(self, go_version: str, commit_message: str,
			source_branch_name: str) -> Commit:
		"""
		:param go_version: str
		:param commit_message: str
		:param source_branch_name: str
		:return:
		:rtype: str
		"""
		master: Branch = self.repo.get_branch('master')
		sha: str = master.commit.sha
		ref: str = f'refs/heads/{source_branch_name}'
		self.repo.create_git_ref(ref, sha)

		print(f'Created branch {source_branch_name}')
		go_version_file: str = self.getenv(ENV_GO_VERSION_FILE)
		go_file_contents = self.repo.get_contents(go_version_file, ref)
		kwargs = {'path': go_version_file,
			'message': commit_message,
			'content': (go_version + '\n'),
			'sha': go_file_contents.sha,
			'branch': source_branch_name,
		}
		try:
			git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
			git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
			author: InputGitAuthor = InputGitAuthor(name=git_author_name, email=git_author_email)
			kwargs['author'] = author
			kwargs['committer'] = author
		except KeyError:
			print('Committing using the default author')

		commit: Commit = self.repo.update_file(**kwargs).get('commit')
		print(f'Updated {go_version_file} on {self.repo.name}')
		return commit
Exemplo n.º 2
0
	def push_changes(self, source_branch_name: str, commit_message: str) -> Commit:
		"""
		Commits the changes to the remote
		"""
		target_branch = self.repo.get_branch(self.target_branch_name)
		sha = target_branch.commit.sha
		source_branch_ref = f"refs/heads/{source_branch_name}"
		self.repo.create_git_ref(source_branch_ref, sha)
		print(f"Created branch {source_branch_name}")

		with open(ASF_YAML_FILE, encoding="utf-8") as stream:
			asf_yaml = stream.read()

		asf_yaml_contentfile: ContentFile = self.repo.get_contents(ASF_YAML_FILE, source_branch_ref)
		kwargs = {"path": ASF_YAML_FILE,
			"message": commit_message,
			"content": asf_yaml,
			"sha": asf_yaml_contentfile.sha,
			"branch": source_branch_name,
		}
		try:
			git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=GIT_AUTHOR_NAME)
			author = InputGitAuthor(name=GIT_AUTHOR_NAME, email=git_author_email)
			kwargs["author"] = author
			kwargs["committer"] = author
		except KeyError:
			print("Committing using the default author")

		commit: Commit = self.repo.update_file(**kwargs).get("commit")
		print(f"Updated {ASF_YAML_FILE} on {self.repo.name} branch {source_branch_name}")
		return commit
Exemplo n.º 3
0
def create_github_author(s):
    match = re.match(author_pattern, s)
    if match:
        name = match.group(1)
        email = match.group(2)
        return InputGitAuthor(name=name, email=email)
    else:
        return None
Exemplo n.º 4
0
	def __init__(self, gh_api: Github):
		self.gh_api = gh_api
		self.repo = self.get_repo(getenv(ENV_GITHUB_REPOSITORY))

		try:
			git_author_name = getenv(ENV_GIT_AUTHOR_NAME)
			git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(git_author_name=git_author_name)
			self.author = InputGitAuthor(git_author_name, git_author_email)
		except KeyError:
			self.author = None
			print('Will commit using the default author')
Exemplo n.º 5
0
    def __init__(self, gh: Github) -> None:
        self.gh = gh
        repo_name: str = self.get_repo_name()
        self.repo = self.get_repo(repo_name)

        try:
            git_author_name = self.getenv(ENV_GIT_AUTHOR_NAME)
            git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(
                git_author_name=git_author_name)
            self.author = InputGitAuthor(git_author_name, git_author_email)
        except KeyError:
            self.author = NotSet
            print('Will commit using the default author')
Exemplo n.º 6
0
    def create_tag(self, sha, tag_name, message='', tag_type='commit'):
        """
        Creates a tag associated with the sha provided

        Arguments:
            sha (str): The commit we references by the newly created tag
            tag_name (str): The name of the tag
            message (str): The optional description of the tag
            tag_type (str): The type of the tag. Could be 'tree' or 'blob'. Default is 'commit'.

        Returns:
            github.GitTag.GitTag

        Raises:
            github.GithubException.GithubException:
        """
        self.log_rate_limit()
        tag_user = self.user()
        tagger = InputGitAuthor(
            name=tag_user.name or DEFAULT_TAG_USERNAME,
            # GitHub users without a public email address will use a default address.
            email=tag_user.email or DEFAULT_TAG_EMAIL_ADDRESS,
            date=datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'))

        created_tag = self.github_repo.create_git_tag(tag=tag_name,
                                                      message=message,
                                                      object=sha,
                                                      type=tag_type,
                                                      tagger=tagger)

        try:
            # We need to create a reference based on the tag
            self.github_repo.create_git_ref(
                ref='refs/tags/{}'.format(tag_name), sha=sha)
        except GithubException as exc:
            # Upon trying to create a tag with a tag name that already exists,
            # an "Unprocessable Entity" error with a status code of 422 is returned
            # with a message of 'Reference already exists'.
            # https://developer.github.com/v3/#client-errors
            if exc.status != 422:
                raise
            # Tag is already created. Verify it's on the correct hash.
            existing_tag = self.github_repo.get_git_ref(
                'tags/{}'.format(tag_name))
            if existing_tag.object.sha != sha:
                # The tag is already created and pointed to a different SHA than requested.
                raise GitTagMismatchError(
                    "Tag '{}' exists but points to SHA {} instead of requested SHA {}."
                    .format(tag_name, existing_tag.object.sha, sha))
        return created_tag
Exemplo n.º 7
0
 def git_user(self, user: User) -> InputGitAuthor:
     """
     Return an InputGitAuthor object to be used as a committer.
     Applies default settings for name and email if the input User is None.
     """
     name = settings.GIT_DEFAULT_USER_NAME
     email = settings.GIT_DEFAULT_USER_EMAIL
     if user:
         if features.is_enabled(features.GIT_ANONYMOUS_COMMITS):
             name = f"user_{user.id}"
         else:
             name = user.name or user.username
             email = user.email
     return InputGitAuthor(name, email)
Exemplo n.º 8
0
    def set_go_version(self, go_version: str, commit_message: str,
                       source_branch_name: str) -> Commit:
        """
		Makes the commits necessary to change the Go version used by the
		repository.

		This includes updating the GO_VERSION and .env files at the repository's
		root.
		"""
        master: Branch = self.repo.get_branch('master')
        sha = master.commit.sha
        ref = f'refs/heads/{source_branch_name}'
        self.repo.create_git_ref(ref, sha)

        print(f'Created branch {source_branch_name}')
        go_version_file = getenv(ENV_GO_VERSION_FILE)
        kwargs = {
            "branch": source_branch_name,
            "committer": NotSet,
            "content": f"{go_version}\n",
            "path": go_version_file,
            "message": commit_message,
            "sha": self.file_contents(go_version_file, source_branch_name).sha
        }
        try:
            git_author_name = getenv(ENV_GIT_AUTHOR_NAME)
            git_author_email = GIT_AUTHOR_EMAIL_TEMPLATE.format(
                git_author_name=git_author_name)
            author: InputGitAuthor = InputGitAuthor(name=git_author_name,
                                                    email=git_author_email)
            kwargs["author"] = author
        except KeyError:
            print('Committing using the default author')

        self.repo.update_file(**kwargs)
        print(f'Updated {go_version_file} on {self.repo.name}')
        env_path = os.path.join(os.path.dirname(go_version_file), ".env")
        kwargs["path"] = env_path
        kwargs["content"] = f"GO_VERSION={go_version}\n"
        kwargs["sha"] = self.file_contents(env_path, source_branch_name).sha
        commit: Commit = self.repo.update_file(**kwargs)["commit"]
        print(f"Updated {env_path} on {self.repo.name}")
        return commit
Exemplo n.º 9
0
        input('Double tap enter when pushed changes...')
        input('')

        g = Github(config['user'], config['password'])
        repo = g.get_repo(config['repository'])

        message = 'Tag created at {}'.format(
                datetime.now().strftime('%b %d, %Y %H:%M'))

        branch = repo.get_branch('master')
        sha = repo.get_commits(branch.commit.sha)[0].sha

        tagger = InputGitAuthor(
            name=config['user'],
            email=config['email'],
            date=datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
        )

        t = repo.create_git_tag('v{}'.format(version),
                       message,
                       sha,
                       'commit',
                       tagger)
        repo.create_git_ref('refs/tags/{}'.format(t.tag), t.sha)
        print('tag create success')
    except Exception as e:
        print('Error:', str(e))
        version = botConfig['version']
    finally:
        with open('data/config.json', 'w') as f: