I'm using the Github Kohsuke API to search for content on a remote repo on Github. Currently, I'm only able to pull down content from my default master branch. Is there a way to pull down content on a branch besides master? Here's the code snippet I have, which currently only pulls from my master branch. Thanks for any help!
public class GitCompareTest {
public static void main(String[] args) throws IOException {
GitHub github = GitHub.connect();
GHRepository repo = github.getRepository(repo_name);
List<GHContent> articleContents = repo.getDirectoryContent(path);
for (GHContent content : articleContents) {
if (content.isDirectory()) {
PagedIterable<GHContent> childArticleContents = content.listDirectoryContent();
for (GHContent childArticleContent : childArticleContents) {
String childText = childArticleContent.getContent();
String.out.println(childText);
}
}
}
}
}
Try getDirectoryContent(String path, String ref) using your branch's name for ref.
A branch name is essentially a name for a specific commit in git, and "ref" is git terminology for "name of a specific commit".
(Disclaimer: I haven't used Kohsuke's GitHub library yet, I'm drawing from general git knowledge.)
Related
Is there a way to use GitHub's GraphQL API to retrieve the default branch name of a repository? I can build a query to get all the branch names, but none of the properties I see reference the default branch name. Some repositories I deal with have 'master' for their default, and others have 'main'.
I am aware I can use the HEAD in some commands to workaround this. Such as "HEAD:README.md" for fetching the README.md file, like in this example query below. This repository's default branch is 'main', and I only know that from manual trial and error.
query {
repository(owner: "newrelic", name: "newrelic-ruby-agent") {
object(expression: "HEAD:README.md") {
... on Blob {
text
}
}
}
}
But when I check the local cloned copy of that repository, the .git/HEAD file points to ref: refs/heads/dev. So it seems I am actually pulling the README.md file from the dev branch, and not the default branch?
So is there a nice way to get the name of the default branch for a GitHub repository using their GraphQL API?
There's a field defaultBranchRef on the repository object:
query {
repository(owner: "newrelic", name: "newrelic-ruby-agent") {
defaultBranchRef {
name
}
}
}
I'm trying to get a list of submodules of a repository through GitHub API. After reading Github API docs, I did the following things: In Order to access the submodules of the Jquery, I use the following link to get a list of submodules, however, I cannot see any submodules from it. Could anyone please tell me what field should I use to get a list of submodules of a repository from GitHub API?
You can get the list of git submodules using Github GraphQL API v4 with the submodules connection property :
{
repository(owner: "bertrandmartel", name: "javacard-tutorial") {
submodules(first: 100) {
nodes {
name
path
}
}
}
}
Try this in the explorer
Output :
{
"data": {
"repository": {
"submodules": {
"nodes": [
{
"name": "oracle_javacard_sdks",
"path": "oracle_javacard_sdks"
}
]
}
}
}
}
Note that this will give only submodules on default branch's HEAD, from the documentation :
Returns a list of all submodules in this repository parsed from the .gitmodules file as of the default branch's HEAD commit.
Note that the jquery repository doesn't have any git submodules in its default branch's HEAD (and I don't see any in its other branches)
If you use v3 REST API you can
Get the HEAD commit SHA of the branch.
Use the returned commit SHA as the tree_sha to get tree. GET /repos/{owner}/{repo}/git/trees/{tree_sha}
Iterate the returned tree object for entry that has mode 160000 (submodule)
I have a Github organization.
I created a repository and a team to work on it.
I want to restrict push to any branch to it's creator by the default.
So that no one can push to someone's else branch.
Is there any method to do that other than adding rule for every branch manually?
I tried to add rules manually, but it's time consuming cause there are many people joining the team.
Update:
I went to my organization -> teams.
Selected the team, went to members, selected a member.
Clicked on "manage access" next to one repository, clicked "edit".
Set "Base permissions" to "Write".
Set "Repository creation" to "Disabled".
Everything else is left unchecked.
I won't comment on whether or not this is a good idea.
Suffice to say I was annoyed once leading me to create the following update hook to apply to the canonical repo (note however that Github does not allow custom update hooks so you're out of luck there):
#!/usr/bin/env python
import os
import re
import sys
from pathlib import Path
from subprocess import check_output
branch = sys.argv[1]
old_commit = sys.argv[2]
new_commit = sys.argv[3]
zero = "0000000000000000000000000000000000000000"
branch_pattern = 'feature/.+'
def get_author(commit):
return str(check_output(['git', '--no-pager', 'show', '-s', "--format='%an'", commit]).strip(), 'utf-8')
def allow(message=None):
if message:
print(message)
exit(0)
def deny(message=None):
if message:
print(message)
exit(1)
# if this isn't a feature branch bail
if not re.match(branch_pattern, branch):
allow()
# if the update is a delete bail
if new_commit == zero:
allow("update: deleting branch '%s': OK" % branch)
# if this is the first commit on the branch bail
if old_commit == zero:
allow("update: creating branch '%s': OK" % branch)
branch_log = Path('.git', 'logs', 'refs', 'heads').joinpath(*branch.split(os.path.sep))
with open(branch_log, 'r') as log:
first_commit = log.readline(81).split(sep=' ', maxsplit=1)[1]
branch_author = get_author(first_commit)
new_commit_author = get_author(new_commit)
print("update: branch = '%s'; branch author = %s; commit author = %s" % (branch, branch_author, new_commit_author))
if new_commit_author == branch_author:
allow("update: commit author == branch author: OK")
else:
deny(
"update: branch author != commit author: REJECTED\n"
"update: create a branch for your changes from the tip of %s and request a pull instead"
% branch
)
Organization owners and people with admin permissions for organization-owned repositories can enforce branch restrictions so that only certain users or teams are able to push to a protected branch.
For more info, see here
We want to check in the Jenkins home directory into Github, certainly ignoring some files/folders. As we want to have everything defined by code, we try to achieve this using Job DSL & Pipeline DSL (not writing the pipeline script inside Jenkins GUI but having it read from a workspace file - see below).
My problem right now is that, being not very proficient in both DSL's yet, I don't know how to force git to do an initial clone of the remote repo (and later push) inside the home directory - which is a parent directory of the job's directory.
I tried this pipeline:
node('master') {
dir('../..') {
scm {
git {
remote {
github('company/repo', 'https')
credentials('xyz')
}
}
}
}
}
The job itself is defined like this:
pipelineJob('backup') {
definition {
cps {
script(readFileFromWorkspace('pipelines/backup.groovy'))
sandbox(true)
}
}
}
The job fails with this error message:
ERROR: ‘checkout scm’ is only available when using “Multibranch Pipeline” or “Pipeline script from SCM”
So I guess the above used 'pipelineJob(backup)' does not fit. Should I change this, and if, how, or should I take another approach?
Another shot at this was trying to rewrite the pipeline like this:
node {
dir('../..') {
git url: 'https://github.com/company/repo.git'
}
}
But then it won't work because credentials are missing...
How do you create an orphan branch in libgit2sharp?
All i could find are methods which create a branch which points to a commit.
I'm looking for an effect similar to the command:
git checkout --orphan BRANCH_NAME
git checkout --orphan BRANCH_NAME actually moves the HEAD to an unborn branch BRANCH_NAME without altering the working directory nor the index.
You can perform a similar operation with LibGit2Sharp by updating the target of the HEAD reference with repo.Refs.UpdateTarget() method.
The following test demonstrates this
[Fact]
public void CanCreateAnUnbornBranch()
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
// No branch named orphan
Assert.Null(repo.Branches["orphan"]);
// HEAD doesn't point to an unborn branch
Assert.False(repo.Info.IsHeadUnborn);
// Let's move the HEAD to this branch to be created
repo.Refs.UpdateTarget("HEAD", "refs/heads/orphan");
Assert.True(repo.Info.IsHeadUnborn);
// The branch still doesn't exist
Assert.Null(repo.Branches["orphan"]);
// Create a commit against HEAD
var signature = new Signature("Me", "me#there.com", DateTimeOffset.Now);
Commit c = repo.Commit("New initial root commit", signature, signature);
// Ensure this commit has no parent
Assert.Equal(0, c.Parents.Count());
// The branch now exists...
Branch orphan = repo.Branches["orphan"];
Assert.NotNull(orphan);
// ...and points to that newly created commit
Assert.Equal(c, orphan.Tip);
}
}