1
0
Fork 0
toolkit/packages/core/src/command.ts

88 lines
2.1 KiB
TypeScript
Raw Normal View History

2019-05-21 18:38:29 +00:00
import * as os from 'os'
2019-05-21 18:44:37 +00:00
// For internal use, subject to change.
2019-05-21 21:08:25 +00:00
interface CommandProperties {
[key: string]: string
}
2019-05-21 18:38:29 +00:00
/**
* Commands
*
* Command Format:
* ##[name key=value;key=value]message
*
* Examples:
* ##[warning]This is the user warning message
* ##[set-secret name=mypassword]definitelyNotAPassword!
2019-05-21 18:38:29 +00:00
*/
export function issueCommand(
command: string,
2019-05-21 21:08:25 +00:00
properties: CommandProperties,
2019-05-21 18:38:29 +00:00
message: string
2019-05-21 21:08:25 +00:00
): void {
2019-05-21 18:38:29 +00:00
const cmd = new Command(command, properties, message)
process.stdout.write(cmd.toString() + os.EOL)
}
2019-05-21 21:08:25 +00:00
export function issue(name: string, message: string): void {
2019-05-21 18:38:29 +00:00
issueCommand(name, {}, message)
}
const CMD_PREFIX = '##['
class Command {
2019-05-21 21:08:25 +00:00
private readonly command: string
private readonly message: string
private readonly properties: CommandProperties
constructor(command: string, properties: CommandProperties, message: string) {
2019-05-21 18:38:29 +00:00
if (!command) {
command = 'missing.command'
}
this.command = command
this.properties = properties
this.message = message
}
2019-05-21 21:08:25 +00:00
toString(): string {
2019-05-21 18:38:29 +00:00
let cmdStr = CMD_PREFIX + this.command
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' '
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key]
if (val) {
// safely append the val - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
cmdStr += `${key}=${escape(`${val || ''}`)};`
}
}
}
}
cmdStr += ']'
// safely append the message - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
2019-05-21 21:08:25 +00:00
const message = `${this.message || ''}`
2019-05-21 19:24:46 +00:00
cmdStr += escapeData(message)
2019-05-21 18:38:29 +00:00
return cmdStr
}
}
2019-05-21 19:24:46 +00:00
function escapeData(s: string): string {
2019-05-21 18:38:29 +00:00
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A')
}
function escape(s: string): string {
return s
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
.replace(/]/g, '%5D')
.replace(/;/g, '%3B')
2019-05-21 18:45:27 +00:00
}