github.com/jchengjr77/canaveral@v1.0.1-0.20200715160102-ea9245d1a2fb/reactnative/addReactNative.go (about) 1 package reactnative 2 3 import ( 4 "bufio" 5 "errors" 6 "fmt" 7 "io" 8 "io/ioutil" 9 "os" 10 "os/exec" 11 12 "github.com/jchengjr77/canaveral/lib" 13 ) 14 15 // installExpo checks first that npm is installed. 16 // If it is, then it uses npm to globally install expo 17 // * tested 18 func installExpo() error { 19 if !lib.CheckToolExists("npm") { 20 return errors.New("prerequisite tool 'npm' is not installed") 21 } 22 cmd := exec.Command("npm", "i", "-g", "expo-cli") 23 // set correct pipes 24 cmd.Stdout = os.Stdout 25 cmd.Stderr = os.Stderr 26 err := cmd.Run() 27 return err 28 } 29 30 // confirmInstall listens for user confirmation and returns a boolean 31 // Takes in an input channel to increase testability 32 // * tested 33 func confirmInstall(stdin io.Reader) (res bool, finalErr error) { 34 // defer a recover function that returns the thrown error 35 defer func() { 36 if r := recover(); r != nil { 37 finalErr = r.(error) 38 } 39 }() 40 fmt.Printf("Allow canaveral to globally install 'expo'? ('y' or 'n')\n>") 41 reader := bufio.NewReader(stdin) 42 response, err := reader.ReadByte() 43 lib.Check(err) 44 return (response == 'y'), nil 45 } 46 47 // AddReactNativeProj takes a project name and path, and inits an expo project. 48 // First, must check if the user has installed expo or not. 49 // If yes, then continue. If no, then ask to install. 50 // Running 'expo init' with the project name will create a new project. 51 // * tested 52 func AddReactNativeProj(projName string, wsPath string) (finalErr error) { 53 // defer a recover function that returns the thrown error 54 defer func() { 55 if r := recover(); r != nil { 56 finalErr = r.(error) 57 } 58 }() 59 expoInstalled := lib.CheckToolExists("expo") 60 ws, err := ioutil.ReadFile(wsPath) 61 lib.Check(err) 62 err = os.MkdirAll(string(ws), os.ModePerm) 63 lib.Check(err) 64 if !expoInstalled { 65 fmt.Println("Looks like you haven't installed 'expo'...") 66 confirm, err := confirmInstall(os.Stdin) 67 lib.Check(err) 68 if !confirm { 69 fmt.Printf("Install rejected. Aborting creation of '%s'\n", projName) 70 return 71 } 72 fmt.Println("Attempting to install expo using npm") 73 err = installExpo() 74 lib.Check(err) 75 } 76 cmd := exec.Command("expo", "i", "-t", "blank", "--npm", "--name", projName, projName) 77 // set correct pipes 78 cmd.Stdout = os.Stdout 79 cmd.Stderr = os.Stderr 80 // Go to canaveral workspace 81 err = os.Chdir(string(ws)) 82 lib.Check(err) 83 // expo init projName 84 err = cmd.Run() 85 lib.Check(err) 86 fmt.Printf("Added React Native project %s to workspace %s\n", projName, string(ws)) 87 return nil 88 }