Esempio n. 1
0
        public static int Main(string[] arguments)
        {
            if (0 == arguments.Length)
            {
                showUsage();
                return(0);
            }

            IniFile ini;
            string  outfile = null;

            ini = new IniFile();

            for (int i = 0; i < arguments.Length; i++)
            {
                string a = arguments[i];

                if (a[0] == '-' || a[0] == '/' || a[0] == '!')
                {
                    while (a[0] == '-' || a[0] == '/')
                    {
                        a = a.Substring(1);
                    }
                    string al = a.ToLower();

                    if (al.Equals("?") || al.StartsWith("help"))
                    {
                        showUsage();
                        return(0);
                    }
                    else if (al.StartsWith("q") || al.StartsWith("!q"))
                    {
                        quiet = al.StartsWith("q");
                    }
                    else if (al.StartsWith("v") || al.StartsWith("!v"))
                    {
                        verbose = al.StartsWith("v");

                        //
                        // Output file..
                        //
                    }
                    else if (al.StartsWith("o"))
                    {
                        outfile = a;

                        //
                        // Expand output (adds space between sections and before/after the equal sign)..
                        //
                    }
                    else if (al.StartsWith("expand") || al.StartsWith("!expand"))
                    {
                        ini.Expand = al.StartsWith("expand");

                        //
                        // Case sensitivity..
                        //
                    }
                    else if (al.Equals("i") || al.StartsWith("case-i") || al.StartsWith("casei"))
                    {
                        ini.SectionsStringComparison = StringComparison.CurrentCultureIgnoreCase;
                        ini.EntriesStringComparison  = StringComparison.CurrentCultureIgnoreCase;
                    }
                    else if (al.StartsWith("!i") || al.StartsWith("case-s") || al.StartsWith("cases"))
                    {
                        ini.SectionsStringComparison = StringComparison.CurrentCulture;
                        ini.EntriesStringComparison  = StringComparison.CurrentCulture;
                    }
                    else if (al.Equals("sections-is"))
                    {
                        ini.SectionsStringComparison = StringComparison.CurrentCultureIgnoreCase;
                    }
                    else if (al.Equals("sections-cs"))
                    {
                        ini.SectionsStringComparison = StringComparison.CurrentCulture;
                    }
                    else if (al.Equals("entries-is"))
                    {
                        ini.EntriesStringComparison = StringComparison.CurrentCultureIgnoreCase;
                    }
                    else if (al.Equals("entries-cs"))
                    {
                        ini.EntriesStringComparison = StringComparison.CurrentCulture;

                        //
                        // Sort direction..
                        //
                    }
                    else if (al.Equals("sort-asc") || al.Equals("sortasc"))
                    {
                        ini.SectionsSortOption = SortOption.Ascending;
                        ini.EntriesSortOption  = SortOption.Ascending;
                    }
                    else if (al.Equals("sort-desc") || al.Equals("sortdesc"))
                    {
                        ini.SectionsSortOption = SortOption.Descending;
                        ini.EntriesSortOption  = SortOption.Descending;
                    }
                    else if (al.Equals("!sort") || al.Equals("!sort"))
                    {
                        ini.SectionsSortOption = SortOption.None;
                        ini.EntriesSortOption  = SortOption.None;
                    }
                    else if (al.Equals("sections") || al.Equals("sections-asc"))
                    {
                        ini.SectionsSortOption = SortOption.Ascending;
                    }
                    else if (al.Equals("sections-desc"))
                    {
                        ini.SectionsSortOption = SortOption.Descending;
                    }
                    else if (al.Equals("!sections"))
                    {
                        ini.SectionsSortOption = SortOption.None;
                    }
                    else if (al.Equals("entries") || al.Equals("entries-asc"))
                    {
                        ini.EntriesSortOption = SortOption.Ascending;
                    }
                    else if (al.Equals("entries-desc"))
                    {
                        ini.EntriesSortOption = SortOption.Descending;
                    }
                    else if (al.Equals("!entries"))
                    {
                        ini.EntriesSortOption = SortOption.None;
                    }
                    else
                    {
                        if (!quiet)
                        {
                            Console.WriteLine("Unknown option: " + a);
                        }
                    }
                }
                else
                {
                    if (ini.FileName == null || ini.FileName.Length == 0)
                    {
                        ini.FileName = a;
                        while (ini.FileName.StartsWith("\"") && ini.FileName.EndsWith("\""))
                        {
                            ini.FileName = ini.FileName.Substring(1, ini.FileName.Length - 2);
                        }
                    }
                    else if (outfile == null || outfile.Length == 0)
                    {
                        outfile = a;
                    }
                    else
                    {
                        if (!quiet)
                        {
                            Console.WriteLine("Unknown option: " + a);
                        }
                    }
                }
            }

            if (StdInEx.IsInputRedirected)
            {
                // Ignore the specified `file` (if exists)..
                ini.FileName = StdInEx.RedirectInputToFile();
            }
            else if (ini.FileName == null || (ini.FileName = ini.FileName.Trim()).Length == 0)
            {
                throw new ArgumentNullException("file");
            }
            else if (!File.Exists(ini.FileName))
            {
                throw new ArgumentException("The specified file was not found (or is inaccessible)", "file");
            }

            try {
                // LOAD & SORT
                if (!ini.Load())
                {
                    throw new Exception("Could not load specified file");
                }

                // SORT
                ini.Sort();

                // OUTPUT
                if (!StdInEx.IsOutputRedirected && (outfile == null || outfile.Length == 0))
                {
                    // Write back to the input file..
                    if (!ini.Save())
                    {
                        throw new InvalidOperationException("Failed saving back to file");
                    }
                }
                else
                {
                    if (outfile != null && outfile.Length > 0)
                    {
                        if (!ini.Save(outfile))
                        {
                            throw new InvalidOperationException("Failed saving to outfile");
                        }
                    }
                    if (StdInEx.IsOutputRedirected)
                    {
                        string             tmpOut;
                        DeleteFileWhenDone tmpDel;
                        if (outfile != null && outfile.Length > 0)
                        {
                            tmpOut = outfile; // just output the new file..
                        }
                        else
                        {
                            tmpOut = Path.GetTempFileName();
                            tmpDel = new DeleteFileWhenDone(tmpOut);
                            if (!ini.Save(tmpOut))
                            {
                                throw new InvalidOperationException("Failed saving to temporary output (for stdout)");
                            }
                        }
                        Console.WriteLine(File.ReadAllText(tmpOut));
                    }
                }
            } catch (Exception ex) {
                StringBuilder s = new StringBuilder();
                s.AppendLine("**** ERROR OCURRED")
                .AppendLine(ex.Message);
                Console.Error.WriteLine(s.ToString());
                if (outfile != null && outfile.Length > 0)
                {
                    // Write the error to the destination file..
                    File.WriteAllText(outfile, s.ToString());
                }
                return(1);
            }

            if (!quiet)
            {
                Console.WriteLine("SUCCESS");
            }

            return(0);
        }
Esempio n. 2
0
        public static int Main(string[] args)
        {
            envars = new EnvironmentVariables(appName);

            string file = null;
            SortedDictionary <string, string> dc;
            string        line;
            bool          exists;
            string        name;
            string        comment;
            StringBuilder cb;
            int           index;
            string        a;
            bool          vf;    // verify file exists
            string        sfn;   // saved backup file name
            bool          sf;    // don't delete the backup file
            bool          oc;    // output to the console, instead of back to the file
            Encoding      enc;   // the encoding used to open the source descript.ion file

            vf = false;
            sf = false;
            oc = false;

            // Load environment variables first.
            // Command-line arguments will overwrite them when present.
            if (envars.contains("vf"))
            {
                vf = envars.attr <bool>("vf");
            }
            if (envars.contains("sf"))
            {
                sf = envars.attr <bool>("sf");
            }

            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    a = args[i];
                    if (a.StartsWith("/") || a.StartsWith("-") || a.StartsWith("!"))
                    {
                        while (a.StartsWith("/") || a.StartsWith("-"))
                        {
                            a = a.Substring(1);
                        }

                        if (a.StartsWith("h", StringComparison.CurrentCultureIgnoreCase) || a.Equals("?", StringComparison.CurrentCultureIgnoreCase))
                        {
                            usage();
                            return(0);
                        }
                        else if (a.Equals("vf", StringComparison.CurrentCultureIgnoreCase))
                        {
                            vf = true;
                        }
                        else if (a.Equals("!vf", StringComparison.CurrentCultureIgnoreCase))
                        {
                            vf = false;
                        }
                        else if (a.Equals("sf", StringComparison.CurrentCultureIgnoreCase))
                        {
                            sf = true;
                        }
                        else if (a.Equals("!sf", StringComparison.CurrentCultureIgnoreCase))
                        {
                            sf = false;
                        }
                        else if (a.Equals("oc", StringComparison.CurrentCultureIgnoreCase))
                        {
                            oc = true;
                        }
                        else if (a.Equals("!oc", StringComparison.CurrentCultureIgnoreCase))
                        {
                            oc = false;
                        }
                    }
                    else
                    {
                        // get the filename
                        file = a;
                    }
                }
            }

            if (StdInEx.IsInputRedirected)
            {
                file = StdInEx.RedirectInputToFile();
                oc   = true;
            }
            else
            {
                if (file == null || file.Length == 0)
                {
                    //Console.WriteLine("Using: " + Environment.CurrentDirectory);
                    file = Path.Combine(Environment.CurrentDirectory, "descript.ion");
                }
            }

            if (!File.Exists(file))
            {
                Console.WriteLine("there is no descript.ion file in the current folder");
                return(1);
            }

            try {
                BackupFile(file, "bak_", out sfn);
            } catch (Exception ex) {
                Console.WriteLine("error backing up descript.ion file: " + ex.Message);
                return(2);
            }

            dc  = new SortedDictionary <string, string>();
            cb  = new StringBuilder();
            enc = Encoding.Default;

            using (StreamReader r = new StreamReader(File.OpenRead(file), Encoding.Default, true)) {
                enc = r.CurrentEncoding;

                while (!r.EndOfStream)
                {
                    if ((line = r.ReadLine()) != null)
                    {
                        // do not trim the line itself!
                        if (line.Trim().Length == 0)
                        {
                            continue;
                        }

                        // Get the file name and comments
                        if (line.StartsWith("\""))
                        {
                            index = line.IndexOf("\" ", 1);
                            if (index == -1)
                            {
                                Console.WriteLine("--> invalid line:");
                                Console.WriteLine("    " + line.Substring(0, Math.Min(80, line.Length)));
                                continue;
                            }
                            index += 2;
                        }
                        else
                        {
                            index = line.IndexOf(' ');
                        }

                        if (index == -1)
                        {
                            continue;
                        }

                        name    = line.Substring(0, index).Trim().Trim('"', ' ', '\t');
                        comment = line.Substring(index).Trim();

                        // Verify that the file exists in the current folder.
                        if (vf)
                        {
                            if (!File.Exists(name) && !Directory.Exists(name))
                            {
                                Console.WriteLine("--> file/folder was not found: " + name);
                                sf = true;
                                continue;
                            }
                        }

                        // Ensure a unique file name for the dictionary
                        exists = false;
                        while (dc.ContainsKey(name))
                        {
                            exists = true;
                            name  += "_";
                        }
                        if (exists)
                        {
                            Console.WriteLine("--> duplicate entry was found.. saved as: " + name);
                        }

                        // Cleanup the comment
                        //while (comment.IndexOf('’') > -1) {
                        //   comment = comment.Replace('’', '\'');
                        //}

                        //cb.Clear();
                        //foreach (char ch in comment) {
                        //   if (ch < 32 || ch > 126) {
                        //      // 9=tab
                        //      // 10=new line
                        //      // 13=carriage return
                        //      // 169=copyright symbol
                        //      // 174=registered symbol
                        //      //
                        //      if (ch != 9 && ch != 10 && ch != 13 && ch != 169 && ch != 174 && ch != '•') {
                        //         //cb.Append(' ');
                        //         continue;
                        //      }
                        //   }
                        //   cb.Append(ch);
                        //}
                        //comment = cb.ToString().Trim();

                        while (comment.IndexOf("\\\\n") > -1)
                        {
                            comment = comment.Replace("\\\\n", "\\n");
                        }

                        while (comment.IndexOf((char)4) == comment.Length - 1 || comment.IndexOf((char)194) == comment.Length - 1)
                        {
                            comment = comment.Substring(0, comment.Length - 1);
                        }

                        while (comment.EndsWith("\\n"))
                        {
                            comment = comment.Substring(0, comment.Length - 2).TrimEnd();
                        }

                        dc.Add(name, comment);
                    }
                }

                r.Close();
            }

            try {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            } catch (Exception ex) {
                Console.WriteLine("error: " + ex.Message);
                return(3);
            }

            if (dc.Count > 0)
            {
                if (oc)
                {
                    foreach (KeyValuePair <string, string> p in dc)
                    {
                        Console.Write(string.Format("{0,-30}{1}", p.Key, p.Value));
                    }
                }
                else if (enc != null)
                {
                    try {
                        using (FileStream fs = File.Create(file)) {
                            foreach (KeyValuePair <string, string> p in dc)
                            {
                                byte[] b;

                                if (p.Key.Contains(" "))
                                {
                                    name = "\"" + p.Key + "\"";
                                }
                                else
                                {
                                    name = p.Key;
                                }
                                comment = p.Value;

                                b = new byte[name.Length];
                                enc.GetBytes(name.ToCharArray(), 0, name.Length, b, 0);
                                fs.Write(b, 0, b.Length);

                                fs.Write(new byte[] { 32 }, 0, 1);

                                b = new byte[comment.Length];
                                enc.GetBytes(comment.ToCharArray(), 0, comment.Length, b, 0);
                                fs.Write(b, 0, b.Length);

                                // Write out the special characters to indicate to Total Commander that there are new lines in the comments.
                                if (comment.IndexOf("\\n") > -1)
                                {
                                    fs.Write(new byte[] { 4, 194 }, 0, 2);
                                }

                                // New line and carriage return.
                                fs.Write(new byte[] { 13, 10 }, 0, 2);
                            }
                            fs.Flush();
                            fs.Close();
                        }
                    } catch (Exception ex) {
                        Console.WriteLine("error writing descript.ion file: " + ex.Message);
                        if (File.Exists(file))
                        {
                            File.SetAttributes(file, FileAttributes.Normal);
                            File.Delete(file);
                        }
                        File.Move(sfn, file);
                        Console.WriteLine("original file was put back");
                        return(4);
                    }
                }
                else
                {
                    Console.WriteLine("**** ERROR: failed to get the encoding of the input.");
                }
            }

            // Since we're not updating the file, there is no
            // need to create a backup of it. --> !oc
            if (!sf && !oc)
            {
                try {
                    File.SetAttributes(sfn, FileAttributes.Normal);
                    File.Delete(sfn);
                } catch (Exception ex) {
                    Console.WriteLine("error deleting backup file: " + ex.Message);
                    return(5);
                }
            }

            return(0);
        }