cmd

package
v1.1.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfigCommand *cobra.Command = &cobra.Command{
	Use:     "config [provider]",
	Short:   "Create or modify a ddev project configuration in the current directory",
	Example: `"ddev config" or "ddev config --docroot=. --projectname=d7-kickstart --projecttype=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(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("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 ddev project %s: %v", app.GetName(), err)
			}

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

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(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: "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 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", 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 projects",
	Long:  `List projects.`,
	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 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)
		}

	},
}

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. 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: "Import the database of an existing project to the dev environment.",
	Long: `Import 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)
		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 project to the default public upload directory of your project.",
	Long: `Import 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.`,
	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.")
		}

		ddevDir := util.GetGlobalDdevDir()
		sessionLocation := filepath.Join(ddevDir, "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{"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)
			}
		}

		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.\nFor upgrade help see %s", updateURL, updateDocURL)
			}
		}

	},
}

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

		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(), ", "))
		}
	},
}

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