/// <summary>
        /// </summary>
        protected override void ProcessRecord()
        {
            var r = new RespositorySettings();

            var listOfRepositories = r.Read(_name);

            /// Print out repos
            foreach (var repo in listOfRepositories)
            {
                WriteObject(repo);
            }
        }
Exemplo n.º 2
0
    private IEnumerable <CompletionResult> CompleteRepositoryName(string wordToComplete)
    {
        List <CompletionResult> res = new List <CompletionResult>();

        RespositorySettings      repositorySettings = new RespositorySettings();
        IReadOnlyList <PSObject> listOfRepositories = repositorySettings.Read(null);

        foreach (PSObject repo in listOfRepositories)
        {
            string repoName = repo.Properties["Name"].Value.ToString();
            if (repoName.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))
            {
                res.Add(new CompletionResult(repoName));
            }
        }

        return(res);
    }
Exemplo n.º 3
0
        /// <summary>
        /// </summary>
        protected override void ProcessRecord()
        {
            source            = new CancellationTokenSource();
            cancellationToken = source.Token;

            var r = new RespositorySettings();
            var listOfRepositories = r.Read(_repository);


            //if (string.Equals(listOfRepositories[0].Properties["Trusted"].Value.ToString(), "false", StringComparison.InvariantCultureIgnoreCase) && !_trustRepository && !_force)
            //{
            // throw error saying repository is not trusted
            // throw new System.ArgumentException(string.Format(CultureInfo.InvariantCulture, "This repository is not trusted"));  /// we should prompt for user input to accept

            /*
             * Untrusted repository
             * You are installing the modules from an untrusted repository.  If you trust this repository, change its InstallationPolicy value by running the Set-PSResourceRepository cmdlet.
             * Are you sure you want to install the modules from '<repo name >'?
             * [Y]  Yes  [A]  Yes to ALl   [N]  No  [L]  No to all  [s]  suspendd [?] Help  (default is "N"):
             */
            // }


            pkgsLeftToInstall = _name.ToList();
            foreach (var repoName in listOfRepositories)
            {
                // if it can't find the pkg in one repository, it'll look in the next one in the list
                // returns any pkgs that weren't found
                var returnedPkgsNotInstalled = InstallHelper(repoName.Properties["Url"].Value.ToString(), pkgsLeftToInstall, cancellationToken);
                if (!pkgsLeftToInstall.Any())
                {
                    return;
                }
                pkgsLeftToInstall = returnedPkgsNotInstalled;
            }
        }
Exemplo n.º 4
0
        protected override void ProcessRecord()
        {
            _path = string.IsNullOrEmpty(_path) ? _literalPath : _path;

            // Get the .psd1 file or .ps1 file
            // Returns the name of the file or the name of the directory, depending on path
            var    pkgFileOrDir = new DirectoryInfo(_path);
            string moduleManifestOrScriptPath;

            if (isScript)
            {
                moduleManifestOrScriptPath = pkgFileOrDir.FullName;
                pkgName = pkgFileOrDir.Name.Remove(pkgFileOrDir.Name.Length - 4);
            }
            else
            {
                moduleManifestOrScriptPath = System.IO.Path.Combine(_path, pkgFileOrDir.Name + ".psd1");
                // Validate that there's a module manifest
                if (!File.Exists(moduleManifestOrScriptPath))
                {
                    var message = String.Format("No file with a .psd1 extension was found in {0}.  Please specify a path to a valid modulemanifest.", moduleManifestOrScriptPath);
                    var ex      = new ArgumentException(message);
                    var moduleManifestNotFound = new ErrorRecord(ex, "moduleManifestNotFound", ErrorCategory.ObjectNotFound, null);

                    this.ThrowTerminatingError(moduleManifestNotFound);
                }
                pkgName = pkgFileOrDir.Name;
            }

            FileInfo moduleFileInfo;

            moduleFileInfo = new FileInfo(moduleManifestOrScriptPath);
            // if there's no specified destination path to publish the nupkg, we'll just create a temp folder and delete it later
            string outputDir = !string.IsNullOrEmpty(_destinationPath) ? _destinationPath : System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());

            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }

            // if user does not specify that they want to use a nuspec they've created, we'll create a nuspec
            var dependencies = new Hashtable();

            if (string.IsNullOrEmpty(_nuspec))
            {
                _nuspec = createNuspec(outputDir, moduleFileInfo);
            }
            else
            {
                // Read the nuspec passed in to pull out the dependency information
                XDocument doc = XDocument.Load(_nuspec);

                // ex: <version>2.2.1</version>
                var versionNode = doc.Descendants("version");
                NuGetVersion.TryParse(versionNode.FirstOrDefault().Value, out NuGetVersion version);

                if (version == null)
                {
                    var message         = "Version is not specified in the .nuspec provided. Please provide a valid version in the .nuspec.";
                    var ex              = new ArgumentException(message);
                    var versionNotFound = new ErrorRecord(ex, "versionNotFound", ErrorCategory.NotSpecified, null);

                    this.ThrowTerminatingError(versionNotFound);
                }

                // ex: <dependency id="Carbon" version="2.9.2" />
                var dependencyNode = doc.Descendants("dependency");
                foreach (var dep in dependencyNode)
                {
                    dependencies.Add(dep.Attribute("id"), dep.Attribute("version"));
                }
            }

            // find repository
            var r             = new RespositorySettings();
            var repositoryUrl = r.Read(new[] { _repository });

            if (!repositoryUrl.Any())
            {
                var message            = String.Format("The resource repository '{0}' is not a registered. Please run 'Register-PSResourceRepository' in order to publish to this repository.", _repository);
                var ex                 = new ArgumentException(message);
                var repositoryNotFound = new ErrorRecord(ex, "repositoryNotFound", ErrorCategory.ObjectNotFound, null);

                this.ThrowTerminatingError(repositoryNotFound);
            }

            if (!_skipDependenciesCheck)
            {
                // Check to see that all dependencies are in the repository
                var findHelper = new FindHelper();

                foreach (var dependency in dependencies.Keys)
                {
                    // Need to make individual calls since we're look for exact version numbers or ranges.
                    var depName    = new[] { (string)dependency };
                    var depVersion = (string)dependencies[dependency];
                    var type       = new[] { "module", "script" };
                    var repository = new[] { _repository };

                    // Search for and return the dependency if it's in the repository.
                    var dependencyFound = findHelper.beginFindHelper(depName, type, depVersion, true, null, null, repository, _credential, false, false);

                    if (!dependencyFound.Any())
                    {
                        var message            = String.Format("Dependency {0} was not found in repository {1}.  Make sure the dependency is published to the repository before publishing this module.", depName, _repository);
                        var ex                 = new ArgumentException(message); // System.ArgumentException vs PSArgumentException
                        var dependencyNotFound = new ErrorRecord(ex, "DependencyNotFound", ErrorCategory.ObjectNotFound, null);

                        this.ThrowTerminatingError(dependencyNotFound);
                    }
                }
            }

            if (isScript)
            {
                File.Copy(_path, System.IO.Path.Combine(outputDir, pkgName + ".ps1"), true);
            }
            else
            {
                // Create subdirectory structure in temp folder
                foreach (string dir in System.IO.Directory.GetDirectories(_path, "*", System.IO.SearchOption.AllDirectories))
                {
                    var dirName = dir.Substring(_path.Length).Trim(PathSeparators);
                    System.IO.Directory.CreateDirectory(System.IO.Path.Combine(outputDir, dirName));
                }
                // Copy files over to temp folder
                foreach (string fileNamePath in System.IO.Directory.GetFiles(_path, "*", System.IO.SearchOption.AllDirectories))
                {
                    var fileName = fileNamePath.Substring(_path.Length).Trim(PathSeparators);
                    System.IO.File.Copy(fileNamePath, System.IO.Path.Combine(outputDir, fileName));
                }
            }

            var outputDirectory = System.IO.Path.Combine(outputDir, "nupkg");
            // Pack the module or script into a nupkg given a nuspec.
            var builder = new PackageBuilder();
            var runner  = new PackCommandRunner(
                new PackArgs
            {
                CurrentDirectory = outputDir,
                OutputDirectory  = outputDirectory,
                Path             = _nuspec,
                Exclude          = _exclude,
                Symbols          = false,
                Logger           = NullLogger.Instance
            },
                MSBuildProjectFactory.ProjectCreator,
                builder);

            runner.BuildPackage();


            // Push the nupkg to the appropriate repository
            // Pkg version is parsed from .ps1 file or .psd1 file
            var fullNupkgPath = System.IO.Path.Combine(outputDirectory, pkgName + "." + pkgVersion.ToNormalizedString() + ".nupkg");

            var repoURL         = repositoryUrl.First().Properties["Url"].Value.ToString();
            var publishLocation = repoURL.EndsWith("/v2", StringComparison.OrdinalIgnoreCase) ? repoURL + "/package" : repoURL;

            var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null);

            NuGet.Common.ILogger log = new NuGetLogger();
            PushRunner.Run(
                Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null),
                new PackageSourceProvider(settings),
                fullNupkgPath,
                publishLocation,
                _APIKey, // api key
                null,    // symbols source
                null,    // symbols api key
                0,       // timeout
                false,   // disable buffering
                false,   // no symbols
                         // Skip duplicate: if a package and version already exists, skip it and continue with the next package in the push, if any.
                false,   // no skip duplicate
                false,   // enable server endpoint
                log).GetAwaiter().GetResult();
        }
Exemplo n.º 5
0
        /// <summary>
        /// </summary>
        protected override void ProcessRecord()
        {
            source            = new CancellationTokenSource();
            cancellationToken = source.Token;


            var id = WindowsIdentity.GetCurrent();
            var consoleIsElevated = (id.Owner != id.User);



            // TODO:  Test this!
            // if not core CLR
            var isWindowsPS = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory().ToLower().Contains("windows") ? true : false;

            if (isWindowsPS)
            {
                programFilesPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "WindowsPowerShell");
                /// TODO:  Come back to this
                var userENVpath = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Documents");


                myDocumentsPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "WindowsPowerShell");
            }
            else
            {
                programFilesPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "PowerShell");
                myDocumentsPath  = Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "PowerShell");
            }


            psModulesPathAllDirs = (Directory.GetDirectories(psModulesPath)).ToList();
            psScriptsPathAllDirs = (Directory.GetDirectories(psScriptsPath)).ToList();

            var r = new RespositorySettings();
            var listOfRepositories = r.Read(_repository);


            //if (string.Equals(listOfRepositories[0].Properties["Trusted"].Value.ToString(), "false", StringComparison.InvariantCultureIgnoreCase) && !_trustRepository && !_force)
            //{
            // throw error saying repository is not trusted
            // throw new System.ArgumentException(string.Format(CultureInfo.InvariantCulture, "This repository is not trusted"));  /// we should prompt for user input to accept

            /*
             * Untrusted repository
             * You are installing the modules from an untrusted repository.  If you trust this repository, change its InstallationPolicy value by running the Set-PSResourceRepository cmdlet.
             * Are you sure you want to install the modules from '<repo name >'?
             * [Y]  Yes  [A]  Yes to ALl   [N]  No  [L]  No to all  [s]  suspendd [?] Help  (default is "N"):
             */

            //}



            pkgsLeftToInstall = _name.ToList();
            foreach (var repoName in listOfRepositories)
            {
                // if it can't find the pkg in one repository, it'll look in the next one in the list
                // returns any pkgs that weren't found
                var returnedPkgsNotInstalled = InstallHelper(repoName.Properties["Url"].Value.ToString(), pkgsLeftToInstall, cancellationToken);
                if (!pkgsLeftToInstall.Any())
                {
                    return;
                }
                pkgsLeftToInstall = returnedPkgsNotInstalled;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// </summary>
        protected override void ProcessRecord()
        {
            source            = new CancellationTokenSource();
            cancellationToken = source.Token;


            var id = WindowsIdentity.GetCurrent();
            var consoleIsElevated = (id.Owner != id.User);



            // TODO:  Test this!
            // if not core CLR
            var isWindowsPS = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory().ToLower().Contains("windows") ? true : false;

            if (isWindowsPS)
            {
                programFilesPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "WindowsPowerShell");
                /// TODO:  Come back to this
                var userENVpath = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Documents");


                myDocumentsPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "WindowsPowerShell");
            }
            else
            {
                programFilesPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "PowerShell");
                myDocumentsPath  = Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "PowerShell");
            }



            // if Scope is AllUsers and there is no console elevation
            if (!string.IsNullOrEmpty(_scope) && _scope.Equals("AllUsers") && !consoleIsElevated)
            {
                // throw an error when Install-PSResource is used as a non-admin user and '-Scope AllUsers'
                throw new System.ArgumentException(string.Format(CultureInfo.InvariantCulture, "Install-PSResource requires admin privilege for AllUsers scope."));
            }

            // if no scope is specified (whether or not the console is elevated) default installation will be to CurrentUser
            // If running under admin on Windows with PowerShell less than PS6, default will be AllUsers
            if (string.IsNullOrEmpty(_scope))
            {
                _scope = "CurrentUser";

                //If Windows and elevated default scope will be all users
                // If non-Windows or non-elevated default scope will be current user


                // * TODO:  TEST Come back here! Add is Elevated
                // if (!Platform.IsCoreCLR && consoleIsElevated)
                if (isWindowsPS)
                {
                    _scope = "AllUsers";
                }
            }
            // if scope is Current user & (no elevation or elevation)
            // install to current user path



            psPath        = string.Equals(_scope, "AllUsers") ? programFilesPath : myDocumentsPath;
            psModulesPath = Path.Combine(psPath, "Modules");
            psScriptsPath = Path.Combine(psPath, "Scripts");


            psModulesPathAllDirs = (Directory.GetDirectories(psModulesPath)).ToList();
            psScriptsPathAllDirs = (Directory.GetDirectories(psScriptsPath)).ToList();

            var r = new RespositorySettings();
            var listOfRepositories = r.Read(_repository);


            //if (string.Equals(listOfRepositories[0].Properties["Trusted"].Value.ToString(), "false", StringComparison.InvariantCultureIgnoreCase) && !_trustRepository && !_force)
            //{
            // throw error saying repository is not trusted
            // throw new System.ArgumentException(string.Format(CultureInfo.InvariantCulture, "This repository is not trusted"));  /// we should prompt for user input to accept

            /*
             * Untrusted repository
             * You are installing the modules from an untrusted repository.  If you trust this repository, change its InstallationPolicy value by running the Set-PSResourceRepository cmdlet.
             * Are you sure you want to install the modules from '<repo name >'?
             * [Y]  Yes  [A]  Yes to ALl   [N]  No  [L]  No to all  [s]  suspendd [?] Help  (default is "N"):
             */

            //}



            pkgsLeftToInstall = _name.ToList();
            foreach (var repoName in listOfRepositories)
            {
                // if it can't find the pkg in one repository, it'll look in the next one in the list
                // returns any pkgs that weren't found
                var returnedPkgsNotInstalled = InstallHelper(repoName.Properties["Url"].Value.ToString(), pkgsLeftToInstall, cancellationToken);
                if (!pkgsLeftToInstall.Any())
                {
                    return;
                }
                pkgsLeftToInstall = returnedPkgsNotInstalled;
            }
        }