How to use WriteToDisk method of refactor Package

Best Gauge code snippet using refactor.WriteToDisk

cli.go

Source:cli.go Github

copy

Full Screen

1// Copyright 2016-2018 Auburn University and others. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4// The cli package provides a command-line interface for the Go Doctor.5package cli6import (7 "bytes"8 "flag"9 "fmt"10 "html/template"11 "io"12 "io/ioutil"13 "os"14 "path/filepath"15 "time"16 "strings"17 "github.com/godoctor/godoctor/doc"18 "github.com/godoctor/godoctor/engine"19 "github.com/godoctor/godoctor/engine/protocol"20 "github.com/godoctor/godoctor/filesystem"21 "github.com/godoctor/godoctor/refactoring"22 "github.com/godoctor/godoctor/text"23)24// Usage is the text template used to produce the output of "godoctor -help"25var Usage string26// ensureUsageIsSet sets the Usage template if it has not already been set27// (e.g., in main.go)28func ensureUsageIsSet() {29 if Usage != "" {30 // Usage has already been set by main.go31 return32 }33 numRefactorings := len(engine.AllRefactoringNames())34 if numRefactorings == 1 {35 refac := engine.GetRefactoring(engine.AllRefactoringNames()[0])36 if len(refac.Description().Params) == 0 {37 Usage = `{{.AboutText}}38Usage: {{.CommandName}} [<flag> ...]39Each <flag> must be one of the following:40{{.Flags}}41`42 } else {43 args := refac.Description().Usage44 idx := strings.Index(args, "<")45 if idx < 0 {46 args = ""47 } else {48 args = " " + args[idx:]49 }50 Usage = `{{.AboutText}}51Usage: {{.CommandName}} [<flag> ...]` + args + `52Each <flag> must be one of the following:53{{.Flags}}54`55 }56 } else {57 Usage = `{{.AboutText}} - Go source code refactoring tool.58Usage: {{.CommandName}} [<flag> ...] <refactoring> [<args> ...]59Each <flag> must be one of the following:60{{.Flags}}61The <refactoring> argument determines the refactoring to perform:62{{.Refactorings}}63The <args> following the refactoring name vary depending on the refactoring.64If a refactoring requires arguments but none are supplied, a message will be65displayed with a synopsis of the correct usage.66For complete usage information, see the user manual: http://gorefactor.org/doc.html67`68 }69}70func printHelp(cmdName, aboutText string, flags *flag.FlagSet, stderr io.Writer) {71 var usageFields struct {72 AboutText string73 CommandName string74 Flags string75 Refactorings string76 }77 usageFields.AboutText = aboutText78 usageFields.CommandName = cmdName79 var flagList bytes.Buffer80 flags.VisitAll(func(flag *flag.Flag) {81 fmt.Fprintf(&flagList, " -%-8s %s\n", flag.Name, flag.Usage)82 })83 usageFields.Flags = flagList.String()84 var refactorings bytes.Buffer85 for _, key := range engine.AllRefactoringNames() {86 r := engine.GetRefactoring(key)87 if !r.Description().Hidden {88 fmt.Fprintf(&refactorings, " %-15s %s\n",89 key, r.Description().Synopsis)90 }91 }92 usageFields.Refactorings = refactorings.String()93 ensureUsageIsSet()94 t := template.Must(template.New("usage").Parse(Usage))95 err := t.Execute(stderr, usageFields)96 if err != nil {97 fmt.Fprintln(stderr, err)98 }99}100type CLIFlags struct {101 *flag.FlagSet102 fileFlag *string103 posFlag *string104 scopeFlag *string105 completeFlag *bool106 writeFlag *bool107 verboseFlag *bool108 veryVerboseFlag *bool109 listFlag *bool110 jsonFlag *bool111 docFlag *string112}113// Flags returns the flags supported by the godoctor command line tool.114func Flags() *CLIFlags {115 flags := CLIFlags{116 FlagSet: flag.NewFlagSet("godoctor", flag.ContinueOnError)}117 flags.fileFlag = flags.String("file", "",118 "Filename containing an element to refactor (default: stdin)")119 flags.posFlag = flags.String("pos", "1,1:1,1",120 "Position of a syntax element to refactor (default: entire file)")121 flags.scopeFlag = flags.String("scope", "",122 "Package name(s), or source file containing a program entrypoint")123 flags.completeFlag = flags.Bool("complete", false,124 "Output entire modified source files instead of displaying a diff")125 flags.writeFlag = flags.Bool("w", false,126 "Modify source files on disk (write) instead of displaying a diff")127 flags.verboseFlag = flags.Bool("v", false,128 "Verbose: list affected files")129 flags.veryVerboseFlag = flags.Bool("vv", false,130 "Very verbose: list individual edits (implies -v)")131 flags.listFlag = flags.Bool("list", false,132 "List all refactorings and exit")133 flags.jsonFlag = flags.Bool("json", false,134 "Accept commands in OpenRefactory JSON protocol format")135 flags.docFlag = flags.String("doc", "",136 "Output documentation (install, user, man, or vim) and exit")137 return &flags138}139// Run runs the Go Doctor command-line interface. Typical usage is140// os.Exit(cli.Run(os.Stdin, os.Stdout, os.Stderr, os.Args))141// All arguments must be non-nil, and args[0] is required.142func Run(aboutText string, stdin io.Reader, stdout io.Writer, stderr io.Writer, args []string) int {143 cmdName := args[0]144 flags := Flags()145 // Don't print full help unless -help was requested.146 // Just gently remind users that it's there.147 flags.Usage = func() {}148 flags.Init(cmdName, flag.ContinueOnError)149 flags.SetOutput(stderr)150 if err := flags.Parse(args[1:]); err != nil {151 // (err has already been printed)152 if err == flag.ErrHelp {153 // Invoked as "godoctor [flags] -help"154 printHelp(cmdName, aboutText, flags.FlagSet, stderr)155 return 2156 }157 fmt.Fprintf(stderr, "Run '%s -help' for more information.\n", cmdName)158 return 1159 }160 args = flags.Args()161 if *flags.docFlag != "" {162 if len(args) > 0 || flags.NFlag() != 1 {163 fmt.Fprintln(stderr, "Error: The -doc flag cannot "+164 "be used with any other flags or arguments")165 return 1166 }167 switch *flags.docFlag {168 case "man":169 doc.PrintManPage(aboutText, flags.FlagSet, stdout)170 case "install":171 doc.PrintInstallGuide(aboutText, flags.FlagSet, stdout)172 case "user":173 doc.PrintUserGuide(aboutText, flags.FlagSet, stdout)174 case "vim":175 doc.PrintVimdoc(aboutText, flags.FlagSet, stdout)176 default:177 fmt.Fprintln(stderr, "Error: The -doc flag must be "+178 "\"man\", \"install\", \"user\", or \"vim\"")179 return 1180 }181 return 0182 }183 if *flags.listFlag {184 if len(args) > 0 {185 fmt.Fprintln(stderr, "Error: The -list flag "+186 "cannot be used with any arguments")187 return 1188 }189 if *flags.verboseFlag || *flags.veryVerboseFlag ||190 *flags.writeFlag || *flags.completeFlag ||191 *flags.jsonFlag {192 fmt.Fprintln(stderr, "Error: The -list flag "+193 "cannot be used with the -v, -vv, -w, "+194 "-complete, or -json flags")195 return 1196 }197 // Invoked: godoctor [-file=""] [-pos=""] [-scope=""] -list198 fmt.Fprintf(stderr, "%-15s\t%-47s\t%s\n",199 "Refactoring", "Description", " Multifile?")200 fmt.Fprintf(stderr, "--------------------------------------------------------------------------------\n")201 for _, key := range engine.AllRefactoringNames() {202 r := engine.GetRefactoring(key)203 d := r.Description()204 if !r.Description().Hidden {205 fmt.Fprintf(stderr, "%-15s\t%-50s\t%v\n",206 key, d.Synopsis, d.Multifile)207 }208 }209 return 0210 }211 if *flags.jsonFlag {212 if flags.NFlag() != 1 {213 fmt.Fprintln(stderr, "Error: The -json flag "+214 "cannot be used with any other flags")215 return 1216 }217 // Invoked as "godoctor -json [args]218 protocol.Run(os.Stdout, aboutText, args)219 return 0220 }221 if *flags.writeFlag && *flags.completeFlag {222 fmt.Fprintln(stderr, "Error: The -w and -complete flags "+223 "cannot both be present")224 return 1225 }226 if len(args) > 0 && args[0] == "help" {227 // Invoked as "godoctor [flags] help"228 printHelp(cmdName, aboutText, flags.FlagSet, stderr)229 return 2230 }231 var refacName string232 if len(engine.AllRefactoringNames()) == 1 {233 refacName = engine.AllRefactoringNames()[0]234 } else {235 if len(args) == 0 {236 // Invoked as "godoctor [flags]" with no refactoring237 printHelp(cmdName, aboutText, flags.FlagSet, stderr)238 return 2239 }240 refacName = args[0]241 args = args[1:]242 }243 refac := engine.GetRefactoring(refacName)244 if refac == nil {245 fmt.Fprintf(stderr, "There is no refactoring named \"%s\"\n",246 refacName)247 return 1248 }249 if flags.NFlag() == 0 && flags.NArg() == 1 &&250 len(engine.AllRefactoringNames()) != 1 &&251 len(refac.Description().Params) > 0 {252 // Invoked as "godoctor refactoring" but arguments are required253 fmt.Fprintf(stderr, "Usage: %s %s\n",254 refacName, refac.Description().Usage)255 return 2256 }257 stdinPath := ""258 var fileName string259 var fileSystem filesystem.FileSystem260 if *flags.fileFlag != "" && *flags.fileFlag != "-" {261 fileName = *flags.fileFlag262 fileSystem = &filesystem.LocalFileSystem{}263 } else {264 // Filename is - or no filename given; read from standard input265 var err error266 stdinPath, err = filesystem.FakeStdinPath()267 if err != nil {268 fmt.Fprintln(stderr, err)269 return 1270 }271 fileName = stdinPath272 if *flags.fileFlag == "" {273 fmt.Fprintln(stderr, "Reading Go source code from standard input...")274 }275 bytes, err := ioutil.ReadAll(stdin)276 if err != nil {277 fmt.Fprintln(stderr, err)278 return 1279 }280 fileSystem, err = filesystem.NewSingleEditedFileSystem(281 stdinPath, string(bytes))282 if err != nil {283 fmt.Fprintln(stderr, err)284 return 1285 }286 }287 selection, err := text.NewSelection(fileName, *flags.posFlag)288 if err != nil {289 fmt.Fprintf(stderr, "Error: %s.\n", err)290 return 1291 }292 var scope []string293 if *flags.scopeFlag == "" {294 // If no scope provided, let refactoring.go guess the scope295 scope = nil296 } else if *flags.scopeFlag == "-" && stdinPath != "" {297 // Use -scope=- to indicate "stdin file (not package) scope"298 scope = []string{stdinPath}299 } else {300 // Use -scope=a,b,c to specify multiple files/packages301 scope = strings.Split(*flags.scopeFlag, ",")302 }303 verbosity := 0304 if *flags.verboseFlag {305 verbosity = 1306 }307 if *flags.veryVerboseFlag {308 verbosity = 2309 }310 result := refac.Run(&refactoring.Config{311 FileSystem: fileSystem,312 Scope: scope,313 Selection: selection,314 Args: refactoring.InterpretArgs(args, refac),315 Verbosity: verbosity})316 // Display log in GNU-style 'file:line.col-line.col: message' format317 cwd, err := os.Getwd()318 if err != nil {319 cwd = ""320 }321 result.Log.Write(stderr, cwd)322 // If input was supplied on standard input, ensure that the refactoring323 // makes changes only to that code (and does not affect any other files)324 if stdinPath != "" {325 for f := range result.Edits {326 if f != stdinPath {327 fmt.Fprintf(stderr, "Error: When source code is given on standard input, refactorings are prohibited from changing any other files. This refactoring would require modifying %s.\n", f)328 return 1329 }330 }331 }332 debugOutput := result.DebugOutput.String()333 if len(debugOutput) > 0 {334 fmt.Fprintln(stdout, debugOutput)335 }336 if *flags.writeFlag {337 err = writeToDisk(result, fileSystem)338 } else if *flags.completeFlag {339 err = writeFileContents(stdout, result.Edits, fileSystem)340 } else {341 err = writeDiff(stdout, result.Edits, fileSystem)342 }343 if err != nil {344 fmt.Fprintf(stderr, "Error: %s.\n", err)345 return 1346 }347 if result.Log.ContainsErrors() {348 return 3349 } else {350 return 0351 }352}353// writeDiff outputs a multi-file unified diff describing this refactoring's354// changes. It can be applied using GNU patch.355func writeDiff(out io.Writer, edits map[string]*text.EditSet, fs filesystem.FileSystem) error {356 for f, e := range edits {357 p, err := filesystem.CreatePatch(e, fs, f)358 if err != nil {359 return err360 }361 if !p.IsEmpty() {362 inFile := f363 outFile := f364 stdinPath, _ := filesystem.FakeStdinPath()365 if f == stdinPath {366 inFile = os.Stdin.Name()367 outFile = os.Stdout.Name()368 } else {369 rel := relativePath(f)370 inFile = rel371 outFile = rel372 }373 fmt.Fprintf(out, "diff -u %s %s\n", inFile, outFile)374 p.Write(inFile, outFile, time.Time{}, time.Time{}, out)375 }376 }377 return nil378}379// relativePath returns a relative path to fname, or fname if a relative path380// cannot be computed due to an error381func relativePath(fname string) string {382 if cwd, err := os.Getwd(); err == nil {383 if rel, err := filepath.Rel(cwd, fname); err == nil {384 return rel385 }386 }387 return fname388}389// writeFileContents outputs the complete contents of each file affected by390// this refactoring.391func writeFileContents(out io.Writer, edits map[string]*text.EditSet, fs filesystem.FileSystem) error {392 for filename, edits := range edits {393 data, err := filesystem.ApplyEdits(edits, fs, filename)394 if err != nil {395 return err396 }397 stdinPath, _ := filesystem.FakeStdinPath()398 if filename == stdinPath {399 filename = os.Stdin.Name()400 }401 if _, err := fmt.Fprintf(out, "@@@@@ %s @@@@@ %d @@@@@\n",402 filename, len(data)); err != nil {403 return err404 }405 n, err := out.Write(data)406 if n < len(data) && err == nil {407 err = io.ErrShortWrite408 }409 if err != nil {410 return err411 }412 if len(data) > 0 && data[len(data)-1] != '\n' {413 fmt.Fprintln(out)414 }415 }416 return nil417}418// writeToDisk overwrites existing files with their refactored versions and419// applies any other changes to the file system that the refactoring requires420// (e.g., renaming directories).421func writeToDisk(result *refactoring.Result, fs filesystem.FileSystem) error {422 for filename, edits := range result.Edits {423 data, err := filesystem.ApplyEdits(edits, fs, filename)424 if err != nil {425 return err426 }427 f, err := fs.OverwriteFile(filename)428 if err != nil {429 return err430 }431 n, err := f.Write(data)432 if err == nil && n < len(data) {433 err = io.ErrShortWrite434 }435 if err1 := f.Close(); err == nil {436 err = err1437 }438 if err != nil {439 return err440 }441 }442 return nil443}...

Full Screen

Full Screen

WriteToDisk

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 refactor.WriteToDisk()5}6import (7func WriteToDisk() {8 fmt.Println("Hello, playground")9 data := []byte("hello world")10 err := ioutil.WriteFile("data.txt", data, 0644)11 if err != nil {12 panic(err)13 }14}15We can also use the following import statement to import the package:16import refactor "github.com/user/repo"17import (18func main() {19 fmt.Println("Hello, playground")20 refactor.WriteToDisk()21}22import (23func main() {24 fmt.Println("Hello, playground")25 refactor.WriteToDisk()26}27import (28func main() {29 fmt.Println("Hello, playground")30 refactor.WriteToDisk()31}32import (33func main() {34 fmt.Println("Hello, playground")

Full Screen

Full Screen

WriteToDisk

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 r := refactor.NewRefactor()5 r.WriteToDisk()6}7import (8func main() {9 fmt.Println("Hello World")10 r := refactor.NewRefactor()11 r.ReadFromDisk()12}13import (14func main() {15 fmt.Println("Hello World")16 r := refactor.NewRefactor()17 r.WriteToDisk()18}19import (20func main() {21 fmt.Println("Hello World")22 r := refactor.NewRefactor()23 r.ReadFromDisk()24}25import (26func main() {27 fmt.Println("Hello World")28 r := refactor.NewRefactor()29 r.WriteToDisk()30}31import (32func main() {33 fmt.Println("Hello World")34 r := refactor.NewRefactor()35 r.ReadFromDisk()36}37import (38func main() {39 fmt.Println("Hello World")40 r := refactor.NewRefactor()41 r.WriteToDisk()42}43import (44func main() {45 fmt.Println("Hello World")46 r := refactor.NewRefactor()47 r.ReadFromDisk()48}49import (50func main() {51 fmt.Println("Hello World

Full Screen

Full Screen

WriteToDisk

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var refactoredCode = refactor.WriteToDisk()4 fmt.Println(refactoredCode)5}6import (7func main() {8 var refactoredCode = refactor.WriteToDisk()9 fmt.Println(refactoredCode)10}11import (12func main() {13 var refactoredCode = refactor.WriteToDisk()14 fmt.Println(refactoredCode)15}16import (17func main() {18 var refactoredCode = refactor.WriteToDisk()19 fmt.Println(refactoredCode)20}21import (22func main() {23 var refactoredCode = refactor.WriteToDisk()24 fmt.Println(refactoredCode)25}26import (27func main() {28 var refactoredCode = refactor.WriteToDisk()29 fmt.Println(refactoredCode)30}31import (32func main() {33 var refactoredCode = refactor.WriteToDisk()34 fmt.Println(refactoredCode)35}36import (37func main() {38 var refactoredCode = refactor.WriteToDisk()39 fmt.Println(refactoredCode)40}41import (

Full Screen

Full Screen

WriteToDisk

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 r := refactor.NewRefactor()5 r.WriteToDisk("Hello", "output.txt")6}7import (8func main() {9 fmt.Println("Hello, playground")10 r := refactor.NewRefactor()11 r.ReadFromDisk("output.txt")12}13import (14func main() {15 fmt.Println("Hello, playground")16 r := refactor.NewRefactor()17 r.WriteToDisk("Hello", "output.txt")18 r.ReadFromDisk("output.txt")19}20import (21func main() {22 fmt.Println("Hello, playground")23 r := refactor.NewRefactor()24 r.WriteToDisk("Hello", "output.txt")25 r.ReadFromDisk("output.txt")26}27import (28func main() {29 fmt.Println("Hello, playground")30 r := refactor.NewRefactor()31 r.WriteToDisk("Hello", "output.txt")32 r.ReadFromDisk("output.txt")33}

Full Screen

Full Screen

WriteToDisk

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ref := refactor.NewRefactor()4 ref.WriteToDisk("test.go")5 fmt.Println("Done!")6}7import (8func main() {9 ref := refactor.NewRefactor()10 ref.WriteToDisk("test.go")11 fmt.Println("Done!")12}13import (14func main() {15 ref := refactor.NewRefactor()16 ref.WriteToDisk("test.go")17 fmt.Println("Done!")18}19import (20func main() {21 ref := refactor.NewRefactor()22 ref.WriteToDisk("test.go")23 fmt.Println("Done!")24}25import (26func main() {27 ref := refactor.NewRefactor()28 ref.WriteToDisk("test.go")29 fmt.Println("Done!")30}31import (32func main() {33 ref := refactor.NewRefactor()34 ref.WriteToDisk("test.go")35 fmt.Println("Done!")36}37import (38func main() {39 ref := refactor.NewRefactor()40 ref.WriteToDisk("test

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 Gauge automation tests on LambdaTest cloud grid

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

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful