Skip to content

Commit

Permalink
Refactor: replace API with octokit (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
LasyIsLazy authored Nov 28, 2021
1 parent d3c5a7d commit 997e5c8
Show file tree
Hide file tree
Showing 375 changed files with 75,372 additions and 7,436 deletions.
33 changes: 33 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module.exports = {
'env': {
'commonjs': true,
'es6': true,
'node': true
},
'extends': 'eslint:recommended',
'globals': {
'Atomics': 'readonly',
'SharedArrayBuffer': 'readonly'
},
'parserOptions': {
'ecmaVersion': 2018
},
'rules': {
'indent': [
'error',
4
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'never'
]
}
}
145 changes: 55 additions & 90 deletions checkBranch.js
Original file line number Diff line number Diff line change
@@ -1,100 +1,65 @@
/**
* 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}`)
const core = require('@actions/core')
const github = require('@actions/github')

if (branches == null) {
core.debug(`Error loading existing branches from API`)
return null
}
async function checkBranch({ token, owner, repo, branchName }) {
const octokit = github.getOctokit(token)

// check if the branch name already exists
let branch = branches.find(function(branch) { return branch.name === branchName })
core.debug(
`Checking if branch exists with name ${branchName} in repo ${repo}`
)

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}`)
// load all branches, since we need the info about the default branch as well
const { data: branches } = await octokit.rest.repos
.listBranches({ owner, repo })
.catch(({ status, data, message }) => {
core.error('Error loading existing branches from API')
core.debug(`status: ${status}`)
core.error(JSON.stringify(data))
throw new Error(message)
})
core.debug(`Branches: ${JSON.stringify(branches)}`)

let branchCreateUrl = BASE_URL +
path.posix.join(
`/repos/${owner}/${repo}/git/refs`
)
core.debug(`Request URL to create new branch: ${branchCreateUrl}`)
if (!branches || !branches.length) {
throw new Error('No branches found')
}

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
// 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`
)
core.debug('✔️ Check branch Done')
return branch
} else {
core.debug(`Need to create a new branch first with name ${branchName}`)
let defaultBranch = branches[0]
core.debug(
`Found default branch to branch of: ${defaultBranch.name} with sha: ${defaultBranch.commit.sha}`
)

// Docs: https://octokit.github.io/rest.js/v18#git-create-ref
const { data } = await octokit.rest.git
.createRef({
owner,
repo,
ref: `refs/heads/${branchName}`,
sha: defaultBranch.commit.sha,
})
.catch(err => {
core.error(`Error creatng new branch: ${err}`)
throw err
})
core.debug(
`Created new branch with ref: ${data.ref} based on ${defaultBranch.name}`
)
}
}
module.exports = checkBranch
core.debug('✔️ Check branch Done')
}
module.exports = checkBranch
128 changes: 54 additions & 74 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const inputOwner = core.getInput('owner')
const inputRepo = core.getInput('repo')
const commitMessage = core.getInput('commit-message')
const branchName = core.getInput('branch-name')
const token = core.getInput('access-token')
core.debug('Input path: ' + inputPath)
core.debug('Input remoteDir: ' + inputRemoteDir)
core.debug('Input owner: ' + inputOwner)
Expand All @@ -17,98 +18,77 @@ core.debug('Input commitMessage: ' + commitMessage)
core.debug('Input branchName: ' + branchName)

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

if (inputRepo.indexOf('/') !== -1) {
core.setFailed(`inputRepo cannot contain any slashes use the owner parameter to indicate the owner`)
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
}
core.setFailed(
'inputRepo cannot contain any slashes use the owner parameter to indicate the owner'
)
return
}

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

function getAllFilePaths(curDir) {
function search(curPath, paths = []) {
const dir = fs.readdirSync(curPath)
dir.forEach(item => {
const itemPath = path.join(curPath, item)
const stat = fs.lstatSync(itemPath)
if (stat.isDirectory()) {
search(itemPath, paths)
} else {
paths.push(itemPath)
}
})
return paths
}
return search(curDir)
function search(curPath, paths = []) {
const dir = fs.readdirSync(curPath)
dir.forEach(item => {
const itemPath = path.join(curPath, item)
const stat = fs.lstatSync(itemPath)
if (stat.isDirectory()) {
search(itemPath, paths)
} else {
paths.push(itemPath)
}
})
return paths
}
return search(curDir)
}

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} on branch ${branchName} for repository ${inputRepo}`)
const base64Content = fs.readFileSync(curPath, {
encoding: 'base64'
})
try {
let result = await upload(base64Content, {
Authorization: `Bearer ${core.getInput('access-token')}`,
owner: inputOwner,
repo: inputRepo,
commitMessage,
remotePath,
branchName
})

if (result === null) {
core.setFailed('Error uploading the file')
}
await checkBranch({
token,
owner: inputOwner,
repo: inputRepo,
branchName,
})
} catch (error) {
console.log('Unhandled error uploading the file')
core.setFailed(error)
core.setFailed(`checkBranch failed: ${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)
)
core.debug(
`Upload ${curPath} to ${remotePath} on branch ${branchName} for repository ${inputRepo}`
)
try {
await upload(curPath, {
token,
owner: inputOwner,
repo: inputRepo,
commitMessage,
remotePath,
branchName,
})
} catch (error) {
core.setFailed(`Upload ${curPath} failed: ${error}`)
return
}
}
}
}

uploadAll()
31 changes: 28 additions & 3 deletions node_modules/.yarn-integrity

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 997e5c8

Please sign in to comment.