2015-11-16 11:21:57 -08:00
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
2015-10-13 14:31:29 -07:00
using System ;
using System.Collections.Generic ;
using System.IO ;
2015-10-15 15:09:37 -07:00
using Microsoft.Extensions.JsonParser.Sources ;
2015-10-13 14:31:29 -07:00
2015-11-27 16:19:54 -08:00
namespace Microsoft.DotNet.ProjectModel
2015-10-13 14:31:29 -07:00
{
public class GlobalSettings
{
2015-10-15 15:09:37 -07:00
public const string FileName = "global.json" ;
2015-10-13 14:31:29 -07:00
public IList < string > ProjectSearchPaths { get ; private set ; }
public string PackagesPath { get ; private set ; }
public string FilePath { get ; private set ; }
public string DirectoryPath
{
get
{
return Path . GetFullPath ( Path . GetDirectoryName ( FilePath ) ) ;
}
}
public static bool TryGetGlobalSettings ( string path , out GlobalSettings globalSettings )
{
globalSettings = null ;
string globalJsonPath = null ;
2015-10-15 15:09:37 -07:00
if ( Path . GetFileName ( path ) = = FileName )
2015-10-13 14:31:29 -07:00
{
globalJsonPath = path ;
path = Path . GetDirectoryName ( path ) ;
}
else if ( ! HasGlobalFile ( path ) )
{
return false ;
}
else
{
2015-10-15 15:09:37 -07:00
globalJsonPath = Path . Combine ( path , FileName ) ;
2015-10-13 14:31:29 -07:00
}
globalSettings = new GlobalSettings ( ) ;
try
{
using ( var fs = File . OpenRead ( globalJsonPath ) )
{
var reader = new StreamReader ( fs ) ;
2015-10-15 15:09:37 -07:00
var jobject = JsonDeserializer . Deserialize ( reader ) as JsonObject ;
2015-10-13 14:31:29 -07:00
if ( jobject = = null )
{
throw new InvalidOperationException ( "The JSON file can't be deserialized to a JSON object." ) ;
}
var projectSearchPaths = jobject . ValueAsStringArray ( "projects" ) ? ?
jobject . ValueAsStringArray ( "sources" ) ? ?
new string [ ] { } ;
globalSettings . ProjectSearchPaths = new List < string > ( projectSearchPaths ) ;
2015-10-15 15:09:37 -07:00
globalSettings . PackagesPath = jobject . ValueAsString ( "packages" ) ;
2015-10-13 14:31:29 -07:00
globalSettings . FilePath = globalJsonPath ;
}
}
catch ( Exception ex )
{
throw FileFormatException . Create ( ex , globalJsonPath ) ;
}
return true ;
}
public static bool HasGlobalFile ( string path )
{
2015-10-15 15:09:37 -07:00
string projectPath = Path . Combine ( path , FileName ) ;
2015-10-13 14:31:29 -07:00
return File . Exists ( projectPath ) ;
}
}
}