// setupCommonRootCommand contains the setup common to
// SetupRootCommand and SetupPluginRootCommand.
429167
func setupCommonRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet, *cobra.Command) {
	opts := cliflags.NewClientOptions()
	flags := rootCmd.Flags()

	flags.StringVar(&opts.ConfigDir, "config", cliconfig.Dir(), "Location of client config files")
	opts.Common.InstallFlags(flags)

	cobra.AddTemplateFunc("add", func(a, b int) int { return a + b })
	cobra.AddTemplateFunc("hasSubCommands", hasSubCommands)
	cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands)
	cobra.AddTemplateFunc("hasInvalidPlugins", hasInvalidPlugins)
	cobra.AddTemplateFunc("operationSubCommands", operationSubCommands)
	cobra.AddTemplateFunc("managementSubCommands", managementSubCommands)
	cobra.AddTemplateFunc("invalidPlugins", invalidPlugins)
	cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
	cobra.AddTemplateFunc("vendorAndVersion", vendorAndVersion)
	cobra.AddTemplateFunc("invalidPluginReason", invalidPluginReason)
	cobra.AddTemplateFunc("isPlugin", isPlugin)
	cobra.AddTemplateFunc("decoratedName", decoratedName)

	rootCmd.SetUsageTemplate(usageTemplate)
	rootCmd.SetHelpTemplate(helpTemplate)
	rootCmd.SetFlagErrorFunc(FlagErrorFunc)
	rootCmd.SetHelpCommand(helpCommand)

	rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
	rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
	rootCmd.PersistentFlags().Lookup("help").Hidden = true

	return opts, flags, helpCommand
}
1018424
func (g *Generator) SetRootPath(path string) {
	g.initConfigRoot()
	g.Config.Root.Path = path
}
1135991
func (s *Service) InstallCommands() ([]string, error) {
	cmd := fmt.Sprintf(serviceCreateCommandTemplate[1:],
		renderer.Quote(s.Service.Name),
		renderer.Quote(s.Service.Conf.Desc),
		renderer.Quote(s.Service.Conf.ExecStart),
		renderer.Quote(s.Service.Name),
		renderer.Quote(s.Service.Conf.Desc),
		renderer.Quote(s.Service.Conf.ExecStart),
		renderer.Quote(s.Service.Name),
		renderer.Quote(s.Service.Name),
	)
	return strings.Split(cmd, "\n"), nil
}
934298
func SetupRootCommand(rootCmd *cobra.Command) {
	cobra.AddTemplateFunc("hasSubCommands", hasSubCommands)
	cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands)
	cobra.AddTemplateFunc("operationSubCommands", operationSubCommands)
	cobra.AddTemplateFunc("managementSubCommands", managementSubCommands)
	cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)

	rootCmd.SetUsageTemplate(usageTemplate)
	rootCmd.SetHelpTemplate(helpTemplate)
	rootCmd.SetFlagErrorFunc(FlagErrorFunc)
	rootCmd.SetVersionTemplate("Docker version {{.Version}}\n")

	rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
	rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
}
594678
func (s *Service) setup() error {
	for _, m := range s.modules {
		n := getModuleName(m)
		c := s.configs[n]
		if c.Setup != nil {
			BootPrintln("[service] setup", n)
			err := c.Setup()
			if err != nil {
				return err
			}
		}

		if s.Env.IsTest() && c.SetupTest != nil {
			BootPrintln("[service] setup for test", n)
			c.SetupTest()
		}
	}
	return nil
}
1020410
func (m *JobExecutor) Setup() error {
	if m == nil {
		return fmt.Errorf("JobExecutor is nil?")
	}
	if m.RootTask == nil {
		return fmt.Errorf("No task exists for this job")
	}
	return m.RootTask.Setup(0)
}
750774
func Setup(conf config.Config) error {
	nsConf := conf.NetworkServer.NetworkSettings
	rejoinRequestEnabled = nsConf.RejoinRequest.Enabled
	rejoinRequestMaxCountN = nsConf.RejoinRequest.MaxCountN
	rejoinRequestMaxTimeN = nsConf.RejoinRequest.MaxTimeN

	classBPingSlotDR = nsConf.ClassB.PingSlotDR
	classBPingSlotFrequency = nsConf.ClassB.PingSlotFrequency

	rx2Frequency = nsConf.RX2Frequency
	rx2DR = nsConf.RX2DR
	rx1DROffset = nsConf.RX1DROffset
	rx1Delay = nsConf.RX1Delay
	rxWindow = nsConf.RXWindow

	downlinkTXPower = nsConf.DownlinkTXPower

	disableMACCommands = nsConf.DisableMACCommands
	disableADR = nsConf.DisableADR

	classCDownlinkLockDuration = conf.NetworkServer.Scheduler.ClassC.DownlinkLockDuration

	return nil
}
1277351
func (m *Command) setupNetworking() error {
	if m.Config.Cluster.Disabled {
		return nil
	}

	gossipPort, err := strconv.Atoi(m.Config.Gossip.Port)
	if err != nil {
		return errors.Wrap(err, "parsing port")
	}

	// get the host portion of addr to use for binding
	gossipHost := m.listenURI.Host
	m.gossipTransport, err = gossip.NewTransport(gossipHost, gossipPort, m.logger.Logger())
	if err != nil {
		return errors.Wrap(err, "getting transport")
	}

	gossipMemberSet, err := gossip.NewMemberSet(
		m.Config.Gossip,
		m.API,
		gossip.WithLogOutput(&filteredWriter{logOutput: m.logOutput, v: m.Config.Verbose}),
		gossip.WithPilosaLogger(m.logger),
		gossip.WithTransport(m.gossipTransport),
	)
	if err != nil {
		return errors.Wrap(err, "getting memberset")
	}
	m.gossipMemberSet = gossipMemberSet

	return errors.Wrap(gossipMemberSet.Open(), "opening gossip memberset")
}
698702
func Setup(
	eventStore eh.EventStore,
	eventBus eh.EventBus,
	commandBus *bus.CommandHandler,
	invitationRepo, guestListRepo eh.ReadWriteRepo,
	eventID uuid.UUID) {

	// Add a logger as an observer.
	eventBus.AddObserver(eh.MatchAny(), &Logger{})

	// Create the aggregate repository.
	aggregateStore, err := events.NewAggregateStore(eventStore, eventBus)
	if err != nil {
		log.Fatalf("could not create aggregate store: %s", err)
	}

	// Create the aggregate command handler and register the commands it handles.
	invitationHandler, err := aggregate.NewCommandHandler(InvitationAggregateType, aggregateStore)
	if err != nil {
		log.Fatalf("could not create command handler: %s", err)
	}
	commandHandler := eh.UseCommandHandlerMiddleware(invitationHandler, LoggingMiddleware)
	commandBus.SetHandler(commandHandler, CreateInviteCommand)
	commandBus.SetHandler(commandHandler, AcceptInviteCommand)
	commandBus.SetHandler(commandHandler, DeclineInviteCommand)
	commandBus.SetHandler(commandHandler, ConfirmInviteCommand)
	commandBus.SetHandler(commandHandler, DenyInviteCommand)

	// Create and register a read model for individual invitations.
	invitationProjector := projector.NewEventHandler(
		NewInvitationProjector(), invitationRepo)
	invitationProjector.SetEntityFactory(func() eh.Entity { return &Invitation{} })
	eventBus.AddHandler(eh.MatchAnyEventOf(
		InviteCreatedEvent,
		InviteAcceptedEvent,
		InviteDeclinedEvent,
		InviteConfirmedEvent,
		InviteDeniedEvent,
	), invitationProjector)

	// Create and register a read model for a guest list.
	guestListProjector := NewGuestListProjector(guestListRepo, eventID)
	eventBus.AddHandler(eh.MatchAnyEventOf(
		InviteAcceptedEvent,
		InviteDeclinedEvent,
		InviteConfirmedEvent,
		InviteDeniedEvent,
	), guestListProjector)

	// Setup the saga that responds to the accepted guests and limits the total
	// amount of guests, responding with a confirmation or denial.
	responseSaga := saga.NewEventHandler(NewResponseSaga(2), commandBus)
	eventBus.AddHandler(eh.MatchEvent(InviteAcceptedEvent), responseSaga)
}
1141302
func rootCommands() {
	for _, cmd := range root.Command.Commands() {
		if !cmd.Hidden {
			fmt.Printf("%s ", cmd.Name())
		}
	}
}
1005489
func (s *Service) InstallCommands() ([]string, error) {
	conf, err := s.render()
	if err != nil {
		return nil, err
	}
	cmd := fmt.Sprintf("cat > %s << 'EOF'\n%sEOF\n", s.confPath(), conf)
	return []string{cmd}, nil
}
962862
func setup(c *caddy.Controller) error {
	found := false

	for c.Next() {
		if found {
			return c.Err("pprof can only be specified once")
		}
		if len(c.RemainingArgs()) != 0 {
			return c.ArgErr()
		}
		if c.NextBlock() {
			return c.ArgErr()
		}
		found = true
	}

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return &Handler{Next: next, Mux: NewMux()}
	})

	return nil
}
1023783
func (f *Facade) AddCommand(name string, command cli.Command) {
	f.commands[name] = func() (cli.Command, error) {
		return command, nil
	}
}
720759
func (m *MountPoint) Setup(mountLabel string, rootIDs idtools.Identity, checkFun func(m *MountPoint) error) (path string, err error) {
	if m.SkipMountpointCreation {
		return m.Source, nil
	}

	defer func() {
		if err != nil || !label.RelabelNeeded(m.Mode) {
			return
		}

		var sourcePath string
		sourcePath, err = filepath.EvalSymlinks(m.Source)
		if err != nil {
			path = ""
			err = errors.Wrapf(err, "error evaluating symlinks from mount source %q", m.Source)
			return
		}
		err = label.Relabel(sourcePath, mountLabel, label.IsShared(m.Mode))
		if err == syscall.ENOTSUP {
			err = nil
		}
		if err != nil {
			path = ""
			err = errors.Wrapf(err, "error setting label on mount source '%s'", sourcePath)
		}
	}()

	if m.Volume != nil {
		id := m.ID
		if id == "" {
			id = stringid.GenerateNonCryptoID()
		}
		path, err := m.Volume.Mount(id)
		if err != nil {
			return "", errors.Wrapf(err, "error while mounting volume '%s'", m.Source)
		}

		m.ID = id
		m.active++
		return path, nil
	}

	if len(m.Source) == 0 {
		return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined")
	}

	if m.Type == mounttypes.TypeBind {
		// Before creating the source directory on the host, invoke checkFun if it's not nil. One of
		// the use case is to forbid creating the daemon socket as a directory if the daemon is in
		// the process of shutting down.
		if checkFun != nil {
			if err := checkFun(m); err != nil {
				return "", err
			}
		}

		// idtools.MkdirAllNewAs() produces an error if m.Source exists and is a file (not a directory)
		// also, makes sure that if the directory is created, the correct remapped rootUID/rootGID will own it
		if err := idtools.MkdirAllAndChownNew(m.Source, 0755, rootIDs); err != nil {
			if perr, ok := err.(*os.PathError); ok {
				if perr.Err != syscall.ENOTDIR {
					return "", errors.Wrapf(err, "error while creating mount source path '%s'", m.Source)
				}
			}
		}
	}
	return m.Source, nil
}
984255
func setup(ctx *cli.Context) (err error) {
	setting.Debug = ctx.GlobalBool("debug")
	log.NonColor = ctx.GlobalBool("noterm")
	log.Verbose = ctx.Bool("verbose")

	log.Info("App Version: %s", ctx.App.Version)

	setting.HomeDir, err = base.HomeDir()
	if err != nil {
		return fmt.Errorf("Fail to get home directory: %v", err)
	}
	setting.HomeDir = strings.Replace(setting.HomeDir, "\\", "/", -1)

	setting.InstallRepoPath = path.Join(setting.HomeDir, ".gopm/repos")
	if runtime.GOOS == "windows" {
		setting.IsWindows = true
	}
	os.MkdirAll(setting.InstallRepoPath, os.ModePerm)
	log.Info("Local repository path: %s", setting.InstallRepoPath)

	if !setting.LibraryMode || len(setting.WorkDir) == 0 {
		setting.WorkDir, err = os.Getwd()
		if err != nil {
			return fmt.Errorf("Fail to get work directory: %v", err)
		}
		setting.WorkDir = strings.Replace(setting.WorkDir, "\\", "/", -1)
	}
	setting.DefaultGopmfile = path.Join(setting.WorkDir, setting.GOPMFILE)
	setting.DefaultVendor = path.Join(setting.WorkDir, setting.VENDOR)
	setting.DefaultVendorSrc = path.Join(setting.DefaultVendor, "src")

	if !ctx.Bool("remote") {
		if ctx.Bool("local") {
			// gf, _, _, err := genGopmfile(ctx)
			// if err != nil {
			// 	return err
			// }
			// setting.InstallGopath = gf.MustValue("project", "local_gopath")
			// if ctx.Command.Name != "gen" {
			// 	if com.IsDir(setting.InstallGopath) {
			// 		log.Log("Indicated local GOPATH: %s", setting.InstallGopath)
			// 		setting.InstallGopath += "/src"
			// 	} else {
			// 		if setting.LibraryMode {
			// 			return fmt.Errorf("Local GOPATH does not exist or is not a directory: %s",
			// 				setting.InstallGopath)
			// 		}
			// 		log.Error("", "Invalid local GOPATH path")
			// 		log.Error("", "Local GOPATH does not exist or is not a directory:")
			// 		log.Error("", "\t"+setting.InstallGopath)
			// 		log.Help("Try 'go help gopath' to get more information")
			// 	}
			// }

		} else {
			// Get GOPATH.
			setting.InstallGopath = base.GetGOPATHs()[0]
			if base.IsDir(setting.InstallGopath) {
				log.Info("Indicated GOPATH: %s", setting.InstallGopath)
				setting.InstallGopath += "/src"
				setting.HasGOPATHSetting = true
			} else {
				if ctx.Bool("gopath") {
					return fmt.Errorf("Local GOPATH does not exist or is not a directory: %s",
						setting.InstallGopath)
				} else {
					// It's OK that no GOPATH setting
					// when user does not specify to use.
					log.Warn("No GOPATH setting available")
				}
			}
		}
	}

	setting.ConfigFile = path.Join(setting.HomeDir, ".gopm/data/gopm.ini")
	if err = setting.LoadConfig(); err != nil {
		return err
	}

	setting.PkgNameListFile = path.Join(setting.HomeDir, ".gopm/data/pkgname.list")
	if err = setting.LoadPkgNameList(); err != nil {
		return err
	}

	setting.LocalNodesFile = path.Join(setting.HomeDir, ".gopm/data/localnodes.list")
	if err = setting.LoadLocalNodes(); err != nil {
		return err
	}
	return nil
}
922494
func NamespaceKeyRootFunc(ctx context.Context, prefix string) string {
	key := prefix
	ns, ok := genericapirequest.NamespaceFrom(ctx)
	if ok && len(ns) > 0 {
		key = key + "/" + ns
	}
	return key
}
1362790
func WithCommonOptions(daemon *Daemon, c *container.Container) coci.SpecOpts {
	return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
		if c.BaseFS == nil {
			return errors.New("populateCommonSpec: BaseFS of container " + c.ID + " is unexpectedly nil")
		}
		linkedEnv, err := daemon.setupLinkedContainers(c)
		if err != nil {
			return err
		}
		s.Root = &specs.Root{
			Path:     c.BaseFS.Path(),
			Readonly: c.HostConfig.ReadonlyRootfs,
		}
		if err := c.SetupWorkingDirectory(daemon.idMapping.RootPair()); err != nil {
			return err
		}
		cwd := c.Config.WorkingDir
		if len(cwd) == 0 {
			cwd = "/"
		}
		s.Process.Args = append([]string{c.Path}, c.Args...)

		// only add the custom init if it is specified and the container is running in its
		// own private pid namespace.  It does not make sense to add if it is running in the
		// host namespace or another container's pid namespace where we already have an init
		if c.HostConfig.PidMode.IsPrivate() {
			if (c.HostConfig.Init != nil && *c.HostConfig.Init) ||
				(c.HostConfig.Init == nil && daemon.configStore.Init) {
				s.Process.Args = append([]string{inContainerInitPath, "--", c.Path}, c.Args...)
				path := daemon.configStore.InitPath
				if path == "" {
					path, err = exec.LookPath(daemonconfig.DefaultInitBinary)
					if err != nil {
						return err
					}
				}
				s.Mounts = append(s.Mounts, specs.Mount{
					Destination: inContainerInitPath,
					Type:        "bind",
					Source:      path,
					Options:     []string{"bind", "ro"},
				})
			}
		}
		s.Process.Cwd = cwd
		s.Process.Env = c.CreateDaemonEnvironment(c.Config.Tty, linkedEnv)
		s.Process.Terminal = c.Config.Tty

		s.Hostname = c.Config.Hostname
		setLinuxDomainname(c, s)

		return nil
	}
}