Skip to content

Commit

Permalink
Save and restore files
Browse files Browse the repository at this point in the history
  • Loading branch information
Derroylo committed Dec 3, 2023
1 parent 1bd1567 commit f861960
Show file tree
Hide file tree
Showing 4 changed files with 196 additions and 5 deletions.
133 changes: 133 additions & 0 deletions commands/environment/AddEnvCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
using System.Linq;
using System.Text.RegularExpressions;
using System;
using System.IO;
using System.Text;
using Gitpod.Tool.Helper;

namespace Gitpod.Tool.Commands.Environment
{
Expand All @@ -28,6 +31,8 @@ public override int Execute(CommandContext context, Settings settings)

if (envType == "Variable") {
AddVariable();
} else if (envType == "File") {
AddFile();
}

return 0;
Expand All @@ -36,6 +41,134 @@ public override int Execute(CommandContext context, Settings settings)
[GeneratedRegex(@"^([a-z0-9-_]+)$")]
private static partial Regex EnvNameMatchRegex();

private void AddFile()
{
bool finished = false;

do {
var envFileShortname = string.Empty;
bool inputInvalid = false;

do {
inputInvalid = false;

envFileShortname = AnsiConsole.Ask<string>("Shortname for the file? (Will only be used as entry name in .gpt.yml.): ");

if (!EnvNameMatchRegex().Match(envFileShortname).Success) {
AnsiConsole.MarkupLine("[red]The name should only consist of the following characters: a-z 0-9 - _[/]");
inputInvalid = true;
}

if (EnvironmentConfig.Files.Keys.Contains(envFileShortname, StringComparer.OrdinalIgnoreCase)) {
if (!AnsiConsole.Confirm("An entry with that name already exists. Do you want to replace it?", false)) {
inputInvalid = true;
}
}
} while (inputInvalid);

var envFilePath = string.Empty;
FileInfo fileInfo = null;

do {
inputInvalid = false;

envFilePath = AnsiConsole.Ask<string>("Enter the full path to the file:");

if (!File.Exists(envFilePath)) {
AnsiConsole.MarkupLine("[red]The file could not be found![/]");
inputInvalid = true;
}

fileInfo = new FileInfo(envFilePath);

if (fileInfo.Length > 32768) {
AnsiConsole.MarkupLine("[red]The file needs to be less then 32kb in size.[/]");
inputInvalid = true;
}
} while (inputInvalid);

var saveLocations = new string[] {".gpt.yml", "gitpod"};

var saveLocation = AnsiConsole.Prompt(
new SelectionPrompt<string>()
.Title("Where should the content of the file being saved?")
.PageSize(10)
.AddChoices(saveLocations)
);

var gpVariable = string.Empty;

if (saveLocation == "gitpod") {
do {
inputInvalid = false;

gpVariable = AnsiConsole.Ask<string>("What is the name of the variable?");

if (!EnvNameMatchRegex().Match(gpVariable).Success) {
AnsiConsole.MarkupLine("[red]The variable name should only consist of the following characters: a-z 0-9 - _[/]");
inputInvalid = true;
}
} while (inputInvalid);
}

string encodedFileContent = string.Empty;

try {
var fileContent = File.ReadAllText(envFilePath);
encodedFileContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContent));
} catch (Exception e) {
AnsiConsole.WriteException(e);
}

EnvironmentConfig.Files.TryGetValue(envFileShortname, out Dictionary<string, string> existingEntry);

if (existingEntry != null) {
if (existingEntry.ContainsKey("file")) {
existingEntry["file"] = envFilePath;
} else {
existingEntry.Add("file", envFilePath);
}

if (existingEntry.ContainsKey("content") && saveLocation == ".gpt.yml") {
existingEntry["content"] = encodedFileContent;
} else if (!existingEntry.ContainsKey("content") && saveLocation == ".gpt.yml") {
existingEntry.Add("content", encodedFileContent);
} else if (existingEntry.ContainsKey("content") && saveLocation != ".gpt.yml") {
existingEntry.Remove("content");
}

if (existingEntry.ContainsKey("var") && saveLocation != ".gpt.yml") {
existingEntry.Remove("var");
}
} else {
var newEntry = new Dictionary<string, string>() {
{"file", envFilePath}
};

if (saveLocation == ".gpt.yml") {
newEntry.Add("content", encodedFileContent);
} else {
newEntry.Add("var", gpVariable);
}

EnvironmentConfig.Files.Add(envFileShortname, newEntry);
}

if (saveLocation != ".gpt.yml") {
ExecCommand.Exec("gp env " + gpVariable + "=" + encodedFileContent, 10);
}

// Mark the config as updated, so it will be saved on exiting the application
EnvironmentConfig.ConfigUpdated = true;

if (!AnsiConsole.Confirm("Do you want to add more files?", false)) {
finished = true;
}
} while (!finished);

AnsiConsole.MarkupLine("[green]The changes have been saved.[/]");
}

private void AddVariable()
{
AnsiConsole.MarkupLine("[red]Don´t save any sensible informations via this command![/]");
Expand Down
3 changes: 2 additions & 1 deletion commands/restore/RestoreEnvCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public class Settings : CommandSettings

public override int Execute(CommandContext context, Settings settings)
{
RestoreHelper.RestoreEnvVariables(settings.Debug);
//RestoreHelper.RestoreEnvVariables(settings.Debug);
RestoreHelper.RestoreEnvFiles(settings.Debug);

return 0;
}
Expand Down
20 changes: 18 additions & 2 deletions helper/RestoreHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ public static void RestoreNodeJsVersion(bool debug = false)
public static void RestoreEnvVariables(bool debug = false)
{
// Check if there has been something set via config file
AnsiConsole.Write("Checking if environment variables/files has been set via config....");
AnsiConsole.Write("Checking if environment variables has been set via config....");

if (EnvironmentConfig.Variables.Count == 0 && EnvironmentConfig.Files.Count == 0) {
if (EnvironmentConfig.Variables.Count == 0) {
AnsiConsole.MarkupLine("[cyan3]Not found[/]");

return;
Expand All @@ -68,5 +68,21 @@ public static void RestoreEnvVariables(bool debug = false)

EnvRestoreHelper.RestoreEnvironmentVariables(debug);
}

public static void RestoreEnvFiles(bool debug = false)
{
// Check if there has been something set via config file
AnsiConsole.Write("Checking if environment files has been set via config....");

if (EnvironmentConfig.Files.Count == 0) {
AnsiConsole.MarkupLine("[cyan3]Not found[/]");

return;
}

AnsiConsole.MarkupLine("[green1]Found[/]");

EnvRestoreHelper.RestoreEnvironmentFiles(debug);
}
}
}
45 changes: 43 additions & 2 deletions helper/env/EnvRestoreHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Gitpod.Tool.Helper.Internal.Config.Sections;
using Spectre.Console;

namespace Gitpod.Tool.Helper.Env
{
Expand All @@ -16,14 +18,53 @@ public static void RestoreEnvironmentVariables(bool debug = false)

var applicationDir = AppDomain.CurrentDomain.BaseDirectory;

List<string> envVariables = new();
envVariables.Add("#!/usr/bin/env bash");
List<string> envVariables = new() {
{"#!/usr/bin/env bash"}
};

foreach (KeyValuePair<string, string> entry in EnvironmentConfig.Variables) {
envVariables.Add("export " + entry.Key + "=\"" + entry.Value + "\"");
}

File.WriteAllText(applicationDir + ".env_restore", string.Join("\n", envVariables.ToArray<string>()));
}

public static void RestoreEnvironmentFiles(bool debug = false)
{
if (EnvironmentConfig.Files.Count == 0) {
return;
}

foreach (KeyValuePair<string, Dictionary<string, string>> entry in EnvironmentConfig.Files) {
entry.Value.TryGetValue("file", out string outputFileName);

if (outputFileName == null || outputFileName == string.Empty) {
AnsiConsole.MarkupLine("[red]Missing value \"file\" for restoring env " + entry.Key + "[/]");

continue;
}

entry.Value.TryGetValue("content", out string encodedFileContent);
entry.Value.TryGetValue("gpVariable", out string gpVariable);

if (encodedFileContent == null && gpVariable != null) {

}

if (encodedFileContent != null && encodedFileContent != string.Empty) {
string decodedFileString = string.Empty;

try {
decodedFileString = Encoding.UTF8.GetString(Convert.FromBase64String(encodedFileContent));
} catch (Exception e) {
AnsiConsole.WriteException(e);

continue;
}

File.WriteAllText(outputFileName, decodedFileString);
}
}
}
}
}

0 comments on commit f861960

Please sign in to comment.