Skip to content

Instantly share code, notes, and snippets.

@sleemanj
Created April 17, 2017 00:07
Show Gist options
  • Save sleemanj/b1ca63c934147996cf6eb612fb5185ba to your computer and use it in GitHub Desktop.
Save sleemanj/b1ca63c934147996cf6eb612fb5185ba to your computer and use it in GitHub Desktop.
Convert DipTrace .asc library Export Format into an XML structure, and back again.
#!/usr/bin/php
<?php
// Convert .asc into a .xml representation, or the reverse
//
// The attributes of each "asc" element '(Blah 123 "abc" )' are just dumped
// into _PARAMS="" attribute of the node '<Blah _PARAMS="123 &quot;abc&quot;" />'
//
// Take note that in the XML, _UNCLOSED="1" means that this tag
// when converted to asc must have the closing ")" on a separate line
// even if it is empty, not all do.
if(preg_match('/\.asc$/', $argv[1]))
{
$f = file($argv[1]);
$Stack = array( array('NodeName' => 'DipTraceLibrary', 'Args' => '', 'Content' => '' ) );
echo '<DipTraceLibraryConversion>';
foreach($f as $l)
{
// An enclosed element "(Abc args)"
if(preg_match('/^\s*\(([A-Za-z0-9]+)(.*)\)\s*$/', $l, $M))
{
$E = array('NodeName' => $M[1], 'Args'=> trim($M[2]), 'Content' => '');
$Stack[count($Stack)-1]['Content'] .= '<'.$E['NodeName'].' _PARAMS="'.htmlspecialchars($E['Args']).'" _UNCLOSED="0"/>';
}
// Unclosed
elseif(preg_match('/^\s*\(([A-Za-z0-9]+)(.*)\s*$/', $l, $M))
{
$E = array('NodeName' => $M[1], 'Args'=> trim($M[2]), 'Content' => '');
$Stack[count($Stack)-1]['Content'] .= '<'.$E['NodeName'].' _PARAMS="'.htmlspecialchars($E['Args']).'" _UNCLOSED="1">';
array_push($Stack, $E);
}
elseif(preg_match('/^\s*\)/', $l, $M))
{
if(count($Stack)>1)
{
$E = array_pop($Stack);
$Stack[count($Stack)-1]['Content'] .= $E['Content'].'</'.$E['NodeName'].'>';
}
}
}
echo $Stack[0]['Content'];
echo '</DipTraceLibraryConversion>';
}
else
{
$Root = new SimpleXMLElement(file_get_contents($argv[1]));
function output($Node, $Depth)
{
if(count($Node->children()) || ((int)$Node['_UNCLOSED']) == 1)
{
echo str_repeat(' ', $Depth*2) . '('.$Node->getName(). ' ' . $Node['_PARAMS'] . "\r\n";
foreach($Node->children() as $Child)
{
output($Child, $Depth+1);
}
echo str_repeat(' ', $Depth*2) . ")\r\n";
}
else
{
echo str_repeat(' ', $Depth*2) . '('.$Node->getName(). ' ' . $Node['_PARAMS'] . ")\r\n";
}
}
output($Root->Source[0], 0);
output($Root->Library[0], 1);
// For some reason there is an extra trailing ), I don't know if it matters.
// echo ")\r\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment