How to use git method in Best

Best JavaScript code snippet using best

git-command-manager.ts

Source:git-command-manager.ts Github

copy

Full Screen

1import * as core from '@actions/core'2import * as exec from '@actions/exec'3import * as fshelper from './fs-helper'4import * as io from '@actions/io'5import * as path from 'path'6import * as refHelper from './ref-helper'7import * as regexpHelper from './regexp-helper'8import * as retryHelper from './retry-helper'9import {GitVersion} from './git-version'10// Auth header not supported before 2.911// Wire protocol v2 not supported before 2.1812export const MinimumGitVersion = new GitVersion('2.18')13export interface IGitCommandManager {14 branchDelete(remote: boolean, branch: string): Promise<void>15 branchExists(remote: boolean, pattern: string): Promise<boolean>16 branchList(remote: boolean): Promise<string[]>17 checkout(ref: string, startPoint: string): Promise<void>18 checkoutDetach(): Promise<void>19 config(20 configKey: string,21 configValue: string,22 globalConfig?: boolean,23 add?: boolean24 ): Promise<void>25 configExists(configKey: string, globalConfig?: boolean): Promise<boolean>26 fetch(refSpec: string[], fetchDepth?: number): Promise<void>27 getDefaultBranch(repositoryUrl: string): Promise<string>28 getWorkingDirectory(): string29 init(): Promise<void>30 isDetached(): Promise<boolean>31 lfsFetch(ref: string): Promise<void>32 lfsInstall(): Promise<void>33 log1(format?: string): Promise<string>34 remoteAdd(remoteName: string, remoteUrl: string): Promise<void>35 removeEnvironmentVariable(name: string): void36 revParse(ref: string): Promise<string>37 setEnvironmentVariable(name: string, value: string): void38 shaExists(sha: string): Promise<boolean>39 submoduleForeach(command: string, recursive: boolean): Promise<string>40 submoduleSync(recursive: boolean): Promise<void>41 submoduleUpdate(fetchDepth: number, recursive: boolean): Promise<void>42 tagExists(pattern: string): Promise<boolean>43 tryClean(): Promise<boolean>44 tryConfigUnset(configKey: string, globalConfig?: boolean): Promise<boolean>45 tryDisableAutomaticGarbageCollection(): Promise<boolean>46 tryGetFetchUrl(): Promise<string>47 tryReset(): Promise<boolean>48}49export async function createCommandManager(50 workingDirectory: string,51 lfs: boolean52): Promise<IGitCommandManager> {53 return await GitCommandManager.createCommandManager(workingDirectory, lfs)54}55class GitCommandManager {56 private gitEnv = {57 GIT_TERMINAL_PROMPT: '0', // Disable git prompt58 GCM_INTERACTIVE: 'Never' // Disable prompting for git credential manager59 }60 private gitPath = ''61 private lfs = false62 private workingDirectory = ''63 // Private constructor; use createCommandManager()64 private constructor() {}65 async branchDelete(remote: boolean, branch: string): Promise<void> {66 const args = ['branch', '--delete', '--force']67 if (remote) {68 args.push('--remote')69 }70 args.push(branch)71 await this.execGit(args)72 }73 async branchExists(remote: boolean, pattern: string): Promise<boolean> {74 const args = ['branch', '--list']75 if (remote) {76 args.push('--remote')77 }78 args.push(pattern)79 const output = await this.execGit(args)80 return !!output.stdout.trim()81 }82 async branchList(remote: boolean): Promise<string[]> {83 const result: string[] = []84 // Note, this implementation uses "rev-parse --symbolic-full-name" because the output from85 // "branch --list" is more difficult when in a detached HEAD state.86 // Note, this implementation uses "rev-parse --symbolic-full-name" because there is a bug87 // in Git 2.18 that causes "rev-parse --symbolic" to output symbolic full names.88 const args = ['rev-parse', '--symbolic-full-name']89 if (remote) {90 args.push('--remotes=origin')91 } else {92 args.push('--branches')93 }94 const output = await this.execGit(args)95 for (let branch of output.stdout.trim().split('\n')) {96 branch = branch.trim()97 if (branch) {98 if (branch.startsWith('refs/heads/')) {99 branch = branch.substr('refs/heads/'.length)100 } else if (branch.startsWith('refs/remotes/')) {101 branch = branch.substr('refs/remotes/'.length)102 }103 result.push(branch)104 }105 }106 return result107 }108 async checkout(ref: string, startPoint: string): Promise<void> {109 const args = ['checkout', '--progress', '--force']110 if (startPoint) {111 args.push('-B', ref, startPoint)112 } else {113 args.push(ref)114 }115 await this.execGit(args)116 }117 async checkoutDetach(): Promise<void> {118 const args = ['checkout', '--detach']119 await this.execGit(args)120 }121 async config(122 configKey: string,123 configValue: string,124 globalConfig?: boolean,125 add?: boolean126 ): Promise<void> {127 const args: string[] = ['config', globalConfig ? '--global' : '--local']128 if (add) {129 args.push('--add')130 }131 args.push(...[configKey, configValue])132 await this.execGit(args)133 }134 async configExists(135 configKey: string,136 globalConfig?: boolean137 ): Promise<boolean> {138 const pattern = regexpHelper.escape(configKey)139 const output = await this.execGit(140 [141 'config',142 globalConfig ? '--global' : '--local',143 '--name-only',144 '--get-regexp',145 pattern146 ],147 true148 )149 return output.exitCode === 0150 }151 async fetch(refSpec: string[], fetchDepth?: number): Promise<void> {152 const args = ['-c', 'protocol.version=2', 'fetch']153 if (!refSpec.some(x => x === refHelper.tagsRefSpec)) {154 args.push('--no-tags')155 }156 args.push('--prune', '--progress', '--no-recurse-submodules')157 if (fetchDepth && fetchDepth > 0) {158 args.push(`--depth=${fetchDepth}`)159 } else if (160 fshelper.fileExistsSync(161 path.join(this.workingDirectory, '.git', 'shallow')162 )163 ) {164 args.push('--unshallow')165 }166 args.push('origin')167 for (const arg of refSpec) {168 args.push(arg)169 }170 const that = this171 await retryHelper.execute(async () => {172 await that.execGit(args)173 })174 }175 async getDefaultBranch(repositoryUrl: string): Promise<string> {176 let output: GitOutput | undefined177 await retryHelper.execute(async () => {178 output = await this.execGit([179 'ls-remote',180 '--quiet',181 '--exit-code',182 '--symref',183 repositoryUrl,184 'HEAD'185 ])186 })187 if (output) {188 // Satisfy compiler, will always be set189 for (let line of output.stdout.trim().split('\n')) {190 line = line.trim()191 if (line.startsWith('ref:') || line.endsWith('HEAD')) {192 return line193 .substr('ref:'.length, line.length - 'ref:'.length - 'HEAD'.length)194 .trim()195 }196 }197 }198 throw new Error('Unexpected output when retrieving default branch')199 }200 getWorkingDirectory(): string {201 return this.workingDirectory202 }203 async init(): Promise<void> {204 await this.execGit(['init', this.workingDirectory])205 }206 async isDetached(): Promise<boolean> {207 // Note, "branch --show-current" would be simpler but isn't available until Git 2.22208 const output = await this.execGit(209 ['rev-parse', '--symbolic-full-name', '--verify', '--quiet', 'HEAD'],210 true211 )212 return !output.stdout.trim().startsWith('refs/heads/')213 }214 async lfsFetch(ref: string): Promise<void> {215 const args = ['lfs', 'fetch', 'origin', ref]216 const that = this217 await retryHelper.execute(async () => {218 await that.execGit(args)219 })220 }221 async lfsInstall(): Promise<void> {222 await this.execGit(['lfs', 'install', '--local'])223 }224 async log1(format?: string): Promise<string> {225 var args = format ? ['log', '-1', format] : ['log', '-1']226 var silent = format ? false : true227 const output = await this.execGit(args, false, silent)228 return output.stdout229 }230 async remoteAdd(remoteName: string, remoteUrl: string): Promise<void> {231 await this.execGit(['remote', 'add', remoteName, remoteUrl])232 }233 removeEnvironmentVariable(name: string): void {234 delete this.gitEnv[name]235 }236 /**237 * Resolves a ref to a SHA. For a branch or lightweight tag, the commit SHA is returned.238 * For an annotated tag, the tag SHA is returned.239 * @param {string} ref For example: 'refs/heads/main' or '/refs/tags/v1'240 * @returns {Promise<string>}241 */242 async revParse(ref: string): Promise<string> {243 const output = await this.execGit(['rev-parse', ref])244 return output.stdout.trim()245 }246 setEnvironmentVariable(name: string, value: string): void {247 this.gitEnv[name] = value248 }249 async shaExists(sha: string): Promise<boolean> {250 const args = ['rev-parse', '--verify', '--quiet', `${sha}^{object}`]251 const output = await this.execGit(args, true)252 return output.exitCode === 0253 }254 async submoduleForeach(command: string, recursive: boolean): Promise<string> {255 const args = ['submodule', 'foreach']256 if (recursive) {257 args.push('--recursive')258 }259 args.push(command)260 const output = await this.execGit(args)261 return output.stdout262 }263 async submoduleSync(recursive: boolean): Promise<void> {264 const args = ['submodule', 'sync']265 if (recursive) {266 args.push('--recursive')267 }268 await this.execGit(args)269 }270 async submoduleUpdate(fetchDepth: number, recursive: boolean): Promise<void> {271 const args = ['-c', 'protocol.version=2']272 args.push('submodule', 'update', '--init', '--force')273 if (fetchDepth > 0) {274 args.push(`--depth=${fetchDepth}`)275 }276 if (recursive) {277 args.push('--recursive')278 }279 await this.execGit(args)280 }281 async tagExists(pattern: string): Promise<boolean> {282 const output = await this.execGit(['tag', '--list', pattern])283 return !!output.stdout.trim()284 }285 async tryClean(): Promise<boolean> {286 const output = await this.execGit(['clean', '-ffdx'], true)287 return output.exitCode === 0288 }289 async tryConfigUnset(290 configKey: string,291 globalConfig?: boolean292 ): Promise<boolean> {293 const output = await this.execGit(294 [295 'config',296 globalConfig ? '--global' : '--local',297 '--unset-all',298 configKey299 ],300 true301 )302 return output.exitCode === 0303 }304 async tryDisableAutomaticGarbageCollection(): Promise<boolean> {305 const output = await this.execGit(306 ['config', '--local', 'gc.auto', '0'],307 true308 )309 return output.exitCode === 0310 }311 async tryGetFetchUrl(): Promise<string> {312 const output = await this.execGit(313 ['config', '--local', '--get', 'remote.origin.url'],314 true315 )316 if (output.exitCode !== 0) {317 return ''318 }319 const stdout = output.stdout.trim()320 if (stdout.includes('\n')) {321 return ''322 }323 return stdout324 }325 async tryReset(): Promise<boolean> {326 const output = await this.execGit(['reset', '--hard', 'HEAD'], true)327 return output.exitCode === 0328 }329 static async createCommandManager(330 workingDirectory: string,331 lfs: boolean332 ): Promise<GitCommandManager> {333 const result = new GitCommandManager()334 await result.initializeCommandManager(workingDirectory, lfs)335 return result336 }337 private async execGit(338 args: string[],339 allowAllExitCodes = false,340 silent = false341 ): Promise<GitOutput> {342 fshelper.directoryExistsSync(this.workingDirectory, true)343 const result = new GitOutput()344 const env = {}345 for (const key of Object.keys(process.env)) {346 env[key] = process.env[key]347 }348 for (const key of Object.keys(this.gitEnv)) {349 env[key] = this.gitEnv[key]350 }351 const stdout: string[] = []352 const options = {353 cwd: this.workingDirectory,354 env,355 silent,356 ignoreReturnCode: allowAllExitCodes,357 listeners: {358 stdout: (data: Buffer) => {359 stdout.push(data.toString())360 }361 }362 }363 result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options)364 result.stdout = stdout.join('')365 return result366 }367 private async initializeCommandManager(368 workingDirectory: string,369 lfs: boolean370 ): Promise<void> {371 this.workingDirectory = workingDirectory372 // Git-lfs will try to pull down assets if any of the local/user/system setting exist.373 // If the user didn't enable `LFS` in their pipeline definition, disable LFS fetch/checkout.374 this.lfs = lfs375 if (!this.lfs) {376 this.gitEnv['GIT_LFS_SKIP_SMUDGE'] = '1'377 }378 this.gitPath = await io.which('git', true)379 // Git version380 core.debug('Getting git version')381 let gitVersion = new GitVersion()382 let gitOutput = await this.execGit(['version'])383 let stdout = gitOutput.stdout.trim()384 if (!stdout.includes('\n')) {385 const match = stdout.match(/\d+\.\d+(\.\d+)?/)386 if (match) {387 gitVersion = new GitVersion(match[0])388 }389 }390 if (!gitVersion.isValid()) {391 throw new Error('Unable to determine git version')392 }393 // Minimum git version394 if (!gitVersion.checkMinimum(MinimumGitVersion)) {395 throw new Error(396 `Minimum required git version is ${MinimumGitVersion}. Your git ('${this.gitPath}') is ${gitVersion}`397 )398 }399 if (this.lfs) {400 // Git-lfs version401 core.debug('Getting git-lfs version')402 let gitLfsVersion = new GitVersion()403 const gitLfsPath = await io.which('git-lfs', true)404 gitOutput = await this.execGit(['lfs', 'version'])405 stdout = gitOutput.stdout.trim()406 if (!stdout.includes('\n')) {407 const match = stdout.match(/\d+\.\d+(\.\d+)?/)408 if (match) {409 gitLfsVersion = new GitVersion(match[0])410 }411 }412 if (!gitLfsVersion.isValid()) {413 throw new Error('Unable to determine git-lfs version')414 }415 // Minimum git-lfs version416 // Note:417 // - Auth header not supported before 2.1418 const minimumGitLfsVersion = new GitVersion('2.1')419 if (!gitLfsVersion.checkMinimum(minimumGitLfsVersion)) {420 throw new Error(421 `Minimum required git-lfs version is ${minimumGitLfsVersion}. Your git-lfs ('${gitLfsPath}') is ${gitLfsVersion}`422 )423 }424 }425 // Set the user agent426 const gitHttpUserAgent = `git/${gitVersion} (github-actions-checkout)`427 core.debug(`Set git useragent to: ${gitHttpUserAgent}`)428 this.gitEnv['GIT_HTTP_USER_AGENT'] = gitHttpUserAgent429 }430}431class GitOutput {432 stdout = ''433 exitCode = 0...

Full Screen

Full Screen

git-host-info.js

Source:git-host-info.js Github

copy

Full Screen

1'use strict'2var gitHosts = module.exports = {3 github: {4 // First two are insecure and generally shouldn't be used any more, but5 // they are still supported.6 'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ],7 'domain': 'github.com',8 'treepath': 'tree',9 'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}',10 'bugstemplate': 'https://{domain}/{user}/{project}/issues',11 'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}',12 'tarballtemplate': 'https://codeload.{domain}/{user}/{project}/tar.gz/{committish}'13 },14 bitbucket: {15 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],16 'domain': 'bitbucket.org',17 'treepath': 'src',18 'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz'19 },20 gitlab: {21 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],22 'domain': 'gitlab.com',23 'treepath': 'tree',24 'bugstemplate': 'https://{domain}/{user}/{project}/issues',25 'httpstemplate': 'git+https://{auth@}{domain}/{user}/{projectPath}.git{#committish}',26 'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}',27 'pathmatch': /^[/]([^/]+)[/](.+?)(?:[.]git|[/])?$/28 },29 gist: {30 'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ],31 'domain': 'gist.github.com',32 'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]{32,})(?:[.]git)?$/,33 'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}',34 'bugstemplate': 'https://{domain}/{project}',35 'gittemplate': 'git://{domain}/{project}.git{#committish}',36 'sshtemplate': 'git@{domain}:/{project}.git{#committish}',37 'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}',38 'browsetemplate': 'https://{domain}/{project}{/committish}',39 'browsefiletemplate': 'https://{domain}/{project}{/committish}{#path}',40 'docstemplate': 'https://{domain}/{project}{/committish}',41 'httpstemplate': 'git+https://{domain}/{project}.git{#committish}',42 'shortcuttemplate': '{type}:{project}{#committish}',43 'pathtemplate': '{project}{#committish}',44 'tarballtemplate': 'https://codeload.github.com/gist/{project}/tar.gz/{committish}',45 'hashformat': function (fragment) {46 return 'file-' + formatHashFragment(fragment)47 }48 }49}50var gitHostDefaults = {51 'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}',52 'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}',53 'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}',54 'browsefiletemplate': 'https://{domain}/{user}/{project}/{treepath}/{committish}/{path}{#fragment}',55 'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme',56 'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}',57 'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}',58 'shortcuttemplate': '{type}:{user}/{project}{#committish}',59 'pathtemplate': '{user}/{project}{#committish}',60 'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/,61 'hashformat': formatHashFragment62}63Object.keys(gitHosts).forEach(function (name) {64 Object.keys(gitHostDefaults).forEach(function (key) {65 if (gitHosts[name][key]) return66 gitHosts[name][key] = gitHostDefaults[key]67 })68 gitHosts[name].protocols_re = RegExp('^(' +69 gitHosts[name].protocols.map(function (protocol) {70 return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1')71 }).join('|') + '):$')72})73function formatHashFragment (fragment) {74 return fragment.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-')...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var git = require('gift');2var repo = git('/Users/terryharris/Repos/BestBuy');3repo.status(function(err, status) {4 console.log(status);5});6var git = require('gift');7var repo = git('/Users/terryharris/Repos/BestBuy');8repo.status(function(err, status) {9 console.log(status);10});11var git = require('gift');12var repo = git('/Users/terryharris/Repos/BestBuy');13repo.status(function(err, status) {14 console.log(status);15});16var git = require('gift');17var repo = git('/Users/terryharris/Repos/BestBuy');18repo.status(function(err, status) {19 console.log(status);20});21var git = require('gift');22var repo = git('/Users/terryharris/Repos/BestBuy');23repo.status(function(err, status) {24 console.log(status);25});26var git = require('gift');27var repo = git('/Users/terryharris/Repos/BestBuy');28repo.status(function(err, status) {29 console.log(status);30});31var git = require('gift');32var repo = git('/Users/terryharris/Repos/BestBuy');33repo.status(function(err, status) {34 console.log(status);35});36var git = require('gift');37var repo = git('/Users/terryharris/Repos/BestBuy');38repo.status(function(err, status) {39 console.log(status);40});41var git = require('gift');42var repo = git('/Users/terryharris/Repos/BestBuy');43repo.status(function(err, status) {44 console.log(status);45});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful