Skip to content

Instantly share code, notes, and snippets.

@fal-works
Created October 22, 2021 14:38
Show Gist options
  • Save fal-works/214c75946532162cacb8ad73e0cba6c4 to your computer and use it in GitHub Desktop.
Save fal-works/214c75946532162cacb8ad73e0cba6c4 to your computer and use it in GitHub Desktop.
type Filepath for Haxe
import haxe.io.Path;
/**
ファイルパスです。
`haxe.io.Path` と以下の点で異なります。
- イミュータブルです。
- 作成時点で正規化されます。
- ディレクトリーや拡張子が未指定のときは空文字になります。
**/
@:notNull @:forward
abstract Filepath(FilepathData) to FilepathData {
/**
@param dir ファイルの保存先ディレクトリーのパスです。末尾スラッシュは自動的に削られます。
@param name ファイルの名前です。拡張子は含みません。
**/
public static function from(dir:String = "", name:String, ext:String = ""):Filepath
return fromData({dir: dir, name: name, ext: ext});
@:from public static function fromData(data:FilepathData):Filepath {
final ext = data.ext;
final norm = new Path(Path.normalize(dataToString({
dir: data.dir,
name: data.name,
ext: if (ext.startsWith(".")) ext.substr(1) else ext,
})));
return new Filepath({dir: norm.dir, name: norm.file, ext: norm.ext});
}
static inline function dataToString(data:FilepathData):String {
final dir = data.dir;
final dirWithSlash = if (dir.length > 0) '$dir/' else "";
final ext = data.ext;
final extWithDot = if (ext.length > 0) '.$ext' else "";
return '${dirWithSlash}${data.name}${extWithDot}';
}
inline function new(data:FilepathData)
this = data;
/**
`dir` を起点としたファイルパスを文字列として返します。
**/
@:to public inline function toString():String
return dataToString(this);
/**
`haxe.io.Path` に変換します。
**/
@:to public function toHaxePath():Path {
return new Path(toString());
}
}
private typedef FilepathData = {
/**
ファイルの保存先ディレクトリーのパスです。末尾スラッシュは付けません。未指定のときは空文字です。
**/
public final dir:String;
/**
ファイルの名前です。拡張子は含みません。
**/
public final name:String;
/**
拡張子です。冒頭のドットは付けません。未指定のときは空文字です。
**/
public final ext:String;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment