import cryptoRandomString from 'crypto-random-string' ; import findUp from 'find-up' ; import upath from 'upath' ; import { XmlDocument } from 'xmldoc' ; import * as datasourceNuget from '../../datasource/nuget' ; import { logger } from '../../logger' ; import { readFile } from '../../util/fs' ; import { regEx } from '../../util/regex' ; import type { Registry } from './types' ; async function readFileAsXmlDocument ( file ) { try { return new XmlDocument ( await readFile ( file , 'utf8' ) ) ; } catch ( err ) { logger . debug ( { err } , `failed to parse '${ file }' as XML document` ) ; return undefined ; } } export function getRandomString ( ) { return cryptoRandomString ( { length : 16 } ) ; } export function getDefaultRegistries ( ) { return datasourceNuget . defaultRegistryUrls . map ( ( registryUrl ) => ( { url : registryUrl , } as Registry ) ) ; } export async function getConfiguredRegistries ( packageFile , localDir ) { const nuGetConfigFileNames = [ 'nuget.config' , 'NuGet.config' , 'NuGet.Config' ] ; const normalizedLocalDir = upath . normalizeSafe ( localDir ) ; const nuGetConfigPath = await findUp ( nuGetConfigFileNames , { cwd : upath . dirname ( upath . join ( normalizedLocalDir , packageFile ) ) , type : 'file' , } ) ; if ( ! nuGetConfigPath || upath . normalizeSafe ( nuGetConfigPath ) . startsWith ( normalizedLocalDir ) !== true ) { return undefined ; } logger . debug ( { nuGetConfigPath } , 'found NuGet.config' ) ; const nuGetConfig = await readFileAsXmlDocument ( nuGetConfigPath ) ; if ( ! nuGetConfig ) { return undefined ; } const packageSources = nuGetConfig . childNamed ( 'packageSources' ) ; if ( ! packageSources ) { return undefined ; } const registries = getDefaultRegistries ( ) ; for ( const child of packageSources . children ) { if ( child . type === 'element' ) { if ( child . name === 'clear' ) { logger . debug ( `clearing registry URLs` ) ; registries . length = 0 ; } else if ( child . name === 'add' ) { const isHttpUrl = regEx ( /^https?:\/\//i ) . test ( child . attr . value ) ; if ( isHttpUrl ) { let registryUrl = child . attr . value ; if ( child . attr . protocolVersion ) { registryUrl += `#protocolVersion=${ child . attr . protocolVersion }` ; } logger . debug ( { registryUrl } , 'adding registry URL' ) ; registries . push ( { name : child . attr . key , url : registryUrl , } ) ; } else { logger . debug ( { registryUrl : child . attr . value } , 'ignoring local registry URL' ) ; } } } } return registries ; }