Skip to content

Commit

Permalink
Merge pull request #5 from rajbos/push-to-branch
Browse files Browse the repository at this point in the history
Push to branch
  • Loading branch information
LasyIsLazy committed Sep 22, 2021
2 parents f1cb99f + b5c7b2c commit 9934976
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 14 deletions.
5 changes: 3 additions & 2 deletions README.md
Expand Up @@ -25,7 +25,7 @@ jobs:
with:
access-token: ${{ secrets.ACCESS_TOKEN }}
file-path: localPath
username: LasyIsLazy
owner: LasyIsLazy
repo: githubRepo
remote-dir: remoteDir
```
Expand All @@ -41,7 +41,8 @@ jobs:
| -------------- | -------- | --------------------------- | --------------------------------------------------------------------------------------------------------- |
| access-token || ${{ secrets.ACCESS_TOKEN }} | Token access to repository. |
| file-path || localDir/localPath | Local file path/directory. |
| username || LasyIsLazy | GitHub username. |
| owner || LasyIsLazy | Repo owner. |
| repo || my-repository | Repository name. |
| remote-dir | | remoteDir/remotePath | Remote repository file path/directory(will be created if not exist). Default: The root of the repository. |
| commit-message | | Upload files to GitHub | Git commit message |
| branch-name | | my-branch-name | Branch name to upload the file(s) to. Branch must exists |
7 changes: 5 additions & 2 deletions action.yml
Expand Up @@ -11,11 +11,14 @@ inputs:
file-path:
description: 'Local file path/directory'
required: true
username:
description: 'GitHub username'
owner:
description: 'Repository owner'
required: true
repo:
description: 'Repository name'
required: true
branch-name:
description: 'Branch name to upload the file to'
required: true
remote-dir:
description: 'Remote repository file path/directory, default: The root of repository'
Expand Down
100 changes: 100 additions & 0 deletions checkBranch.js
@@ -0,0 +1,100 @@
/**
* API: https://docs.github.com/en/rest/reference/repos#get-a-branch
*/
const axios = require('axios')
const path = require('path')
const core = require('@actions/core')
const { connected } = require('process')

async function checkBranch(
{ Authorization, owner, repo, branchName }
) {

// load api url from context
let BASE_URL = process.env.GITHUB_API_URL
core.debug(`Using API url: ${BASE_URL}`)
core.debug(`Checking if branch exists with name ${branchName} in repo ${repo}`)

const url =
BASE_URL +
path.posix.join(
`/repos/${owner}/${repo}/branches`
)
core.debug(`Request URL: ${url}`)
// load all branches, since we need the info about the default branch as well
const res = await axios({
method: 'get',
url,
responseType: 'application/json',
headers: {
Authorization,
'Content-Type': 'application/json'
}
})
.then(({data}) => {
// result succesful
let jsonResult = JSON.stringify(data);
core.debug(`Succesful API call with result: ${jsonResult}`)
return { data: data }
})
.catch(err => {
if (err.toString() !== 'Error: Request failed with status code 404') {
console.log(err)
}
// errors should not happen
return { data: { } }
})
let branches = res.data

let json = JSON.stringify(branches);
core.debug(`Branches: ${json}`)

if (branches == null) {
core.debug(`Error loading existing branches from API`)
return null
}

// check if the branch name already exists
let branch = branches.find(function(branch) { return branch.name === branchName })

if (branch) {
core.debug(`Branch with name ${branchName} already exists, continuing as normal`)
return { }
}
else {
console.log(`Need to create a new branch first with name ${branchName}`)
let defaultBranch = branches[0]
console.log(`Found default branch to branch of: ${defaultBranch.name} with sha: ${defaultBranch.commit.sha}`)

let branchCreateUrl = BASE_URL +
path.posix.join(
`/repos/${owner}/${repo}/git/refs`
)
core.debug(`Request URL to create new branch: ${branchCreateUrl}`)

return axios({
method: 'post',
url: branchCreateUrl,
responseType: 'application/json',
headers: {
Authorization,
'Content-Type': 'application/json'
},
data: {
ref: `refs/heads/${branchName}`,
sha: defaultBranch.commit.sha
}
}).then(({ data }) => {
core.debug(`Branch with name ${defaultBranch.name} created`)
// return non empty object to check on
console.log(`Created new branch with ref: ${data.ref} based on ${defaultBranch.name}`)
return { }
}).catch(err => {
core.debug(`Error creatng new branch: ${err}`)
console.log(`Error creating the branch with name ${branchName} and sha ${defaultBranch.commit.sha}: ${error}`)
return null
})
}
}
module.exports = checkBranch

55 changes: 48 additions & 7 deletions index.js
Expand Up @@ -2,20 +2,42 @@ const fs = require('fs')
const path = require('path')
const upload = require('./upload.js')
const core = require('@actions/core')
const checkBranch = require('./checkBranch.js')
const inputPath = core.getInput('file-path')
const inputRemoteDir = core.getInput('remote-dir')
const inputUsername = core.getInput('username')
const inputOwner = core.getInput('owner')
const inputRepo = core.getInput('repo')
const commitMessage = core.getInput('commit-message')
const branchName = core.getInput('branch-name')
core.debug('Input path: ' + inputPath)
core.debug('Input remoteDir: ' + inputRemoteDir)
core.debug('Input username: ' + inputUsername)
core.debug('Input owner: ' + inputOwner)
core.debug('Input repo: ' + inputRepo)
core.debug('Input commitMessage: ' + commitMessage)
core.debug('Input branchName: ' + branchName)

if (!fs.existsSync(inputPath)) {
core.setFailed(`filePath doesn't exist: ${inputPath}`)
return
}

async function createBranchIfNotExists() {
let branchResult = await checkBranch({
Authorization: `Bearer ${core.getInput('access-token')}`,
owner: inputOwner,
repo: inputRepo,
branchName
})

if (branchResult == null) {
core.setFailed('Error checking or creating the branch')
return false
}
else {
return true
}
}

const isInputPathDir = fs.lstatSync(inputPath).isDirectory()
const localDir = isInputPathDir ? inputPath : ''

Expand All @@ -40,26 +62,45 @@ const filePaths = isInputPathDir ? getAllFilePaths(inputPath) : [inputPath]
core.debug(`filePaths: ${filePaths}`)

async function uploadAll() {

try {
let branchExists = await createBranchIfNotExists()
if (!branchExists) {
core.setFailed(error)
return
}
} catch (error) {
// break off further execution
core.setFailed(error)
return
}

for (let index = 0; index < filePaths.length; index++) {
const curPath = filePaths[index]
const remotePath = path.join(
// `remotePath` can not start with `/`
inputRemoteDir.replace(/^\//, ''),
path.relative(localDir, curPath)
)
console.log(`Upload ${curPath} to ${remotePath}`)
const base64Cotent = fs.readFileSync(curPath, {
console.log(`Upload ${curPath} to ${remotePath} on branch ${branchName} for repository ${inputRepo}`)
const base64Content = fs.readFileSync(curPath, {
encoding: 'base64'
})
try {
await upload(base64Cotent, {
let result = await upload(base64Content, {
Authorization: `Bearer ${core.getInput('access-token')}`,
username: inputUsername,
owner: inputOwner,
repo: inputRepo,
commitMessage,
remotePath
remotePath,
branchName
})

if (result === null) {
core.setFailed('Error uploading the file')
}
} catch (error) {
console.log('Unhandled error uploading the file')
core.setFailed(error)
}
}
Expand Down
10 changes: 7 additions & 3 deletions upload.js
Expand Up @@ -7,7 +7,7 @@ const core = require('@actions/core')

async function upload(
base64Content,
{ Authorization, remotePath, username, repo, commitMessage }
{ Authorization, remotePath, owner, repo, commitMessage, branchName }
) {

// load api url from context
Expand All @@ -17,7 +17,7 @@ async function upload(
const url =
BASE_URL +
path.posix.join(
`/repos/${username}/${repo}/contents`,
`/repos/${owner}/${repo}/contents`,
// GitHub API will decode the remotePath
encodeURIComponent(remotePath)
)
Expand Down Expand Up @@ -52,7 +52,8 @@ async function upload(
data: {
message: commitMessage,
sha,
content: base64Content
content: base64Content,
branch: branchName
}
}).then(({ data }) => {
const { path, sha: currentSha } = data.content
Expand All @@ -66,6 +67,9 @@ async function upload(
sha,
currentSha
}
}).catch(err => {
console.log(`Error uploading the file. Check if the branch [${branchName}] exists and if the access-token has write rights.`)
return null
})
}
module.exports = upload

0 comments on commit 9934976

Please sign in to comment.