k8s-deploy/src/utilities/fileUtils.ts
dependabot[bot] bf768b3109
Bump the actions group across 1 directory with 7 updates (#346)
* Bump the actions group across 1 directory with 7 updates

Bumps the actions group with 7 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) | `1.10.1` | `1.11.1` |
| [@octokit/core](https://github.com/octokit/core.js) | `3.6.0` | `6.1.2` |
| [@octokit/plugin-retry](https://github.com/octokit/plugin-retry.js) | `3.0.9` | `7.1.2` |
| [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) | `29.5.13` | `29.5.14` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `22.7.4` | `22.8.7` |
| [prettier](https://github.com/prettier/prettier) | `2.8.8` | `3.3.3` |
| [typescript](https://github.com/microsoft/TypeScript) | `5.6.2` | `5.6.3` |



Updates `@actions/core` from 1.10.1 to 1.11.1
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

Updates `@octokit/core` from 3.6.0 to 6.1.2
- [Release notes](https://github.com/octokit/core.js/releases)
- [Commits](https://github.com/octokit/core.js/compare/v3.6.0...v6.1.2)

Updates `@octokit/plugin-retry` from 3.0.9 to 7.1.2
- [Release notes](https://github.com/octokit/plugin-retry.js/releases)
- [Commits](https://github.com/octokit/plugin-retry.js/compare/v3.0.9...v7.1.2)

Updates `@types/jest` from 29.5.13 to 29.5.14
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

Updates `@types/node` from 22.7.4 to 22.8.7
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `prettier` from 2.8.8 to 3.3.3
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/2.8.8...3.3.3)

Updates `typescript` from 5.6.2 to 5.6.3
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release.yml)
- [Commits](https://github.com/microsoft/TypeScript/compare/v5.6.2...v5.6.3)

---
updated-dependencies:
- dependency-name: "@actions/core"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: "@octokit/core"
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: "@octokit/plugin-retry"
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: "@types/jest"
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: actions
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: prettier
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>

* fixed octokit imports

* fix fs imports

* prettier

* babel config

* format

* format action update

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: David Gamero <david340804@gmail.com>
2024-11-07 09:18:35 -05:00

236 lines
7.0 KiB
TypeScript

import fs from 'node:fs'
import * as https from 'https'
import * as path from 'path'
import * as core from '@actions/core'
import * as os from 'os'
import * as yaml from 'js-yaml'
import {Errorable, succeeded, failed, Failed} from '../types/errorable'
import {getCurrentTime} from './timeUtils'
import {isHttpUrl} from './githubUtils'
import {K8sObject} from '../types/k8sObject'
export const urlFileKind = 'urlfile'
export function getTempDirectory(): string {
return process.env['runner.tempDirectory'] || os.tmpdir()
}
export function writeObjectsToFile(inputObjects: any[]): string[] {
const newFilePaths = []
inputObjects.forEach((inputObject: any) => {
try {
const inputObjectString = JSON.stringify(inputObject)
if (inputObject?.metadata?.name) {
const fileName = getNewTempManifestFileName(
inputObject.kind,
inputObject.metadata.name
)
fs.writeFileSync(path.join(fileName), inputObjectString)
newFilePaths.push(fileName)
} else {
core.debug(
'Input object is not proper K8s resource object. Object: ' +
inputObjectString
)
}
} catch (ex) {
core.debug(
`Exception occurred while writing object to file ${inputObject}: ${ex}`
)
}
})
return newFilePaths
}
export function writeManifestToFile(
inputObjectString: string,
kind: string,
name: string
): string {
if (inputObjectString) {
try {
const fileName = getNewTempManifestFileName(kind, name)
fs.writeFileSync(path.join(fileName), inputObjectString)
return fileName
} catch (ex) {
throw Error(
`Exception occurred while writing object to file: ${inputObjectString}. Exception: ${ex}`
)
}
}
}
export function moveFileToTmpDir(originalFilepath: string) {
const tempDirectory = getTempDirectory()
const newPath = path.join(tempDirectory, originalFilepath)
core.debug(`reading original contents from path: ${originalFilepath}`)
const contents = fs.readFileSync(originalFilepath).toString()
const dirName = path.dirname(newPath)
if (!fs.existsSync(dirName)) {
core.debug(`path ${dirName} doesn't exist yet, making new dir...`)
fs.mkdirSync(dirName, {recursive: true})
}
core.debug(`writing contents to new path ${newPath}`)
fs.writeFileSync(path.join(newPath), contents)
core.debug(`moved contents from ${originalFilepath} to ${newPath}`)
return newPath
}
function getNewTempManifestFileName(kind: string, name: string) {
const filePath = `${kind}_${name}_${getCurrentTime().toString()}`
const tempDirectory = getTempDirectory()
return path.join(tempDirectory, path.basename(filePath))
}
export async function getFilesFromDirectoriesAndURLs(
filePaths: string[]
): Promise<string[]> {
const fullPathSet: Set<string> = new Set<string>()
let fileCounter = 0
for (const fileName of filePaths) {
try {
if (isHttpUrl(fileName)) {
try {
const tempFilePath: string = await writeYamlFromURLToFile(
fileName,
fileCounter++
)
fullPathSet.add(tempFilePath)
} catch (e) {
throw Error(
`encountered error trying to pull YAML from URL ${fileName}: ${e}`
)
}
} else if (fs.lstatSync(fileName).isDirectory()) {
recurisveManifestGetter(fileName).forEach((file) => {
fullPathSet.add(file)
})
} else if (
getFileExtension(fileName) === 'yml' ||
getFileExtension(fileName) === 'yaml'
) {
fullPathSet.add(fileName)
} else {
core.debug(
`Detected non-manifest file, ${fileName}, continuing... `
)
}
} catch (ex) {
throw Error(
`Exception occurred while reading the file ${fileName}: ${ex}`
)
}
}
const arr = Array.from(fullPathSet)
return arr
}
export async function writeYamlFromURLToFile(
url: string,
fileNumber: number
): Promise<string> {
return new Promise((resolve, reject) => {
https
.get(url, async (response) => {
const code = response.statusCode ?? 0
if (code >= 400) {
reject(
Error(
`received response status ${response.statusMessage} from url ${url}`
)
)
}
const targetPath = getNewTempManifestFileName(
urlFileKind,
fileNumber.toString()
)
// save the file to disk
const fileWriter = fs
.createWriteStream(targetPath)
.on('finish', () => {
const verification = verifyYaml(targetPath, url)
if (succeeded(verification)) {
core.debug(
`outputting YAML contents from ${url} to ${targetPath}: ${JSON.stringify(
verification.result
)}`
)
resolve(targetPath)
} else {
reject(verification.error)
}
})
response.pipe(fileWriter)
})
.on('error', (error) => {
reject(error)
})
})
}
function verifyYaml(filepath: string, url: string): Errorable<K8sObject[]> {
const fileContents = fs.readFileSync(filepath).toString()
let inputObjects
try {
inputObjects = yaml.loadAll(fileContents)
} catch (e) {
return {
succeeded: false,
error: `failed to parse manifest from url ${url}: ${e}`
}
}
if (!inputObjects || inputObjects.length == 0) {
return {
succeeded: false,
error: `failed to parse manifest from url ${url}: no objects detected in manifest`
}
}
for (const obj of inputObjects) {
if (!obj.kind || !obj.apiVersion || !obj.metadata) {
return {
succeeded: false,
error: `failed to parse manifest from ${url}: missing fields`
}
}
}
return {succeeded: true, result: inputObjects}
}
function recurisveManifestGetter(dirName: string): string[] {
const toRet: string[] = []
fs.readdirSync(dirName).forEach((fileName) => {
const fnwd: string = path.join(dirName, fileName)
if (fs.lstatSync(fnwd).isDirectory()) {
toRet.push(...recurisveManifestGetter(fnwd))
} else if (
getFileExtension(fileName) === 'yml' ||
getFileExtension(fileName) === 'yaml'
) {
toRet.push(path.join(dirName, fileName))
} else {
core.debug(`Detected non-manifest file, ${fileName}, continuing... `)
}
})
return toRet
}
function getFileExtension(fileName: string) {
return fileName.slice(((fileName.lastIndexOf('.') - 1) >>> 0) + 2)
}