Skip to content

Commit 3306990

Browse files
committed
Improved dotnet script init with logging and binary path patching
1 parent 7ff508b commit 3306990

File tree

5 files changed

+130
-40
lines changed

5 files changed

+130
-40
lines changed

src/Dotnet.Script.Core/Scaffolder.cs

Lines changed: 81 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,78 +2,124 @@
22
using System.IO;
33
using System.Linq;
44
using System.Reflection;
5+
using System.Text.RegularExpressions;
56
using Dotnet.Script.Core.Templates;
67
using Dotnet.Script.DependencyModel.Environment;
8+
using Dotnet.Script.DependencyModel.ProjectSystem;
79
using Newtonsoft.Json.Linq;
810

911
namespace Dotnet.Script.Core
1012
{
1113
public class Scaffolder
1214
{
1315
private ScriptEnvironment _scriptEnvironment;
16+
private readonly ScriptLogger _logger;
17+
private const string DefaultScriptFileName = "main.csx";
1418

15-
public Scaffolder()
19+
public Scaffolder(ScriptLogger logger)
1620
{
1721
_scriptEnvironment = ScriptEnvironment.Default;
22+
_logger = logger;
1823
}
1924

20-
public void InitializerFolder(string fileName)
25+
public void InitializerFolder(string fileName, string currentWorkingDirectory)
26+
{
27+
CreateLaunchConfiguration(currentWorkingDirectory);
28+
CreateOmniSharpConfigurationFile(currentWorkingDirectory);
29+
CreateScriptFile(fileName, currentWorkingDirectory);
30+
}
31+
32+
public void CreateNewScriptFile(string fileName, string currentDirectory)
2133
{
22-
string currentDirectory = Directory.GetCurrentDirectory();
23-
string vsCodeDirectory = Path.Combine(currentDirectory, ".vscode");
24-
if (!Directory.Exists(vsCodeDirectory))
34+
_logger.Log($"Creating '{fileName}'");
35+
var pathToScriptFile = Path.Combine(currentDirectory, fileName);
36+
if (!File.Exists(pathToScriptFile))
2537
{
26-
Directory.CreateDirectory(vsCodeDirectory);
38+
var scriptFileTemplate = TemplateLoader.ReadTemplate("helloworld.csx.template");
39+
FileUtils.WriteFile(pathToScriptFile, scriptFileTemplate);
40+
_logger.Log($"...'{pathToScriptFile}' [Created]");
41+
}
42+
else
43+
{
44+
_logger.Log($"...'{pathToScriptFile}' already exists [Skipping]");
2745
}
46+
}
2847

29-
string pathToLaunchFile = Path.Combine(vsCodeDirectory, "launch.json");
30-
if (!File.Exists(pathToLaunchFile))
48+
private void CreateScriptFile(string fileName, string currentWorkingDirectory)
49+
{
50+
if (string.IsNullOrWhiteSpace(fileName))
3151
{
32-
string installLocation = _scriptEnvironment.InstallLocation;
33-
string dotnetScriptPath = Path.Combine(installLocation, "dotnet-script.dll").Replace(@"\", "/");
34-
35-
string lauchFileTemplate = TemplateLoader.ReadTemplate("launch.json.template");
52+
CreateDefaultScriptFile(currentWorkingDirectory);
53+
}
54+
else
55+
{
56+
CreateNewScriptFile(fileName,currentWorkingDirectory);
57+
}
58+
}
3659

37-
string launchFileContent = lauchFileTemplate.Replace("PATH_TO_DOTNET-SCRIPT", dotnetScriptPath);
38-
WriteFile(pathToLaunchFile, launchFileContent);
60+
private void CreateDefaultScriptFile(string currentWorkingDirectory)
61+
{
62+
_logger.Log($"Creating default script file '{DefaultScriptFileName}'");
63+
if (Directory.GetFiles(currentWorkingDirectory, "*.csx").Any())
64+
{
65+
_logger.Log("...Folder already contains one or more script files [Skipping]");
66+
}
67+
else
68+
{
69+
CreateNewScriptFile(DefaultScriptFileName, currentWorkingDirectory);
3970
}
40-
41-
string pathToOmniSharpJson = Path.Combine(currentDirectory, "omnisharp.json");
71+
}
72+
73+
private void CreateOmniSharpConfigurationFile(string currentWorkingDirectory)
74+
{
75+
_logger.Log("Creating OmniSharp configuration file");
76+
string pathToOmniSharpJson = Path.Combine(currentWorkingDirectory, "omnisharp.json");
4277
if (!File.Exists(pathToOmniSharpJson))
4378
{
4479
var omniSharpFileTemplate = TemplateLoader.ReadTemplate("omnisharp.json.template");
4580
JObject settings = JObject.Parse(omniSharpFileTemplate);
4681
settings["script"]["defaultTargetFramework"] = _scriptEnvironment.TargetFramework;
47-
WriteFile(pathToOmniSharpJson, settings.ToString());
82+
FileUtils.WriteFile(pathToOmniSharpJson, settings.ToString());
83+
_logger.Log($"...'{pathToOmniSharpJson}' [Created]");
4884
}
49-
50-
if (Directory.GetFiles(currentDirectory, "*.csx").Any()
51-
&& string.IsNullOrWhiteSpace(fileName))
85+
else
5286
{
53-
return;
87+
_logger.Log($"...'{pathToOmniSharpJson} already exists' [Skipping]");
5488
}
55-
56-
CreateNewScriptFile(fileName ?? "main.csx");
5789
}
5890

59-
public void CreateNewScriptFile(string file)
91+
private void CreateLaunchConfiguration(string currentWorkingDirectory)
6092
{
61-
string currentDirectory = Directory.GetCurrentDirectory();
62-
var pathToScriptFile = Path.Combine(currentDirectory, file);
63-
if (!File.Exists(pathToScriptFile))
93+
string vsCodeDirectory = Path.Combine(currentWorkingDirectory, ".vscode");
94+
if (!Directory.Exists(vsCodeDirectory))
6495
{
65-
var scriptFileTemplate = TemplateLoader.ReadTemplate("helloworld.csx.template");
66-
WriteFile(pathToScriptFile, scriptFileTemplate);
96+
Directory.CreateDirectory(vsCodeDirectory);
6797
}
68-
}
6998

70-
private void WriteFile(string path, string content)
71-
{
72-
using (var fileStream = new FileStream(path, FileMode.Create))
99+
_logger.Log("Creating VS Code launch configuration file");
100+
string pathToLaunchFile = Path.Combine(vsCodeDirectory, "launch.json");
101+
string installLocation = _scriptEnvironment.InstallLocation;
102+
string dotnetScriptPath = Path.Combine(installLocation, "dotnet-script.dll").Replace(@"\", "/");
103+
if (!File.Exists(pathToLaunchFile))
104+
{
105+
string lauchFileTemplate = TemplateLoader.ReadTemplate("launch.json.template");
106+
string launchFileContent = lauchFileTemplate.Replace("PATH_TO_DOTNET-SCRIPT", dotnetScriptPath);
107+
FileUtils.WriteFile(pathToLaunchFile, launchFileContent);
108+
_logger.Log($"...'{pathToLaunchFile}' [Created]");
109+
}
110+
else
73111
{
74-
using (var streamWriter = new StreamWriter(fileStream))
112+
_logger.Log($"...'{pathToLaunchFile}' already exists' [Skipping]");
113+
var launchFileContent = FileUtils.ReadFile(pathToLaunchFile);
114+
string pattern = @"^(\s*"")(.*dotnet-script.dll)("").*$";
115+
if (Regex.IsMatch(launchFileContent, pattern, RegexOptions.Multiline))
75116
{
76-
streamWriter.Write(content);
117+
var newLaunchFileContent = Regex.Replace(launchFileContent, pattern, $"$1{dotnetScriptPath}$3", RegexOptions.Multiline);
118+
if (launchFileContent != newLaunchFileContent)
119+
{
120+
_logger.Log($"...Fixed path to dotnet-script: '{dotnetScriptPath}' [Updated]");
121+
FileUtils.WriteFile(pathToLaunchFile, newLaunchFileContent);
122+
}
77123
}
78124
}
79125
}

src/Dotnet.Script.DependencyModel/ProjectSystem/FileUtils.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@ public static string ReadFile(string path)
1919
}
2020
}
2121

22+
public static void WriteFile(string path, string content)
23+
{
24+
using (var fileStream = new FileStream(path, FileMode.Create))
25+
{
26+
using (var streamWriter = new StreamWriter(fileStream))
27+
{
28+
streamWriter.Write(content);
29+
}
30+
}
31+
}
32+
2233
public static string CreateTempFolder(string targetDirectory)
2334
{
2435
if (!Path.IsPathRooted(targetDirectory))

src/Dotnet.Script.Tests/FileUtils.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ namespace Dotnet.Script.Tests
55
{
66
public class FileUtils
77
{
8+
public static void WriteFile(string path, string content)
9+
{
10+
using (var fileStream = new FileStream(path, FileMode.Create))
11+
{
12+
using (var streamWriter = new StreamWriter(fileStream))
13+
{
14+
streamWriter.Write(content);
15+
}
16+
}
17+
}
18+
819
public static void RemoveDirectory(string path)
920
{
1021
if (!Directory.Exists(path))

src/Dotnet.Script.Tests/ScaffoldingTests.cs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
using System.IO;
22
using Xunit;
3-
using Newtonsoft.Json.Converters;
43
using Newtonsoft.Json;
54
using Newtonsoft.Json.Linq;
65
using Dotnet.Script.DependencyModel.Environment;
76

7+
88
namespace Dotnet.Script.Tests
99
{
1010
public class ScaffoldingTests
@@ -86,6 +86,26 @@ public void ShouldNotCreateDefaultFileForFolderWithExistingScriptFiles()
8686
}
8787
}
8888

89+
[Fact]
90+
public void ShouldUpdatePathToDotnetScript()
91+
{
92+
using (var scriptFolder = new DisposableFolder())
93+
{
94+
Execute("init", scriptFolder.Path);
95+
var pathToLaunchConfiguration = Path.Combine(scriptFolder.Path, ".vscode/launch.json");
96+
var config = JObject.Parse(File.ReadAllText(pathToLaunchConfiguration));
97+
98+
config.SelectToken("configurations[0].args[1]").Replace("InvalidPath/dotnet-script.dll,");
99+
100+
FileUtils.WriteFile(pathToLaunchConfiguration, config.ToString());
101+
102+
var result = Execute("init", scriptFolder.Path);
103+
104+
config = JObject.Parse(File.ReadAllText(pathToLaunchConfiguration));
105+
Assert.NotEqual("InvalidPath/dotnet-script.dll", config.SelectToken("configurations[0].args[1]").Value<string>());
106+
}
107+
}
108+
89109
/// <summary>
90110
/// Use this if you need to debug.
91111
/// </summary>

src/Dotnet.Script/Program.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,11 @@ private static int Wain(string[] args)
9797
{
9898
c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script.";
9999
var fileName = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'");
100+
var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue);
100101
c.OnExecute(() =>
101102
{
102-
var scaffolder = new Scaffolder();
103-
scaffolder.InitializerFolder(fileName.Value);
103+
var scaffolder = new Scaffolder(new ScriptLogger(ScriptConsole.Default.Error, debugMode.HasValue()));
104+
scaffolder.InitializerFolder(fileName.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
104105
return 0;
105106
});
106107
});
@@ -109,15 +110,16 @@ private static int Wain(string[] args)
109110
{
110111
c.Description = "Creates a new script file";
111112
var fileNameArgument = c.Argument("filename", "The script file name");
113+
var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue);
112114
c.OnExecute(() =>
113115
{
114-
var scaffolder = new Scaffolder();
116+
var scaffolder = new Scaffolder(new ScriptLogger(ScriptConsole.Default.Error, debugMode.HasValue()));
115117
if (fileNameArgument.Value == null)
116118
{
117119
c.ShowHelp();
118120
return 0;
119121
}
120-
scaffolder.CreateNewScriptFile(fileNameArgument.Value);
122+
scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
121123
return 0;
122124
});
123125
});

0 commit comments

Comments
 (0)