os#EOL TypeScript Examples
The following examples show how to use
os#EOL.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: workspace-util.ts From vscode-code-review with MIT License | 7 votes |
getFileContentForRange = (pathToFile: string, range: Range): string => {
let fileContent = '';
try {
fileContent = fs.readFileSync(pathToFile, 'utf8');
} catch (error) {
console.log('Error reading file', pathToFile, error);
}
const fileContentLines = fileContent.split(EOL);
return fileContentLines.slice(range.start.line, range.end.line).join(EOL);
}
Example #2
Source File: storage-utils.ts From vscode-code-review with MIT License | 7 votes |
/**
* Store the comments
*
* @param pathToFile The path to the file to write
* @param rows The lines to store
* @param overwrite Replace all (true) / append (false)
* @return true if the operation was successful, false otherwise
*/
export function setCsvFileLines(pathToFile: string, rows: string[], overwrite: boolean = true): boolean {
// The last line of the file must always be terminated with an EOL
const content = cleanCsvStorage(rows).join(EOL) + EOL;
try {
if (overwrite) {
fs.writeFileSync(pathToFile, content);
} else {
fs.appendFileSync(pathToFile, content);
}
return true;
} catch (error) {
console.log('Error writing content of file', pathToFile, error);
return false;
}
}
Example #3
Source File: storage-utils.ts From vscode-code-review with MIT License | 7 votes |
/**
* Get the lines as stored in CSV
*
* @param pathToFile The path to the CSV file
* @return Generator<string>
*/
export function* getCsvFileLinesAsIterable(pathToFile: string): Generator<string> {
let fileContent = '';
try {
fileContent = fs.readFileSync(pathToFile, 'utf8');
} catch (error) {
console.log('Error reading header from file', pathToFile, error);
return;
}
for (const line of cleanCsvStorage(fileContent.split(EOL))) {
yield line;
}
}
Example #4
Source File: rc.ts From free-swagger with MIT License | 6 votes |
private stringifyConfigData(rcConfig: RcConfig): string {
const data = JSON.stringify(rcConfig)
// hack: 由于 JSON.stringify 不能保存函数,这里手动将函数拼接并写入 rc 文件
// 去除尾部分号,否则会报词法错误
let templateFunction = this.configData.core.templateFunction
?.toString()
.replace(EOL, '')
.trim()
if (templateFunction?.endsWith(';')) {
templateFunction = templateFunction.slice(0, templateFunction.length - 1)
}
const functionCode = `templateFunction: ${templateFunction}`
const index = data.search(/"source"/)
if (index === -1) {
throw new Error(
'找不到 source 属性,运行 free-swagger-cli -r 重置 rc 文件'
)
}
const prevCode = data.slice(0, index)
const afterCode = data.slice(index, data.length)
return prettier.format(
`${MODULE_EXPORTS} ${prevCode} ${functionCode}, ${afterCode}`,
{
parser: 'babel',
}
)
}
Example #5
Source File: getCompletions.ts From language-tools with MIT License | 6 votes |
componentDocumentationCompletion: CompletionItem = {
label: '@component',
insertText: `component${EOL}$1${EOL}`,
documentation:
'Documentation for this component. ' +
'It will show up on hover. You can use markdown and code blocks here',
insertTextFormat: InsertTextFormat.Snippet,
kind: CompletionItemKind.Snippet,
sortText: '-1',
filterText: 'component',
preselect: true
}
Example #6
Source File: getQuickfixes.ts From language-tools with MIT License | 6 votes |
async function getSvelteIgnoreEdit(svelteDoc: SvelteDocument, ast: Ast, diagnostic: Diagnostic) {
const {
code,
range: { start, end }
} = diagnostic;
const transpiled = await svelteDoc.getTranspiled();
const content = transpiled.getText();
const lineOffsets = getLineOffsets(content);
const { html } = ast;
const generatedStart = transpiled.getGeneratedPosition(start);
const generatedEnd = transpiled.getGeneratedPosition(end);
const diagnosticStartOffset = offsetAt(generatedStart, content, lineOffsets);
const diagnosticEndOffset = offsetAt(generatedEnd, content, lineOffsets);
const offsetRange: ts.TextRange = {
pos: diagnosticStartOffset,
end: diagnosticEndOffset
};
const node = findTagForRange(html, offsetRange);
const nodeStartPosition = positionAt(node.start, content, lineOffsets);
const nodeLineStart = offsetAt(
{
line: nodeStartPosition.line,
character: 0
},
content,
lineOffsets
);
const afterStartLineStart = content.slice(nodeLineStart);
const indent = getIndent(afterStartLineStart);
// TODO: Make all code action's new line consistent
const ignore = `${indent}<!-- svelte-ignore ${code} -->${EOL}`;
const position = Position.create(nodeStartPosition.line, 0);
return mapObjWithRangeToOriginal(transpiled, TextEdit.insert(position, ignore));
}
Example #7
Source File: runAndLog.ts From task-scheduler with MIT License | 6 votes |
async function runAndCollectLogs(
runner: (stdout: Writable, stderr: Writable) => Promise<boolean>,
globals: Globals
): Promise<TaskResult> {
const stdout = new streams.WritableStream();
const stderr = new streams.WritableStream();
try {
const success = await runner(stdout, stderr);
return { success, stdout: stdout.toString(), stderr: stderr.toString() };
} catch (error) {
if (error) {
const exceptionMessage = globals.errorFormatter(error);
stderr.write(EOL + exceptionMessage);
}
return {
success: false,
stdout: stdout.toString(),
stderr: stderr.toString(),
};
}
}
Example #8
Source File: output.ts From task-scheduler with MIT License | 6 votes |
/*
* format stdout and stderr in the following format:
*
* ```
* STDOUT:
* | some output
* STDERR:
* | some stderr output
* ```
*/
export function formatOutput(result: TaskResult): string {
let message = "";
if (result.stdout.length !== 0) {
message += `STDOUT${EOL}`;
message += prefix(result.stdout, " | ");
message += `${EOL}`;
}
if (result.stderr.length !== 0) {
message += `STDERR${EOL}`;
message += prefix(result.stderr, " | ");
message += `${EOL}`;
}
return message;
}
Example #9
Source File: output.ts From task-scheduler with MIT License | 6 votes |
/*
* Take a block of text and add a prefix in front of each line.
*/
function prefix(message: string, prefix: string): string {
return (
prefix +
message
.split(EOL)
.filter((m) => m !== "")
.join(`${EOL}${prefix}`)
);
}
Example #10
Source File: output.ts From task-scheduler with MIT License | 6 votes |
/*
* Ouptut to console the result of a task.
*/
export function outputResult(
message: string,
p: string,
name: string,
result: "success" | "failure",
logger: Logger
): void {
const state = result === "success" ? "Done" : "Failed";
const log = result === "success" ? logger.log : logger.error;
if (message === "") {
log(`${state} ${name} in ${p}${EOL}`);
} else {
log(` / ${state} ${name} in ${p}`);
log(prefix(message, " | "));
log(` \\ ${state} ${name} in ${p}${EOL}`);
}
}
Example #11
Source File: record-page-errors.ts From playwright-fluent with MIT License | 6 votes |
export async function recordPageErrors(
page: Page | undefined,
callback: (error: Error) => void,
): Promise<void> {
if (!page) {
throw new Error(`Cannot record page errors because no browser has been launched`);
}
page.on('pageerror', (err) => {
callback(err);
});
page.on('console', async (msg) => {
try {
if (msg.type() === 'error') {
const location = msg.location();
const text = msg
.text()
.replace(/JSHandle@object/g, '')
.trim();
const args = msg.args();
const stackTrace: string[] = [];
stackTrace.push(`at '${location.url}'`);
stackTrace.push(`line: ${location.lineNumber}`);
for (let index = 1; index < args.length; index++) {
const arg = args[index];
const argValue = JSON.stringify(await arg.jsonValue(), null, 2);
stackTrace.push(argValue);
}
const err = new Error(text);
err.stack = stackTrace.join(EOL);
callback(err);
}
} catch (error) {
callback(error as Error);
}
});
}
Example #12
Source File: diagnostics.ts From fakesharper with MIT License | 6 votes |
export function updateDiagnostics(files: File[], diagnosticCollection: vscode.DiagnosticCollection): void {
for (let i = 0; i < files.length; i++) {
const file: File = files[i];
const data: string = readFileSync(file.path);
const uri: vscode.Uri = vscode.Uri.file(file.path);
diagnosticCollection.set(uri, file.issues.map(issue => ({
message: issue.message + (issue.issueType.wikiUrl ? EOL + issue.issueType.wikiUrl : ''),
range: getIssueRange(data, issue),
severity: getIssueSeverity(issue),
code: issue.typeId,
source: EXTENSION_NAME
})));
}
}
Example #13
Source File: SearchHelper.ts From remix-project with MIT License | 6 votes |
function getEOL(text) {
const m = text.match(/\r\n|\n/g);
const u = m && m.filter(a => a === '\n').length;
const w = m && m.length - u;
if (u === w) {
return EOL; // use the OS default
}
return u > w ? '\n' : '\r\n';
}
Example #14
Source File: service-generator.ts From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
getSteadyContent = (filePath: string, content?: string) => {
if (!fs.existsSync(filePath) || !content) {
return `
${license.GPLV3}`;
} else if (!content.includes('GENERATED')) {
return `${content}
// > AUTO GENERATED
`;
} else {
const lastIndex = content.indexOf('GENERATED');
const steadyContent = lastIndex ? content.slice(0, lastIndex + 9) : content;
return `${steadyContent}${EOL}`;
}
}
Example #15
Source File: AssertionError.ts From earl with MIT License | 6 votes |
constructor(options: AssertionErrorOptions) {
let message = options.message
if (options.extraMessage) {
message += EOL + 'Extra message: ' + options.extraMessage
}
super(message)
this.name = 'AssertionError'
this.actual = options.actual
this.expected = options.expected
this.stack = `${this.name}: ${this.message}\n${options.stack}`
}
Example #16
Source File: file-generator.ts From vscode-code-review with MIT License | 6 votes |
/**
* Try to create the code review file if not already exist
*
* @return boolean true if the file was successfully created, false otherwise
*/
public create(): boolean {
if (fs.existsSync(this.absoluteReviewFilePath)) {
if (!this.check()) {
return false;
}
} else {
try {
fs.writeFileSync(this.absoluteReviewFilePath, `${CsvStructure.headerLine}${EOL}`);
window.showInformationMessage(`Code review file: '${this.absoluteReviewFilePath}' successfully created.`);
} catch (err) {
window.showErrorMessage(
`Error when trying to create code review file: '${this.absoluteReviewFilePath}': ${err}`,
);
return false;
}
}
return true;
}
Example #17
Source File: export-factory.ts From vscode-code-review with MIT License | 6 votes |
private getCodeForFile(filename: string, lines: string): string {
if (!filename) {
filename = '';
}
if (!lines) {
lines = '';
}
let result = '';
const lineRanges = splitStringDefinition(lines); // split: 2:2-12:2|8:0-18:5
const filePath = toAbsolutePath(this.workspaceRoot, filename);
if (lineRanges) {
lineRanges.forEach((rangeString: string) => {
if (rangeString) {
const range = rangeFromStringDefinition(rangeString, 1);
const fileContent = stripIndent(getFileContentForRange(filePath, range));
if (result) {
result = `${result}${EOL}...${EOL}${EOL}${fileContent}`;
} else {
result = fileContent;
}
}
});
}
return encode(result);
}
Example #18
Source File: npmLogin.ts From cli with Apache License 2.0 | 6 votes |
npmLogin = async () => {
const args = [...npm(), 'adduser', '--registry=http://localhost:4873'];
const npmAddUser = new Terminal(args.shift()!, args);
npmAddUser.orchestrator.process.stdout.pipe(process.stdout);
npmAddUser.orchestrator.process.stderr.pipe(process.stderr);
npmAddUser
.when(/Username:/)
.on('stdout')
.do(answerPrompt(`notgroot${EOL}`))
.until(/Password:/);
npmAddUser
.when(/Password:/)
.on('stdout')
.do(answerPrompt(`notGrootButMoreThan10CharactersReally${EOL}`))
.until(/Email:/);
npmAddUser
.when(/Email:/)
.on('stdout')
.do(answerPrompt(`[email protected]${EOL}`))
.until(/Logged in as/);
await npmAddUser
.when(/Logged in as/)
.on('stdout')
.do()
.once();
}
Example #19
Source File: file.ts From cli with Apache License 2.0 | 6 votes |
export function saveToEnvFile(
pathToEnv: string,
additionalEnvironment: Record<string, unknown>
) {
ensureFileSync(pathToEnv);
const environment = parse(readFileSync(pathToEnv, {encoding: 'utf-8'}));
const updatedEnvironment = {
...environment,
...additionalEnvironment,
};
truncateSync(pathToEnv);
for (const [key, value] of Object.entries(updatedEnvironment)) {
appendFileSync(pathToEnv, `${key}=${value}${EOL}`);
}
}
Example #20
Source File: default.renderer.ts From listr2 with MIT License | 6 votes |
public createRender (options?: { tasks?: boolean, bottomBar?: boolean, prompt?: boolean }): string {
options = {
...{
tasks: true,
bottomBar: true,
prompt: true
},
...options
}
const render: string[] = []
const renderTasks = this.multiLineRenderer(this.tasks)
const renderBottomBar = this.renderBottomBar()
const renderPrompt = this.renderPrompt()
if (options.tasks && renderTasks?.trim().length > 0) {
render.push(renderTasks)
}
if (options.bottomBar && renderBottomBar?.trim().length > 0) {
render.push((render.length > 0 ? EOL : '') + renderBottomBar)
}
if (options.prompt && renderPrompt?.trim().length > 0) {
render.push((render.length > 0 ? EOL : '') + renderPrompt)
}
return render.length > 0 ? render.join(EOL) : ''
}
Example #21
Source File: default.renderer.ts From listr2 with MIT License | 6 votes |
public end (): void {
clearInterval(this.id)
if (this.id) {
this.id = undefined
}
// clear log updater
logUpdate.clear()
logUpdate.done()
// directly write to process.stdout, since logupdate only can update the seen height of terminal
if (!this.options.clearOutput) {
process.stdout.write(this.createRender({ prompt: false }) + EOL)
}
}
Example #22
Source File: default.renderer.ts From listr2 with MIT License | 6 votes |
private renderBottomBar (): string {
// parse through all objects return only the last mentioned items
if (Object.keys(this.bottomBar).length > 0) {
this.bottomBar = Object.keys(this.bottomBar).reduce<Record<PropertyKey, { data?: string[], items?: number }>>((o, key) => {
if (!o?.[key]) {
o[key] = {}
}
o[key] = this.bottomBar[key]
this.bottomBar[key].data = this.bottomBar[key].data.slice(-this.bottomBar[key].items)
o[key].data = this.bottomBar[key].data
return o
}, {})
return Object.values(this.bottomBar)
.reduce((o, value) => o = [ ...o, ...value.data ], [])
.filter(Boolean)
.join(EOL)
}
}
Example #23
Source File: default.renderer.ts From listr2 with MIT License | 6 votes |
private formatString (str: string, icon: string, level: number): string {
// we dont like empty data around here
if (str.trim() === '') {
return
}
str = `${icon} ${str}`
let parsedStr: string[]
let columns = process.stdout.columns ? process.stdout.columns : 80
columns = columns - level * this.options.indentation - 2
switch (this.options.formatOutput) {
case 'truncate':
parsedStr = str.split(EOL).map((s, i) => {
return cliTruncate(this.indentMultilineOutput(s, i), columns)
})
break
case 'wrap':
parsedStr = cliWrap(str, columns, { hard: true })
.split(EOL)
.map((s, i) => this.indentMultilineOutput(s, i))
break
default:
throw new Error('Format option for the renderer is wrong.')
}
// this removes the empty lines
if (this.options.removeEmptyLines) {
parsedStr = parsedStr.filter(Boolean)
}
return indentString(parsedStr.join(EOL), level * this.options.indentation)
}
Example #24
Source File: simple.renderer.ts From listr2 with MIT License | 6 votes |
// Writes sanitized output
public log (output?: string): void {
const logOut = (msg: string): void => {
// Need appent \n to mimic console.log
process[this.options.output].write(msg.endsWith(EOL) ? msg : `${msg}${EOL}`)
}
if (!this.options.prefixWithTimestamp) {
logOut(`${output}`)
return
}
const now = SimpleRenderer.now()
const timestamp = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0') + ':' + String(now.getSeconds()).padStart(2, '0')
logOut(`${colorette.dim(`[${timestamp}]`)} ${output}`)
}
Example #25
Source File: node.ts From js-sdk with MIT License | 5 votes |
log = (message: unknown, ...args: any[]) => {
process.stderr.write(`${util.format(message, ...args)}${EOL}`)
}
Example #26
Source File: github.ts From data-sync with MIT License | 5 votes |
public async updateRepo(path: string, str: string) {
const { ctx, logger } = this;
const config = ctx.app.config.github;
if (!config.enable) return;
const octokit = new Octokit({
auth: config.token,
});
const options = {
owner: config.owner,
repo: config.repo,
};
const time = moment().format();
let sha = '';
const newContent = Buffer.from(str).toString('base64');
try {
const res = await octokit.repos.getContents({
...options,
path,
});
sha = (res.data as any).sha;
const content = (res.data as any).content;
if (content.split(EOL).join('') === newContent) {
// returned content have multi lines, need to join
// no need to update
return;
}
} catch (err) {
if (err.name !== 'HttpError') { throw err; }
}
logger.info(`Goona update file ${path}`);
try {
await octokit.repos.createOrUpdateFile({
...options,
path,
message: `[${config.message}] ${time}`,
content: newContent,
sha,
});
} catch (e) {
logger.error(e);
}
}
Example #27
Source File: psql-builder.ts From exercises.json with The Unlicense | 5 votes |
createLineBreak = (amount: number = 1): Array<string> =>
[...new Array(amount)].map(() => EOL)
Example #28
Source File: NextObjectIdCompletionProvider.ts From al-objid with MIT License | 5 votes |
async function getTypeAtPositionRaw(
document: TextDocument,
position: Position,
context: NextIdContext
): Promise<string | null> {
const matches: DocumentSymbol[] = [];
const symbol = await getSymbolAtPosition(document.uri, position, matches);
// Check for table fields
if (
matches.length > 1 &&
matches[0].name.toLowerCase().startsWith("table") &&
matches[1].name.toLowerCase() === "fields"
) {
const objectParts = matches[0].name.toLowerCase().split(" ");
const isField = await isTableField(document, position, context);
if (!isField) {
return null;
}
if (objectParts[1] !== "0") {
if (isField === ";") {
context.injectSemicolon = true;
}
return `${objectParts[0]}_${objectParts[1]}`;
}
return null;
}
// Check for enum values
if (matches.length > 0 && matches[0].name.toLowerCase().startsWith("enum")) {
const objectParts = matches[0].name.toLowerCase().split(" ");
const isValue = await isEnumValue(document, position, context);
if (isValue) {
if (objectParts[1] !== "0") {
if (isValue === ";") {
context.injectSemicolon = true;
}
return `${objectParts[0]}_${objectParts[1]}`;
}
return null;
}
}
if (!symbol) {
const line = document.lineAt(position.line).text.substring(0, position.character).trim();
return line;
}
const match = symbol.name.match(/^(?<type>\w+)\s(?<id>\d+)\s(?<name>"?.+"?)?$/);
if (match) {
const { type, id } = match.groups as SymbolInfo;
if (id !== "0") return null;
const pos = position.translate(
-symbol.range.start.line,
position.line === symbol.range.start.line ? -symbol.range.start.character : 0
);
const lines = document
.getText(symbol.range)
.split(EOL)
.slice(0, pos.line + 1);
lines[lines.length - 1] = lines[lines.length - 1].substring(0, pos.character);
const text = lines.join("").trim();
if (text.toLowerCase() === type.toLowerCase()) return type;
}
return null;
}
Example #29
Source File: index.test.ts From task-scheduler with MIT License | 5 votes |
function getGlobals(stdoutAsStderr = false): TestingGlobals {
const _stdout: string[] = [];
const _stderr: string[] = stdoutAsStderr ? _stdout : [];
let _exitCode = 0;
return {
validateOuput(expectedStdout: string[], expectedStderr: string[]): void {
expect(_stderr.length).toBe(expectedStderr.length);
expect(_stdout.length).toBe(expectedStdout.length);
expectedStdout.forEach((m, i) => expect(_stdout[i]).toBe(m));
expectedStderr.forEach((m, i) => expect(_stderr[i]).toBe(m));
},
logger: {
log(message: string): void {
message.split(EOL).forEach((m) => _stdout.push(m));
},
error(message: string): void {
message.split(EOL).forEach((m) => _stderr.push(m));
},
},
cwd(): string {
return "/";
},
exit(int: number): void {
_exitCode = int;
},
get stdout(): string[] {
return _stdout;
},
get stderr(): string[] {
return _stderr;
},
get exitCode(): number {
return _exitCode;
},
errorFormatter(err: Error): string {
return `stack trace for following error: ${err.message}`;
},
targetsOnly: false,
};
}