How to use AbortIfError method of command Package

Best Ginkgo code snippet using command.AbortIfError

main.go

Source:main.go Github

copy

Full Screen

1package main2import (3 "bytes"4 "crypto/sha1"5 "encoding/hex"6 "flag"7 "fmt"8 "github.com/imobulus/bitsplit"9 "github.com/imobulus/bitsplit/osutil"10 "io/ioutil"11 "log"12 "math/rand"13 "os"14 "path/filepath"15)16const (17 LockFileName = ".lock"18 CodeSuccess = 019 CodeLockDirNotExist = 120 CodeKeyDirNotExist = 221 CodeCantReadKeyFile = 322)23var (24 errLog = log.New(os.Stderr, "error: ", 0)25 stdLog = log.New(os.Stdout, "", 0)26)27func errorFatal(message string, err error) {28 if err != nil {29 if message != "" {30 errLog.Println(message)31 }32 errLog.Println(err)33 os.Exit(1)34 }35}36// returns a non-zero code and error if some directory not exists, otherwise kills the program. Fix in future37func Lock(lockDir, keyDir string) (int, error) {38 if !osutil.DirExists(lockDir) {39 return CodeLockDirNotExist, fmt.Errorf("can't find directory %s", lockDir)40 }41 if !osutil.DirExists(keyDir) {42 return CodeKeyDirNotExist, fmt.Errorf("can't find directory %s", keyDir)43 }44 keyDir, _ = filepath.Abs(keyDir)45 lockDir, _ = filepath.Abs(lockDir)46 if lockDir == os.TempDir() {47 errLog.Fatal("can't lock tmp directory")48 }49 err := os.Chdir(lockDir)50 errorFatal("can't set working directory for some reason", err)51 if osutil.FileExists(LockFileName) &&52 !osutil.Promptf(53 "lock file %s already exists, the directory could already be locked. " +54 "This operation will overwrite the lock file. Proceed?",55 LockFileName) {56 os.Exit(0)57 }58 execDir, err := filepath.Abs(filepath.Dir(os.Args[0]))59 errorFatal("can't get directory of executable for some reason", err)60 if lockDir == execDir && !osutil.Prompt(61 "this action will encrypt the program binary file. You will need to get it again to decrypt. Proceed?"){62 os.Exit(0)63 }64 tempDir, err := ioutil.TempDir("", "~temp")65 errorFatal("can't create temporary directory", err)66 // copying entire directory into temporary dir to avoid partial encrypting67 err = osutil.CopyDir(".", tempDir)68 //if there's an error while copying, abort entire process69 if err != nil {70 err1 := os.RemoveAll(tempDir)71 errorFatal(72 fmt.Sprintf(73 "can't remove temporary directory %s while aborting. Please remove manually", tempDir), err1)74 errLog.Fatal("copying unsuccessful\n" + err.Error())75 }76 h := sha1.New()77 key := make([]byte, 32)78 rand.Seed(bitsplit.GetSeed())79 rand.Read(key)80 h.Write(key)81 hash := hex.EncodeToString(h.Sum(nil))82 //if there are further errors we call abortIfError() to undo changes83 abortIfError := func(errMaster error, message string) {84 if errMaster == nil {85 return86 }87 errLog.Println(message)88 errLog.Println(errMaster.Error(), "\naborting...")89 err = os.Remove(filepath.Join(keyDir, hash))90 if err != nil {91 errLog.Printf("error removing key file %s, remove manually\n", filepath.Join(keyDir, hash))92 }93 _ = os.Chdir("..")94 err = osutil.RemoveContents(lockDir)95 if err != nil {96 errLog.Fatalf (97 "abort removing current dir unsuccessful. All files are stored in %s\n%e",98 tempDir,99 err.Error() )100 }101 err = osutil.CopyDir(tempDir, lockDir)102 if err != nil {103 errLog.Fatalf (104 "abort copying unsuccessful. All files are stored in %s\n%e",105 tempDir,106 err.Error() )107 }108 err = os.RemoveAll(tempDir)109 if err != nil {110 errLog.Fatalf (111 "abort removing temp dir unsuccessful. Remove %s manually.\n%e",112 tempDir,113 err.Error() )114 }115 os.Exit(1)116 }117 abortIfError( ioutil.WriteFile(filepath.Join(keyDir, hash), key, 0644), "while writing key" )118 //encrypting119 err = filepath.Walk(".", func (path string, info os.FileInfo, err error) error {120 if err != nil {121 return err122 }123 if info.IsDir() {124 return nil125 }126 file, err := os.Open(path)127 if err != nil {128 return bitsplit.OSError{Details: fmt.Sprintf("can't open %s", path), Contents: err}129 }130 fileContents, err := ioutil.ReadAll(file)131 if err != nil {132 return bitsplit.OSError{Details: fmt.Sprintf("can't read %s", path), Contents: err}133 }134 err = file.Close()135 if err != nil {136 return bitsplit.OSError{Details: fmt.Sprintf("can't close %s", path), Contents: err}137 }138 h.Write(fileContents)139 var buf bytes.Buffer140 err = bitsplit.AesGCMEncrypt(bytes.NewReader(fileContents), &buf, key)141 if err != nil {142 return bitsplit.OSError{Details: fmt.Sprintf("can't encrypt %s", path), Contents: err}143 }144 err = ioutil.WriteFile(path, buf.Bytes(), 0644)145 if err != nil {146 return bitsplit.OSError{Details: fmt.Sprintf("can't write to %s", path), Contents: err}147 }148 return nil149 })150 abortIfError(err, "while walking file tree")151 abortIfError( osutil.HideFile(filepath.Join(keyDir, hash)), "can't hide key file" )152 abortIfError( ioutil.WriteFile(LockFileName, []byte(hash), 0644), "can't write key file" )153 abortIfError( osutil.HideFile(LockFileName), "can't hide lock file" )154 err = os.Chmod(LockFileName, 0444)155 if err != nil {156 errLog.Println("can't make lock file read-only")157 }158 err = os.Chmod(filepath.Join(keyDir, hash), 0444)159 if err != nil {160 errLog.Println("can't make key file read-only")161 }162 err = os.RemoveAll(tempDir)163 if err != nil {164 errLog.Printf("cant remove temporary directory %s. Please, remove manually\n%e", tempDir, err)165 }166 return CodeSuccess, nil167}168// returns a non-zero code and error if some directory not exists, otherwise kills the program. Fix in future169func Unlock(unlockDir, keyDir string) (int, error) {170 if !osutil.DirExists(unlockDir) {171 return CodeLockDirNotExist, fmt.Errorf("can't find directory %s", unlockDir)172 }173 if !osutil.DirExists(keyDir) {174 return CodeKeyDirNotExist, fmt.Errorf("can't find directory %s", keyDir)175 }176 if tmp, _ := filepath.Abs(unlockDir); tmp == os.TempDir() {177 errLog.Fatal("can't unlock tmp directory")178 }179 unlockDir, _ = filepath.Abs(unlockDir)180 err := os.Chdir(unlockDir)181 errorFatal("can't set working directory for some reason", err)182 if !osutil.FileExists(LockFileName){183 errLog.Fatalf("lock file %s does not exist", LockFileName)184 }185 keyFileBytes, err := ioutil.ReadFile(LockFileName)186 if err != nil {187 errLog.Fatalf("can't read lock file %s", LockFileName)188 }189 keyFileName := string(keyFileBytes)190 key, err := ioutil.ReadFile(filepath.Join(keyDir, keyFileName))191 if err != nil {192 return CodeCantReadKeyFile, fmt.Errorf("can't read key file %s", filepath.Join(keyDir, keyFileName))193 }194 //create temporary dir195 tempDir, err := ioutil.TempDir("", "~temp")196 errorFatal("can't create temporary directory", err)197 //copy the entire directory into temporary dir to avoid partial encrypting198 err = osutil.CopyDir(".", tempDir)199 //if there's an error while copying, abort entire process200 if err != nil {201 err1 := os.RemoveAll(tempDir)202 errorFatal(203 fmt.Sprintf(204 "couldn't remove temporary directory %s while aborting. Please remove manually", tempDir), err1)205 errLog.Fatal("copying unsuccessful\n" + err.Error())206 }207 //if there are further errors we call abortIfError() to undo changes208 abortIfError := func(errMaster error, message string) {209 if errMaster == nil {210 return211 }212 errLog.Println(message)213 errLog.Println(errMaster.Error(), "\naborting...")214 _ = os.Chdir("..")215 err = osutil.RemoveContents(unlockDir)216 if err != nil {217 errLog.Fatalf(218 "abort removing current dir unsuccessful. All files are stored in %s\n%e",219 tempDir,220 err.Error())221 }222 err = osutil.CopyDir(tempDir, unlockDir)223 if err != nil {224 errLog.Fatalf(225 "abort copying unsuccessful. All files are stored in %s\n%e",226 tempDir,227 err.Error())228 }229 err = os.RemoveAll(tempDir)230 if err != nil {231 errLog.Fatalf(232 "abort removing temp dir unsuccessful. Remove %s manually.\n%e",233 tempDir,234 err.Error())235 }236 os.Exit(1)237 }238 //remove the lock file since it is not encrypted239 abortIfError( os.Chmod(LockFileName, 0222), "can't make lock file writable" )240 abortIfError( os.Remove(LockFileName), "can't remove lock file" )241 //decrypting242 err = filepath.Walk(".", func (path string, info os.FileInfo, err error) error {243 if err != nil {244 return err245 }246 if info.IsDir() {247 return nil248 }249 var buf bytes.Buffer250 file, err := os.Open(path)251 if err != nil {252 return bitsplit.OSError{Details: fmt.Sprintf("can't open %s", path), Contents: err}253 }254 err = bitsplit.AesGCMDecrypt(file, &buf, key)255 if err != nil {256 return bitsplit.OSError{Details: fmt.Sprintf("can't decrypt %s", path), Contents: err}257 }258 err = file.Close()259 if err != nil {260 return bitsplit.OSError{Details: fmt.Sprintf("can't close %s", path), Contents: err}261 }262 err = ioutil.WriteFile(path, buf.Bytes(), 0644)263 if err != nil {264 return bitsplit.OSError{Details: fmt.Sprintf("can't write to %s", path), Contents: err}265 }266 return nil267 })268 abortIfError(err, "while walking file tree")269 err = os.Remove(filepath.Join(keyDir, keyFileName))270 if err != nil {271 errLog.Printf("removing key file %s unsuccessful. Please remove manually", filepath.Join(keyDir, keyFileName))272 }273 err = os.RemoveAll(tempDir)274 if err != nil {275 errLog.Printf("cant remove temporary directory %s. Please, remove manually\n%e", tempDir, err)276 }277 return CodeSuccess, nil278}279func runCommandLine() {280 if len(os.Args) < 2 {281 stdLog.Println("this is directory locker")282 return283 }284 lock := flag.NewFlagSet("lock", flag.ExitOnError)285 lockKeyDir := lock.String("keydir", "", "specify key directory")286 lockDir := lock.String("dir", ".", "specify lock directory")287 switch os.Args[1] {288 case "lock":289 err := lock.Parse(os.Args[2:])290 errorFatal("can't parse flags", err)291 if !osutil.IsFlagPassedInSet(lock,"keydir") {292 drives := osutil.GetDrives()293 if len(drives) == 0 {294 errLog.Fatal("specify your key directory using -keydir")295 }296 if !osutil.Promptf("use disk %s as key storage?", drives[len(drives) - 1]) {297 os.Exit(1)298 }299 *lockKeyDir = drives[len(drives) - 1]300 }301 _, err = Lock(*lockDir, *lockKeyDir)302 errorFatal("", err)303 case "unlock":304 err := lock.Parse(os.Args[2:])305 errorFatal("can't parse flags", err)306 if !osutil.IsFlagPassedInSet(lock,"keydir") {307 for _, d := range osutil.GetDrives() {308 code, err := Unlock(*lockDir, d)309 switch code {310 case CodeSuccess:311 os.Exit(0)312 case CodeCantReadKeyFile:313 continue314 default:315 errLog.Fatal(err)316 }317 }318 errLog.Fatal("can't find external key. Specify key directory using -keydir")319 } else {320 _, err := Unlock(*lockDir, *lockKeyDir)321 errorFatal("", err)322 }323 }324}325func main() {326 runCommandLine()327}...

Full Screen

Full Screen

claim.go

Source:claim.go Github

copy

Full Screen

...48 var (49 forkURL = fmt.Sprintf("https://github.com/%s/%s.git", config.GitName, config.RegistryForkName)50 forkRepoFolder = path.Join(config.Workspace, config.RegistryForkName)51 )52 utils.AbortIfError(err, "error fetching the chain ID: %v", err)53 // check if root url is valid54 _, err = url.Parse(config.RegistryRoot)55 utils.AbortIfError(err, "the registry root url is not a valid url: %s", config.RegistryRoot)56 repo, err := gitwrap.CloneOrOpen(forkURL, forkRepoFolder, config.BasicAuth())57 utils.AbortIfError(err, "aborted due to an error cloning registry fork repo: %v", err)58 gitwrap.PullBranch(repo, config.RegistryRootBranch)59 utils.AbortIfError(err, "something went wrong checking out branch %s: %v", config.RegistryRootBranch, err)60 // now we have the root repo61 // read the the codeowners file62 co, err := codeowners.FromFile(forkRepoFolder)63 utils.AbortIfError(err, "cannot find the CODEOWNERS file: %v", err)64 // see if there are already owners65 owners := co.LocalOwners(claimName)66 if owners != nil {67 currentUser, isOwner := fmt.Sprintf("@%s", config.GitName), false68 // owners already exists for path, check if the current user is among them69 for _, o := range owners {70 if o == currentUser {71 isOwner = true72 break73 }74 }75 if isOwner {76 println("you already successfully claimed the name %s, perhaps you want to update it?")77 return78 }79 // named owned by someone else80 println("the name", claimName, "is already claimed by someone else!")81 fmt.Printf("%#v", owners)82 return83 }84 // create the branch with the name `claimName`85 // TODO check if the branch exits86 println("checking out branch ", claimName)87 err = gitwrap.CreateBranch(repo, claimName)88 utils.AbortCleanupIfError(err, forkRepoFolder, "cannot create branch: %v", err)89 // fetch the chain data90 err = node.DumpInfo(forkRepoFolder, claimName, rpcAddress, logger)91 println("fetching chain data")92 utils.AbortCleanupIfError(err, forkRepoFolder, fmt.Sprintf("error connecting to the node at %s: %v", rpcAddress, err), err)93 println("starting claiming process for", claimName)94 // add rule to the codeowner95 // TODO: ensure that the chain id is compliant to CAIP-296 err = co.AddPattern(fmt.Sprintf("/%s/", claimName), []string{fmt.Sprint("@", config.GitName)})97 utils.AbortIfError(err, "invalid claim name folder: %v", err)98 coFile := path.Join(forkRepoFolder, codeownersFile)99 err = co.ToFile(coFile)100 // commit the data101 err = gitwrap.StageToCommit(repo, codeownersFile, claimName)102 println("schedule changes to commit:")103 println("-", codeownersFile)104 println("-", claimName)105 utils.AbortIfError(err, "error adding the %s to git: %v", codeownersFile, err)106 commitMsg := fmt.Sprintf("submit record for chain ID %s", claimName)107 commit, err := gitwrap.CommitAndPush(repo,108 config.GitName,109 config.GitEmail,110 commitMsg,111 time.Now(),112 config.BasicAuth())113 utils.AbortCleanupIfError(err, forkRepoFolder, "git push error : %v; perhaps there is already a branch with the same name in the remote repository?", err)114 println("changes committed with hash", commit)115 // open the github page to submit the PR to mainRepo116 prURL := fmt.Sprintf("%s/compare/%s...%s:%s", config.RegistryRoot, config.RegistryRootBranch, config.GitName, claimName)117 println(`118The changes have been recorded in your private fork,119to submit your request for review file a pull request to...

Full Screen

Full Screen

outline_command.go

Source:outline_command.go Github

copy

Full Screen

...59 src = os.Stdin60 } else {61 var err error62 src, err = os.Open(filename)63 command.AbortIfError("Failed to open file:", err)64 }65 fset := token.NewFileSet()66 parsedSrc, err := parser.ParseFile(fset, filename, src, 0)67 command.AbortIfError("Failed to parse source:", err)68 o, err := FromASTFile(fset, parsedSrc)69 command.AbortIfError("Failed to create outline:", err)70 var oerr error71 switch format {72 case "csv":73 _, oerr = fmt.Print(o)74 case "indent":75 _, oerr = fmt.Print(o.StringIndent(indentWidth))76 case "json":77 b, err := json.Marshal(o)78 if err != nil {79 println(fmt.Sprintf("error marshalling to json: %s", err))80 }81 _, oerr = fmt.Println(string(b))82 default:83 command.AbortWith("Format %s not accepted", format)84 }85 command.AbortIfError("Failed to write outline:", oerr)86}

Full Screen

Full Screen

AbortIfError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 app := cli.NewApp()4 app.Commands = []cli.Command{5 {6 Action: func(c *cli.Context) error {7 return cli.NewExitError("error", 1)8 },9 },10 }11 app.Run(os.Args)12}

Full Screen

Full Screen

AbortIfError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ls", "-l", "/")4 err := cmd.Run()5 if err != nil {6 fmt.Println(err)7 os.Exit(1)8 }9 fmt.Println("Command executed successfully")10}

Full Screen

Full Screen

AbortIfError

Using AI Code Generation

copy

Full Screen

1import (2var cmd = &cobra.Command{3}4func main() {5 cmd.AddCommand(&cobra.Command{6 Run: func(cmd *cobra.Command, args []string) {7 cmd.Println("a command")8 },9 })10 cmd.AddCommand(&cobra.Command{11 Run: func(cmd *cobra.Command, args []string) {12 cmd.Println("b command")13 },14 })15 if err := cmd.Execute(); err != nil {16 fmt.Println(err)17 os.Exit(1)18 }19}20import (21var cmd = &cobra.Command{22}23func main() {24 cmd.AddCommand(&cobra.Command{25 Run: func(cmd *cobra.Command, args []string) {26 cmd.Println("a command")27 },28 })29 cmd.AddCommand(&cobra.Command{30 Run: func(cmd *cobra.Command, args []string) {31 cmd.Println("b command")32 },33 })34 if err := cmd.Execute(); err != nil {35 fmt.Println(err)36 os.Exit(1)37 }38}39import (40var cmd = &cobra.Command{41}42func main() {43 cmd.AddCommand(&cobra.Command{

Full Screen

Full Screen

AbortIfError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 app := cli.NewApp()4 app.Action = func(c *cli.Context) error {5 fmt.Println("Hello World")6 }7 app.Run(os.Args)8}9import (10func main() {11 app := cli.NewApp()12 app.Action = func(c *cli.Context) error {13 fmt.Println("Hello World")14 }15 app.Run(os.Args)16}17import (18func main() {19 app := cli.NewApp()20 app.Action = func(c *cli.Context) error {21 fmt.Println("Hello World")22 }23 app.Run(os.Args)24}25import (26func main() {27 app := cli.NewApp()28 app.Action = func(c *cli.Context) error {29 fmt.Println("Hello World")30 }31 app.Run(os.Args)32}33import (34func main() {35 app := cli.NewApp()36 app.Action = func(c *cli.Context) error {37 fmt.Println("Hello World")38 }39 app.Run(os.Args)40}41import (

Full Screen

Full Screen

AbortIfError

Using AI Code Generation

copy

Full Screen

1func main() {2 cmd := command.NewCommand()3 cmd.Execute("echo", "Hello", "World")4 cmd.AbortIfError()5}6func main() {7 cmd := command.NewCommand()8 cmd.Execute("echo", "Hello", "World")9 cmd.AbortIfError()10 cmd.Execute("echo", "Hello", "World")11 cmd.AbortIfError()12}13func main() {14 cmd := command.NewCommand()15 cmd.Execute("echo", "Hello", "World")16 cmd.AbortIfError()17 cmd.Execute("echo", "Hello", "World")18 cmd.AbortIfError()19 cmd.Execute("echo", "Hello", "World")20 cmd.AbortIfError()21}22func main() {23 cmd := command.NewCommand()24 cmd.Execute("echo", "Hello", "World")25 cmd.AbortIfError()26 cmd.Execute("echo", "Hello", "World")27 cmd.AbortIfError()28 cmd.Execute("echo", "Hello", "World")29 cmd.AbortIfError()30 cmd.Execute("echo", "Hello", "World")31 cmd.AbortIfError()32}

Full Screen

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 Ginkgo 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