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

91 lines
1.9 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:
2020-01-19 04:52:44 +00:00
* ::name key=value,key=value::message
2019-05-21 18:38:29 +00:00
*
* Examples:
2020-01-19 04:52:44 +00:00
* ::warning::This is the message
* ::set-env name=MY_VAR::some value
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-08-29 02:35:27 +00:00
export function issue(name: string, message: string = ''): void {
2019-05-21 18:38:29 +00:00
issueCommand(name, {}, message)
}
const CMD_STRING = '::'
2019-05-21 18:38:29 +00:00
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 {
let cmdStr = CMD_STRING + this.command
2019-05-21 18:38:29 +00:00
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' '
let first = true
2019-05-21 18:38:29 +00:00
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key]
if (val) {
if (first) {
first = false
} else {
cmdStr += ','
}
2020-01-19 04:52:44 +00:00
cmdStr += `${key}=${escapeProperty(val)}`
2019-05-21 18:38:29 +00:00
}
}
}
}
2020-01-19 04:52:44 +00:00
cmdStr += `${CMD_STRING}${escapeData(this.message)}`
2019-05-21 18:38:29 +00:00
return cmdStr
}
}
2019-05-21 19:24:46 +00:00
function escapeData(s: string): string {
2020-01-19 04:52:44 +00:00
return (s || '')
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
2019-05-21 18:38:29 +00:00
}
2020-01-19 04:52:44 +00:00
function escapeProperty(s: string): string {
return (s || '')
.replace(/%/g, '%25')
2019-05-21 18:38:29 +00:00
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
2020-01-19 04:52:44 +00:00
.replace(/:/g, '%3A')
.replace(/,/g, '%2C')
2019-05-21 18:45:27 +00:00
}