cmd

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 30, 2018 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfigCommand = &cobra.Command{
	Use:   "config [provider]",
	Short: "Create or modify a ddev project configuration in the current directory",
	Run: func(cmd *cobra.Command, args []string) {

		appRoot, err := os.Getwd()
		if err != nil {
			util.Failed("Could not determine current working directory: %v", err)
		}

		provider := ddevapp.DefaultProviderName

		if len(args) > 1 {
			output.UserOut.Fatal("Invalid argument detected. Please use 'ddev config' or 'ddev config [provider]' to configure a site.")
		}

		if len(args) == 1 {
			provider = args[0]
		}

		app, err := ddevapp.NewApp(appRoot, provider)
		if err != nil {
			util.Failed("Could not create new config: %v", err)
		}

		if showConfigLocation {
			activeApp, err := ddevapp.GetActiveApp("")
			if err != nil {
				if strings.Contains(err.Error(), "Have you run 'ddev config'") {
					util.Failed("No project configuration currently exists")
				} else {
					util.Failed("Failed to access project configuration: %v", err)
				}
			}
			if activeApp.ConfigPath != "" && activeApp.ConfigExists() {
				rawResult := make(map[string]interface{})
				rawResult["configpath"] = activeApp.ConfigPath
				rawResult["approot"] = activeApp.AppRoot

				friendlyMsg := fmt.Sprintf("The project config location is %s", activeApp.ConfigPath)
				output.UserOut.WithField("raw", rawResult).Print(friendlyMsg)
				return
			}
		}

		if siteName == "" && docrootRelPath == "" && pantheonEnvironment == "" && appType == "" {
			err = app.PromptForConfig()
			if err != nil {
				util.Failed("There was a problem configuring your application: %v", err)
			}
		} else {

			app.WarnIfConfigReplace()

			if app.Name != "" && siteName == "" {

			} else if siteName != "" {
				app.Name = siteName
			} else {

				pwd, err := os.Getwd()
				util.CheckErr(err)
				app.Name = filepath.Base(pwd)
			}

			if docrootRelPath != "" {
				app.Docroot = docrootRelPath
				if _, err = os.Stat(docrootRelPath); os.IsNotExist(err) {
					util.Failed("The docroot provided (%v) does not exist", docrootRelPath)
				}
			}

			if provider != "pantheon" && pantheonEnvironment != "" {
				util.Failed("--pantheon-environment can only be used with pantheon provider, for example 'ddev config pantheon --pantheon-environment=dev --docroot=docroot'")
			}

			if appType != "" && !ddevapp.IsValidAppType(appType) {
				validAppTypes := strings.Join(ddevapp.GetValidAppTypes(), ", ")
				util.Failed("apptype must be one of %s", validAppTypes)
			}

			detectedApptype := app.DetectAppType()
			fullPath, pathErr := filepath.Abs(app.Docroot)
			if pathErr != nil {
				util.Failed("Failed to get absolute path to Docroot %s: %v", app.Docroot, pathErr)
			}
			if appType == "" || appType == detectedApptype {
				appType = detectedApptype
				util.Success("Found a %s codebase at %s", detectedApptype, fullPath)
			} else if appType != "" {
				util.Warning("You have specified an apptype of %s but no app of that type is found in %s", appType, fullPath)
			} else if appType != "" && detectedApptype != appType {
				util.Warning("You have specified an apptype of %s but an app of type %s was discovered in %s", appType, detectedApptype, fullPath)
			}
			app.Type = appType

			prov, _ := app.GetProvider()

			if provider == "pantheon" {
				pantheonProvider := prov.(*ddevapp.PantheonProvider)
				if pantheonEnvironment == "" {
					pantheonEnvironment = fallbackPantheonEnvironment
				}
				pantheonProvider.SetSiteNameAndEnv(pantheonEnvironment)
			}

			appTypeErr := prov.Validate()
			if appTypeErr != nil {
				util.Failed("Failed to validate project name %v and environment %v with provider %v: %v", app.Name, pantheonEnvironment, provider, appTypeErr)
			} else {
				util.Success("Using project name '%s' and environment '%s'.", app.Name, pantheonEnvironment)
			}
			err = app.ConfigFileOverrideAction()
			if err != nil {
				util.Failed("Failed to run ConfigFileOverrideAction: %v", err)
			}

		}
		err = app.WriteConfig()
		if err != nil {
			util.Failed("Could not write ddev config file: %v", err)
		}

		switch provider {
		case ddevapp.DefaultProviderName:
			util.Success("Configuration complete. You may now run 'ddev start'.")
		default:
			util.Success("Configuration complete. You may now run 'ddev start' or 'ddev pull'")
		}
	},
}

ConfigCommand represents the `ddev config` command

View Source
var DdevExecCmd = &cobra.Command{
	Use:     "exec <command>",
	Aliases: []string{"."},
	Short:   "Execute a shell command in the container for a service. Uses the web service by default.",
	Long:    `Execute a shell command in the container for a service. Uses the web service by default. To run your command in the container for another service, run "ddev exec --service <service> <cmd>"`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(1)
		}

		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to exec command: %v", err)
		}

		if strings.Contains(app.SiteStatus(), ddevapp.SiteNotFound) {
			util.Failed("App not currently running. Try 'ddev start'.")
		}

		if strings.Contains(app.SiteStatus(), ddevapp.SiteStopped) {
			util.Failed("App is stopped. Run 'ddev start' to start the environment.")
		}

		app.DockerEnv()

		out, _, err := app.Exec(serviceType, args...)
		if err != nil {
			util.Failed("Failed to execute command %s: %v", args, err)
		}
		output.UserOut.Print(out)
	},
}

DdevExecCmd allows users to execute arbitrary bash commands within a container.

View Source
var DdevLogsCmd = &cobra.Command{
	Use:   "logs",
	Short: "Get the logs from your running services.",
	Long:  `Uses 'docker logs' to display stdout from the running services.`,
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to retrieve logs: %v", err)
		}

		if strings.Contains(app.SiteStatus(), ddevapp.SiteNotFound) {
			util.Failed("App not currently running. Try 'ddev start'.")
		}

		if strings.Contains(app.SiteStatus(), ddevapp.SiteStopped) {
			util.Failed("App is stopped. Run 'ddev start' to start the environment.")
		}

		err = app.Logs(serviceType, follow, timestamp, tail)
		if err != nil {
			util.Failed("Failed to retrieve logs for %s: %v", app.GetName(), err)
		}
	},
}

DdevLogsCmd contains the "ddev logs" command

View Source
var DdevRemoveCmd = &cobra.Command{
	Use:     "remove [sitename]",
	Aliases: []string{"rm"},
	Short:   "Remove the development environment for a site.",
	Long: `Remove the development environment for a site. You can run 'ddev remove'
from a site directory to remove that site, or you can specify a site to remove
by running 'ddev remove <sitename>'. By default, remove is a non-destructive operation and will
leave database contents intact. Remove never touches your code or files directories.

To remove database contents, you may use the --remove-data flag with remove.`,
	Run: func(cmd *cobra.Command, args []string) {
		var siteName string

		if len(args) > 1 {
			util.Failed("Too many arguments provided. Please use 'ddev remove' or 'ddev remove [appname]'")
		}

		if len(args) == 1 {
			siteName = args[0]
		}

		app, err := ddevapp.GetActiveApp(siteName)
		if err != nil {
			util.Failed("Failed to remove: %v", err)
		}

		if app.SiteStatus() == ddevapp.SiteNotFound {
			util.Failed("App not currently running. Try 'ddev start'.")
		}

		err = app.Down(removeData)
		if err != nil {
			util.Failed("Failed to remove %s: %s", app.GetName(), err)
		}

		util.Success("Successfully removed the %s application.", app.GetName())
	},
}

DdevRemoveCmd represents the remove command

View Source
var DdevRestartCmd = &cobra.Command{
	Use:   "restart",
	Short: "Restart the development environment for a site.",
	Long:  `Restart stops the containers for site's environment and starts them back up again.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(0)
		}

		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to restart: %v", err)
		}

		output.UserOut.Printf("Restarting environment for %s...", app.GetName())
		err = app.Stop()
		if err != nil {
			util.Failed("Failed to restart %s: %v", app.GetName(), err)
		}

		err = app.Start()
		if err != nil {
			util.Failed("Failed to restart %s: %v", app.GetName(), err)
		}

		util.Success("Successfully restarted %s", app.GetName())
		util.Success("Your project can be reached at: %s and %s", app.GetHTTPURL(), app.GetHTTPSURL())
	},
}

DdevRestartCmd rebuilds an apps settings

View Source
var DdevSSHCmd = &cobra.Command{
	Use:   "ssh",
	Short: "Starts a shell session in the container for a service. Uses web service by default.",
	Long:  `Starts a shell session in the container for a service. Uses web service by default. To start a shell session for another service, run "ddev ssh --service <service>`,
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to ssh: %v", err)
		}

		if strings.Contains(app.SiteStatus(), ddevapp.SiteNotFound) {
			util.Failed("App not currently running. Try 'ddev start'.")
		}

		if strings.Contains(app.SiteStatus(), ddevapp.SiteStopped) {
			util.Failed("App is stopped. Run 'ddev start' to start the environment.")
		}

		app.DockerEnv()

		err = app.ExecWithTty(serviceType, "bash")

		if err != nil {
			util.Failed("Failed to ssh %s: %s", app.GetName(), err)
		}
	},
}

DdevSSHCmd represents the ssh command.

View Source
var DdevSequelproCmd = &cobra.Command{
	Use:   "sequelpro",
	Short: "Easily connect a dev site to sequelpro",
	Long:  `A helper command for easily using sequelpro (OSX database browser) with a running ddev app.`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) != 0 {
			output.UserOut.Fatalf("invalid arguments to sequelpro command: %v", args)
		}

		out, err := handleSequelProCommand(SequelproLoc)
		if err != nil {
			output.UserOut.Fatalf("Could not run sequelpro command: %s", err)
		}
		util.Success(out)
	},
}

DdevSequelproCmd represents the sequelpro command

View Source
var DdevStopCmd = &cobra.Command{
	Use:   "stop [sitename]",
	Short: "Stop the development environment for a site.",
	Long: `Stop the development environment for a site. You can run 'ddev stop'
from a site directory to stop that site, or you can specify a running site
to stop by running 'ddev stop <sitename>.`,
	Run: func(cmd *cobra.Command, args []string) {
		var siteName string

		if len(args) > 1 {
			util.Failed("Too many arguments provided. Please use 'ddev stop' or 'ddev stop [sitename]'")
		}

		if len(args) == 1 {
			siteName = args[0]
		}

		app, err := ddevapp.GetActiveApp(siteName)
		if err != nil {
			util.Failed("Failed to stop: %v", err)
		}

		err = app.Stop()
		if err != nil {
			util.Failed("Failed to stop containers for %s: %v", app.GetName(), err)
		}

		util.Success("Application has been stopped.")
	},
}

DdevStopCmd represents the stop command

View Source
var DescribeCommand = &cobra.Command{
	Use:   "describe [sitename]",
	Short: "Get a detailed description of a running ddev site.",
	Long: `Get a detailed description of a running ddev site. Describe provides basic
information about a ddev site, including its name, location, url, and status.
It also provides details for MySQL connections, and connection information for
additional services like MailHog and phpMyAdmin. You can run 'ddev describe' from
a site directory to stop that site, or you can specify a site to describe by
running 'ddev stop <sitename>.`,
	Run: func(cmd *cobra.Command, args []string) {
		var siteName string

		if len(args) > 1 {
			util.Failed("Too many arguments provided. Please use 'ddev describe' or 'ddev describe [appname]'")
		}

		if len(args) == 1 {
			siteName = args[0]
		}

		site, err := ddevapp.GetActiveApp(siteName)
		if err != nil {
			util.Failed("Unable to find any active site named %s: %v", siteName, err)
		}

		if site.SiteStatus() == ddevapp.SiteNotFound {
			util.Failed("no site found. have you run 'ddev start'?")
		}

		desc, err := site.Describe()
		if err != nil {
			util.Failed("Failed to describe site %s: %v", err)
		}

		renderedDesc, err := renderAppDescribe(desc)
		util.CheckErr(err)
		output.UserOut.WithField("raw", desc).Print(renderedDesc)
	},
}

DescribeCommand represents the `ddev config` command

View Source
var DevListCmd = &cobra.Command{
	Use:   "list",
	Short: "List applications",
	Long:  `List applications.`,
	Run: func(cmd *cobra.Command, args []string) {
		for {
			apps := ddevapp.GetApps()
			var appDescs []map[string]interface{}

			if len(apps) < 1 {
				output.UserOut.Println("There are no running ddev applications.")
			} else {
				table := ddevapp.CreateAppTable()
				for _, app := range apps {
					desc, err := app.Describe()
					if err != nil {
						util.Failed("Failed to describe site %s: %v", app.GetName(), err)
					}
					appDescs = append(appDescs, desc)
					ddevapp.RenderAppRow(table, desc)
				}
				output.UserOut.WithField("raw", appDescs).Print(table.String() + "\n" + ddevapp.RenderRouterStatus())
			}

			if !continuous {
				break
			}

			time.Sleep(time.Second)
		}

	},
}

DevListCmd represents the list command

View Source
var HostNameCmd = &cobra.Command{
	Use:   "hostname [hostname] [ip]",
	Short: "Manage your hostfile entries.",
	Long:  `Manage your hostfile entries.`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) != 2 {
			output.UserOut.Fatal("Invalid arguments supplied. Please use 'ddev hostname [hostname] [ip]'")
		}

		rawResult := make(map[string]interface{})

		hostname, ip := args[0], args[1]
		hosts, err := goodhosts.NewHosts()
		if err != nil {
			rawResult["error"] = "READERROR"
			rawResult["full_error"] = fmt.Sprintf("%v", err)
			output.UserOut.WithField("raw", rawResult).Fatal(fmt.Sprintf("could not open hosts file for read: %v", err))
			return
		}
		if hosts.Has(ip, hostname) {
			if output.JSONOutput {
				rawResult["error"] = "SUCCESS"
				rawResult["detail"] = "hostname already exists in hosts file"
				output.UserOut.WithField("raw", rawResult).Info("")
			}
			return
		}

		err = hosts.Add(ip, hostname)
		if err != nil {
			rawResult["error"] = "ADDERROR"
			rawResult["full_error"] = fmt.Sprintf("%v", err)
			output.UserOut.WithField("raw", rawResult).Fatal(fmt.Sprintf("could not add hostname %s at %s: %v", hostname, ip, err))
		}

		if err := hosts.Flush(); err != nil {
			rawResult["error"] = "WRITEERROR"
			rawResult["full_error"] = fmt.Sprintf("%v", err)
			output.UserOut.WithField("raw", rawResult).Fatal(fmt.Sprintf("Could not write hosts file: %v", err))
		} else {
			rawResult["error"] = "SUCCESS"
			rawResult["detail"] = "hostname added to hosts file"
			output.UserOut.WithField("raw", rawResult).Info("")
		}
	},
}

HostNameCmd represents the hostname command

View Source
var ImportDBCmd = &cobra.Command{
	Use:   "import-db",
	Short: "Import the database of an existing site to the dev environment.",
	Long: `Import the database of an existing site to the development environment.
The database can be provided as a SQL dump in a .sql, .sql.gz, .zip, .tgz, or .tar.gz
format. For the zip and tar formats, the path to a .sql file within the archive
can be provided if it is not located at the top-level of the archive.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(0)
		}
		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to import database: %v", err)
		}

		if app.SiteStatus() != ddevapp.SiteRunning {
			util.Failed("The site is not running. The site must be running in order to import a database.")
		}

		err = app.ImportDB(dbSource, dbExtPath)
		if err != nil {
			util.Failed("Failed to import database for %s: %v", app.GetName(), err)
		}
		util.Success("Successfully imported database for %v", app.GetName())
	},
}

ImportDBCmd represents the `ddev import-db` command.

View Source
var ImportFileCmd = &cobra.Command{
	Use:   "import-files",
	Short: "Import the uploaded files directory of an existing site to the default public upload directory of your application.",
	Long: `Import the uploaded files directory of an existing site to the default public
upload directory of your application. The files can be provided as a directory
path or an archive in .tar, .tar.gz, .tgz, or .zip format. For the .zip and tar formats,
the path to a directory within the archive can be provided if it is not located at the
top-level of the archive. If the destination directory exists, it will be replaced with
the assets being imported.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(0)
		}
		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to import files: %v", err)
		}

		err = app.ImportFiles(fileSource, fileExtPath)
		if err != nil {
			util.Failed("Failed to import files for %s: %v", app.GetName(), err)
		}
		util.Success("Successfully imported files for %v", app.GetName())
	},
}

ImportFileCmd represents the `ddev import-db` command.

View Source
var PantheonAuthCommand = &cobra.Command{
	Use:   "auth-pantheon [token]",
	Short: "Provide a machine token for the global pantheon auth.",
	Long:  "Configure global machine token for pantheon authentication. See https://pantheon.io/docs/machine-tokens/ for instructions on creating a token.",
	Run: func(cmd *cobra.Command, args []string) {

		if len(args) == 0 {
			util.Failed("You must provide a Pantheon machine token, e.g. 'ddev auth-pantheon [token]'. See https://pantheon.io/docs/machine-tokens/ for instructions on creating a token.")
		}
		if len(args) != 1 {
			util.Failed("Too many arguments detected. Please provide only your Pantheon Machine token., e.g. 'ddev auth-pantheon [token]'. See https://pantheon.io/docs/machine-tokens/ for instructions on creating a token.")
		}
		userDir, err := gohomedir.Dir()
		util.CheckErr(err)
		sessionLocation := filepath.Join(userDir, ".ddev", "pantheonconfig.json")

		session := pantheon.NewAuthSession(args[0])
		err = session.Auth()
		if err != nil {
			util.Failed("Could not authenticate with pantheon: %v", err)
		}

		err = session.Write(sessionLocation)
		if err != nil {
			util.Failed("Failed session.Write(), err=%v", err)
		}
		util.Success("Authentication successful!\nYou may now use the 'ddev config pantheon' command when configuring sites!")
	},
}

PantheonAuthCommand represents the `ddev auth-pantheon` command

View Source
var PullCmd = &cobra.Command{
	Use:   "pull",
	Short: "Import files and database using a configured provider plugin.",
	Long: `Import files and database using a configured provider plugin.
	Running pull will connect to the configured provider and download + import the
	latest backups.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(0)
		}
		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		appImport(skipConfirmation)
	},
}

PullCmd represents the `ddev pull` command.

View Source
var RootCmd = &cobra.Command{
	Use:   "ddev",
	Short: "A CLI for interacting with ddev.",
	Long:  "This Command Line Interface (CLI) gives you the ability to interact with the ddev to create a development environment.",
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		ignores := []string{"list", "version", "describe", "config", "hostname"}
		command := strings.Join(os.Args, " ")

		output.LogSetUp()

		for _, k := range ignores {
			if strings.Contains(command, " "+k) {
				break
			}
		}

		err := dockerutil.CheckDockerVersion(version.DockerVersionConstraint)
		if err != nil {
			if err.Error() == "no docker" {
				if os.Args[1] != "version" && os.Args[1] != "config" {
					util.Failed("Could not connect to docker. Please ensure Docker is installed and running.")
				}
			} else {
				util.Failed("The docker version currently installed does not meet ddev's requirements: %v", err)
			}
		}

		err = dockerutil.CheckDockerCompose(version.DockerComposeVersionConstraint)
		if err != nil {
			if err.Error() == "no docker-compose" {
				util.Failed("docker-compose does not appear to be installed.")
			} else {
				util.Failed("The docker-compose version currently installed does not meet ddev's requirements: %v", err)
			}
		}

		userDdevDir := util.GetGlobalDdevDir()

		updateFile := filepath.Join(userDdevDir, ".update")

		timeToCheckForUpdates, err := updatecheck.IsUpdateNeeded(updateFile, updateInterval)
		if err != nil {
			util.Warning("Could not perform update check: %v", err)
		}

		if timeToCheckForUpdates {

			err = updatecheck.ResetUpdateTime(updateFile)
			if err != nil {
				util.Warning("Failed to update updatecheck file %s", updateFile)
				return
			}

			updateNeeded, updateURL, err := updatecheck.AvailableUpdates("drud", "ddev", version.DdevVersion)

			if err != nil {
				util.Warning("Could not check for updates. This is most often caused by a networking issue.")
				log.Debug(err)
				return
			}

			if updateNeeded {
				util.Warning("\n\nA new update is available! please visit %s to download the update.", updateURL)
			}
		}

	},
}

RootCmd represents the base command when called without any subcommands

View Source
var SequelproLoc = "/Applications/sequel pro.app"

SequelproLoc is where we expect to find the sequel pro.app It's global so it can be mocked in testing.

View Source
var StartCmd = &cobra.Command{
	Use:     "start",
	Aliases: []string{"add"},
	Short:   "Start the development environment for a site.",
	Long: `Start initializes and configures the web server and database containers to
provide a working environment for development.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(0)
		}

		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		appStart()
	},
}

StartCmd represents the add command

Functions

func Execute

func Execute()

Execute adds all child commands to the root command sets flags appropriately. This is called by main.main(). It only needs to happen once to the rootCmd.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL