Пример #1
0
        public bool Commit(string message, string authorName = null, string emailAddress = null)
        {
            if (!Repository.Status().Any())
            {
                return(false);
            }

            Repository.AddRemove();

            var overrideAuthor = string.Empty;

            if (!string.IsNullOrEmpty(authorName) &&
                !string.IsNullOrEmpty(emailAddress))
            {
                overrideAuthor = string.Format("{0} <{1}>", authorName, emailAddress);
            }

            var command = new CommitCommand
            {
                OverrideAuthor = overrideAuthor,
                Message        = message
            };

            var id = Repository.Commit(command);

            return(id != null);
        }
 /// <summary>
 /// Execute the CommitCommand
 /// </summary>
 protected virtual void ExecuteCommitCommand()
 {
     if (CommitCommand != null && CommitCommand.CanExecute(CommitCommandParameter))
     {
         CommitCommand.Execute(CommitCommandParameter);
     }
 }
Пример #3
0
        void OnCommitClicked(object src, EventArgs args)
        {
            // Nothing to commit
            if (changeSet.IsEmpty)
            {
                return;
            }

            int comments = changeSet.CommentsCount;

            if ((comments > 0) && (changeSet.Count > comments))
            {
                if (MessageService.AskQuestion(
                        GettextCatalog.GetString("Some of the files in this commit do not have ChangeLog messages."),
                        GettextCatalog.GetString("You may have forgotten to unselect items."),
                        AlertButton.Cancel, AlertButton.Proceed) != AlertButton.Proceed)
                {
                    return;
                }
            }

            VersionControlService.FileStatusChanged -= OnFileStatusChanged;
            CommitCommand.Commit(vc, changeSet.Clone(), false);
            VersionControlService.FileStatusChanged += OnFileStatusChanged;
        }
Пример #4
0
        public void ExecuteWithAllOptions()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks).Expecting(() =>
            {
                conn.Post("/update", "<commit waitSearcher=\"true\" waitFlush=\"true\" expungeDeletes=\"true\" maxSegments=\"2\" />");
                LastCall.On(conn).Repeat.Once().Do(new Writer(delegate(string ignored, string s)
                {
                    Console.WriteLine(s);
                    return(null);
                }));
            }).Verify(() =>
            {
                var cmd = new CommitCommand
                {
                    MaxSegments    = 2,
                    ExpungeDeletes = true,
                    WaitFlush      = true,
                    WaitSearcher   = true
                };
                cmd.Execute(conn);
            });
        }
Пример #5
0
        public CommitSubcommand()
        {
            Name        = "commit";
            Description = "git commit -m <message>";

            var userNameOption = new CommandOption("-u|--username <USERNAME>", CommandOptionType.SingleValue);

            Options.Add(userNameOption);

            var emailOption = new CommandOption("-e|--email <EMAIL>", CommandOptionType.SingleValue);

            Options.Add(emailOption);

            var commitMessageOption = new CommandOption("-m|--message <MESSAGE>", CommandOptionType.SingleValue);

            Options.Add(commitMessageOption);

            OnExecute(() =>
            {
                string userName      = userNameOption.Value();
                string email         = emailOption.Value();
                string commitMessage = commitMessageOption.Value();

                var command = new CommitCommand();
                command.Execute(PathValueOrDefault, userName, email, commitMessage);

                if (!Quiet)
                {
                    Console.WriteLine("Committed");
                }

                return(0);
            });
        }
Пример #6
0
        private void OnCommitClicked(object src, EventArgs args)
        {
            // Nothing to commit
            if (changeSet.IsEmpty)
            {
                return;
            }

            int comments = changeSet.CommentsCount;

            if ((comments > 0) && (changeSet.Count > comments))
            {
                if (MessageService.AskQuestion(
                        GettextCatalog.GetString("Some of the files in this commit do not have ChangeLog messages."),
                        GettextCatalog.GetString("You may have forgotten to unselect items."),
                        AlertButton.Cancel, AlertButton.Proceed) != AlertButton.Proceed)
                {
                    return;
                }
            }

            // Reset the global comment. It may be already set from previous commits.
            changeSet.GlobalComment = string.Empty;

            if (!CommitCommand.Commit(vc, changeSet.Clone(), false))
            {
                return;
            }
        }
Пример #7
0
        /// <summary>
        /// Commits posted documents
        /// </summary>
        /// <param name="waitFlush">wait for flush</param>
        /// <param name="waitSearcher">wait for new searcher</param>
        /// <param name="expungeDeletes">Merge segments with deletes away</param>
        /// <param name="maxSegments">Optimizes down to, at most, this number of segments</param>
        public static void Commit(bool waitFlush, bool waitSearcher, bool expungeDeletes, int maxSegments)
        {
            var cmd = new CommitCommand {
                WaitFlush = waitFlush, WaitSearcher = waitSearcher, ExpungeDeletes = expungeDeletes, MaxSegments = maxSegments
            };

            cmd.Execute(Connection);
        }
Пример #8
0
        private void OnGeneratePuzzle(EDifficulty difficulty)
        {
            // memorize difficulty
            Difficulty = difficulty;

            // Close dialog
            CommitCommand.Execute();
        }
Пример #9
0
 private void StatusVM_PropertyChanged(object sender, PropertyChangedEventArgs e)
 {
     if (e.PropertyName == "IsStaged")
     {
         NotifyPropertyChanged("AllStaged");
         MainWindow.Instance.Dispatcher.Invoke(() => CommitCommand.RaiseCanExecuteChanged());
     }
 }
Пример #10
0
        /// <summary>
        /// Commits posted documents
        /// </summary>
        /// <param name="waitFlush">wait for flush</param>
        /// <param name="waitSearcher">wait for new searcher</param>
        public static void Commit(bool waitFlush, bool waitSearcher)
        {
            var cmd = new CommitCommand {
                WaitFlush = waitFlush, WaitSearcher = waitSearcher
            };

            cmd.Execute(Connection);
        }
Пример #11
0
 private void UpdateCommandsCanExecuteStatus()
 {
     CancelCommand.RaiseCanExecuteChanged();
     CommitCommand.RaiseCanExecuteChanged();
     BeginEditCommand.RaiseCanExecuteChanged();
     AddCommand.RaiseCanExecuteChanged();
     DeleteCommand.RaiseCanExecuteChanged();
 }
        public ProjectRepairViewModel(Project project, string message)
        {
            clone_         = project.Clone();
            ProjectSetting = new ProjectSettingViewModel(clone_);
            Message.Value  = message + "プロジェクト型を元の型に設定しなおしてください。必要であればアセンブリを設定しなおしてください。";

            CommitCommand = clone_.IsValid.ToReactiveCommand();
            CommitCommand.PublishTask(x => CommitAsync(), e => ShowError(e, "エラー"));
        }
Пример #13
0
 private void ItemsView_PropertyChanged(object sender, PropertyChangedEventArgs e)
 {
     if (e.PropertyName == nameof(IEditableCollectionView.IsEditingItem) ||
         e.PropertyName == nameof(IEditableCollectionView.IsAddingNew))
     {
         OnPropertyChanged(nameof(IsEditingItem));
         CommitCommand.RaiseCanExecuteChanged();
         CancelCommand.RaiseCanExecuteChanged();
         ReloadCommand.RaiseCanExecuteChanged();
         ToggleEditCommand.RaiseCanExecuteChanged();
     }
 }
Пример #14
0
        public ResponseHeader Commit(CommitOptions options)
        {
            options = options ?? new CommitOptions();
            var cmd = new CommitCommand {
                WaitFlush      = options.WaitFlush,
                WaitSearcher   = options.WaitSearcher,
                ExpungeDeletes = options.ExpungeDeletes,
                MaxSegments    = options.MaxSegments,
            };

            return(SendAndParseHeader(cmd));
        }
Пример #15
0
        public Server(CreateCommand createCommand, LoginCommand loginCommand, UseCommand useCommand, 
            ShowCommand showCommand, CommitCommand commitCommand, PullCommand pullCommand, ILocalService localService)
        {
            this.createCommand = createCommand;
            this.loginCommand = loginCommand;
            this.useCommand = useCommand;
            this.showCommand = showCommand;
            this.commitCommand = commitCommand;
            this.pullCommand = pullCommand;

            this.localService = localService;
        }
Пример #16
0
        private async Task TestAccountAsync()
        {
            AccountDefinition worker = AccountDefinition.GetByPrefix(ConnectedAccount.Prefix);

            IsValidating = true;
            Exception ex = await worker.ValidateInteractiveAsync(ConnectedAccount.Id, ConnectedAccount.StorageConnectionString);

            ValidationError        = ex?.Message;
            ValidationErrorDetails = ex?.ToString();
            IsValidating           = false;
            ValidationPassed       = ex == null;
            CommitCommand?.RaiseCanExecuteChanged();
        }
Пример #17
0
        private static CommitCommand GetCommitCommand(CommitOptions options)
        {
            options = options ?? new CommitOptions();
            var cmd = new CommitCommand
            {
                WaitFlush      = options.WaitFlush,
                WaitSearcher   = options.WaitSearcher,
                ExpungeDeletes = options.ExpungeDeletes,
                MaxSegments    = options.MaxSegments,
            };

            return(cmd);
        }
Пример #18
0
        public void ExecuteBasic()
        {
            var conn = new Mocks.MSolrConnection();

            conn.post += (url, content) => {
                Assert.AreEqual("/update", url);
                Assert.AreEqual("<commit />", content);
                Console.WriteLine(content);
                return(null);
            };
            var cmd = new CommitCommand();

            cmd.Execute(conn);
            Assert.AreEqual(1, conn.post.Calls);
        }
Пример #19
0
        public void ExecuteWithBasicOptions()
        {
            var conn = new Mocks.MSolrConnection();

            conn.post += (url, content) => {
                Assert.AreEqual("/update", url);
                Assert.AreEqual("<commit waitSearcher=\"true\" waitFlush=\"true\" />", content);
                Console.WriteLine(content);
                return(null);
            };
            var cmd = new CommitCommand {
                WaitFlush = true, WaitSearcher = true
            };

            cmd.Execute(conn);
            Assert.AreEqual(1, conn.post.Calls);
        }
Пример #20
0
        private static void RegisterPullSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory)
        {
            packagesCmd.Command("pull", c =>
            {
                c.Description = "Incremental copy of files from remote location to local packages";
                var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                var argSource = c.Argument("[source]",
                                           "Path to source packages folder, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var reports = reportsFactory.CreateReports(quiet: false);

                    bool success;
                    if (Directory.Exists(argSource.Value))
                    {
                        // Implicitly commit changes before pull
                        var commitOptions = new CommitOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        success           = commitCommand.Execute();
                        if (!success)
                        {
                            return(1);
                        }
                    }

                    var pullOptions = new PullOptions
                    {
                        Reports        = reports,
                        SourcePackages = argSource.Value,
                        RemotePackages = argRemote.Value
                    };
                    var pullCommand = new PullCommand(pullOptions);
                    success         = pullCommand.Execute();
                    return(success ? 0 : 1);
                });
            });
        }
Пример #21
0
        public bool Commit(string message, string authorName = "")
        {
            if (!Repository.Status().Any())
            {
                return(false);
            }

            Repository.AddRemove();

            var command = new CommitCommand
            {
                OverrideAuthor = authorName ?? String.Empty,
                Message        = message
            };

            var id = Repository.Commit(command);

            return(id != null);
        }
Пример #22
0
        public void ExecuteBasic()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks).Expecting(() =>
            {
                conn.Post("/update", "<commit />");
                LastCall.On(conn).Repeat.Once().Do(new Writer(delegate(string ignored, string s)
                {
                    Console.WriteLine(s);
                    return(null);
                }));
            }).Verify(() =>
            {
                var cmd = new CommitCommand();
                cmd.Execute(conn);
            });
        }
Пример #23
0
        public ChangeSet Commit(string authorName, string message)
        {
            if (!GetStatus().Any()) {
                return null;
            }

            _repository.AddRemove();

            var command = new CommitCommand {
                OverrideAuthor = authorName,
                Message = message
            };

            var id = _repository.Commit(command);

            // TODO: Figure out why is id null
            id = id ?? CurrentId;

            return GetChangeSet(id);
        }
Пример #24
0
        public void SetStaged(List <StatusEntryVM> statusEntries, bool staged)
        {
            if (staged)
            {
                _areaVM.Area.RecordChanges(_status, statusEntries.Select(x => x.StatusEntry).ToList(), true, false, (se, code, b) => { se.Code = code; se.Staged = true; });
            }
            else
            {
                _areaVM.Area.Revert(statusEntries.Select(x => x.StatusEntry).ToList(), false, false, false, (se, code) => { se.Code = code; se.Staged = false; });
            }

            statusEntries.ForEach(x =>
            {
                x.NotifyPropertyChanged("IsStaged");
                x.NotifyPropertyChanged("Code");
            });

            NotifyPropertyChanged("AllStaged");
            MainWindow.Instance.Dispatcher.Invoke(() => CommitCommand.RaiseCanExecuteChanged());
        }
Пример #25
0
        private static void RegisterPushSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory)
        {
            packagesCmd.Command("push", c =>
            {
                c.Description = "Incremental copy of files from local packages to remote location";
                var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                var argSource = c.Argument("[source]",
                    "Path to source packages folder, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var reports = reportsFactory.CreateReports(quiet: false);

                    // Implicitly commit changes before push
                    var commitOptions = new CommitOptions
                    {
                        Reports = reports,
                        SourcePackages = argSource.Value
                    };
                    var commitCommand = new CommitCommand(commitOptions);
                    var success = commitCommand.Execute();
                    if (!success)
                    {
                        return 1;
                    }

                    var pushOptions = new PushOptions
                    {
                        Reports = reports,
                        SourcePackages = argSource.Value,
                        RemotePackages = argRemote.Value
                    };
                    var pushCommand = new PushCommand(pushOptions);
                    success = pushCommand.Execute();
                    return success ? 0 : 1;
                });
            });
        }
Пример #26
0
        public void ExecuteWithAllOptions()
        {
            var conn = new Mocks.MSolrConnection();

            conn.post += (url, content) => {
                Assert.Equal("/update", url);
                Assert.Equal("<commit waitSearcher=\"true\" waitFlush=\"true\" expungeDeletes=\"true\" maxSegments=\"2\" />", content);
                testOutputHelper.WriteLine(content);
                return(null);
            };

            var cmd = new CommitCommand {
                MaxSegments    = 2,
                ExpungeDeletes = true,
                WaitFlush      = true,
                WaitSearcher   = true
            };

            cmd.Execute(conn);
            Assert.Equal(1, conn.post.Calls);
        }
Пример #27
0
        public ChangeSet Commit(string message, string authorName = "")
        {
            if (!GetStatus().Any())
            {
                return(null);
            }

            Repository.AddRemove();

            var command = new CommitCommand
            {
                OverrideAuthor = authorName ?? String.Empty,
                Message        = message
            };

            var id = Repository.Commit(command);

            // TODO: Figure out why is id null
            id = id ?? CurrentId;

            return(GetChangeSet(id));
        }
Пример #28
0
        private void UpdateAccountFields()
        {
            AccountFields.Clear();
            if (SelectedConnectionType == null)
            {
                return;
            }

            foreach (AccountField accountField in SelectedConnectionType.Fields)
            {
                ConnectedAccount.StorageConnectionString.Parameters.TryGetValue(accountField.Name, out string fieldValue);

                accountField.Value = fieldValue ?? string.Empty;

                if (accountField is HiddenAccountField)
                {
                    ConnectedAccount.StorageConnectionString.Parameters[accountField.Name] = accountField.Value;
                }

                PropertyChangedEventHandler eh = (sender, pcea) =>
                {
                    if (pcea.PropertyName == nameof(AccountField.Value) && sender is AccountField af)
                    {
                        //update connection string parameter
                        ConnectedAccount.StorageConnectionString.Parameters[af.Name] = af.Value;

                        IsDirty = true;
                        CommitCommand?.RaiseCanExecuteChanged();

                        Debug.WriteLine($"{ConnectedAccount.DisplayName}: {af.Name} => {af.Value}");
                    }
                };

                accountField.PropertyChanged += eh;
                _fieldToHandler[accountField] = eh;
                AccountFields.Add(accountField);
            }
        }
Пример #29
0
        public void Refresh()
        {
            if (_areaVM.IsValid)
            {
                lock (refreshLock)
                {
                    _status   = _areaVM.Area.GetStatus(_areaVM.Area.Root);
                    _elements = new List <StatusEntryVM>();

                    _tagPresets = new List <TagPresetVM>();
                    if (_areaVM.Area.Directives.TagPresets != null)
                    {
                        _tagPresets.AddRange(_areaVM.Area.Directives.TagPresets.Select(x => new TagPresetVM(x)));
                    }

                    foreach (Status.StatusEntry statusEntry in Status.Elements.OrderBy(x => x.CanonicalName))
                    {
                        if (statusEntry.Code != StatusCode.Ignored &&
                            statusEntry.Code != StatusCode.Excluded &&
                            statusEntry.Code != StatusCode.Unchanged)
                        {
                            StatusEntryVM statusEntryVM = new StatusEntryVM(statusEntry, this, _areaVM.Area);
                            if (statusEntryVM != null)
                            {
                                _elements.Add(statusEntryVM);
                                statusEntryVM.PropertyChanged += StatusVM_PropertyChanged;
                            }
                        }
                    }

                    NotifyPropertyChanged("Status");
                    NotifyPropertyChanged("Elements");
                    NotifyPropertyChanged("AllStaged");
                    NotifyPropertyChanged("TagPresets");
                    MainWindow.Instance.Dispatcher.Invoke(() => CommitCommand.RaiseCanExecuteChanged());
                }
            }
        }
Пример #30
0
        public static void HgCommit(this ICakeContext context, DirectoryPath repositoryPath, string message)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (repositoryPath == null)
            {
                throw new ArgumentNullException(nameof(repositoryPath));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            using (var repository = context.Hg(repositoryPath))
            {
                var command = new CommitCommand()
                              .WithMessage(message)
                              .WithAddRemove();

                repository.Commit(command);
            }
        }
Пример #31
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "dnu";
            app.FullName = "Microsoft .NET Development Utility";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion);

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var feedOptions = FeedOptions.Add(c);
                var optLock = c.Option("--lock",
                    "Creates dependencies file with locked property set to true. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optUnlock = c.Option("--unlock",
                    "Creates dependencies file with locked property set to false. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optParallel = c.Option("--parallel",
                    "Restores in parallel when more than one project.json is discovered.",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var command = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                    command.RestoreDirectory = argRoot.Value;
                    command.FeedOptions = feedOptions;
                    command.Lock = optLock.HasValue();
                    command.Unlock = optUnlock.HasValue();
                    command.Parallel = optParallel.HasValue();

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var success = await command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("publish", c =>
            {
                c.Description = "Publish application for deployment";

                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
                    CommandOptionType.SingleValue);
                var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
                    CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include, or \"active\" for current runtime on PATH",
                    CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                    CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                    CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                    "Name of public folder in the output, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                    CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of published files",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new PublishOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                            string.Join(";", optionRuntime.Values).
                                Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                            new string[0],
                        Native = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new PublishManager(_hostServices, options);
                    if (!manager.Publish())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = true;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");

                var feedOptions = FeedOptions.Add(c);

                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);

                    var addCmd = new AddCommand();
                    addCmd.Reports = reports;
                    addCmd.Name = argName.Value;
                    addCmd.Version = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd = new RestoreCommand(_environment);
                    restoreCmd.Reports = reports;
                    restoreCmd.FeedOptions = feedOptions;

                    restoreCmd.RestoreDirectory = argProject.Value;

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var installCmd = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return 2;
                });

                packagesCommand.Command("add", c =>
                {
                    c.Description = "Add a NuGet package to the specified packages folder";
                    var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package");
                    var argSource = c.Argument("[source]", "Path to packages folder");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async () =>
                    {
                        var options = new AddOptions
                        {
                            Reports = CreateReports(optionVerbose.HasValue(), quiet: false),
                            SourcePackages = argSource.Value,
                            NuGetPackage = argNupkg.Value
                        };
                        var command = new Packages.AddCommand(options);
                        var success = await command.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("push", c =>
                {
                    c.Description = "Incremental copy of files from local packages to remote location";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        // Implicitly commit changes before push
                        var commitOptions = new CommitOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        var success = commitCommand.Execute();
                        if (!success)
                        {
                            return 1;
                        }

                        var pushOptions = new PushOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pushCommand = new PushCommand(pushOptions);
                        success = pushCommand.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("pull", c =>
                {
                    c.Description = "Incremental copy of files from remote location to local packages";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        bool success;
                        if (Directory.Exists(argSource.Value))
                        {
                            // Implicitly commit changes before pull
                            var commitOptions = new CommitOptions
                            {
                                Reports = reports,
                                SourcePackages = argSource.Value
                            };
                            var commitCommand = new CommitCommand(commitOptions);
                            success = commitCommand.Execute();
                            if (!success)
                            {
                                return 1;
                            }
                        }

                        var pullOptions = new PullOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pullCommand = new PullCommand(pullOptions);
                        success = pullCommand.Execute();
                        return success ? 0 : 1;
                    });
                });
            });

            app.Command("list", c =>
            {
                c.Description = "Print the dependencies of a given project";
                var showAssemblies = c.Option("-a|--assemblies",
                    "Show the assembly files that are depended on by given project",
                    CommandOptionType.NoValue);
                var frameworks = c.Option("--framework <TARGET_FRAMEWORK>",
                    "Show dependencies for only the given frameworks",
                    CommandOptionType.MultipleValue);
                var runtimeFolder = c.Option("--runtime <PATH>",
                    "The folder containing all available framework assemblies",
                    CommandOptionType.SingleValue);
                var hideDependents = c.Option("--hide-dependents",
                    "Hide the immediate dependents of libraries referenced in the project",
                    CommandOptionType.NoValue);
                var resultsFilter = c.Option("--filter <PATTERN>",
                    "Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?",
                    CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject)
                    {
                        TargetFrameworks = frameworks.Values,
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                        HideDependents = hideDependents.HasValue(),
                        ResultsFilter = resultsFilter.Value()
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName));
                            return 1;
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return 2;
                        }
                    }

                    var command = new DependencyListCommand(options, _environment.RuntimeFramework);
                    return command.Execute();
                });
            });

            app.Command("commands", cmd =>
            {
                cmd.Description = "Commands related to managing application commands (add, remove)";
                cmd.HelpOption("-?|-h|--help");
                cmd.OnExecute(() =>
                {
                    cmd.ShowHelp();
                    return 2;
                });

                cmd.Command("install", c =>
                {
                    c.Description = "Installs application commands";

                    var argPackage = c.Argument("[package]", "The name of the application package");
                    var argVersion = c.Argument("[version]", "The version of the application package");

                    var optOverwrite = c.Option("-o|--overwrite", "Overwrites conflicting commands", CommandOptionType.NoValue);

                    var feedOptions = FeedOptions.Add(c);

                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async () =>
                    {
                        var command = new InstallGlobalCommand(
                                _environment,
                                string.IsNullOrEmpty(feedOptions.TargetPackagesFolder) ?
                                    AppCommandsFolderRepository.CreateDefault() :
                                    AppCommandsFolderRepository.Create(feedOptions.TargetPackagesFolder));

                        command.FeedOptions = feedOptions;
                        command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                        command.OverwriteCommands = optOverwrite.HasValue();

                        if (feedOptions.Proxy != null)
                        {
                            Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                        }

                        var success = await command.Execute(argPackage.Value, argVersion.Value);
                        return success ? 0 : 1;
                    });

                });

                cmd.Command("uninstall", c =>
                {
                    c.Description = "Uninstalls application commands";

                    var argCommand = c.Argument("[command]", "The name of the command to uninstall");

                    var optNoPurge = c.Option("--no-purge", "Do not try to remove orphaned packages", CommandOptionType.NoValue);

                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var command = new UninstallCommand(
                            _environment,
                            AppCommandsFolderRepository.CreateDefault(),
                            reports: CreateReports(optionVerbose.HasValue(), quiet: false));

                        command.NoPurge = optNoPurge.HasValue();

                        var success = command.Execute(argCommand.Value);
                        return success ? 0 : 1;
                    });
                });
            });

            app.Command("wrap", c =>
            {
                c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files";

                var argPath = c.Argument("[path]", "Path to csproj to be wrapped");
                var optConfiguration = c.Option("--configuration <CONFIGURATION>",
                    "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue);
                var optMsBuildPath = c.Option("--msbuild <PATH>",
                    @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'",
                    CommandOptionType.SingleValue);
                var optInPlace = c.Option("-i|--in-place",
                    "Generate or update project.json files in project directories of csprojs",
                    CommandOptionType.NoValue);
                var optFramework = c.Option("-f|--framework",
                    "Target framework of assembly to be wrapped",
                    CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command = new WrapCommand();
                    command.Reports = reports;
                    command.InputFilePath = argPath.Value;
                    command.Configuration = optConfiguration.Value();
                    command.MsBuildPath = optMsBuildPath.Value();
                    command.InPlace = optInPlace.HasValue();
                    command.Framework = optFramework.Value();

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            return app.Execute(args);
        }
Пример #32
0
        private void ParseCommand(string line)
        {
            if (string.IsNullOrEmpty(line))
            {
                return;
            }
            //NOTE: Parse in ascending length order!
            if (line.Substring(0, 1).Equals("#"))
            {
                return;
            }
            if (line.Length < 4)
            {
                Warn("invalid command: {0}", line);
                return;
            }

            if (line.Substring(0, 4).ToLower().Equals("quit") || line.Substring(0, 4).ToLower().Equals("exit"))
            {
                return;
            }

            var    idx = line.IndexOf(' ');
            string cmd;

            if (idx < 0)
            {
                idx = 0;
                cmd = line;
            }
            else
            {
                cmd = line.Substring(0, idx).ToLower();
            }

            var args = idx == 0 ? string.Empty : line.Substring(idx + 1).Trim();

            if (CR.abort.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new AbortCommand();
                c.Execute(context);
                StopTimer(CR.abort + " " + args);
                return;
            }
            if (CR.addalias.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new AddAliasCommand();
                c.Execute(context, args);
                StopTimer(CR.addalias + " " + args);
                return;
            }
            if (CR.addindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new AddIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.addindex + " " + args);
                return;
            }
            if (CR.close.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CloseCommand();
                c.Execute(context, args);
                StopTimer(CR.close + " " + args);
                return;
            }
            if (CR.commit.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CommitCommand();
                c.Execute(context, args);
                StopTimer(CR.commit + " " + args);
                return;
            }
            if (CR.compactcontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CompactContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.compactcontainer + " " + args);
                return;
            }
            if (CR.contextquery.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new ContextQueryCommand();
                c.Execute(context, args);
                StopTimer(CR.contextquery + " " + args);
                return;
            }
            if (CR.cquery.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CQueryCommand();
                c.Execute(context, args);
                StopTimer(CR.cquery + " " + args);
                return;
            }
            if (CR.createcontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new CreateContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.createcontainer + " " + args);
                return;
            }
            if (CR.delindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new DeleteIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.delindex + " " + args);
                return;
            }
            if (CR.echo.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                Msg(args);
                return;
            }
            if (CR.getdocuments.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new GetDocumentsCommand();
                c.Execute(context, args);
                StopTimer(CR.getdocuments + " " + args);
                return;
            }
            if (CR.getmetadata.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new GetMetadataCommand();
                c.Execute(context, args);
                StopTimer(CR.getmetadata + " " + args);
                return;
            }
            if (CR.help.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                var c = new HelpCommand();
                c.Execute(args);
                return;
            }
            if (CR.info.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new InfoCommand();
                c.Execute(context, args);
                StopTimer(CR.info + " " + args);
                return;
            }
            if (CR.listindexes.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new ListIndexesCommand();
                c.Execute(context, args);
                StopTimer(CR.listindexes + " " + args);
                return;
            }
            if (CR.lookupedgeindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new LookupEdgeIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.lookupedgeindex + " " + args);
                return;
            }
            if (CR.lookupindex.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new LookupIndexCommand();
                c.Execute(context, args);
                StopTimer(CR.lookupindex + " " + args);
                return;
            }
            if (CR.lookupstats.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new LookupStatisticsCommand();
                c.Execute(context, args);
                StopTimer(CR.lookupstats + " " + args);
                return;
            }
            if (CR.opencontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new OpenContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.opencontainer + " " + args);
                return;
            }
            if (CR.preload.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new PreloadCommand();
                c.Execute(context, args);
                StopTimer(CR.preload + " " + args);
                return;
            }
            if (CR.prepare.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new PrepareCommand();
                c.Execute(context, args);
                StopTimer(CR.prepare + " " + args);
                return;
            }
            if (CR.print.IndexOf(cmd, 0, StringComparison.Ordinal) == 0 || cmd.ToLower().Equals("printnames"))
            {
                StartTimer();
                var c = new PrintCommand();
                c.Execute(context, cmd.Equals("printnames") ? "printnames " + args : args);
                StopTimer(cmd.Equals("printnames") ? "printNames" : CR.print);
                return;
            }
            if (CR.putdocuments.Equals(cmd))
            {
                StartTimer();
                var c = new PutDocumentsCommand();
                c.Execute(context, args);
                StopTimer(CR.putdocuments + " " + args);
                return;
            }
            if (CR.putdocument.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new PutDocumentCommand();
                c.Execute(context, args);
                StopTimer(CR.putdocument + " " + args);
                return;
            }
            if (CR.query.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new QueryCommand();
                c.Execute(context, args);
                StopTimer(CR.query + " " + args);
                return;
            }
            if (CR.queryplan.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new QueryPlanCommand();
                c.Execute(context, args);
                StopTimer(CR.queryplan + " " + args);
                return;
            }
            if (CR.reindexcontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new ReindexContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.reindexcontainer + " " + args);
                return;
            }
            if (CR.removealias.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new RemoveAliasCommand();
                c.Execute(context, args);
                StopTimer(CR.removealias + " " + args);
                return;
            }
            if (CR.removecontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new RemoveContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.removecontainer + " " + args);
                return;
            }
            if (CR.removedocument.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new RemoveDocumentCommand();
                c.Execute(context, args);
                StopTimer(CR.removedocument + " " + args);
                return;
            }
            if (CR.run.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                var c = new RunCommand();
                c.Execute(context, args);
                var l2 = new List <string>(originalArgs)
                {
                    "-s", c.Script
                };
                StartTimer();
                Main(l2.ToArray());
                StopTimer(CR.run + " " + args);
                return;
            }
            if (CR.setautoindexing.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetAutoIndexingCommand();
                c.Execute(context, args);
                StopTimer(CR.setautoindexing + " " + args);
                return;
            }
            if (CR.setbaseuri.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetBaseUriCommand();
                c.Execute(context, args);
                StopTimer(CR.setbaseuri + " " + args);
                return;
            }
            if (CR.setignore.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                var c = new SetIgnoreCommand();
                c.Execute(context, args);
                ignoreErrors = c.Ignore;
                return;
            }
            if (CR.setlazy.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetLazyCommand();
                c.Execute(context, args);
                StopTimer(CR.setlazy + " " + args);
                return;
            }
            if (CR.setmetadata.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetMetadataCommand();
                c.Execute(context, args);
                StopTimer(CR.setmetadata + " " + args);
                return;
            }
            if (CR.setnamespace.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetNamespaceCommand();
                c.Execute(context, args);
                StopTimer(CR.setnamespace + " " + args);
                return;
            }
            if (CR.setprojection.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetProjectionCommand();
                c.Execute(context, args);
                StopTimer(CR.setprojection + " " + args);
                return;
            }
            if (CR.setquerytimeout.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetQueryTimeoutCommand();
                c.Execute(context, args);
                StopTimer(CR.setquerytimeout + " " + args);
                return;
            }
            if (CR.setvariable.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetVariableCommand();
                c.Execute(context, args);
                StopTimer(CR.setvariable + " " + args);
                return;
            }
            if (CR.setverbose.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new SetVerboseCommand();
                c.Execute(context, args);
                StopTimer(CR.setverbose + " " + args);
                return;
            }
            if (CR.sync.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                context.Sync();
                StopTimer(CR.sync + " " + args);
                return;
            }
            if (CR.time.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                time = true;
                ParseCommand(args);
                return;
            }
            if (CR.transaction.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new TransactionCommand();
                c.Execute(context, args);
                StopTimer(CR.transaction + " " + args);
                return;
            }
            if (CR.upgradecontainer.IndexOf(cmd, 0, StringComparison.Ordinal) == 0)
            {
                StartTimer();
                var c = new UpgradeContainerCommand();
                c.Execute(context, args);
                StopTimer(CR.upgradecontainer + " " + args);
                return;
            }

            Warn("Command not recognized: {0}", cmd);
        }
 /// <summary>
 /// Called when edit is enabled.
 /// </summary>
 private void OnEnableEdit()
 {
     Reset(false);
     CommitCommand.RaiseCanExecuteChanged();
 }
Пример #34
0
        public bool Commit(string message, string authorName = "")
        {
            if (!Repository.Status().Any())
            {
                return false;
            }

            Repository.AddRemove();

            var command = new CommitCommand
            {
                OverrideAuthor = authorName ?? String.Empty,
                Message = message
            };

            var id = Repository.Commit(command);
            return id != null;
        }
Пример #35
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.Name     = "dnu";
            app.FullName = "Microsoft .NET Development Utility";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);

            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion);

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return(2);
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot     = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var feedOptions = FeedOptions.Add(c);
                var optLock     = c.Option("--lock",
                                           "Creates dependencies file with locked property set to true. Overwrites file if it exists.",
                                           CommandOptionType.NoValue);
                var optUnlock = c.Option("--unlock",
                                         "Creates dependencies file with locked property set to false. Overwrites file if it exists.",
                                         CommandOptionType.NoValue);
                var optParallel = c.Option("--parallel",
                                           "Restores in parallel when more than one project.json is discovered.",
                                           CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async() =>
                {
                    var command              = new RestoreCommand(_environment);
                    command.Reports          = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                    command.RestoreDirectory = argRoot.Value;
                    command.FeedOptions      = feedOptions;
                    command.Lock             = optLock.HasValue();
                    command.Unlock           = optUnlock.HasValue();
                    command.Parallel         = optParallel.HasValue();

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var success = await command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("publish", c =>
            {
                c.Description = "Publish application for deployment";

                var argProject          = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut           = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
                                                   CommandOptionType.SingleValue);
                var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
                                              CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include, or \"active\" for current runtime on PATH",
                                             CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                                            CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                                             CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                                                "Name of public folder in the output, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                                                CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of published files",
                                           CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new PublishOptions
                    {
                        OutputDir              = optionOut.Value(),
                        ProjectDir             = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration          = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot    = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        NoSource   = optionNoSource.HasValue(),
                        Runtimes   = optionRuntime.HasValue() ?
                                     string.Join(";", optionRuntime.Values).
                                     Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                                     new string[0],
                        Native  = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new PublishManager(_hostServices, options);
                    if (!manager.Publish())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework     = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut           = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies  = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet         = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                                                   CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions              = new BuildOptions();
                    buildOptions.OutputDir        = optionOut.Value();
                    buildOptions.ProjectDir       = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations   = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = true;
                    buildOptions.Reports          = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                var optionFramework     = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut           = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionQuiet         = c.Option("--quiet", "Do not show output such as dependencies in use",
                                                   CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions              = new BuildOptions();
                    buildOptions.OutputDir        = optionOut.Value();
                    buildOptions.ProjectDir       = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations   = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports          = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName    = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");

                var feedOptions = FeedOptions.Add(c);

                c.HelpOption("-?|-h|--help");

                c.OnExecute(async() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);

                    var addCmd        = new AddCommand();
                    addCmd.Reports    = reports;
                    addCmd.Name       = argName.Value;
                    addCmd.Version    = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd         = new RestoreCommand(_environment);
                    restoreCmd.Reports     = reports;
                    restoreCmd.FeedOptions = feedOptions;

                    restoreCmd.RestoreDirectory = argProject.Value;

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var installCmd     = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return(2);
                });

                packagesCommand.Command("add", c =>
                {
                    c.Description = "Add a NuGet package to the specified packages folder";
                    var argNupkg  = c.Argument("[nupkg]", "Path to a NuGet package");
                    var argSource = c.Argument("[source]", "Path to packages folder");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async() =>
                    {
                        var options = new AddOptions
                        {
                            Reports        = CreateReports(optionVerbose.HasValue(), quiet: false),
                            SourcePackages = argSource.Value,
                            NuGetPackage   = argNupkg.Value
                        };
                        var command = new Packages.AddCommand(options);
                        var success = await command.Execute();
                        return(success ? 0 : 1);
                    });
                });

                packagesCommand.Command("push", c =>
                {
                    c.Description = "Incremental copy of files from local packages to remote location";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                                               "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        // Implicitly commit changes before push
                        var commitOptions = new CommitOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        var success       = commitCommand.Execute();
                        if (!success)
                        {
                            return(1);
                        }

                        var pushOptions = new PushOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pushCommand = new PushCommand(pushOptions);
                        success         = pushCommand.Execute();
                        return(success ? 0 : 1);
                    });
                });

                packagesCommand.Command("pull", c =>
                {
                    c.Description = "Incremental copy of files from remote location to local packages";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                                               "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        bool success;
                        if (Directory.Exists(argSource.Value))
                        {
                            // Implicitly commit changes before pull
                            var commitOptions = new CommitOptions
                            {
                                Reports        = reports,
                                SourcePackages = argSource.Value
                            };
                            var commitCommand = new CommitCommand(commitOptions);
                            success           = commitCommand.Execute();
                            if (!success)
                            {
                                return(1);
                            }
                        }

                        var pullOptions = new PullOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pullCommand = new PullCommand(pullOptions);
                        success         = pullCommand.Execute();
                        return(success ? 0 : 1);
                    });
                });
            });

            app.Command("list", c =>
            {
                c.Description      = "Print the dependencies of a given project";
                var showAssemblies = c.Option("-a|--assemblies",
                                              "Show the assembly files that are depended on by given project",
                                              CommandOptionType.NoValue);
                var frameworks = c.Option("--framework <TARGET_FRAMEWORK>",
                                          "Show dependencies for only the given frameworks",
                                          CommandOptionType.MultipleValue);
                var runtimeFolder = c.Option("--runtime <PATH>",
                                             "The folder containing all available framework assemblies",
                                             CommandOptionType.SingleValue);
                var hideDependents = c.Option("--hide-dependents",
                                              "Hide the immediate dependents of libraries referenced in the project",
                                              CommandOptionType.NoValue);
                var resultsFilter = c.Option("--filter <PATTERN>",
                                             "Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?",
                                             CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject)
                    {
                        TargetFrameworks = frameworks.Values,
                        ShowAssemblies   = showAssemblies.HasValue(),
                        RuntimeFolder    = runtimeFolder.Value(),
                        HideDependents   = hideDependents.HasValue(),
                        ResultsFilter    = resultsFilter.Value()
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName));
                            return(1);
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return(2);
                        }
                    }

                    var command = new DependencyListCommand(options, _environment.RuntimeFramework);
                    return(command.Execute());
                });
            });

            app.Command("commands", cmd =>
            {
                cmd.Description = "Commands related to managing application commands (add, remove)";
                cmd.HelpOption("-?|-h|--help");
                cmd.OnExecute(() =>
                {
                    cmd.ShowHelp();
                    return(2);
                });

                cmd.Command("install", c =>
                {
                    c.Description = "Installs application commands";

                    var argPackage = c.Argument("[package]", "The name of the application package");
                    var argVersion = c.Argument("[version]", "The version of the application package");

                    var optOverwrite = c.Option("-o|--overwrite", "Overwrites conflicting commands", CommandOptionType.NoValue);

                    var feedOptions = FeedOptions.Add(c);

                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async() =>
                    {
                        var command = new InstallGlobalCommand(
                            _environment,
                            string.IsNullOrEmpty(feedOptions.TargetPackagesFolder) ?
                            AppCommandsFolderRepository.CreateDefault() :
                            AppCommandsFolderRepository.Create(feedOptions.TargetPackagesFolder));

                        command.FeedOptions       = feedOptions;
                        command.Reports           = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                        command.OverwriteCommands = optOverwrite.HasValue();

                        if (feedOptions.Proxy != null)
                        {
                            Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                        }

                        var success = await command.Execute(argPackage.Value, argVersion.Value);
                        return(success ? 0 : 1);
                    });
                });

                cmd.Command("uninstall", c =>
                {
                    c.Description = "Uninstalls application commands";

                    var argCommand = c.Argument("[command]", "The name of the command to uninstall");

                    var optNoPurge = c.Option("--no-purge", "Do not try to remove orphaned packages", CommandOptionType.NoValue);

                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var command = new UninstallCommand(
                            _environment,
                            AppCommandsFolderRepository.CreateDefault(),
                            reports: CreateReports(optionVerbose.HasValue(), quiet: false));

                        command.NoPurge = optNoPurge.HasValue();

                        var success = command.Execute(argCommand.Value);
                        return(success ? 0 : 1);
                    });
                });
            });

            app.Command("wrap", c =>
            {
                c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files";

                var argPath          = c.Argument("[path]", "Path to csproj to be wrapped");
                var optConfiguration = c.Option("--configuration <CONFIGURATION>",
                                                "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue);
                var optMsBuildPath = c.Option("--msbuild <PATH>",
                                              @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'",
                                              CommandOptionType.SingleValue);
                var optInPlace = c.Option("-i|--in-place",
                                          "Generate or update project.json files in project directories of csprojs",
                                          CommandOptionType.NoValue);
                var optFramework = c.Option("-f|--framework",
                                            "Target framework of assembly to be wrapped",
                                            CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command           = new WrapCommand();
                    command.Reports       = reports;
                    command.InputFilePath = argPath.Value;
                    command.Configuration = optConfiguration.Value();
                    command.MsBuildPath   = optMsBuildPath.Value();
                    command.InPlace       = optInPlace.HasValue();
                    command.Framework     = optFramework.Value();

                    var success = command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            return(app.Execute(args));
        }
Пример #36
0
        public bool Commit(string message, string authorName = null, string emailAddress = null)
        {
            if (!Repository.Status().Any())
            {
                return false;
            }

            Repository.AddRemove();

            var overrideAuthor = string.Empty;
            if (!string.IsNullOrEmpty(authorName) &&
                !string.IsNullOrEmpty(emailAddress))
            {
                overrideAuthor = string.Format("{0} <{1}>", authorName, emailAddress);
            }

            var command = new CommitCommand
            {
                OverrideAuthor = overrideAuthor,
                Message = message
            };

            var id = Repository.Commit(command);
            return id != null;
        }
Пример #37
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                    CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                    CommandOptionType.SingleValue);
                var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                    CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                    "Ignore failed remote sources if there are local packages meeting version requirements",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var command = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    command.RestoreDirectory = argRoot.Value;
                    command.Sources = optSource.Values;
                    command.FallbackSources = optFallbackSource.Values;
                    command.NoCache = optNoCache.HasValue();
                    command.PackageFolder = optPackageFolder.Value();
                    command.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var success = await command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("bundle", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
                    CommandOptionType.SingleValue);
                var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders",
                    CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
                    CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include",
                    CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                    CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                    CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                    "Name of public folder in the bundle, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                    CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of bundled files",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new BundleOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        Overwrite = optionOverwrite.HasValue(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                            string.Join(";", optionRuntime.Values).
                                Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                            new string[0],
                        Native = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new BundleManager(_hostServices, options);
                    if (!manager.Bundle())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = true;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use",
                    CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command = new AddCommand();
                    command.Reports = reports;
                    command.Name = argName.Value;
                    command.Version = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                    CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                    CommandOptionType.SingleValue);
                var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                    CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                    "Ignore failed remote sources if there are local packages meeting version requirements",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    var addCmd = new AddCommand();
                    addCmd.Reports = reports;
                    addCmd.Name = argName.Value;
                    addCmd.Version = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd = new RestoreCommand(_environment);
                    restoreCmd.Reports = reports;

                    restoreCmd.RestoreDirectory = argProject.Value;
                    restoreCmd.Sources = optSource.Values;
                    restoreCmd.FallbackSources = optFallbackSource.Values;
                    restoreCmd.NoCache = optNoCache.HasValue();
                    restoreCmd.PackageFolder = optPackageFolder.Value();
                    restoreCmd.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var installCmd = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return 2;
                });

                packagesCommand.Command("add", c =>
                {
                    c.Description = "Add a NuGet package to the specified packages folder";
                    var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package");
                    var argSource = c.Argument("[source]", "Path to packages folder");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async () =>
                    {
                        var options = new AddOptions
                        {
                            Reports = CreateReports(optionVerbose.HasValue(), quiet: false),
                            SourcePackages = argSource.Value,
                            NuGetPackage = argNupkg.Value
                        };
                        var command = new Packages.AddCommand(options);
                        var success = await command.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("push", c =>
                {
                    c.Description = "Incremental copy of files from local packages to remote location";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        // Implicitly commit changes before push
                        var commitOptions = new CommitOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        var success = commitCommand.Execute();
                        if (!success)
                        {
                            return 1;
                        }

                        var pushOptions = new PushOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pushCommand = new PushCommand(pushOptions);
                        success = pushCommand.Execute();
                        return success ? 0 : 1;
                    });
                });

                packagesCommand.Command("pull", c =>
                {
                    c.Description = "Incremental copy of files from remote location to local packages";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                        "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        bool success;
                        if (Directory.Exists(argSource.Value))
                        {
                            // Implicitly commit changes before pull
                            var commitOptions = new CommitOptions
                            {
                                Reports = reports,
                                SourcePackages = argSource.Value
                            };
                            var commitCommand = new CommitCommand(commitOptions);
                            success = commitCommand.Execute();
                            if (!success)
                            {
                                return 1;
                            }
                        }

                        var pullOptions = new PullOptions
                        {
                            Reports = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pullCommand = new PullCommand(pullOptions);
                        success = pullCommand.Execute();
                        return success ? 0 : 1;
                    });
                });
            });

            app.Command("list", c =>
            {
                c.Description = "Print the dependencies of a given project.";
                var showAssemblies = c.Option("-a|--assemblies",
                    "Show the assembly files that are depended on by given project.",
                    CommandOptionType.NoValue);
                var framework = c.Option("--framework",
                    "Show dependencies for only the given framework.",
                    CommandOptionType.SingleValue);
                var runtimeFolder = c.Option("--runtime",
                    "The folder containing all available framework assemblies.",
                    CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "The path to project. If omitted, the command will use the project in the current directory.");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject, framework)
                    {
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("A project could not be found in {0}.", options.Path).Red());
                            return 1;
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return 2;
                        }
                    }

                    var command = new DependencyListCommand(options);
                    return command.Execute();
                });
            });

            // "kpm wrap" invokes MSBuild, which is not available on *nix
            if (!PlatformHelper.IsMono)
            {
                app.Command("wrap", c =>
                {
                    c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files";

                    var argPath = c.Argument("[path]", "Path to csproj to be wrapped");
                    var optConfiguration = c.Option("--configuration <CONFIGURATION>",
                        "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue);
                    var optMsBuildPath = c.Option("--msbuild <PATH>",
                        @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'",
                        CommandOptionType.SingleValue);
                    var optInPlace = c.Option("-i|--in-place",
                        "Generate or update project.json files in project directories of csprojs",
                        CommandOptionType.NoValue);
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        var command = new WrapCommand();
                        command.Reports = reports;
                        command.CsProjectPath = argPath.Value;
                        command.Configuration = optConfiguration.Value();
                        command.MsBuildPath = optMsBuildPath.Value();
                        command.InPlace = optInPlace.HasValue();

                        var success = command.ExecuteCommand();

                        return success ? 0 : 1;
                    });
                });
            }

            return app.Execute(args);
        }