Skip to content

Instantly share code, notes, and snippets.

@nrkn
Last active December 17, 2015 22:49
Show Gist options
  • Save nrkn/5684937 to your computer and use it in GitHub Desktop.
Save nrkn/5684937 to your computer and use it in GitHub Desktop.
Make a path into a collapsible tree
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace FileSystemToTree
{
class Program
{
static void Main(string[] args)
{
var start = args[0];
var node = PathToNodes(start);
var html = Root(node);
File.WriteAllText(node.Name + ".html", html, Encoding.UTF8);
}
static Node PathToNodes(string path)
{
var folder = new DirectoryInfo(path);
var node = new Node { Name = folder.Name };
var directories = folder.GetDirectories().Select(dir => PathToNodes(dir.FullName));
var files = folder.GetFiles().Select(file => new Node { Name = file.Name });
node.Children = directories.Concat(files);
return node;
}
static string Root(Node node)
{
var builder = new StringBuilder();
builder.AppendLine("<style>body{font-family:sans-serif;}</style>");
builder.AppendLine("<script src='http://code.jquery.com/jquery-1.10.0.min.js'></script>");
builder.AppendLine("<script src='http://code.jquery.com/jquery-migrate-1.2.1.min.js'></script>");
builder.AppendLine("<script>");
builder.AppendLine("$(function(){");
builder.AppendLine("$('ul:not(#root)').hide();");
builder.AppendLine("$('a').on('click',");
builder.AppendLine("function(){");
builder.AppendLine("var p=$(this).parent('p');");
builder.AppendLine("var li=p.parent('li')");
builder.AppendLine("li.find('>ul').toggle();");
builder.AppendLine("return false;");
builder.AppendLine("});");
builder.AppendLine("});");
builder.AppendLine("</script>");
builder.AppendLine("<ul id='root'>");
builder.AppendLine("<li>");
builder.AppendLine(node.ToString());
builder.AppendLine("</li></ul>");
return builder.ToString();
}
}
class Node
{
public string Name { get; set; }
public IEnumerable<Node> Children { get; set; }
public override string ToString()
{
var hasChildren = Children != null && Children.Any();
var builder = new StringBuilder();
builder.AppendLine("<p>");
if (hasChildren)
{
builder.AppendLine("<a href='#'>");
}
builder.AppendLine(Name);
{
builder.AppendLine("</a>");
}
builder.AppendLine("</p>");
if (hasChildren)
{
builder.AppendLine("<ul>");
foreach (var node in Children)
{
builder.AppendLine("<li>");
builder.AppendLine(node.ToString());
builder.AppendLine("</li>");
}
builder.AppendLine("</ul>");
}
return builder.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment