* <feat> 多语言支持
* <feat> text tool 只读模式
This commit is contained in:
2022-12-01 17:26:37 +08:00
committed by GitHub
parent d6fd2b0f9a
commit de264e58a0
29 changed files with 1818 additions and 59 deletions

15
src/DirOption.cs Normal file
View File

@ -0,0 +1,15 @@
namespace Dot;
public class DirOption : IOption
{
[Option('f', "filter", HelpText = nameof(Strings.FileSearchPattern), Default = "*.*"
, ResourceType = typeof(Strings))]
public string Filter { get; set; }
[Value(0, HelpText = nameof(Strings.FolderPath), Default = ".", ResourceType = typeof(Strings))]
public string Path { get; set; }
[Option('r', "readonly", HelpText = nameof(Strings.ReadOnly), Default = false, ResourceType = typeof(Strings))]
public bool ReadOnly { get; set; }
}

View File

@ -1,2 +1,3 @@
global using ShellProgressBar;
global using CommandLine;
global using CommandLine;
global using Dot.Lang;

View File

@ -12,6 +12,6 @@ public sealed class Main : Tool<Option>
var guid = System.Guid.NewGuid().ToString();
if (Opt.Upper) guid = guid.ToUpper();
ClipboardService.SetText(guid);
Console.WriteLine($"已复制到剪贴板:{guid}");
Console.WriteLine(Strings.Copied, guid);
}
}

View File

@ -1,8 +1,8 @@
namespace Dot.Guid;
[Verb("guid", HelpText = "GUID工具")]
[Verb("guid", HelpText = nameof(Strings.GuidTool), ResourceType = typeof(Strings))]
public class Option : IOption
{
[Option('u', "upper", HelpText = "大写", Default = false)]
[Option('u', "upper", HelpText = nameof(Strings.UseUppercase), Default = false, ResourceType = typeof(Strings))]
public bool Upper { get; set; } //normal options here
}

251
src/Lang/Strings.Designer.cs generated Normal file
View File

@ -0,0 +1,251 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Dot.Lang {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Dot.Lang.Strings", typeof(Strings).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to 转换换行符为LF.
/// </summary>
public static string ConvertEndOfLineToLF {
get {
return ResourceManager.GetString("ConvertEndOfLineToLF", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}(已复制到剪贴板).
/// </summary>
public static string Copied {
get {
return ResourceManager.GetString("Copied", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 文件通配符.
/// </summary>
public static string FileSearchPattern {
get {
return ResourceManager.GetString("FileSearchPattern", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 要处理的目录路径.
/// </summary>
public static string FolderPath {
get {
return ResourceManager.GetString("FolderPath", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to GUID工具.
/// </summary>
public static string GuidTool {
get {
return ResourceManager.GetString("GuidTool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 文本编码工具.
/// </summary>
public static string HelpForText {
get {
return ResourceManager.GetString("HelpForText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 输入文本为空.
/// </summary>
public static string InputTextIsEmpty {
get {
return ResourceManager.GetString("InputTextIsEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 没有需要处理的文件.
/// </summary>
public static string NoFileToBeProcessed {
get {
return ResourceManager.GetString("NoFileToBeProcessed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 指定的路径“{0}”不存在.
/// </summary>
public static string PathNotFound {
get {
return ResourceManager.GetString("PathNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 按下任意键继续....
/// </summary>
public static string PressAnyKey {
get {
return ResourceManager.GetString("PressAnyKey", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to BitSet 1[0-9]2[a-z]4[A-Z]8[ascii.0x21-0x2F].
/// </summary>
public static string PwdGenerateTypes {
get {
return ResourceManager.GetString("PwdGenerateTypes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 密码长度.
/// </summary>
public static string PwdLength {
get {
return ResourceManager.GetString("PwdLength", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 随机密码生成器.
/// </summary>
public static string RandomPasswordGenerator {
get {
return ResourceManager.GetString("RandomPasswordGenerator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 只读模式(仅做测试,不实际修改).
/// </summary>
public static string ReadOnly {
get {
return ResourceManager.GetString("ReadOnly", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 移除文件尾部换行和空格.
/// </summary>
public static string RemoveTrailingWhiteSpaces {
get {
return ResourceManager.GetString("RemoveTrailingWhiteSpaces", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 查找文件....
/// </summary>
public static string SearchingFile {
get {
return ResourceManager.GetString("SearchingFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} 个文件.
/// </summary>
public static string SearchingFileOK {
get {
return ResourceManager.GetString("SearchingFileOK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 已读取:{0}/{1},处理:{2},跳过:{3}.
/// </summary>
public static string ShowMessageTemp {
get {
return ResourceManager.GetString("ShowMessageTemp", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 要处理的文本(默认取取剪贴板值).
/// </summary>
public static string TextTobeProcessed {
get {
return ResourceManager.GetString("TextTobeProcessed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 移除文件的uf8 bom.
/// </summary>
public static string TrimUtf8Bom {
get {
return ResourceManager.GetString("TrimUtf8Bom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 使用大写输出.
/// </summary>
public static string UseUppercase {
get {
return ResourceManager.GetString("UseUppercase", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
id="root" xmlns="">
<xsd:element name="root" msdata:IsDataSet="true"></xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</resheader>
<data name="InputTextIsEmpty" xml:space="preserve">
<value>The input text is empty</value>
</data>
<data name="SearchingFile" xml:space="preserve">
<value>Find files...</value>
</data>
<data name="PathNotFound" xml:space="preserve">
<value>The specified path "{0}" does not exist</value>
</data>
<data name="SearchingFileOK" xml:space="preserve">
<value>Find files...OK</value>
</data>
<data name="ShowMessageTemp" xml:space="preserve">
<value>Read: {0}/{1}, processed: {2}, skipped: {3}</value>
</data>
<data name="HelpForText" xml:space="preserve">
<value>Text encoding tool</value>
</data>
<data name="Copied" xml:space="preserve">
<value>{0}(copied to clipboard)</value>
</data>
<data name="FileSearchPattern" xml:space="preserve">
<value>File wildcards</value>
</data>
<data name="FolderPath" xml:space="preserve">
<value>Directory path to be processed</value>
</data>
<data name="ConvertEndOfLineToLF" xml:space="preserve">
<value>Convert newline characters to LF</value>
</data>
<data name="GuidTool" xml:space="preserve">
<value>GUID tool</value>
</data>
<data name="UseUppercase" xml:space="preserve">
<value>Use uppercase output</value>
</data>
<data name="RandomPasswordGenerator" xml:space="preserve">
<value>Random password generator</value>
</data>
<data name="PwdLength" xml:space="preserve">
<value>Password length</value>
</data>
<data name="PwdGenerateTypes" xml:space="preserve">
<value>BitSet 1[0-9]2[a-z]4[A-Z]8[ascii.0x21-0x2F]</value>
</data>
<data name="RemoveTrailingWhiteSpaces" xml:space="preserve">
<value>Remove line breaks and spaces at the end of the file</value>
</data>
<data name="TrimUtf8Bom" xml:space="preserve">
<value>Remove the uf8 bom of the file</value>
</data>
<data name="TextTobeProcessed" xml:space="preserve">
<value>Text to be processed (clipboard value is taken by default)</value>
</data>
<data name="PressAnyKey" xml:space="preserve">
<value>Press any key to continue...</value>
</data>
<data name="ReadOnly" xml:space="preserve">
<value>Read-only mode (only for testing, no actual modification)</value>
</data>
<data name="NoFileToBeProcessed" xml:space="preserve">
<value>No documents to be processed</value>
</data>
</root>

94
src/Lang/Strings.resx Normal file
View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
id="root"
xmlns="">
<xsd:element name="root" msdata:IsDataSet="true">
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
</value>
</resheader>
<data name="InputTextIsEmpty" xml:space="preserve">
<value>输入文本为空</value>
</data>
<data name="SearchingFile" xml:space="preserve">
<value>查找文件...</value>
</data>
<data name="PathNotFound" xml:space="preserve">
<value>指定的路径“{0}”不存在</value>
</data>
<data name="SearchingFileOK" xml:space="preserve">
<value>{0} 个文件</value>
</data>
<data name="ShowMessageTemp" xml:space="preserve">
<value>已读取:{0}/{1},处理:{2},跳过:{3}</value>
</data>
<data name="HelpForText" xml:space="preserve">
<value>文本编码工具</value>
</data>
<data name="TextTobeProcessed" xml:space="preserve">
<value>要处理的文本(默认取取剪贴板值)</value>
</data>
<data name="Copied" xml:space="preserve">
<value>{0}(已复制到剪贴板)</value>
</data>
<data name="FileSearchPattern" xml:space="preserve">
<value>文件通配符</value>
</data>
<data name="FolderPath" xml:space="preserve">
<value>要处理的目录路径</value>
</data>
<data name="ConvertEndOfLineToLF" xml:space="preserve">
<value>转换换行符为LF</value>
</data>
<data name="GuidTool" xml:space="preserve">
<value>GUID工具</value>
</data>
<data name="UseUppercase" xml:space="preserve">
<value>使用大写输出</value>
</data>
<data name="RandomPasswordGenerator" xml:space="preserve">
<value>随机密码生成器</value>
</data>
<data name="PwdLength" xml:space="preserve">
<value>密码长度</value>
</data>
<data name="PwdGenerateTypes" xml:space="preserve">
<value>BitSet 1[0-9]2[a-z]4[A-Z]8[ascii.0x21-0x2F]</value>
</data>
<data name="RemoveTrailingWhiteSpaces" xml:space="preserve">
<value>移除文件尾部换行和空格</value>
</data>
<data name="TrimUtf8Bom" xml:space="preserve">
<value>移除文件的uf8 bom</value>
</data>
<data name="PressAnyKey" xml:space="preserve">
<value>按下任意键继续...</value>
</data>
<data name="ReadOnly" xml:space="preserve">
<value>只读模式(仅做测试,不实际修改)</value>
</data>
<data name="NoFileToBeProcessed" xml:space="preserve">
<value>没有需要处理的文件</value>
</data>
</root>

53
src/Pwd/Main.cs Normal file
View File

@ -0,0 +1,53 @@
using NSExt.Extensions;
using TextCopy;
namespace Dot.Pwd;
public sealed class Main : Tool<Option>
{
private readonly char[][] _charTable = {
"0123456789".ToCharArray() //
, "abcdefghijklmnopqrstuvwxyz".ToCharArray()
, "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".ToCharArray()
};
public Main(Option opt) : base(opt) { }
public override void Run()
{
unsafe {
var pSource = stackalloc char[_charTable.Sum(x => x.Length)];
var pDest = stackalloc char[Opt.Length];
var sourceLen = 0;
if (Opt.Type.HasFlag(Option.GenerateTypes.Number))
foreach (var c in _charTable[0])
*(pSource + sourceLen++) = c;
if (Opt.Type.HasFlag(Option.GenerateTypes.LowerCaseLetter))
foreach (var c in _charTable[1])
*(pSource + sourceLen++) = c;
if (Opt.Type.HasFlag(Option.GenerateTypes.UpperCaseLetter))
foreach (var c in _charTable[2])
*(pSource + sourceLen++) = c;
if (Opt.Type.HasFlag(Option.GenerateTypes.SpecialCharacter))
foreach (var c in _charTable[3])
*(pSource + sourceLen++) = c;
var randScope = new[] { 0, sourceLen };
for (var i = 0; i != Opt.Length; ++i) //
*(pDest + i) = *(pSource + randScope.Rand());
var result = new string(pDest, 0, Opt.Length);
ClipboardService.SetText(result);
Console.WriteLine(Strings.Copied, result);
}
}
}

21
src/Pwd/Option.cs Normal file
View File

@ -0,0 +1,21 @@
namespace Dot.Pwd;
[Verb("pwd", HelpText = nameof(Strings.RandomPasswordGenerator), ResourceType = typeof(Strings))]
public class Option : IOption
{
[Flags]
public enum GenerateTypes
{
Number = 1
, LowerCaseLetter = 2
, UpperCaseLetter = 4
, SpecialCharacter = 8
}
[Value(1, Required = true, HelpText = nameof(Strings.PwdLength), ResourceType = typeof(Strings))]
public int Length { get; set; }
[Value(0, Required = true, HelpText = nameof(Strings.PwdGenerateTypes), ResourceType = typeof(Strings))]
public GenerateTypes Type { get; set; }
}

113
src/RmBlank/Main.cs Normal file
View File

@ -0,0 +1,113 @@
using System.Diagnostics.CodeAnalysis;
using NSExt.Extensions;
namespace Dot.RmBlank;
public sealed class Main : Tool<Option>, IDisposable
{
private int _breakCnt;
private bool _disposed;
private static readonly object _lockObj = new();
private int _procedCnt;
private int _replaceCnt;
private ChildProgressBar _step2Bar;
private int _totalCnt;
public Main(Option opt) : base(opt) { }
~Main()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing) _step2Bar?.Dispose();
_disposed = true;
}
private void FileHandle(string file)
{
_step2Bar.Tick();
ShowMessage(1, 0, 0);
var spacesCnt = 0;
using var fsrw = OpenFileStream(file, FileMode.Open, FileAccess.ReadWrite);
if (Opt.ReadOnly) { //测试,只读模式
ShowMessage(0, 1, 0);
return;
}
if (fsrw is null || fsrw.Length == 0 || (spacesCnt = GetSpacesCnt(fsrw)) == 0) {
ShowMessage(0, 0, 1);
return;
}
fsrw.Seek(0, SeekOrigin.Begin);
if (!fsrw.IsTextStream()) return;
ShowMessage(0, 1, 0);
fsrw.SetLength(fsrw.Length - spacesCnt);
}
private static int GetSpacesCnt(Stream fsr)
{
var trimLen = 0;
fsr.Seek(-1, SeekOrigin.End);
int data;
while ((data = fsr.ReadByte()) != -1)
if (new[] { 0x20, 0x0d, 0x0a }.Contains(data)) {
++trimLen;
if (fsr.Position - 2 < 0) break;
fsr.Seek(-2, SeekOrigin.Current);
}
else {
break;
}
return trimLen;
}
private void ShowMessage(int procedCnt, int removeCnt, int breakCnt)
{
lock (_lockObj) {
_procedCnt += procedCnt;
_replaceCnt += removeCnt;
_breakCnt += breakCnt;
_step2Bar.Message = string.Format(Strings.ShowMessageTemp, _procedCnt, _totalCnt, _replaceCnt, _breakCnt);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <inheritdoc />
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public override void Run()
{
if (!Directory.Exists(Opt.Path))
throw new ArgumentException(nameof(Opt.Path), string.Format(Strings.PathNotFound, Opt.Path));
using var step1Bar = new IndeterminateProgressBar(Strings.SearchingFile, DefaultProgressBarOptions);
var fileList = EnumerateFiles(Opt.Path, Opt.Filter);
_totalCnt = fileList.Count();
step1Bar.Message = string.Format(Strings.SearchingFileOK, _totalCnt);
step1Bar.Finished();
if (_totalCnt == 0) return;
_step2Bar = step1Bar.Spawn(_totalCnt, string.Empty, DefaultProgressBarOptions);
Parallel.ForEach(fileList, FileHandle);
}
}

4
src/RmBlank/Option.cs Normal file
View File

@ -0,0 +1,4 @@
namespace Dot.RmBlank;
[Verb("rm-blank", HelpText = nameof(Strings.RemoveTrailingWhiteSpaces), ResourceType = typeof(Strings))]
public class Option : DirOption { }

103
src/RmBom/Main.cs Normal file
View File

@ -0,0 +1,103 @@
using System.Diagnostics.CodeAnalysis;
namespace Dot.RmBom;
public sealed class Main : Tool<Option>, IDisposable
{
private int _breakCnt;
private bool _disposed;
private static readonly object _lockObj = new();
private int _procedCnt;
private ChildProgressBar _step2Bar;
private int _totalCnt;
private int _trimCnt;
public Main(Option opt) : base(opt) { }
~Main()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing) _step2Bar?.Dispose();
_disposed = true;
}
private void ShowMessage(int procedCnt, int replaceCnt, int breakCnt)
{
lock (_lockObj) {
_procedCnt += procedCnt;
_trimCnt += replaceCnt;
_breakCnt += breakCnt;
_step2Bar.Message = string.Format(Strings.ShowMessageTemp, _procedCnt, _totalCnt, _trimCnt, _breakCnt);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public override void Run()
{
if (!Directory.Exists(Opt.Path))
throw new ArgumentException(nameof(Opt.Path), string.Format(Strings.PathNotFound, Opt.Path));
var utf8Bom = new byte[] { 0xef, 0xbb, 0xbf };
using var step1Bar = new IndeterminateProgressBar(Strings.SearchingFile, DefaultProgressBarOptions);
var fileList = EnumerateFiles(Opt.Path, Opt.Filter);
_totalCnt = fileList.Count();
step1Bar.Message = string.Format(Strings.SearchingFileOK, _totalCnt);
step1Bar.Finished();
if (_totalCnt == 0) return;
_step2Bar = step1Bar.Spawn(_totalCnt, string.Empty, DefaultProgressBarOptions);
Parallel.ForEach(fileList, file => {
_step2Bar.Tick();
ShowMessage(1, 0, 0);
var tmpFile = $"{file}.tmp";
var isReplaced = false;
using (var fsr = OpenFileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
if (Opt.ReadOnly) { //测试,只读模式
ShowMessage(0, 1, 0);
return;
}
if (fsr is null) {
ShowMessage(0, 0, 1);
return;
}
Span<byte> buffer = stackalloc byte[utf8Bom.Length];
var readLen = fsr.Read(buffer);
if (readLen == utf8Bom.Length && buffer.SequenceEqual(utf8Bom)) {
using var fsw = OpenFileStream(tmpFile, FileMode.OpenOrCreate, FileAccess.Write);
int data;
while ((data = fsr.ReadByte()) != -1) fsw.WriteByte((byte)data);
isReplaced = true;
}
}
if (isReplaced) {
MoveFile(tmpFile, file);
ShowMessage(0, 1, 0);
}
else {
ShowMessage(0, 0, 1);
}
});
}
}

4
src/RmBom/Option.cs Normal file
View File

@ -0,0 +1,4 @@
namespace Dot.RmBom;
[Verb("rm-bom", HelpText = nameof(Strings.TrimUtf8Bom), ResourceType = typeof(Strings))]
public class Option : DirOption { }

View File

@ -28,7 +28,7 @@ public sealed class Main : Tool<Option>
public Main(Option opt) : base(opt)
{
if (Opt.Text.NullOrEmpty()) Opt.Text = ClipboardService.GetText();
if (Opt.Text.NullOrEmpty()) throw new ArgumentException("输入文本为空");
if (Opt.Text.NullOrEmpty()) throw new ArgumentException(Strings.InputTextIsEmpty);
}
private static Output BuildOutput(string text, Encoding enc)
@ -102,5 +102,7 @@ html-decode: {o.HtmlDecode}
PrintOutput(utf8);
PrintOutput(unicodeLittleEndian);
PrintOutput(unicodeBigEndian);
Console.Write(Strings.PressAnyKey);
Console.ReadKey();
}
}

View File

@ -1,8 +1,8 @@
namespace Dot.Text;
[Verb("text", HelpText = "文本编码工具")]
[Verb("text", HelpText = nameof(Strings.HelpForText), ResourceType = typeof(Strings))]
public class Option : IOption
{
[Value(0, MetaName = "文本", HelpText = "要处理的文本,不指定此参数:取剪贴板值")]
[Value(0, HelpText = nameof(Strings.TextTobeProcessed), ResourceType = typeof(Strings))]
public string Text { get; set; }
}

127
src/ToLf/Main.cs Normal file
View File

@ -0,0 +1,127 @@
using System.Diagnostics.CodeAnalysis;
namespace Dot.ToLf;
public sealed class Main : Tool<Option>, IDisposable
{
private int _breakCnt;
private bool _disposed;
private static readonly object _lockObj = new();
private int _procedCnt;
private int _replaceCnt;
private ChildProgressBar _step2Bar;
private int _totalCnt;
public Main(Option opt) : base(opt) { }
~Main()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing) _step2Bar?.Dispose();
_disposed = true;
}
private void FileHandle(string file)
{
_step2Bar.Tick();
ShowMessage(1, 0, 0);
var tmpFile = $"{file}.tmp";
var isReplaced = false;
var isBin = false;
int data;
using (var fsr = OpenFileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
if (Opt.ReadOnly) { //测试,只读模式
ShowMessage(0, 1, 0);
return;
}
if (fsr is null) {
ShowMessage(0, 0, 1);
return;
}
using var fsw = OpenFileStream(tmpFile, FileMode.OpenOrCreate, FileAccess.Write);
while ((data = fsr.ReadByte()) != -1) {
switch (data) {
case 0x0d when fsr.ReadByte() == 0x0a: // crlf windows
fsw.WriteByte(0x0a);
isReplaced = true;
continue;
case 0x0d: //cr macos
fsw.WriteByte(0x0a);
fsr.Seek(-1, SeekOrigin.Current);
isReplaced = true;
continue;
case 0x00 or 0xff: //非文本文件
isBin = true;
break;
default:
fsw.WriteByte((byte)data);
continue;
}
break;
}
}
if (isReplaced && !isBin) {
MoveFile(tmpFile, file);
ShowMessage(0, 1, 0);
}
else {
File.Delete(tmpFile);
ShowMessage(0, 0, 1);
}
}
private void ShowMessage(int procedCnt, int replaceCnt, int breakCnt)
{
lock (_lockObj) {
_procedCnt += procedCnt;
_replaceCnt += replaceCnt;
_breakCnt += breakCnt;
_step2Bar.Message = string.Format(Strings.ShowMessageTemp, _procedCnt, _totalCnt, _replaceCnt, _breakCnt);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public override void Run()
{
if (!Directory.Exists(Opt.Path))
throw new ArgumentException(nameof(Opt.Path), string.Format(Strings.PathNotFound, Opt.Path));
using var step1Bar = new IndeterminateProgressBar(Strings.SearchingFile, DefaultProgressBarOptions);
var fileList = EnumerateFiles(Opt.Path, Opt.Filter);
_totalCnt = fileList.Count();
step1Bar.Message = string.Format(Strings.SearchingFileOK, _totalCnt);
step1Bar.Finished();
if (_totalCnt == 0) return;
_step2Bar = step1Bar.Spawn(_totalCnt, string.Empty, DefaultProgressBarOptions);
Parallel.ForEach(fileList, FileHandle);
}
}

4
src/ToLf/Option.cs Normal file
View File

@ -0,0 +1,4 @@
namespace Dot.ToLf;
[Verb("tolf", HelpText = nameof(Strings.ConvertEndOfLineToLF), ResourceType = typeof(Strings))]
public class Option : DirOption { }

View File

@ -9,10 +9,11 @@ public abstract class Tool<TOption> : ITool
, ForegroundColor = ConsoleColor.Yellow
, ForegroundColorDone = ConsoleColor.DarkGreen
, BackgroundColor = ConsoleColor.DarkGray
, BackgroundCharacter = '\u2593'
, BackgroundCharacter = '\u2500'
, ProgressCharacter = '\u2500'
};
protected virtual TOption Opt { get; set; }
protected TOption Opt { get; set; }
protected Tool(TOption opt)
{
@ -43,17 +44,23 @@ public abstract class Tool<TOption> : ITool
}
}
protected static FileStream OpenFileToWrite(string file)
protected static FileStream OpenFileStream(string file, FileMode mode, FileAccess access
, FileShare share = FileShare.Read)
{
FileStream fsr;
FileStream fsr = null;
try {
fsr = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
fsr = new FileStream(file, mode, access, share);
}
catch (UnauthorizedAccessException) {
File.SetAttributes(file, new FileInfo(file).Attributes & ~FileAttributes.ReadOnly);
fsr = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
try {
File.SetAttributes(file, new FileInfo(file).Attributes & ~FileAttributes.ReadOnly);
fsr = new FileStream(file, mode, access, share);
}
catch (Exception) {
// ignored
}
}
catch (IOException) { }
return fsr;
}

View File

@ -1,4 +1,4 @@
using Dot.TrimUtf8Bom;
using Dot.RmBom;
namespace Dot;
@ -7,13 +7,13 @@ public static class ToolsFactory
public static ITool Create(IOption option)
{
return option switch {
Option o => new Main(o)
, Convert2Lf.Option o => new Convert2Lf.Main(o)
, RemoveTrailingWhiteSpace.Option o => new RemoveTrailingWhiteSpace.Main(o)
, Random.Option o => new Random.Main(o)
, Text.Option o => new Text.Main(o)
, Guid.Option o => new Guid.Main(o)
, _ => throw new ArgumentOutOfRangeException(nameof(option))
Option o => new Main(o)
, ToLf.Option o => new ToLf.Main(o)
, RmBlank.Option o => new RmBlank.Main(o)
, Pwd.Option o => new Pwd.Main(o)
, Text.Option o => new Text.Main(o)
, Guid.Option o => new Guid.Main(o)
, _ => throw new ArgumentOutOfRangeException(nameof(option))
};
}
}

View File

@ -6,12 +6,12 @@
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Dot</RootNamespace>
<AssemblyName>dot</AssemblyName>
<Version>1.0.1</Version>
<Version>1.1.0</Version>
<Authors>nsnail</Authors>
<Copyright>Copyright (c) 2022 nsnail</Copyright>
<RepositoryUrl>https://github.com/nsnail/dot.git</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<AssemblyTitle>功能全面的实用工具-程序员的瑞士军刀</AssemblyTitle>
<AssemblyTitle>功能全面的实用工具 - 程序员的瑞士军刀</AssemblyTitle>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
@ -29,4 +29,19 @@
<PackageReference Include="TextCopy" Version="6.2.0"/>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Lang\Strings.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Strings.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Compile Update="Lang\Strings.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
</ItemGroup>
</Project>