cmd

package
v1.5.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AuthCmd = &cobra.Command{
	Use:   "auth [command]",
	Short: "A collection of authentication commands",
	Run: func(cmd *cobra.Command, args []string) {
		err := cmd.Usage()
		util.CheckErr(err)
	},
}

AuthCmd is the top-level "ddev auth" command

View Source
var AuthSSHCommand = &cobra.Command{
	Use:   "ssh",
	Short: "Add ssh key authentication to the ddev-ssh-auth container",
	Long:  `Use this command to provide the password to your ssh key to the ddev-ssh-agent container, where it can be used by other containers. Normal usage is just "ddev auth ssh", or if your key is not in ~/.ssh, ddev auth ssh --keydir=/some/path/.ssh"`,
	Run: func(cmd *cobra.Command, args []string) {
		var err error
		if len(args) > 0 {
			util.Failed("This command takes no arguments.")
		}

		_, _, uidStr, _ := util.GetContainerUIDGid()

		if sshKeyPath == "" {
			homeDir, err := homedir.Dir()
			if err != nil {
				util.Failed("Unable to determine home directory: %v", err)
			}
			sshKeyPath = filepath.Join(homeDir, ".ssh")
		}
		if !filepath.IsAbs(sshKeyPath) {
			sshKeyPath, err = filepath.Abs(sshKeyPath)
			if err != nil {
				util.Failed("Failed to derive absolute path for ssh key path %s: %v", sshKeyPath, err)
			}
		}
		fi, err := os.Stat(sshKeyPath)
		if os.IsNotExist(err) {
			util.Failed("The ssh key directory %s was not found", sshKeyPath)
		}
		if err != nil {
			util.Failed("Failed to check status of ssh key directory %s: %v", sshKeyPath, err)
		}
		if !fi.IsDir() {
			util.Failed("The ssh key directory (%s) must be a directory", sshKeyPath)
		}

		app := ddevapp.DdevApp{}
		err = app.EnsureSSHAgentContainer()
		if err != nil {
			util.Failed("Failed to start ddev-ssh-agent container: %v", err)
		}
		sshKeyPath = dockerutil.MassageWindowsHostMountpoint(sshKeyPath)

		dockerCmd := []string{"run", "-it", "--rm", "--volumes-from=" + ddevapp.SSHAuthName, "--user=" + uidStr, "--mount=type=bind,src=" + sshKeyPath + ",dst=/tmp/.ssh", version.SSHAuthImage + ":" + version.SSHAuthTag, "ssh-add"}
		err = exec.RunInteractiveCommand("docker", dockerCmd)

		if err != nil {
			util.Failed("Docker command 'docker %v' failed: %v", dockerCmd, err)
		}
	},
}

AuthSSHCommand implements the "ddev auth ssh" command

View Source
var ComposeConfigCmd = &cobra.Command{
	Use:   "compose-config [project]",
	Short: "Prints the docker-compose configuration of the current project",
	Run: func(cmd *cobra.Command, args []string) {
		projectName := ""

		if len(args) > 1 {
			util.Failed("This command only takes one optional argument: project name")
		}

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

		app, err := ddevapp.GetActiveApp(projectName)
		if err != nil {
			util.Failed("Failed to get compose-config: %v", err)
		}

		if err = app.WriteDockerComposeConfig(); err != nil {
			util.Failed("Failed to get compose-config: %v", err)
		}

		app.DockerEnv()
		files, err := app.ComposeFiles()
		if err != nil {
			util.Failed("Failed to get compose-config: %v", err)
		}

		out, _, err := dockerutil.ComposeCmd(files, "config")
		if err != nil {
			util.Failed("Failed to get compose-config: %v", err)
		}

		output.UserOut.Printf(strings.TrimSpace(out))
	},
}

ComposeConfigCmd implements the ddev debug compose-config command

View Source
var ComposerCmd = &cobra.Command{
	Use:   "composer [command]",
	Short: "Executes a composer command within the web container",
	Long: `Executes a composer command at the project root in the web container. Generally,
any composer command can be forwarded to the container context by prepending
the command with 'ddev'. For example:

ddev composer require <package>
ddev composer outdated --minor-only`,
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed(err.Error())
		}

		if app.SiteStatus() != ddevapp.SiteRunning {
			if err = app.Start(); err != nil {
				util.Failed("Failed to start %s: %v", app.Name, err)
			}
		}

		output.UserOut.Printf("Executing [composer %s] at the project root (/var/www/html in the container, %s on the host)", strings.Join(args, " "), app.AppRoot)
		stdout, _, _ := app.Exec(&ddevapp.ExecOpts{
			Service: "web",
			Dir:     "/var/www/html",
			Cmd:     append([]string{"composer"}, args...),
		})
		if runtime.GOOS == "windows" && !util.IsDockerToolbox() {
			replaceSimulatedLinks(app.AppRoot)
		}

		if len(stdout) > 0 {
			fmt.Println(stdout)
		}
	},
}
View Source
var ComposerCreateCmd = &cobra.Command{
	Use:   "create [flags] <package> [<version>]",
	Short: "Executes 'composer create-project' within the web container",
	Long: `Directs basic invocations of 'composer create-project' within the context of the
web container. Projects will be installed to a temporary directory and moved to
the project root directory after installation. Any existing files in the
project root will be deleted when creating a project.`,
	Example: "ddev composer create drupal-composer/drupal-project:8.x-dev --stability dev --no-interaction\nddev composer create typo3/cms-base-distribution ^9",
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) < 1 || len(args) > 2 {
			err := cmd.Usage()
			util.CheckErr(err)
			os.Exit(-1)
		}

		var pkg, ver string
		if len(args) == 2 {
			pkg = args[len(args)-2]
			ver = args[len(args)-1]
		} else if len(args) == 1 {
			pkg = args[len(args)-1]
		}

		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed(err.Error())
		}

		if app.SiteStatus() != ddevapp.SiteRunning {
			err = app.Start()
			if err != nil {
				util.Failed("Failed to start app %s to run create-project: %v", app.Name, err)
			}
		}

		util.Warning("Warning: Any existing contents of the project root (%s) will be removed", app.AppRoot)
		if !noInteractionArg {
			if !util.Confirm("Would you like to continue?") {
				util.Failed("create-project cancelled")
			}
		}

		util.Warning("Removing any existing files in project root")
		objs, err := fileutil.ListFilesInDir(app.AppRoot)
		if err != nil {
			util.Failed("Failed to create project: %v", err)
		}

		for _, o := range objs {

			if o == ".ddev" {
				continue
			}

			if err = os.RemoveAll(filepath.Join(app.AppRoot, o)); err != nil {
				util.Failed("Failed to create project: %v", err)
			}
		}

		tmpDir := fmt.Sprintf(".tmp_ddev_composer_create_%s", util.RandString(6))
		containerInstallPath := path.Join("/var/www/html", tmpDir)
		hostInstallPath := filepath.Join(app.AppRoot, tmpDir)

		if !app.WebcacheEnabled {
			defer cleanupTmpDir(hostInstallPath)
		}

		composerCmd := []string{
			"composer",
			"create-project",
			pkg,
			containerInstallPath,
		}

		if ver != "" {
			composerCmd = append(composerCmd, ver)
		}

		if devArg {
			composerCmd = append(composerCmd, "--dev")
		}

		if noDevArg {
			composerCmd = append(composerCmd, "--no-dev")
		}

		if stabilityArg != "" {
			composerCmd = append(composerCmd, "--stability", stabilityArg)
		}

		if noInteractionArg {
			composerCmd = append(composerCmd, "--no-interaction")
		}

		if preferDistArg {
			composerCmd = append(composerCmd, "--prefer-dist")
		}

		composerCmdString := strings.TrimSpace(strings.Join(composerCmd, " "))
		output.UserOut.Printf("Executing composer command: %s\n", composerCmdString)
		stdout, _, err := app.Exec(&ddevapp.ExecOpts{
			Service: "web",
			Cmd:     composerCmd,
		})
		if err != nil {
			util.Failed("Failed to create project")
		}

		if len(stdout) > 0 {
			fmt.Println(strings.TrimSpace(stdout))
		}

		output.UserOut.Printf("Moving installation to project root")

		if !app.WebcacheEnabled {

			err = filepath.Walk(hostInstallPath, func(path string, info os.FileInfo, err error) error {

				if path == hostInstallPath {
					return nil
				}

				elements := strings.Split(path, tmpDir)
				newPath := filepath.Join(elements...)

				if info.IsDir() {
					if err := os.MkdirAll(newPath, info.Mode()); err != nil {
						return fmt.Errorf("unable to move %s to %s: %v", path, newPath, err)
					}

					return nil
				}

				if err := os.Rename(path, newPath); err != nil {
					return fmt.Errorf("unable to move %s to %s: %v", path, newPath, err)
				}

				return nil
			})
		} else {

			_, _, err = app.Exec(&ddevapp.ExecOpts{
				Service: "web",
				Cmd:     []string{"bash", "-c", fmt.Sprintf("shopt -s dotglob && mv %s/* /var/www/html && rmdir %s", containerInstallPath, containerInstallPath)},
			})
		}

		if err != nil {
			util.Failed("Failed to create project: %v", err)
		}
		if runtime.GOOS == "windows" && !util.IsDockerToolbox() {
			replaceSimulatedLinks(app.AppRoot)
		}

	},
}
View Source
var ComposerCreateProjectCmd = &cobra.Command{
	Use: "create-project",
	Run: func(cmd *cobra.Command, args []string) {
		util.Failed(`'ddev composer create-project' is unsupported. Please use 'ddev composer create'
for basic project creation or 'ddev ssh' into the web container and execute
'composer create-project' directly.`)
	},
}
View Source
var ConfigCommand *cobra.Command = &cobra.Command{
	Use:     "config [provider or 'global']",
	Short:   "Create or modify a ddev project configuration in the current directory",
	Example: `"ddev config" or "ddev config --docroot=. --project-name=d7-kickstart --project-type=drupal7"`,
	Args:    cobra.ExactArgs(0),
	Run:     handleConfigRun,
}

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("Project is not currently running. Try 'ddev start'.")
		}

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

		app.DockerEnv()

		out, _, err := app.Exec(&ddevapp.ExecOpts{
			Service: serviceType,
			Dir:     execDirArg,
			Cmd:     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 DdevListCmd = &cobra.Command{
	Use:   "list",
	Short: "List projects",
	Long:  `List projects.`,
	Run: func(cmd *cobra.Command, args []string) {
		for {
			apps := ddevapp.GetApps()
			appDescs := make([]map[string]interface{}, 0)

			if len(apps) < 1 {
				output.UserOut.WithField("raw", appDescs).Println("There are no active ddev projects.")
			} else {
				table := ddevapp.CreateAppTable()
				for _, app := range apps {
					desc, err := app.Describe()
					if err != nil {
						util.Failed("Failed to describe project %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)
		}
	},
}

DdevListCmd represents the list command

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("Project is not currently running. Try 'ddev start'.")
		}

		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 [projectname ...]",
	Aliases: []string{"rm"},
	Short:   "Remove the development environment for a project.",
	Long: `Remove the development environment for a project. You can run 'ddev remove'
from a project directory to remove that project, or you can remove projects in
any directory by running 'ddev remove projectname [projectname ...]'.

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 "ddev remove --remove-data".

To snapshot the database on remove, use "ddev remove --snapshot"; A snapshot is automatically created on
"ddev remove --remove-data" unless you use "ddev remove --remove-data --omit-snapshot".
`,
	Run: func(cmd *cobra.Command, args []string) {

		if removeAll && removeData {
			util.Failed("Illegal option combination: --all and --remove-data")
		}
		if createSnapshot && omitSnapshot {
			util.Failed("Illegal option combination: --snapshot and --omit-snapshot:")
		}

		apps, err := getRequestedApps(args, removeAll)
		if err != nil {
			util.Failed("Unable to get project(s): %v", err)
		}

		for _, app := range apps {
			if app.SiteStatus() == ddevapp.SiteNotFound {
				util.Warning("Project %s is not currently running. Try 'ddev start'.", app.GetName())
			}

			doSnapshot := ((createSnapshot || removeData) && !omitSnapshot)
			if err := app.Down(removeData, doSnapshot); err != nil {
				util.Failed("Failed to remove project %s: \n%v", app.GetName(), err)
			}

			util.Success("Project %s has been removed.", app.GetName())
		}
		if stopSSHAgent {
			err = ddevapp.RemoveSSHAgentContainer()
			if err != nil {
				util.Error("Failed to remove ddev-ssh-agent: %v", err)
			}
		}
	},
}

DdevRemoveCmd represents the remove command

View Source
var DdevRestartCmd = &cobra.Command{
	Use:   "restart",
	Short: "Restart the development environment for a project.",
	Long:  `Restart stops the containers for project 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 project %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", strings.Join(app.GetAllURLs(), ", "))
	},
}

DdevRestartCmd rebuilds an apps settings

View Source
var DdevRestoreSnapshotCommand = &cobra.Command{
	Use:   "restore-snapshot [snapshot_name]",
	Short: "Restore a project's database to the provided snapshot version.",
	Long: `Uses mariabackup command to restore a project database to a particular snapshot from the .ddev/db_snapshots folder.
Example: "ddev restore-snapshot d8git_20180717203845"`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) != 1 {
			util.Warning("Please provide the name of the snapshot you want to restore." +
				"\nThe available snapshots are in .ddev/db_snapshots.")
			_ = cmd.Usage()
			os.Exit(1)
		}

		snapshotName := args[0]
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to find active project: %v", err)
		}

		if err := app.RestoreSnapshot(snapshotName); err != nil {
			util.Failed("Failed to restore snapshot %s for project %s: %v", snapshotName, app.GetName(), err)
		}
	},
}

DdevRestoreSnapshotCommand provides the ability to revert to a database snapshot

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("Project is not currently running. Try 'ddev start'.")
		}

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

		app.DockerEnv()

		err = app.ExecWithTty(&ddevapp.ExecOpts{
			Service: serviceType,
			Cmd:     []string{"bash"},
			Dir:     sshDirArg,
		})

		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: "Connect sequelpro to a project database",
	Long:  `A helper command for using sequelpro (macOS database browser) with a running DDEV-Local project's database'.`,
	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 DdevSnapshotCommand = &cobra.Command{
	Use:   "snapshot [projectname projectname...]",
	Short: "Create a database snapshot for one or more projects.",
	Long:  `Uses mariabackup command to create a database snapshot in the .ddev/db_snapshots folder.`,
	Run: func(cmd *cobra.Command, args []string) {
		apps, err := getRequestedApps(args, snapshotAll)
		if err != nil {
			util.Failed("Unable to get project(s) %v: %v", args, err)
		}

		for _, app := range apps {
			if snapshotNameOutput, err := app.SnapshotDatabase(snapshotName); err != nil {
				util.Failed("Failed to snapshot %s: %v", app.GetName(), err)
			} else {
				util.Success("Created snapshot %s", snapshotNameOutput)
			}
		}
	},
}

DdevSnapshotCommand provides the snapshot command

View Source
var DdevStopCmd = &cobra.Command{
	Use:   "stop [projectname ...]",
	Short: "Stop the development environment for a project.",
	Long: `Stop the development environment for a project. You can run 'ddev stop'
from a project directory to stop that project, or you can stop running projects
in any directory by running 'ddev stop projectname [projectname ...]'`,
	Run: func(cmd *cobra.Command, args []string) {
		apps, err := getRequestedApps(args, stopAll)
		if err != nil {
			util.Failed("Unable to get project(s): %v", err)
		}

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

			util.Success("Project %s has been stopped.", app.GetName())
		}
	},
}

DdevStopCmd represents the stop command

View Source
var DebugCmd = &cobra.Command{
	Use:   "debug [command]",
	Short: "A collection of debugging commands",
	Run: func(cmd *cobra.Command, args []string) {
		err := cmd.Usage()
		util.CheckErr(err)
	},
}

DebugCmd is the top-level "ddev debug" command

View Source
var DescribeCommand = &cobra.Command{
	Use:   "describe [projectname]",
	Short: "Get a detailed description of a running ddev project.",
	Long: `Get a detailed description of a running ddev project. Describe provides basic
information about a ddev project, 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 project directory to stop that project, or you can specify a project to describe by
running 'ddev stop <projectname>.`,
	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 project named %s: %v", siteName, err)
		}

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

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

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

DescribeCommand represents the `ddev config` command

View Source
var ExportDBCmd = &cobra.Command{
	Use:     "export-db",
	Short:   "Dump a database to stdout or to a file",
	Long:    `Dump a database to stdout or to a file.`,
	Example: "ddev export-db >/tmp/db.sql.gz\nddev export-db --gzip=false >/tmp/db.sql\nddev export-db -f /tmp/db.sql.gz",
	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 find project from which to export database: %v", err)
		}

		if app.SiteStatus() != ddevapp.SiteRunning {
			err = app.Start()
			if err != nil {
				util.Failed("Failed to start app %s to export-db: %v", app.Name, err)
			}
		}

		err = app.ExportDB(outFileName, gzipOption)
		if err != nil {
			util.Failed("Failed to export database for %s: %v", app.GetName(), err)
		}
	},
}

ExportDBCmd is the `ddev export-db` command.

View Source
var HostNameCmd = &cobra.Command{
	Use:   "hostname [hostname] [ip]",
	Short: "Manage your hostfile entries.",
	Long: `Manage your hostfile entries. Managing host names has security and usability
implications and requires elevated privileges. You may be asked for a password
to allow ddev to modify your hosts file.`,
	Run: func(cmd *cobra.Command, args []string) {
		hosts, err := goodhosts.NewHosts()
		if err != nil {
			rawResult := make(map[string]interface{})
			detail := fmt.Sprintf("Could not open hosts file for reading: %v", err)
			rawResult["error"] = "READERROR"
			rawResult["full_error"] = detail
			output.UserOut.WithField("raw", rawResult).Fatal(detail)

			return
		}

		if err := hosts.Flush(); err != nil {
			rawResult := make(map[string]interface{})
			detail := fmt.Sprintf("Please use sudo or execute with administrative privileges: %v", err)
			rawResult["error"] = "WRITEERROR"
			rawResult["full_error"] = detail
			output.UserOut.WithField("raw", rawResult).Fatal(detail)

			return
		}

		if removeInactive {
			if len(args) > 0 {
				output.UserOut.Fatal("Invalid arguments supplied. 'ddev hostname --remove-all' accepts no arguments.")
			}

			removeInactiveHostnames(hosts)

			return
		}

		if len(args) != 2 {
			output.UserOut.Fatal("Invalid arguments supplied. Please use 'ddev hostname [hostname] [ip]'")
		}

		hostname, ip := args[0], args[1]

		if removeHostName {
			removeHostname(hosts, ip, hostname)

			return
		}

		addHostname(hosts, ip, hostname)
	},
}

HostNameCmd represents the hostname command

View Source
var ImportDBCmd = &cobra.Command{
	Use:   "import-db",
	Short: "Pull the database of an existing project to the dev environment.",
	Long: `Pull the database of an existing project 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 {
			err = app.Start()
			if err != nil {
				util.Failed("Failed to start app %s to import-db: %v", app.Name, err)
			}
		}

		err = app.ImportDB(dbSource, dbExtPath, progressOption)
		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: "Pull the uploaded files directory of an existing project to the default public upload directory of your project.",
	Long: `Pull the uploaded files directory of an existing project to the default
public upload directory of your project. 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.

The destination directory can be configured in your project's config.yaml
under the upload_dir key. If no custom upload directory is defined, the app
type's default upload directory will be used.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		dockerutil.EnsureDdevNetwork()
	},
	Args: cobra.ExactArgs(0),
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to import files: %v", err)
		}

		var showExtPathPrompt bool
		if sourcePath == "" {

			if extPath == "" {
				showExtPathPrompt = true
			}

			promptForFileSource(&sourcePath)
		}

		importPath, isArchive, err := appimport.ValidateAsset(sourcePath, "files")
		if err != nil {
			util.Failed("Failed to import files for %s: %v", app.GetName(), err)
		}

		if isArchive && showExtPathPrompt {
			promptForExtPath(&extPath)
		}

		if err = app.ImportFiles(importPath, extPath); 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.")
		}

		globalDir := globalconfig.GetGlobalDdevDir()
		sessionLocation := filepath.Join(globalDir, "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: "Pull files and database using a configured provider plugin.",
	Long: `Pull files and database using a configured provider plugin.
	Running pull will connect to the configured provider and download + import the
	latest backups.`,
	Args: cobra.ExactArgs(0),
	PreRun: func(cmd *cobra.Command, args []string) {
		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		appPull(skipConfirmationArg)
	},
}

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{"version", "config", "hostname", "help", "auth-pantheon", "import-files"}
		command := strings.Join(os.Args[1:], " ")

		output.LogSetUp()

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

		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)
			}
		}

		updateFile := filepath.Join(globalconfig.GetGlobalDdevDir(), ".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.\nFor upgrade help see %s", updateURL, updateDocURL)
			}
		}

	},
	PersistentPostRun: func(cmd *cobra.Command, args []string) {

		ignores := map[string]bool{"list": true, "version": true, "help": true, "auth-pantheon": true, "hostname": true}
		if _, ok := ignores[cmd.CalledAs()]; ok {
			return
		}
		sentryNotSetupWarning()

		cmdCopy := cmd
		var fullCommand = make([]string, 0)
		fullCommand = append(fullCommand, util.GetFirstWord(cmdCopy.Use))
		for cmdCopy.HasParent() {
			fullCommand = append(fullCommand, util.GetFirstWord(cmdCopy.Parent().Use))
			cmdCopy = cmdCopy.Parent()
		}
		uString := "Usage:"
		for i := len(fullCommand) - 1; i >= 0; i = i - 1 {
			uString = uString + " " + fullCommand[i]
		}

		if globalconfig.DdevGlobalConfig.InstrumentationOptIn && version.SentryDSN != "" {
			_ = raven.CaptureMessageAndWait(uString, map[string]string{"severity-level": "info", "report-type": "usage"})
		}
	},
}

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 [projectname ...]",
	Aliases: []string{"add"},
	Short:   "Start a ddev project.",
	Long: `Start initializes and configures the web server and database containers
to provide a local development environment. You can run 'ddev start' from a
project directory to start that project, or you can start stopped projects in
any directory by running 'ddev start projectname [projectname ...]'`,
	PreRun: func(cmd *cobra.Command, args []string) {
		dockerutil.EnsureDdevNetwork()
	},
	Run: func(cmd *cobra.Command, args []string) {
		apps, err := getRequestedApps(args, startAll)
		if err != nil {
			util.Failed("Unable to get project(s): %v", err)
		}

		if len(apps) == 0 {
			output.UserOut.Printf("There are no projects to start.")
		}

		err = checkDdevVersionAndOptInSentry()
		if err != nil {
			util.Failed(err.Error())
		}

		for _, app := range apps {
			output.UserOut.Printf("Starting %s...", app.GetName())

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

			util.Success("Successfully started %s", app.GetName())
			util.Success("Project can be reached at %s", strings.Join(app.GetAllURLs(), ", "))
			if app.WebcacheEnabled {
				util.Warning("All contents were copied to fast docker filesystem,\nbut bidirectional sync operation may not be fully functional for a few minutes.")
			}
		}
	},
}

StartCmd provides the ddev start 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