-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Kadai2 udomomo #37
Open
Udomomo
wants to merge
24
commits into
master
Choose a base branch
from
kadai2-Udomomo
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Kadai2 udomomo #37
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
0e319b9
initial commit
Udomomo 046503c
modify the code to change img format, not just expression
Udomomo 4a0b1d6
implemented image converter
Udomomo 8ec77d2
change directory tree
Udomomo 722470a
add convimg
Udomomo 24e7e40
added flag
Udomomo 2972d62
remove DS_Store
Udomomo 4355888
modified path
Udomomo f6cfb35
add comment to func
Udomomo bbedb80
add README
Udomomo 38505bb
modified build command
Udomomo f786dab
modified searchFile to return a slice of processedPath
Udomomo 2c6ce3a
change import path
Udomomo fc99b25
changed the way printing processed paths
Udomomo 5d7574b
modified to store processedPath into array
Udomomo a912988
move os.Remove for make tests easier
Udomomo 693b34a
modified Print to Println
Udomomo 3d93073
separated search and conv
Udomomo 23ef06a
Found mistake in the condition of generating converter
Udomomo 2c07b82
modified convFile to return error
Udomomo f9613f8
modified validation case
Udomomo b7acf26
added test and testdata
Udomomo 2217bd6
added README
Udomomo b5661d1
change testdata
Udomomo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
## 課題1 | ||
* 次の仕様を満たすコマンドを作って下さい | ||
- ディレクトリを指定する | ||
- 指定したディレクトリ以下のJPGファイルをPNGに変換(デフォルト) | ||
- ディレクトリ以下は再帰的に処理する | ||
- 変換前と変換後の画像形式を指定できる(オプション) | ||
|
||
* 以下を満たすように開発してください | ||
- mainパッケージと分離する | ||
- 自作パッケージと標準パッケージと準標準パッケージのみ使う | ||
- 準標準パッケージ:golang.org/x以下のパッケージ | ||
- ユーザ定義型を作ってみる | ||
- GoDocを生成してみる | ||
|
||
## コマンド | ||
* jpeg, png, jpg, gifに対応 | ||
|
||
## インストール | ||
``` | ||
$ go get github.com/Udomomo/dojo4/kadai1/Udomomo/convimg | ||
$ cd $GOPATH/src/github.com/Udomomo/dojo4/kadai1/Udomomo/convimg | ||
$ git checkout kadai1-Udomomo | ||
$ git fetch && git merge | ||
$ git install | ||
``` | ||
|
||
## ビルド | ||
``` | ||
$ go build -o bin/convimg main.go | ||
``` | ||
|
||
## コマンド | ||
``` | ||
$./bin/convimg [options] [directories] | ||
``` | ||
|
||
### オプション | ||
``` | ||
-f string | ||
format before conversion (default "jpg") | ||
-t string | ||
format after conversion (default "png") | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package convimg | ||
|
||
import ( | ||
"image" | ||
"image/gif" | ||
"image/jpeg" | ||
"image/png" | ||
"io" | ||
) | ||
|
||
type Converter interface { | ||
convimg() error | ||
} | ||
|
||
type jpgConverter struct { | ||
dist io.Writer | ||
img image.Image | ||
} | ||
|
||
type pngConverter struct { | ||
dist io.Writer | ||
img image.Image | ||
} | ||
|
||
type gifConverter struct { | ||
dist io.Writer | ||
img image.Image | ||
} | ||
|
||
//convert : ファイルの形式に合わせて、変換を行うメソッドを呼び分ける | ||
func convert(c Converter) error { | ||
return c.convimg() | ||
} | ||
|
||
func (c jpgConverter) convimg() error { | ||
return jpeg.Encode(c.dist, c.img, nil) | ||
} | ||
|
||
func (c pngConverter) convimg() error { | ||
return png.Encode(c.dist, c.img) | ||
} | ||
|
||
func (c gifConverter) convimg() error { | ||
return gif.Encode(c.dist, c.img, nil) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
package convimg | ||
|
||
import ( | ||
"fmt" | ||
"image" | ||
"io/ioutil" | ||
"log" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
//SearchFile : searchFile関数が出力する変換後のパスを貯めておき、返り値として返す。 | ||
func SearchFile(rootDir, from, to string) []string { | ||
processingPaths := make([]string, 0) | ||
processingPaths = searchFile(rootDir, from, to, processingPaths) | ||
|
||
processedPaths := make([]string, 0) | ||
for _, p := range processingPaths { | ||
e := filepath.Ext(p) | ||
np := p[:len(p)-len(e)] + to | ||
|
||
pp, err := convFile(p, np, to) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
processedPaths = append(processedPaths, pp) | ||
os.Remove(p) | ||
} | ||
|
||
//os.Remove後の結果はユニットテストしづらいので、ここで簡易的に確認する | ||
if len(processingPaths) != len(processedPaths) { | ||
log.Fatal("len of conv results is wrong") | ||
} | ||
return processedPaths | ||
} | ||
|
||
//searchFile : rootDirにあるファイルの一覧を探索。ディレクトリがあれば再帰処理する。 | ||
func searchFile(rootDir, from, to string, processingPaths []string) []string { | ||
|
||
files, err := ioutil.ReadDir(rootDir) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
for _, file := range files { | ||
path := filepath.Join(rootDir, file.Name()) | ||
if file.IsDir() { | ||
processingPaths = searchFile(path, from, to, processingPaths) | ||
continue | ||
} | ||
|
||
willConv := validateIfConvNeeded(path, from, to) | ||
if willConv == false { | ||
continue | ||
} | ||
|
||
processingPaths = append(processingPaths, path) | ||
} | ||
return processingPaths | ||
} | ||
|
||
//generateNewExt : 変換が必要な場合、変換後のパスを生成して返す | ||
func validateIfConvNeeded(path, from, to string) bool { | ||
ext := filepath.Ext(path) | ||
|
||
//変換したい拡張子でなければ何もしない | ||
if ext != from { | ||
return false | ||
} | ||
|
||
//変換する必要がなければ何もしない | ||
if from == to { | ||
return false | ||
} | ||
|
||
return true | ||
} | ||
|
||
//convFile : 変換を実行する | ||
func convFile(path, newPath, toExt string) (string, error) { | ||
file, err := os.Open(path) | ||
if err != nil { | ||
return newPath, fmt.Errorf("Original file open failed. Path: %s", path) | ||
} | ||
defer file.Close() | ||
|
||
decoded, _, err := image.Decode(file) | ||
if err != nil { | ||
return newPath, fmt.Errorf("Original file decode failed. Path: %s", path) | ||
} | ||
|
||
out, err := os.Create(newPath) | ||
if err != nil { | ||
return newPath, fmt.Errorf("New empty file creation failed. Path: %s", newPath) | ||
} | ||
defer out.Close() | ||
|
||
var c Converter | ||
switch toExt { | ||
case ".jpeg", ".jpg": | ||
{ | ||
c = &jpgConverter{out, decoded} | ||
} | ||
case ".png": | ||
{ | ||
c = &pngConverter{out, decoded} | ||
} | ||
case ".gif": | ||
{ | ||
c = &gifConverter{out, decoded} | ||
} | ||
default: | ||
{ | ||
return newPath, fmt.Errorf("Can't convert to illegal format: %s", toExt) | ||
} | ||
} | ||
|
||
if err := c.convimg(); err != nil { | ||
return newPath, fmt.Errorf("Encode failed from %s to %s", path, newPath) | ||
} | ||
|
||
return newPath, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
package convimg | ||
|
||
import ( | ||
"image" | ||
"os" | ||
"testing" | ||
) | ||
|
||
func TestSearchFile(t *testing.T) { | ||
t.Helper() | ||
expProcessingPath := []string{ | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.jpg", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test2/test2.jpg", | ||
} | ||
|
||
processingPath := searchFile("/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata", ".jpg", ".png", make([]string, 0)) | ||
for _, p := range expProcessingPath { | ||
if contains(processingPath, p) == false { | ||
t.Errorf("searchFile failed: %s is not searched", p) | ||
} | ||
} | ||
|
||
if len(processingPath) != len(expProcessingPath) { | ||
t.Errorf("searchFile failed: result is longer than expected: %v", processingPath) | ||
} | ||
} | ||
|
||
func contains(su []string, fl string) bool { | ||
for _, s := range su { | ||
if s == fl { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
|
||
func TestValidateIfConvNeeded(t *testing.T) { | ||
t.Helper() | ||
jpgPath := "/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.jpg" | ||
if validateIfConvNeeded(jpgPath, ".jpg", ".gif") == false { | ||
t.Error("validate failed: file should be converted") | ||
} | ||
if validateIfConvNeeded(jpgPath, ".png", ".gif") == true { | ||
t.Error("validate failed: fromExt difference is ignored") | ||
} | ||
if validateIfConvNeeded(jpgPath, ".jpg", ".jpg") == true { | ||
t.Error("validate failed: from and to are equal") | ||
} | ||
} | ||
|
||
func TestConvFile(t *testing.T) { | ||
t.Helper() | ||
var testCase = []struct { | ||
path string | ||
newPath string | ||
toExt string | ||
expFmt string | ||
wantErr bool | ||
}{ | ||
//正常ケース png->jpg | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.png", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/test.jpg", | ||
".jpg", | ||
"jpeg", | ||
false, | ||
}, | ||
//正常ケース jpg->gif | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.jpg", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/test.gif", | ||
".gif", | ||
"gif", | ||
false, | ||
}, | ||
//正常ケース gif->png | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.gif", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/test.png", | ||
".png", | ||
"png", | ||
false, | ||
}, | ||
//異常ケース 存在しないファイルパスの場合 | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/hogehoge.gif", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/test.png", | ||
".png", | ||
"png", | ||
true, | ||
}, | ||
//異常ケース ファイルが壊れている場合 | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/broken.gif", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/test.png", | ||
".png", | ||
"png", | ||
true, | ||
}, | ||
//異常ケース 書き込み先の権限がない場合 | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.gif", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/permission/test.png", | ||
".png", | ||
"png", | ||
true, | ||
}, | ||
//異常ケース 変換先の拡張子が不正な場合 | ||
{"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/testdata/test.gif", | ||
"/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/test.pmg", | ||
".pmg", | ||
"png", | ||
true, | ||
}, | ||
} | ||
|
||
if err := os.Mkdir("/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output", 0755); err != nil { | ||
t.Fatal(err) | ||
} | ||
defer os.RemoveAll("/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output") | ||
|
||
//書き込み先に権限がない場合のテスト用にディレクトリを作っておく | ||
if err := os.Mkdir("/Users/naoya/Golang_practice/dojo4/kadai1/Udomomo/output/permission", 0555); err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
for _, tc := range testCase { | ||
processedPath, err := convFile(tc.path, tc.newPath, tc.toExt) | ||
if err != nil && tc.wantErr == false { | ||
t.Errorf("Case %s should succeed but returned error: %#v", tc.path, err) | ||
} | ||
|
||
if err == nil && tc.wantErr == true { | ||
t.Errorf("Case %s should fail but succeeded", tc.path) | ||
} | ||
|
||
if err == nil { | ||
file, err := os.Open(processedPath) | ||
if err != nil { | ||
t.Errorf("processed file can't open. Path: %s", processedPath) | ||
} | ||
defer file.Close() | ||
|
||
if _, fmt, _ := image.Decode(file); fmt != tc.expFmt { | ||
t.Errorf("fmt is wrong: expected %s but actually %s", tc.expFmt, fmt) | ||
} | ||
} | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SearchFileとsearchFileを分けたのは、単にテストのためだけです。
再帰関数で処理が終わった後の出力結果をテストしたいと思ったのですが、繰り返し実行されるsearchFile関数の結果を一箇所にためておく方法が思いつきませんでした。クラスがあればプロパティに貯めればよいのですが、Golangの場合はそれはできないので、SearchFIle関数を作りその中でprocessedPathをあらかじめ定義しておくようにしました。